Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor: remove migrated inference implementations

Steven Enamakel37b81bba29aa
diff --git a/crates/openhuman-core/src/inference/auth_error_registry.rs b/crates/openhuman-core/src/inference/auth_error_registry.rs
deleted file mode 100644
index 8456674112..0000000000
--- a/crates/openhuman-core/src/inference/auth_error_registry.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-//! Process-lived registry of BYO provider auth failures (invalid / revoked
-//! API key, HTTP 401 / 403).
-//!
-//! Single source of truth feeding both user-facing surfaces for a rejected
-//! BYO key, so the two can never drift:
-//! - the **notification center** — a one-shot [`crate::core::bus::
-//! DomainEvent::ProviderApiKeyRejected`] published the first time a
-//! provider starts failing, and
-//! - the **AI-settings provider-error notice** — read live via the
-//! `openhuman.inference_provider_auth_errors` RPC ([`snapshot`]).
-//!
-//! Entries are recorded at the demote site
-//! ([`provider::ops::http_error::log_byo_provider_auth_failure`](super::provider::ops::http_error::log_byo_provider_auth_failure)) and cleared
-//! when the user updates or removes that provider's key
-//! (`credentials::ops`). The [`record`] latch is what makes the notification
-//! fire **once per failure episode** rather than once per retry: the
-//! triggering 401 repeats thousands of times (the memory-summarization loop
-//! re-attempts on every scoring pass — TAURI-RUST-4RC: ~9k events / 6 users),
-//! and an unguarded publish would re-flood the notification center the same
-//! way the raw error flooded Sentry.
-
-use std::collections::HashMap;
-use std::sync::{OnceLock, RwLock};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-/// A recorded BYO provider auth failure. Serialized verbatim onto the
-/// `inference_provider_auth_errors` RPC snapshot the AI settings panel reads.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-pub struct ProviderAuthError {
- /// Provider slug as used by the chat factory / classifier, e.g.
- /// `"openrouter"`.
- pub provider: String,
- /// The rejecting HTTP status — always `401` or `403` (the classifier
- /// gate), kept for fidelity in the surfaced copy.
- pub status: u16,
- /// Pre-formatted, user-facing, actionable message — safe to show in a
- /// notification or settings notice as-is. See [`auth_error_message`].
- pub message: String,
- /// Wall-clock milliseconds since the unix epoch when last recorded.
- pub timestamp_ms: u64,
-}
-
-fn registry() -> &'static RwLock<HashMap<String, ProviderAuthError>> {
- static REG: OnceLock<RwLock<HashMap<String, ProviderAuthError>>> = OnceLock::new();
- REG.get_or_init(|| RwLock::new(HashMap::new()))
-}
-
-fn now_ms() -> u64 {
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0)
-}
-
-/// Build the actionable, user-facing message for a BYO key the provider
-/// rejected. Phrased so it reads the same in the notification center and the
-/// AI-settings notice, and points the user at the one fix that resolves it
-/// (the third-party key is invalid / revoked — OpenHuman has no other lever).
-pub fn auth_error_message(provider: &str, status: u16) -> String {
- format!(
- "{provider} rejected the API key (HTTP {status}). Update your {provider} \
- API key in Connections → API keys → LLM to restore it."
- )
-}
-
-/// Record a BYO provider auth failure.
-///
-/// Returns `true` when this is a **new** failure episode for `provider` (no
-/// prior entry) — callers publish the one-shot notification only on `true` so
-/// a 401 that repeats per-retry doesn't re-notify. An existing entry is
-/// refreshed (status / timestamp) and returns `false`.
-pub fn record(provider: &str, status: u16) -> bool {
- let entry = ProviderAuthError {
- provider: provider.to_string(),
- status,
- message: auth_error_message(provider, status),
- timestamp_ms: now_ms(),
- };
- let mut map = registry().write().unwrap_or_else(|e| e.into_inner());
- let is_new = !map.contains_key(provider);
- map.insert(provider.to_string(), entry);
- is_new
-}
-
-/// Clear any recorded auth error for `provider` (the user updated / removed
-/// the key, or a call newly succeeded). Returns `true` if an entry was
-/// removed. Re-arms the [`record`] latch so a fresh failure re-notifies.
-pub fn clear(provider: &str) -> bool {
- registry()
- .write()
- .unwrap_or_else(|e| e.into_inner())
- .remove(provider)
- .is_some()
-}
-
-/// Snapshot all currently-recorded provider auth errors, sorted by provider
-/// slug for a stable RPC payload.
-pub fn snapshot() -> Vec<ProviderAuthError> {
- let map = registry().read().unwrap_or_else(|e| e.into_inner());
- let mut out: Vec<ProviderAuthError> = map.values().cloned().collect();
- out.sort_by(|a, b| a.provider.cmp(&b.provider));
- out
-}
-
-/// Test-only: wipe the registry so a test can't be flaked by an entry an
-/// earlier test left behind (the map is process-global).
-#[cfg(any(test, debug_assertions))]
-pub fn reset_for_tests() {
- registry()
- .write()
- .unwrap_or_else(|e| e.into_inner())
- .clear();
-}
-
-#[cfg(test)]
-#[path = "auth_error_registry_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/auth_error_registry_tests.rs b/crates/openhuman-core/src/inference/auth_error_registry_tests.rs
deleted file mode 100644
index b267b88460..0000000000
--- a/crates/openhuman-core/src/inference/auth_error_registry_tests.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use super::*;
-use std::sync::Mutex;
-
-// The registry is process-global, so these tests would otherwise race:
-// one test's `reset_for_tests` can wipe another's entries mid-run. Serialize
-// them on a shared lock (poison-tolerant) so each runs against a clean,
-// exclusive registry.
-static TEST_LOCK: Mutex<()> = Mutex::new(());
-
-#[test]
-fn record_returns_true_only_on_first_episode() {
- let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- reset_for_tests();
- assert!(record("openrouter", 401), "first record is a new episode");
- assert!(
- !record("openrouter", 401),
- "repeat record of same provider does not re-notify"
- );
- // A different provider is its own episode.
- assert!(record("openai", 403));
- reset_for_tests();
-}
-
-#[test]
-fn clear_removes_entry_and_rearms_latch() {
- let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- reset_for_tests();
- assert!(record("openrouter", 401));
- assert!(clear("openrouter"), "entry was present");
- assert!(!clear("openrouter"), "second clear is a no-op");
- // After clear, the next failure is a new episode again.
- assert!(record("openrouter", 401), "latch re-armed after clear");
- reset_for_tests();
-}
-
-#[test]
-fn snapshot_is_sorted_and_carries_actionable_message() {
- let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- reset_for_tests();
- record("openrouter", 401);
- record("anthropic", 401);
- let snap = snapshot();
- assert_eq!(snap.len(), 2);
- assert_eq!(snap[0].provider, "anthropic");
- assert_eq!(snap[1].provider, "openrouter");
- assert!(snap[1].message.contains("openrouter"));
- assert!(snap[1].message.contains("Connections → API keys → LLM"));
- reset_for_tests();
-}
diff --git a/crates/openhuman-core/src/inference/device.rs b/crates/openhuman-core/src/inference/device.rs
deleted file mode 100644
index fa2c7adb91..0000000000
--- a/crates/openhuman-core/src/inference/device.rs
+++ /dev/null
@@ -1,143 +0,0 @@
-//! Device profile detection for guided model selection.
-
-use serde::{Deserialize, Serialize};
-use std::sync::OnceLock;
-use sysinfo::System;
-
-static DEVICE_PROFILE_CACHE: OnceLock<DeviceProfile> = OnceLock::new();
-
-/// Summary of local hardware relevant for model tier selection.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct DeviceProfile {
- pub total_ram_bytes: u64,
- pub cpu_count: usize,
- pub cpu_brand: String,
- pub os_name: String,
- pub os_version: String,
- pub has_gpu: bool,
- pub gpu_description: Option<String>,
-}
-
-impl DeviceProfile {
- /// Total RAM expressed in whole gigabytes (rounded down).
- pub fn total_ram_gb(&self) -> u64 {
- self.total_ram_bytes / (1024 * 1024 * 1024)
- }
-}
-
-/// Return the detected [`DeviceProfile`] for the current machine.
-///
-/// The profile is probed once on first call and cached for the process lifetime.
-/// Hardware changes during runtime are detected after the app restarts.
-/// GPU detection is best-effort: Apple Silicon is assumed to have a GPU (Metal);
-/// on other platforms we report "unknown" unless more specific probing is added later.
-pub fn detect_device_profile() -> DeviceProfile {
- DEVICE_PROFILE_CACHE
- .get_or_init(detect_device_profile_uncached)
- .clone()
-}
-
-fn detect_device_profile_uncached() -> DeviceProfile {
- let mut sys = System::new_all();
- sys.refresh_all();
-
- let total_ram_bytes = sys.total_memory();
- let cpu_count = sys.cpus().len();
- let cpu_brand = sys
- .cpus()
- .first()
- .map(|c| c.brand().trim().to_string())
- .unwrap_or_default();
-
- let os_name = System::name().unwrap_or_else(|| "unknown".to_string());
- let os_version = System::os_version().unwrap_or_else(|| "unknown".to_string());
-
- let (has_gpu, gpu_description) = detect_gpu(&cpu_brand, &os_name);
-
- tracing::debug!(
- total_ram_bytes,
- cpu_count,
- cpu_brand = %cpu_brand,
- os_name = %os_name,
- os_version = %os_version,
- has_gpu,
- gpu_description = ?gpu_description,
- "device profile detected"
- );
-
- DeviceProfile {
- total_ram_bytes,
- cpu_count,
- cpu_brand,
- os_name,
- os_version,
- has_gpu,
- gpu_description,
- }
-}
-
-/// Best-effort GPU detection.
-///
-/// Apple Silicon always has a unified GPU (Metal). On Windows/Linux, we probe
-/// for NVIDIA GPUs via `nvidia-smi`. On other systems we conservatively report
-/// no GPU.
-fn detect_gpu(cpu_brand: &str, os_name: &str) -> (bool, Option<String>) {
- let brand_lower = cpu_brand.to_ascii_lowercase();
- let os_lower = os_name.to_ascii_lowercase();
-
- // Apple Silicon detection: brand contains "apple" or we're on macOS with an ARM chip.
- if brand_lower.contains("apple") || (os_lower.contains("mac") && brand_lower.contains("arm")) {
- tracing::debug!("GPU detected: Apple Silicon (Metal)");
- return (true, Some("Apple Silicon (Metal)".to_string()));
- }
-
- // Intel Mac: macOS with Intel CPU — no Metal GPU acceleration.
- if os_lower.contains("mac") {
- tracing::debug!("Intel Mac detected — no GPU acceleration available");
- return (false, Some("Intel Mac (no Metal GPU)".to_string()));
- }
-
- // Windows / Linux: probe for NVIDIA GPU via nvidia-smi.
- if let Some(desc) = probe_nvidia_smi() {
- tracing::debug!("GPU detected via nvidia-smi: {desc}");
- return (true, Some(desc));
- }
-
- tracing::debug!("no GPU detected — voice model will use CPU");
- (false, None)
-}
-
-/// Probe for an NVIDIA GPU by running `nvidia-smi --query-gpu=name --format=csv,noheader`.
-/// Returns `Some("NVIDIA <name> (CUDA)")` on success, `None` if nvidia-smi is not available.
-fn probe_nvidia_smi() -> Option<String> {
- let mut cmd = std::process::Command::new("nvidia-smi");
- cmd.args(["--query-gpu=name", "--format=csv,noheader"])
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::null());
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt;
- cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
- }
- let output = cmd.output().ok()?;
-
- if !output.status.success() {
- return None;
- }
-
- let name = String::from_utf8_lossy(&output.stdout)
- .lines()
- .next()?
- .trim()
- .to_string();
-
- if name.is_empty() {
- return None;
- }
-
- Some(format!("NVIDIA {name} (CUDA)"))
-}
-
-#[cfg(test)]
-#[path = "device_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/device_tests.rs b/crates/openhuman-core/src/inference/device_tests.rs
deleted file mode 100644
index fe251d3371..0000000000
--- a/crates/openhuman-core/src/inference/device_tests.rs
+++ /dev/null
@@ -1,143 +0,0 @@
-use super::*;
-
-#[test]
-fn detect_device_profile_returns_nonzero_hardware() {
- let profile = detect_device_profile();
- assert!(profile.total_ram_bytes > 0, "RAM should be > 0");
- assert!(profile.cpu_count > 0, "CPU count should be > 0");
- assert!(!profile.os_name.is_empty(), "OS name should be non-empty");
-}
-
-#[test]
-fn total_ram_gb_rounds_down() {
- let profile = DeviceProfile {
- total_ram_bytes: 17_179_869_184, // 16 GiB exactly
- cpu_count: 8,
- cpu_brand: "test".to_string(),
- os_name: "test".to_string(),
- os_version: "1.0".to_string(),
- has_gpu: false,
- gpu_description: None,
- };
- assert_eq!(profile.total_ram_gb(), 16);
-}
-
-#[test]
-fn total_ram_gb_reports_zero_for_sub_gb_systems() {
- let profile = DeviceProfile {
- total_ram_bytes: 500_000_000,
- cpu_count: 1,
- cpu_brand: "x".into(),
- os_name: "x".into(),
- os_version: "1".into(),
- has_gpu: false,
- gpu_description: None,
- };
- assert_eq!(profile.total_ram_gb(), 0);
-}
-
-#[test]
-fn total_ram_gb_truncates_partial_gigabyte() {
- // 1 GiB + 512 MiB should round down to 1 GiB.
- let profile = DeviceProfile {
- total_ram_bytes: (1024 * 1024 * 1024) + (512 * 1024 * 1024),
- cpu_count: 1,
- cpu_brand: "x".into(),
- os_name: "x".into(),
- os_version: "1".into(),
- has_gpu: false,
- gpu_description: None,
- };
- assert_eq!(profile.total_ram_gb(), 1);
-}
-
-#[test]
-fn detect_gpu_reports_apple_silicon_from_brand() {
- let (has, desc) = detect_gpu("Apple M2 Pro", "Darwin");
- assert!(has);
- assert_eq!(desc.as_deref(), Some("Apple Silicon (Metal)"));
-}
-
-#[test]
-fn detect_gpu_reports_apple_silicon_from_arm_on_mac() {
- // macOS + ARM CPU but brand lacks the literal "apple" string —
- // the arm+mac heuristic must still flag this as Apple Silicon.
- let (has, desc) = detect_gpu("arm based", "macOS");
- assert!(has);
- assert_eq!(desc.as_deref(), Some("Apple Silicon (Metal)"));
-}
-
-#[test]
-fn detect_gpu_reports_no_gpu_on_intel_mac() {
- let (has, desc) = detect_gpu("Intel Core i7", "macOS");
- assert!(!has);
- assert_eq!(desc.as_deref(), Some("Intel Mac (no Metal GPU)"));
-}
-
-#[test]
-fn detect_gpu_no_gpu_on_linux_without_nvidia() {
- // Linux without nvidia-smi should report no GPU (or NVIDIA if nvidia-smi is present).
- // Since we can't mock nvidia-smi here, we at least verify the function doesn't panic.
- let (has, desc) = detect_gpu("AMD Ryzen 9", "Linux");
- // On CI/dev machines without nvidia-smi, this should be (false, None).
- // If nvidia-smi is present, it returns (true, Some("NVIDIA ...")), which is also fine.
- if !has {
- assert!(desc.is_none());
- }
-}
-
-#[test]
-fn detect_gpu_windows_without_nvidia() {
- let (has, desc) = detect_gpu("Intel Core i9", "Windows");
- // Same as Linux: depends on nvidia-smi availability
- if !has {
- assert!(desc.is_none());
- }
-}
-
-#[test]
-fn total_ram_gb_exact_boundary() {
- let profile = DeviceProfile {
- total_ram_bytes: 1024 * 1024 * 1024, // exactly 1 GiB
- cpu_count: 1,
- cpu_brand: "x".into(),
- os_name: "x".into(),
- os_version: "1".into(),
- has_gpu: false,
- gpu_description: None,
- };
- assert_eq!(profile.total_ram_gb(), 1);
-}
-
-#[test]
-fn total_ram_gb_zero_bytes() {
- let profile = DeviceProfile {
- total_ram_bytes: 0,
- cpu_count: 1,
- cpu_brand: "x".into(),
- os_name: "x".into(),
- os_version: "1".into(),
- has_gpu: false,
- gpu_description: None,
- };
- assert_eq!(profile.total_ram_gb(), 0);
-}
-
-#[test]
-fn device_profile_serde_round_trip() {
- let original = DeviceProfile {
- total_ram_bytes: 8 * 1024 * 1024 * 1024,
- cpu_count: 4,
- cpu_brand: "CPU".into(),
- os_name: "OS".into(),
- os_version: "1.2.3".into(),
- has_gpu: true,
- gpu_description: Some("GPU".into()),
- };
- let s = serde_json::to_string(&original).unwrap();
- let back: DeviceProfile = serde_json::from_str(&s).unwrap();
- assert_eq!(back.total_ram_bytes, original.total_ram_bytes);
- assert_eq!(back.cpu_count, original.cpu_count);
- assert_eq!(back.has_gpu, original.has_gpu);
- assert_eq!(back.gpu_description, original.gpu_description);
-}
diff --git a/crates/openhuman-core/src/inference/local/lm_studio.rs b/crates/openhuman-core/src/inference/local/lm_studio.rs
deleted file mode 100644
index 4235751d82..0000000000
--- a/crates/openhuman-core/src/inference/local/lm_studio.rs
+++ /dev/null
@@ -1,213 +0,0 @@
-//! LM Studio OpenAI-compatible HTTP types and helpers.
-//!
-//! LM Studio exposes an OpenAI-compatible API under `http://localhost:1234/v1`
-//! by default. This module keeps the wire contract separate from the Ollama
-//! native API structs so the two providers can evolve independently.
-
-use crate::config::{Config, LocalAiConfig};
-use crate::util::redact_url_for_log;
-use serde::{Deserialize, Serialize};
-
-pub(crate) const DEFAULT_LM_STUDIO_BASE_URL: &str = "http://localhost:1234/v1";
-
-pub(crate) fn lm_studio_base_url(config: &Config) -> String {
- lm_studio_base_url_from_local_ai(&config.local_ai)
-}
-
-pub(crate) fn lm_studio_base_url_from_local_ai(local_ai: &LocalAiConfig) -> String {
- for (source, candidate) in [
- (
- "OPENHUMAN_LM_STUDIO_BASE_URL",
- std::env::var("OPENHUMAN_LM_STUDIO_BASE_URL").ok(),
- ),
- (
- "LM_STUDIO_BASE_URL",
- std::env::var("LM_STUDIO_BASE_URL").ok(),
- ),
- ("config.local_ai.base_url", local_ai.base_url.clone()),
- ] {
- let Some(raw) = candidate else {
- tracing::trace!(source, "[lm-studio] base URL candidate missing");
- continue;
- };
- tracing::trace!(
- source,
- raw = %redact_url_for_log(&raw),
- "[lm-studio] inspecting base URL candidate"
- );
- if let Some(normalized) = normalize_lm_studio_base_url(&raw) {
- tracing::debug!(
- source,
- base_url = %redact_url_for_log(&normalized),
- "[lm-studio] selected normalized base URL"
- );
- return normalized;
- }
- tracing::trace!(source, "[lm-studio] rejected blank base URL candidate");
- }
-
- tracing::debug!(
- base_url = %DEFAULT_LM_STUDIO_BASE_URL,
- "[lm-studio] using default base URL"
- );
- DEFAULT_LM_STUDIO_BASE_URL.to_string()
-}
-
-pub(crate) fn normalize_lm_studio_base_url(raw: &str) -> Option<String> {
- let trimmed = raw.trim().trim_end_matches('/');
- tracing::trace!(
- raw = %redact_url_for_log(raw),
- trimmed = %redact_url_for_log(trimmed),
- "[lm-studio] normalizing base URL"
- );
- if trimmed.is_empty() {
- tracing::trace!("[lm-studio] base URL normalization rejected blank input");
- return None;
- }
-
- let with_scheme = if trimmed.contains("://") {
- trimmed.to_string()
- } else {
- format!("http://{trimmed}")
- };
- tracing::trace!(
- with_scheme = %redact_url_for_log(&with_scheme),
- "[lm-studio] base URL scheme normalized"
- );
-
- let without_known_endpoint = with_scheme
- .trim_end_matches("/chat/completions")
- .trim_end_matches("/models")
- .trim_end_matches('/')
- .to_string();
- tracing::trace!(
- without_known_endpoint = %redact_url_for_log(&without_known_endpoint),
- "[lm-studio] base URL endpoint suffix normalized"
- );
-
- if without_known_endpoint.ends_with("/v1") {
- tracing::trace!(
- appended_v1 = false,
- base_url = %redact_url_for_log(&without_known_endpoint),
- "[lm-studio] base URL normalization complete"
- );
- Some(without_known_endpoint)
- } else {
- let normalized = format!("{without_known_endpoint}/v1");
- tracing::trace!(
- appended_v1 = true,
- base_url = %redact_url_for_log(&normalized),
- "[lm-studio] base URL normalization complete"
- );
- Some(normalized)
- }
-}
-
-pub(crate) fn apply_lm_studio_auth(
- request: reqwest::RequestBuilder,
- config: &Config,
-) -> reqwest::RequestBuilder {
- match config.local_ai.api_key.as_deref().map(str::trim) {
- Some(key) if !key.is_empty() => {
- tracing::trace!(
- api_key_present = true,
- api_key_len = key.len(),
- "[lm-studio] auth applied"
- );
- request.bearer_auth(key)
- }
- _ => {
- tracing::trace!(api_key_present = false, "[lm-studio] auth skipped");
- request
- }
- }
-}
-
-#[derive(Debug, Deserialize)]
-pub(crate) struct LmStudioModelsResponse {
- #[serde(default)]
- pub data: Vec<LmStudioModel>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub(crate) struct LmStudioModel {
- pub id: String,
- #[serde(default)]
- pub object: Option<String>,
- #[serde(default)]
- pub owned_by: Option<String>,
-}
-
-/// LM Studio **native** REST (`GET /api/v0/models`) model entry.
-///
-/// Unlike the OpenAI-compatible `/v1/models` (which returns only
-/// `id`/`object`/`owned_by`), the native API reports the model's context
-/// window — the value the agent harness must budget against to avoid an
-/// `n_ctx` overflow when the user loaded the model with a small context
-/// (issue #3550 / Sentry TAURI-RUST-6V0).
-#[derive(Debug, Clone, Deserialize)]
-pub(crate) struct LmStudioNativeModel {
- pub id: String,
- /// Context window the model is *currently loaded* with — the runtime's
- /// hard limit. Authoritative for budgeting. (LM Studio also returns a
- /// `state` field, which we ignore — we prefer the loaded window whenever
- /// present regardless of load state.)
- #[serde(default)]
- pub loaded_context_length: Option<u64>,
- /// Model's declared maximum context. Fallback when not currently loaded.
- #[serde(default)]
- pub max_context_length: Option<u64>,
-}
-
-#[derive(Debug, Deserialize)]
-pub(crate) struct LmStudioNativeModelsResponse {
- #[serde(default)]
- pub data: Vec<LmStudioNativeModel>,
-}
-
-/// Map a normalized `…/v1` base URL to the LM Studio native models endpoint
-/// `…/api/v0/models` (a sibling of `/v1`, served at the host root).
-pub(crate) fn lm_studio_native_models_url(v1_base_url: &str) -> String {
- format!("{}/api/v0/models", host_root_of(v1_base_url))
-}
-
-/// Strip a trailing `/v1` so sibling endpoints served at the host root can be
-/// derived from an OpenAI-compatible base URL.
-pub(crate) fn host_root_of(v1_base_url: &str) -> &str {
- v1_base_url
- .trim_end_matches('/')
- .trim_end_matches("/v1")
- .trim_end_matches('/')
-}
-
-/// Ollama-native `GET /api/tags` URL derived from an OpenAI-compatible base.
-///
-/// Only used as the one-shot 404 fallback in
-/// [`LocalAiService::list_lm_studio_models`](crate::inference::local::service::LocalAiService):
-/// some runtimes are reachable on an OpenAI-shaped base URL but expose only the
-/// Ollama listing (e.g. plain Ollama configured with a `/v1` base). Discovery is
-/// still chosen by provider type first — this is a recovery path, not a probe
-/// order (GH #5055).
-pub(crate) fn ollama_tags_fallback_url(v1_base_url: &str) -> String {
- format!("{}/api/tags", host_root_of(v1_base_url))
-}
-
-/// Resolve the context window LM Studio reports for `model_id` from a native
-/// `/api/v0/models` payload: prefer the *loaded* context (the limit the
-/// runtime actually enforces), else the model's declared maximum. Zero/absent
-/// values are treated as unknown. Returns `None` when the model isn't present
-/// or reports no usable window.
-pub(crate) fn lm_studio_context_window_for(
- resp: &LmStudioNativeModelsResponse,
- model_id: &str,
-) -> Option<u64> {
- resp.data.iter().find(|m| m.id == model_id).and_then(|m| {
- m.loaded_context_length
- .filter(|&v| v > 0)
- .or(m.max_context_length.filter(|&v| v > 0))
- })
-}
-
-#[cfg(test)]
-#[path = "lm_studio_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/lm_studio_tests.rs b/crates/openhuman-core/src/inference/local/lm_studio_tests.rs
deleted file mode 100644
index efa009bffa..0000000000
--- a/crates/openhuman-core/src/inference/local/lm_studio_tests.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-use super::*;
-
-#[test]
-fn native_models_url_derived_from_v1_base() {
- assert_eq!(
- lm_studio_native_models_url("http://localhost:1234/v1"),
- "http://localhost:1234/api/v0/models"
- );
- // Trailing slash tolerated.
- assert_eq!(
- lm_studio_native_models_url("http://127.0.0.1:1234/v1/"),
- "http://127.0.0.1:1234/api/v0/models"
- );
- // Remote host with path prefix.
- assert_eq!(
- lm_studio_native_models_url("https://lm.example.com/lmstudio/v1"),
- "https://lm.example.com/lmstudio/api/v0/models"
- );
-}
-
-/// GH #5055: the `/api/tags` fallback URL is a sibling of `/v1` at the host
-/// root. Appending to the `/v1` base would produce `/v1/api/tags` — the
-/// exact malformed request LM Studio logs as `Unexpected endpoint or
-/// method` (GH #5053).
-#[test]
-fn ollama_tags_fallback_url_is_host_rooted_not_v1_suffixed() {
- assert_eq!(
- ollama_tags_fallback_url("http://localhost:1234/v1"),
- "http://localhost:1234/api/tags"
- );
- assert_eq!(
- ollama_tags_fallback_url("http://127.0.0.1:1234/v1/"),
- "http://127.0.0.1:1234/api/tags"
- );
- assert_eq!(
- ollama_tags_fallback_url("https://lm.example.com/lmstudio/v1"),
- "https://lm.example.com/lmstudio/api/tags"
- );
- // A host-rooted base (no /v1) is left alone.
- assert_eq!(
- ollama_tags_fallback_url("http://localhost:11434"),
- "http://localhost:11434/api/tags"
- );
- for url in [
- ollama_tags_fallback_url("http://localhost:1234/v1"),
- ollama_tags_fallback_url("http://localhost:1234/v1/"),
- ] {
- assert!(!url.contains("/v1/api/tags"), "malformed probe URL: {url}");
- }
-}
-
-#[test]
-fn context_window_prefers_loaded_then_max() {
- let resp: LmStudioNativeModelsResponse = serde_json::from_str(
- r#"{"data":[
- {"id":"qwen2.5-7b","state":"loaded","loaded_context_length":4096,"max_context_length":32768},
- {"id":"phi-4","state":"not-loaded","max_context_length":16384}
- ]}"#,
- )
- .unwrap();
- // Loaded model → the runtime-enforced loaded window, NOT the trained max.
- assert_eq!(
- lm_studio_context_window_for(&resp, "qwen2.5-7b"),
- Some(4096)
- );
- // Not-loaded model → declared max as fallback.
- assert_eq!(lm_studio_context_window_for(&resp, "phi-4"), Some(16384));
- // Unknown model id → None (caller falls back to profile default).
- assert_eq!(lm_studio_context_window_for(&resp, "missing"), None);
-}
-
-#[test]
-fn context_window_treats_zero_and_absent_as_unknown() {
- let resp: LmStudioNativeModelsResponse = serde_json::from_str(
- r#"{"data":[
- {"id":"zeroed","loaded_context_length":0,"max_context_length":0},
- {"id":"bare"}
- ]}"#,
- )
- .unwrap();
- assert_eq!(lm_studio_context_window_for(&resp, "zeroed"), None);
- assert_eq!(lm_studio_context_window_for(&resp, "bare"), None);
-}
-
-#[test]
-fn normalize_lm_studio_base_url_defaults_scheme_and_v1() {
- assert_eq!(
- normalize_lm_studio_base_url("localhost:1234").as_deref(),
- Some("http://localhost:1234/v1")
- );
-}
-
-#[test]
-fn normalize_lm_studio_base_url_preserves_existing_v1() {
- assert_eq!(
- normalize_lm_studio_base_url("http://127.0.0.1:1234/v1/").as_deref(),
- Some("http://127.0.0.1:1234/v1")
- );
-}
-
-#[test]
-fn normalize_lm_studio_base_url_strips_known_endpoint_suffix() {
- assert_eq!(
- normalize_lm_studio_base_url("http://127.0.0.1:1234/v1/chat/completions").as_deref(),
- Some("http://127.0.0.1:1234/v1")
- );
- assert_eq!(
- normalize_lm_studio_base_url("http://127.0.0.1:1234/v1/models").as_deref(),
- Some("http://127.0.0.1:1234/v1")
- );
-}
diff --git a/crates/openhuman-core/src/inference/local/model_requirements.rs b/crates/openhuman-core/src/inference/local/model_requirements.rs
deleted file mode 100644
index 6a78be4241..0000000000
--- a/crates/openhuman-core/src/inference/local/model_requirements.rs
+++ /dev/null
@@ -1,74 +0,0 @@
-//! Minimum model requirements the memory layer imposes on local models.
-//!
-//! The memory tree's embedder (`bge-m3`) is requested with
-//! `num_ctx = 8192` (see
-//! [`tinyinference::embeddings::RECOMMENDED_OLLAMA_CONTEXT_TOKENS`])
-//! and the summariser hard-caps its output to fit that 8192-token embed
-//! ceiling. A local model whose native context window is below this floor
-//! silently truncates chunks/summaries and corrupts recall, so we refuse
-//! to accept any local model reporting a context window smaller than
-//! [`MIN_CONTEXT_TOKENS`]. There is **no upper requirement** — the
-//! pipeline is deliberately capped at 8k and never needs more from a
-//! local model.
-
-use serde::Serialize;
-
-/// Minimum native context window (tokens) a local model must advertise to
-/// be accepted by the memory layer.
-///
-/// Re-exported from TinyAgents' canonical Ollama context setting so this gate can
-/// never drift from what the memory pipeline actually requests at embed
-/// time. Changing the embedder's context request automatically moves the
-/// acceptance floor with it.
-pub const MIN_CONTEXT_TOKENS: u64 =
- tinyinference::embeddings::RECOMMENDED_OLLAMA_CONTEXT_TOKENS as u64;
-
-/// Verdict for a single model's context window against
-/// [`MIN_CONTEXT_TOKENS`]. Serialized into the diagnostics payload so the
-/// frontend can render / reject each installed model.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(tag = "status", rename_all = "snake_case")]
-pub enum ContextEligibility {
- /// Context window ≥ the minimum. Accepted.
- Ok { context_length: u64 },
- /// Context window below the minimum. Rejected for memory-layer use.
- BelowMinimum { context_length: u64, required: u64 },
- /// Context window could not be determined (`/api/show` error or the
- /// metadata key is absent). Not hard-rejected — surfaced as unknown so
- /// the UI can warn without blocking a model that may still be fine.
- Unknown { required: u64 },
-}
-
-impl ContextEligibility {
- /// `true` only when the model is positively accepted.
- pub fn is_accepted(&self) -> bool {
- matches!(self, ContextEligibility::Ok { .. })
- }
-
- /// `true` when the model is conclusively rejected (reported a context
- /// window below the floor). `Unknown` is **not** a rejection.
- pub fn is_rejected(&self) -> bool {
- matches!(self, ContextEligibility::BelowMinimum { .. })
- }
-}
-
-/// Classify a model's (optional) reported context length against the
-/// memory-layer minimum.
-pub fn evaluate_context(context_length: Option<u64>) -> ContextEligibility {
- match context_length {
- Some(ctx) if ctx >= MIN_CONTEXT_TOKENS => ContextEligibility::Ok {
- context_length: ctx,
- },
- Some(ctx) => ContextEligibility::BelowMinimum {
- context_length: ctx,
- required: MIN_CONTEXT_TOKENS,
- },
- None => ContextEligibility::Unknown {
- required: MIN_CONTEXT_TOKENS,
- },
- }
-}
-
-#[cfg(test)]
-#[path = "model_requirements_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/model_requirements_tests.rs b/crates/openhuman-core/src/inference/local/model_requirements_tests.rs
deleted file mode 100644
index ef83c6a50b..0000000000
--- a/crates/openhuman-core/src/inference/local/model_requirements_tests.rs
+++ /dev/null
@@ -1,66 +0,0 @@
-use super::*;
-
-#[test]
-fn min_context_tracks_embedder_request() {
- // The acceptance floor must equal what the memory embedder actually
- // requests; this guards against the two drifting apart.
- assert_eq!(
- MIN_CONTEXT_TOKENS,
- tinyinference::embeddings::RECOMMENDED_OLLAMA_CONTEXT_TOKENS as u64
- );
- assert_eq!(MIN_CONTEXT_TOKENS, 8_192);
-}
-
-#[test]
-fn at_or_above_minimum_is_accepted() {
- let exact = evaluate_context(Some(8_192));
- assert!(exact.is_accepted());
- assert_eq!(
- exact,
- ContextEligibility::Ok {
- context_length: 8_192
- }
- );
-
- let above = evaluate_context(Some(32_768));
- assert!(above.is_accepted());
- assert!(!above.is_rejected());
-}
-
-#[test]
-fn below_minimum_is_rejected_with_required_floor() {
- let verdict = evaluate_context(Some(2_048));
- assert!(verdict.is_rejected());
- assert!(!verdict.is_accepted());
- assert_eq!(
- verdict,
- ContextEligibility::BelowMinimum {
- context_length: 2_048,
- required: 8_192,
- }
- );
-}
-
-#[test]
-fn unknown_context_is_neither_accepted_nor_rejected() {
- let verdict = evaluate_context(None);
- assert!(!verdict.is_accepted());
- assert!(!verdict.is_rejected());
- assert_eq!(verdict, ContextEligibility::Unknown { required: 8_192 });
-}
-
-#[test]
-fn eligibility_serializes_tagged() {
- let json = serde_json::to_value(evaluate_context(Some(4_096))).unwrap();
- assert_eq!(json["status"], "below_minimum");
- assert_eq!(json["context_length"], 4_096);
- assert_eq!(json["required"], 8_192);
-
- let ok = serde_json::to_value(evaluate_context(Some(8_192))).unwrap();
- assert_eq!(ok["status"], "ok");
- assert_eq!(ok["context_length"], 8_192);
-
- let unknown = serde_json::to_value(evaluate_context(None)).unwrap();
- assert_eq!(unknown["status"], "unknown");
- assert_eq!(unknown["required"], 8_192);
-}
diff --git a/crates/openhuman-core/src/inference/local/ollama.rs b/crates/openhuman-core/src/inference/local/ollama.rs
deleted file mode 100644
index c08e6229ec..0000000000
--- a/crates/openhuman-core/src/inference/local/ollama.rs
+++ /dev/null
@@ -1,495 +0,0 @@
-//! Ollama HTTP JSON types and small helpers (private to this crate).
-
-use serde::{Deserialize, Serialize};
-
-pub(crate) const DEFAULT_OLLAMA_BASE_URL: &str = "http://localhost:11434";
-
-/// Hosts that serve the public Ollama website / model registry — never a local
-/// or self-hosted Ollama API server. Pointing the base URL at one makes every
-/// `/api/tags` poll hit ollama.com (HTTP 429 from its rate limiter), floods
-/// Sentry with `list_models: non-success response`, and sends pointless traffic
-/// to Ollama Inc. (TAURI-RUST-A3T).
-///
-/// Matched **exactly** (no suffix match) so a user's own self-hosted server at
-/// e.g. `ollama.mycompany.com` is unaffected.
-fn is_ollama_registry_host(host: &str) -> bool {
- matches!(
- host.trim()
- .trim_end_matches('.')
- .to_ascii_lowercase()
- .as_str(),
- "ollama.com" | "www.ollama.com" | "ollama.ai" | "www.ollama.ai" | "registry.ollama.ai"
- )
-}
-
-/// Returns `url` unless its host is a public Ollama registry host
-/// ([`is_ollama_registry_host`]), in which case it logs a warning and falls back
-/// to [`DEFAULT_OLLAMA_BASE_URL`]. This heals stale config/env values that
-/// already target ollama.com (set before validation rejected it), so the
-/// diagnostics poller stops hitting the website on the next launch.
-fn reject_registry_host_or_default(url: String) -> String {
- let is_registry = reqwest::Url::parse(&url)
- .ok()
- .and_then(|u| u.host_str().map(is_ollama_registry_host))
- .unwrap_or(false);
- if is_registry {
- log::warn!(
- "[local_ai] ignoring Ollama base URL {} (public website/registry, not a local server) — falling back to {DEFAULT_OLLAMA_BASE_URL}",
- redact_ollama_base_url(&url)
- );
- return DEFAULT_OLLAMA_BASE_URL.to_string();
- }
- url
-}
-
-/// Rewrite unspecified bind addresses (`0.0.0.0`, `[::]`) to their loopback
-/// equivalents (`127.0.0.1`, `[::1]`). Ollama's default `OLLAMA_HOST` is
-/// `0.0.0.0:11434` — a valid *server-side* bind address but an invalid
-/// *client-side* connect target on Windows (and misleading on other OSes).
-fn normalize_unspecified_host(url: &str) -> String {
- if let Ok(parsed) = reqwest::Url::parse(url) {
- let replacement = match parsed.host() {
- Some(url::Host::Ipv4(addr)) if addr.is_unspecified() => Some("localhost"),
- Some(url::Host::Ipv6(addr)) if addr.is_unspecified() => Some("[::1]"),
- _ => None,
- };
- if let Some(new_host) = replacement {
- let scheme = parsed.scheme();
- let port_suffix = parsed.port().map(|p| format!(":{p}")).unwrap_or_default();
- let path = parsed.path().trim_end_matches('/');
- let result = format!("{scheme}://{new_host}{port_suffix}{path}");
- let result = result.trim_end_matches('/').to_string();
- log::debug!(
- "[local_ai] normalize_unspecified_host: rewrote {} -> {}",
- redact_ollama_base_url(url),
- redact_ollama_base_url(&result)
- );
- return result;
- }
- }
- url.to_string()
-}
-
-/// Returns the effective Ollama base URL.
-///
-/// Priority (highest to lowest):
-/// 1. `OPENHUMAN_OLLAMA_BASE_URL` — app-specific override, used in tests.
-/// 2. `OLLAMA_HOST` — Ollama's own env var; normalized to a full URL by
-/// prepending `http://` when no scheme is present.
-/// 3. [`DEFAULT_OLLAMA_BASE_URL`] — `http://localhost:11434`.
-///
-/// Unspecified bind addresses (`0.0.0.0`, `[::]`) are rewritten to their
-/// loopback equivalents so the URL is valid as a client connect target.
-pub(crate) fn ollama_base_url() -> String {
- if let Ok(url) = std::env::var("OPENHUMAN_OLLAMA_BASE_URL") {
- let trimmed = url.trim();
- if !trimmed.is_empty() {
- return reject_registry_host_or_default(normalize_unspecified_host(
- trimmed.trim_end_matches('/'),
- ));
- }
- }
-
- if let Ok(host) = std::env::var("OLLAMA_HOST") {
- let trimmed = host.trim().trim_end_matches('/');
- if !trimmed.is_empty() {
- let url = if trimmed.contains("://") {
- trimmed.to_string()
- } else {
- format!("http://{trimmed}")
- };
- log::debug!("[local_ai] ollama_base_url: using OLLAMA_HOST -> {url}");
- return reject_registry_host_or_default(normalize_unspecified_host(&url));
- }
- }
-
- DEFAULT_OLLAMA_BASE_URL.to_string()
-}
-
-/// Returns the effective Ollama base URL, with `config.local_ai.base_url`
-/// taking highest priority over env vars.
-///
-/// Priority (highest to lowest):
-/// 1. `config.local_ai.base_url` if `Some` and non-empty (after trim)
-/// 2. `OPENHUMAN_OLLAMA_BASE_URL` env var
-/// 3. `OLLAMA_HOST` env var
-/// 4. [`DEFAULT_OLLAMA_BASE_URL`]
-///
-/// Unspecified bind addresses (`0.0.0.0`, `[::]`) are rewritten to their
-/// loopback equivalents so the URL is valid as a client connect target.
-pub(crate) fn ollama_base_url_from_config(config: &crate::config::Config) -> String {
- if let Some(ref url) = config.local_ai.base_url {
- let trimmed = url.trim().trim_end_matches('/');
- if !trimmed.is_empty() {
- let normalized = reject_registry_host_or_default(normalize_unspecified_host(trimmed));
- log::debug!(
- "[local_ai] ollama_base_url_from_config: using config base_url -> {}",
- redact_ollama_base_url(&normalized)
- );
- return normalized;
- }
- }
- let resolved = ollama_base_url();
- log::debug!(
- "[local_ai] ollama_base_url_from_config: config base_url absent, resolved -> {}",
- redact_ollama_base_url(&resolved)
- );
- resolved
-}
-
-/// Validate and normalize a user-supplied Ollama URL.
-///
-/// - Trims whitespace and strips trailing slashes.
-/// - Must have an `http://` or `https://` scheme.
-/// - Must have a non-empty host.
-/// - Rejects URLs with credentials (`user:pass@`).
-/// - Rejects query strings and fragments.
-/// - Strips any path component beyond root, normalizing to `scheme://host:port`.
-///
-/// Returns the normalized URL on success or an error message on failure.
-pub(crate) fn validate_ollama_url(raw: &str) -> Result<String, String> {
- let trimmed = raw.trim().trim_end_matches('/');
- if trimmed.is_empty() {
- return Err("URL must not be empty".to_string());
- }
- if !trimmed.starts_with("http://") && !trimmed.starts_with("https://") {
- return Err("URL must start with http:// or https://".to_string());
- }
- let parsed = reqwest::Url::parse(trimmed).map_err(|e| format!("Invalid URL: {e}"))?;
-
- if parsed.host_str().map(|h| h.is_empty()).unwrap_or(true) {
- return Err("URL must have a non-empty host".to_string());
- }
-
- if parsed
- .host_str()
- .map(is_ollama_registry_host)
- .unwrap_or(false)
- {
- return Err(
- "ollama.com is the Ollama website, not a local server. Enter your local Ollama \
- address (e.g. http://localhost:11434) or your own server's URL."
- .to_string(),
- );
- }
-
- if !parsed.username().is_empty() || parsed.password().is_some() {
- return Err("URL must not contain credentials (user:pass@host)".to_string());
- }
-
- if parsed.query().is_some() {
- return Err("URL must not contain a query string".to_string());
- }
- if parsed.fragment().is_some() {
- return Err("URL must not contain a fragment".to_string());
- }
-
- // Normalize to scheme://host[:port] — strip any path component.
- // Use the Host enum so IPv6 addresses are always re-bracketed correctly,
- // regardless of whether host_str() includes brackets in a given url-crate version.
- let host_formatted = match parsed.host() {
- Some(url::Host::Ipv4(addr)) if addr.is_unspecified() => "localhost".to_string(),
- Some(url::Host::Ipv6(addr)) if addr.is_unspecified() => "[::1]".to_string(),
- Some(url::Host::Ipv6(addr)) => format!("[{addr}]"),
- Some(h) => h.to_string(),
- None => String::new(),
- };
- let mut normalized = format!("{}://{}", parsed.scheme(), host_formatted);
- if let Some(port) = parsed.port() {
- normalized.push(':');
- normalized.push_str(&port.to_string());
- }
-
- log::debug!("[local_ai] validate_ollama_url: raw={trimmed:?} -> normalized={normalized:?}");
- Ok(normalized)
-}
-
-/// Strips userinfo, query, and fragment from `raw` so logs and error messages
-/// don't leak `user:pass@host`-style credentials embedded in the endpoint.
-pub(crate) fn redact_ollama_base_url(raw: &str) -> String {
- reqwest::Url::parse(raw)
- .map(|mut url| {
- let _ = url.set_username("");
- let _ = url.set_password(None);
- url.set_query(None);
- url.set_fragment(None);
- url.to_string()
- })
- .unwrap_or_else(|_| "<invalid-endpoint>".to_string())
-}
-
-#[derive(Debug, Serialize)]
-pub(crate) struct OllamaPullRequest {
- pub name: String,
- pub stream: bool,
-}
-
-#[derive(Debug, Deserialize)]
-pub(crate) struct OllamaPullEvent {
- #[allow(dead_code)]
- pub status: Option<String>,
- #[serde(default)]
- pub digest: Option<String>,
- pub total: Option<u64>,
- pub completed: Option<u64>,
- pub error: Option<String>,
-}
-
-#[derive(Debug, Default, Clone)]
-pub(crate) struct OllamaPullProgress {
- layers: std::collections::BTreeMap<String, OllamaPullLayerProgress>,
- fallback_total: Option<u64>,
- fallback_completed: u64,
-}
-
-#[derive(Debug, Default, Clone, Copy)]
-struct OllamaPullLayerProgress {
- total: Option<u64>,
- completed: u64,
-}
-
-impl OllamaPullProgress {
- pub(crate) fn observe(&mut self, event: &OllamaPullEvent) {
- if let Some(digest) = event
- .digest
- .as_ref()
- .filter(|value| !value.trim().is_empty())
- {
- let layer = self.layers.entry(digest.clone()).or_default();
- if let Some(total) = event.total {
- layer.total = Some(layer.total.unwrap_or(0).max(total));
- layer.completed = layer.completed.min(layer.total.unwrap_or(total));
- }
- if let Some(completed) = event.completed {
- let capped = layer
- .total
- .map(|total| completed.min(total))
- .unwrap_or(completed);
- layer.completed = layer.completed.max(capped);
- }
- return;
- }
-
- if let Some(total) = event.total {
- self.fallback_total = Some(self.fallback_total.unwrap_or(0).max(total));
- self.fallback_completed = self
- .fallback_completed
- .min(self.fallback_total.unwrap_or(total));
- }
- if let Some(completed) = event.completed {
- let capped = self
- .fallback_total
- .map(|total| completed.min(total))
- .unwrap_or(completed);
- self.fallback_completed = self.fallback_completed.max(capped);
- }
- }
-
- pub(crate) fn aggregate_downloaded(&self) -> u64 {
- if !self.layers.is_empty() {
- return self.layers.values().map(|layer| layer.completed).sum();
- }
- self.fallback_completed
- }
-
- pub(crate) fn aggregate_total(&self) -> Option<u64> {
- if !self.layers.is_empty() {
- let mut total = 0_u64;
- let mut has_any = false;
- for layer in self.layers.values() {
- if let Some(layer_total) = layer.total {
- total = total.saturating_add(layer_total);
- has_any = true;
- }
- }
- return has_any.then_some(total);
- }
- self.fallback_total
- }
-}
-
-#[derive(Debug, Deserialize)]
-pub(crate) struct OllamaTagsResponse {
- #[serde(default)]
- pub models: Vec<OllamaModelTag>,
- /// Set when the server answered with an error envelope rather than a
- /// catalog. LM Studio replies to unknown paths with `200 {"error": …}` and
- /// no `models` (GH #5053), which is indistinguishable from a real catalog
- /// by `models` alone — a fresh Ollama with nothing pulled legitimately
- /// returns `{"models":[]}`. Callers must branch on this field, not on
- /// emptiness.
- #[serde(default)]
- pub error: Option<String>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub(crate) struct OllamaModelTag {
- pub name: String,
- #[serde(default)]
- pub size: Option<u64>,
- #[serde(default)]
- pub modified_at: Option<String>,
-}
-
-/// Resolved per-model signals from one Ollama `POST /api/show` round-trip.
-///
-/// Both fields are `None` when `/api/show` failed or omitted the data:
-/// `context_length` → an `Unknown` memory-layer eligibility verdict;
-/// `chat_capable` → "keep visible" in the chat picker (fail-open). See
-/// [`OllamaShowResponse::chat_capability`] and Sentry TAURI-RUST-4P6.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
-pub(crate) struct OllamaModelShow {
- pub context_length: Option<u64>,
- pub chat_capable: Option<bool>,
-}
-
-/// Request body for Ollama `POST /api/show`.
-#[derive(Debug, Serialize)]
-pub(crate) struct OllamaShowRequest {
- /// Model tag (e.g. `bge-m3:latest`). `model` is the current Ollama
- /// field; older servers also accept the legacy `name`, which `model`
- /// is forward-compatible with.
- pub model: String,
-}
-
-/// Subset of Ollama `POST /api/show` we consume.
-///
-/// `model_info` is an open key/value map whose keys are architecture-scoped
-/// (e.g. `llama.context_length`, `bert.embedding_length`). The prefix is
-/// whatever `general.architecture` reports, so the context-length key is
-/// resolved dynamically rather than hard-coded per model family.
-#[derive(Debug, Default, Deserialize)]
-pub(crate) struct OllamaShowResponse {
- #[serde(default)]
- pub model_info: serde_json::Map<String, serde_json::Value>,
- /// Capability tags Ollama advertises for the model (e.g. `"completion"`,
- /// `"tools"`, `"vision"`, `"embedding"`, `"insert"`). Consumed by
- /// [`OllamaShowResponse::chat_capability`] to keep embedding-only models
- /// out of the chat-model picker (Sentry TAURI-RUST-4P6).
- #[serde(default)]
- pub capabilities: Vec<String>,
-}
-
-impl OllamaShowResponse {
- /// Native context window (tokens) advertised by the model's GGUF
- /// metadata, or `None` when the server did not report it.
- pub(crate) fn context_length(&self) -> Option<u64> {
- context_length_from_model_info(&self.model_info)
- }
-
- /// Whether this model can serve chat/completions, from its `capabilities`.
- pub(crate) fn chat_capability(&self) -> Option<bool> {
- ollama_chat_capability(&self.capabilities)
- }
-}
-
-/// Classify whether an Ollama model can serve chat/completions from its
-/// `/api/show` `capabilities` list.
-///
-/// Ollama tags text-generation models with `"completion"` (and newer builds
-/// also `"chat"`); embedding models are tagged `"embedding"` only. We only
-/// declare a model **not** chat-capable when we are confident it is
-/// embedding-only — capabilities is non-empty, carries an embedding marker,
-/// and carries no completion/chat marker. Anything ambiguous returns `None`
-/// (unknown):
-/// * empty / absent capabilities (older Ollama, or an `/api/show` miss);
-/// * a tag set we don't recognise (e.g. `["insert"]` only).
-///
-/// Callers treat `None` as "keep visible" — fail-open, never hide a model
-/// that might be usable for chat. Mirrors the non-rejecting `Unknown` arm of
-/// [`super::model_requirements::ContextEligibility`]. See Sentry TAURI-RUST-4P6.
-pub(crate) fn ollama_chat_capability(capabilities: &[String]) -> Option<bool> {
- if capabilities.is_empty() {
- return None;
- }
- let has = |needle: &str| {
- capabilities
- .iter()
- .any(|c| c.trim().eq_ignore_ascii_case(needle))
- };
- if has("completion") || has("chat") {
- Some(true)
- } else if has("embedding") || has("embed") {
- Some(false)
- } else {
- None
- }
-}
-
-/// Extract `<arch>.context_length` from an Ollama `model_info` map.
-///
-/// Resolution order:
-/// 1. `general.architecture` → `{arch}.context_length` (documented shape).
-/// 2. Fallback: the first key ending in `.context_length` — covers servers
-/// that omit `general.architecture` or use an unexpected prefix.
-pub(crate) fn context_length_from_model_info(
- info: &serde_json::Map<String, serde_json::Value>,
-) -> Option<u64> {
- fn as_u64(v: &serde_json::Value) -> Option<u64> {
- v.as_u64()
- .or_else(|| v.as_i64().filter(|n| *n >= 0).map(|n| n as u64))
- .or_else(|| v.as_f64().filter(|n| *n >= 0.0).map(|n| n as u64))
- }
- if let Some(arch) = info.get("general.architecture").and_then(|v| v.as_str()) {
- if let Some(value) = info.get(&format!("{arch}.context_length")).and_then(as_u64) {
- return Some(value);
- }
- }
- info.iter()
- .filter(|(key, _)| key.ends_with(".context_length"))
- .filter_map(|(_, value)| as_u64(value))
- .max()
-}
-
-#[derive(Debug, Serialize)]
-pub(crate) struct OllamaGenerateRequest {
- pub model: String,
- pub prompt: String,
- pub system: Option<String>,
- pub images: Option<Vec<String>>,
- pub stream: bool,
- pub options: Option<OllamaGenerateOptions>,
-}
-
-#[derive(Debug, Serialize)]
-pub(crate) struct OllamaGenerateOptions {
- pub temperature: Option<f32>,
- pub top_k: Option<u32>,
- pub top_p: Option<f32>,
- pub num_predict: Option<i32>,
-}
-
-#[derive(Debug, Deserialize)]
-pub(crate) struct OllamaGenerateResponse {
- pub response: String,
- #[allow(dead_code)]
- pub done: Option<bool>,
- #[allow(dead_code)]
- pub total_duration: Option<u64>,
- pub prompt_eval_count: Option<u32>,
- pub prompt_eval_duration: Option<u64>,
- pub eval_count: Option<u32>,
- pub eval_duration: Option<u64>,
-}
-
-#[derive(Debug, Serialize, Deserialize, Clone)]
-pub(crate) struct OllamaChatMessage {
- pub role: String,
- pub content: String,
-}
-
-pub(crate) fn ns_to_tps(tokens: f32, duration_ns: u64) -> Option<f32> {
- if duration_ns == 0 || tokens <= 0.0 {
- return None;
- }
- let seconds = duration_ns as f32 / 1_000_000_000.0;
- if seconds <= 0.0 {
- None
- } else {
- Some(tokens / seconds)
- }
-}
-
-#[cfg(test)]
-#[path = "ollama_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/ollama_tests.rs b/crates/openhuman-core/src/inference/local/ollama_tests.rs
deleted file mode 100644
index eec58ef745..0000000000
--- a/crates/openhuman-core/src/inference/local/ollama_tests.rs
+++ /dev/null
@@ -1,612 +0,0 @@
-use super::*;
-
-#[test]
-fn chat_capability_classifies_embedding_completion_and_unknown() {
- let owned = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<Vec<_>>();
-
- // Embedding-only model (bge-m3) → not chat-capable. TAURI-RUST-4P6.
- assert_eq!(ollama_chat_capability(&owned(&["embedding"])), Some(false));
- // Chat/completion models → chat-capable.
- assert_eq!(ollama_chat_capability(&owned(&["completion"])), Some(true));
- assert_eq!(
- ollama_chat_capability(&owned(&["completion", "tools", "vision"])),
- Some(true)
- );
- assert_eq!(ollama_chat_capability(&owned(&["chat"])), Some(true));
- // A model exposing BOTH stays chat-capable (completion wins).
- assert_eq!(
- ollama_chat_capability(&owned(&["embedding", "completion"])),
- Some(true)
- );
- // Unknown / fail-open: empty, or a tag set we don't recognise → None
- // (caller keeps the model visible).
- assert_eq!(ollama_chat_capability(&[]), None);
- assert_eq!(ollama_chat_capability(&owned(&["insert"])), None);
- // Case / whitespace tolerant.
- assert_eq!(
- ollama_chat_capability(&owned(&[" Embedding "])),
- Some(false)
- );
- assert_eq!(ollama_chat_capability(&owned(&["COMPLETION"])), Some(true));
-}
-
-#[test]
-fn pull_progress_aggregates_layered_download_events() {
- let mut progress = OllamaPullProgress::default();
-
- progress.observe(&OllamaPullEvent {
- status: Some("pulling".to_string()),
- digest: Some("sha256:layer-a".to_string()),
- total: Some(100),
- completed: Some(20),
- error: None,
- });
- progress.observe(&OllamaPullEvent {
- status: Some("pulling".to_string()),
- digest: Some("sha256:layer-b".to_string()),
- total: Some(200),
- completed: Some(50),
- error: None,
- });
- progress.observe(&OllamaPullEvent {
- status: Some("pulling".to_string()),
- digest: Some("sha256:layer-a".to_string()),
- total: Some(100),
- completed: Some(100),
- error: None,
- });
-
- assert_eq!(progress.aggregate_downloaded(), 150);
- assert_eq!(progress.aggregate_total(), Some(300));
-}
-
-#[test]
-fn pull_progress_falls_back_when_digest_is_missing() {
- let mut progress = OllamaPullProgress::default();
-
- progress.observe(&OllamaPullEvent {
- status: Some("pulling manifest".to_string()),
- digest: None,
- total: Some(120),
- completed: Some(30),
- error: None,
- });
- progress.observe(&OllamaPullEvent {
- status: Some("pulling manifest".to_string()),
- digest: None,
- total: Some(120),
- completed: Some(80),
- error: None,
- });
-
- assert_eq!(progress.aggregate_downloaded(), 80);
- assert_eq!(progress.aggregate_total(), Some(120));
-}
-
-// ── /api/show context-length extraction ──────────────────────────
-
-fn show_response(json: serde_json::Value) -> OllamaShowResponse {
- serde_json::from_value(json).expect("OllamaShowResponse")
-}
-
-#[test]
-fn context_length_uses_general_architecture_prefix() {
- let resp = show_response(serde_json::json!({
- "model_info": {
- "general.architecture": "bert",
- "bert.context_length": 8192,
- "bert.embedding_length": 1024
- }
- }));
- assert_eq!(resp.context_length(), Some(8192));
-}
-
-#[test]
-fn context_length_falls_back_when_architecture_missing() {
- let resp = show_response(serde_json::json!({
- "model_info": { "llama.context_length": 4096 }
- }));
- assert_eq!(resp.context_length(), Some(4096));
-}
-
-#[test]
-fn context_length_handles_float_and_string_encodings() {
- // Some servers serialize the metadata number as a float.
- let float = show_response(serde_json::json!({
- "model_info": { "general.architecture": "qwen2", "qwen2.context_length": 32768.0 }
- }));
- assert_eq!(float.context_length(), Some(32768));
-
- // Non-numeric / missing → None (caller treats as Unknown, not a hard fail).
- let missing = show_response(serde_json::json!({ "model_info": {} }));
- assert_eq!(missing.context_length(), None);
- let absent_field = show_response(serde_json::json!({}));
- assert_eq!(absent_field.context_length(), None);
-}
-
-#[test]
-fn context_length_prefers_architecture_key_over_unrelated_match() {
- let resp = show_response(serde_json::json!({
- "model_info": {
- "general.architecture": "llama",
- "llama.context_length": 8192,
- "clip.context_length": 77
- }
- }));
- assert_eq!(resp.context_length(), Some(8192));
-}
-
-#[test]
-fn context_length_fallback_returns_max_not_first() {
- // Without `general.architecture`, the fallback must pick the *largest*
- // `.context_length` value, not the first one encountered. Multimodal
- // models can carry a low secondary value (e.g. `clip.context_length:77`)
- // which, if chosen first, would incorrectly mark the model below minimum.
- let resp = show_response(serde_json::json!({
- "model_info": {
- "clip.context_length": 77,
- "llama.context_length": 32768
- }
- }));
- assert_eq!(resp.context_length(), Some(32768));
-}
-
-// ── ollama_base_url env-override behaviour ───────────────────────
-//
-// These tests mutate the process-global `OPENHUMAN_OLLAMA_BASE_URL`
-// variable, so they coordinate with the shared `LOCAL_AI_TEST_MUTEX`
-// used by `public_infer.rs` tests to prevent interleaved set/remove
-// calls from other tests in the same binary.
-
-const ENV_VAR: &str = "OPENHUMAN_OLLAMA_BASE_URL";
-const OLLAMA_HOST_VAR: &str = "OLLAMA_HOST";
-
-struct OllamaEnvGuard {
- var: &'static str,
- prior: Option<String>,
-}
-
-impl OllamaEnvGuard {
- fn clear() -> Self {
- let prior = std::env::var(ENV_VAR).ok();
- unsafe { std::env::remove_var(ENV_VAR) };
- Self {
- var: ENV_VAR,
- prior,
- }
- }
-
- fn set(value: &str) -> Self {
- let prior = std::env::var(ENV_VAR).ok();
- unsafe { std::env::set_var(ENV_VAR, value) };
- Self {
- var: ENV_VAR,
- prior,
- }
- }
-
- fn clear_var(var: &'static str) -> Self {
- let prior = std::env::var(var).ok();
- unsafe { std::env::remove_var(var) };
- Self { var, prior }
- }
-
- fn set_var(var: &'static str, value: &str) -> Self {
- let prior = std::env::var(var).ok();
- unsafe { std::env::set_var(var, value) };
- Self { var, prior }
- }
-}
-
-impl Drop for OllamaEnvGuard {
- fn drop(&mut self) {
- unsafe {
- match self.prior.take() {
- Some(v) => std::env::set_var(self.var, v),
- None => std::env::remove_var(self.var),
- }
- }
- }
-}
-
-fn test_lock() -> std::sync::MutexGuard<'static, ()> {
- crate::inference::inference_test_guard()
-}
-
-#[test]
-fn ollama_base_url_returns_default_when_env_unset() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::clear();
- assert_eq!(ollama_base_url(), DEFAULT_OLLAMA_BASE_URL);
-}
-
-#[test]
-fn ollama_base_url_returns_env_value_for_normal_url() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::set("http://127.0.0.1:55555");
- assert_eq!(ollama_base_url(), "http://127.0.0.1:55555");
-}
-
-#[test]
-fn ollama_base_url_trims_surrounding_whitespace() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::set(" http://127.0.0.1:55555 ");
- assert_eq!(ollama_base_url(), "http://127.0.0.1:55555");
-}
-
-#[test]
-fn ollama_base_url_strips_trailing_slashes() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::set("http://127.0.0.1:55555///");
- assert_eq!(ollama_base_url(), "http://127.0.0.1:55555");
-}
-
-#[test]
-fn ollama_base_url_falls_back_for_empty_or_whitespace_env() {
- let _lock = test_lock();
- {
- let _g = OllamaEnvGuard::set("");
- assert_eq!(ollama_base_url(), DEFAULT_OLLAMA_BASE_URL);
- }
- {
- let _g = OllamaEnvGuard::set(" ");
- assert_eq!(ollama_base_url(), DEFAULT_OLLAMA_BASE_URL);
- }
-}
-
-#[test]
-fn ollama_base_url_uses_ollama_host_when_openhuman_var_unset() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "192.168.1.5:11434");
- assert_eq!(ollama_base_url(), "http://192.168.1.5:11434");
-}
-
-#[test]
-fn ollama_base_url_prepends_http_for_host_without_scheme() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "myhost:11434");
- assert_eq!(ollama_base_url(), "http://myhost:11434");
-}
-
-#[test]
-fn ollama_base_url_preserves_existing_scheme_in_ollama_host() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "https://remote-ollama.example.com");
- assert_eq!(ollama_base_url(), "https://remote-ollama.example.com");
-}
-
-#[test]
-fn ollama_base_url_openhuman_var_takes_priority_over_ollama_host() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::set("http://127.0.0.1:55555");
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "192.168.1.5:11434");
- assert_eq!(ollama_base_url(), "http://127.0.0.1:55555");
-}
-
-#[test]
-fn ollama_base_url_ignores_empty_ollama_host() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, " ");
- assert_eq!(ollama_base_url(), DEFAULT_OLLAMA_BASE_URL);
-}
-
-#[test]
-fn ollama_base_url_strips_trailing_slash_from_ollama_host() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "myhost:11434/");
- assert_eq!(ollama_base_url(), "http://myhost:11434");
-}
-
-// ── ollama_base_url_from_config ───────────────────────────────────
-
-fn make_config_with_base_url(url: Option<&str>) -> crate::config::Config {
- let mut config = crate::config::Config::default();
- config.local_ai.base_url = url.map(|s| s.to_string());
- config
-}
-
-#[test]
-fn ollama_base_url_from_config_takes_priority_over_env() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::set("http://127.0.0.1:55555");
- let config = make_config_with_base_url(Some("http://192.168.1.5:11434"));
- assert_eq!(
- ollama_base_url_from_config(&config),
- "http://192.168.1.5:11434"
- );
-}
-
-#[test]
-fn ollama_base_url_from_config_falls_back_when_none() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::set("http://127.0.0.1:55555");
- let config = make_config_with_base_url(None);
- assert_eq!(
- ollama_base_url_from_config(&config),
- "http://127.0.0.1:55555"
- );
-}
-
-// ── normalize_unspecified_host ──────────────────────────────────────
-
-#[test]
-fn normalize_rewrites_ipv4_unspecified() {
- assert_eq!(
- normalize_unspecified_host("http://0.0.0.0:11434"),
- "http://localhost:11434"
- );
-}
-
-#[test]
-fn normalize_rewrites_ipv6_unspecified() {
- assert_eq!(
- normalize_unspecified_host("http://[::]:11434"),
- "http://[::1]:11434"
- );
-}
-
-#[test]
-fn normalize_preserves_loopback() {
- assert_eq!(
- normalize_unspecified_host("http://127.0.0.1:11434"),
- "http://127.0.0.1:11434"
- );
- assert_eq!(
- normalize_unspecified_host("http://[::1]:11434"),
- "http://[::1]:11434"
- );
-}
-
-#[test]
-fn normalize_preserves_named_host() {
- assert_eq!(
- normalize_unspecified_host("http://localhost:11434"),
- "http://localhost:11434"
- );
- assert_eq!(
- normalize_unspecified_host("http://my-ollama.lan:11434"),
- "http://my-ollama.lan:11434"
- );
-}
-
-#[test]
-fn normalize_preserves_private_ip() {
- assert_eq!(
- normalize_unspecified_host("http://192.168.1.5:11434"),
- "http://192.168.1.5:11434"
- );
-}
-
-#[test]
-fn normalize_handles_invalid_url() {
- assert_eq!(normalize_unspecified_host("not a url"), "not a url");
-}
-
-// ── ollama_base_url: 0.0.0.0 normalization ─────────────────────────
-
-#[test]
-fn ollama_base_url_normalizes_unspecified_in_env_override() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::set("http://0.0.0.0:11434");
- assert_eq!(ollama_base_url(), "http://localhost:11434");
-}
-
-#[test]
-fn ollama_base_url_normalizes_unspecified_in_ollama_host() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "0.0.0.0:11434");
- assert_eq!(ollama_base_url(), "http://localhost:11434");
-}
-
-#[test]
-fn ollama_base_url_normalizes_ipv6_unspecified_in_ollama_host() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "http://[::]:11434");
- assert_eq!(ollama_base_url(), "http://[::1]:11434");
-}
-
-// ── ollama_base_url_from_config: 0.0.0.0 normalization ──────────────
-
-#[test]
-fn ollama_base_url_from_config_normalizes_unspecified() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::clear();
- let config = make_config_with_base_url(Some("http://0.0.0.0:11434"));
- assert_eq!(
- ollama_base_url_from_config(&config),
- "http://localhost:11434"
- );
-}
-
-#[test]
-fn ollama_base_url_from_config_normalizes_ipv6_unspecified() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::clear();
- let config = make_config_with_base_url(Some("http://[::]:11434"));
- assert_eq!(ollama_base_url_from_config(&config), "http://[::1]:11434");
-}
-
-// ── validate_ollama_url ───────────────────────────────────────────
-
-#[test]
-fn validate_ollama_url_accepts_http() {
- assert_eq!(
- validate_ollama_url("http://localhost:11434"),
- Ok("http://localhost:11434".to_string())
- );
-}
-
-#[test]
-fn validate_ollama_url_accepts_https() {
- assert_eq!(
- validate_ollama_url("https://remote-ollama.example.com:11434"),
- Ok("https://remote-ollama.example.com:11434".to_string())
- );
-}
-
-#[test]
-fn validate_ollama_url_rejects_no_scheme() {
- assert!(validate_ollama_url("localhost:11434").is_err());
- assert!(validate_ollama_url("ftp://localhost:11434").is_err());
-}
-
-#[test]
-fn validate_ollama_url_rejects_credentials() {
- assert!(validate_ollama_url("http://user:pass@localhost:11434").is_err());
-}
-
-#[test]
-fn validate_ollama_url_strips_path_and_normalizes() {
- assert_eq!(
- validate_ollama_url("http://192.168.1.5:11434/api/tags"),
- Ok("http://192.168.1.5:11434".to_string())
- );
-}
-
-#[test]
-fn validate_ollama_url_rejects_empty() {
- assert!(validate_ollama_url("").is_err());
- assert!(validate_ollama_url(" ").is_err());
-}
-
-#[test]
-fn validate_ollama_url_handles_ipv6() {
- assert_eq!(
- validate_ollama_url("http://[::1]:11434"),
- Ok("http://[::1]:11434".to_string())
- );
-}
-
-#[test]
-fn validate_ollama_url_rewrites_ipv4_unspecified_to_localhost() {
- assert_eq!(
- validate_ollama_url("http://0.0.0.0:11434"),
- Ok("http://localhost:11434".to_string())
- );
-}
-
-#[test]
-fn validate_ollama_url_rewrites_ipv6_unspecified_to_loopback() {
- assert_eq!(
- validate_ollama_url("http://[::]:11434"),
- Ok("http://[::1]:11434".to_string())
- );
-}
-
-// ── public Ollama registry-host rejection (TAURI-RUST-A3T) ─────────
-
-#[test]
-fn is_ollama_registry_host_matches_public_hosts_case_insensitively() {
- for host in [
- "ollama.com",
- "OLLAMA.COM",
- "www.ollama.com",
- "ollama.ai",
- "www.ollama.ai",
- "registry.ollama.ai",
- "ollama.com.", // trailing FQDN dot
- ] {
- assert!(is_ollama_registry_host(host), "expected reject: {host}");
- }
-}
-
-#[test]
-fn is_ollama_registry_host_allows_self_hosted_and_loopback() {
- // No suffix match: a user's own subdomain must NOT be blocked.
- for host in [
- "localhost",
- "127.0.0.1",
- "ollama.mycompany.com",
- "my-ollama.lan",
- "remote-ollama.example.com",
- "notollama.com",
- ] {
- assert!(!is_ollama_registry_host(host), "expected allow: {host}");
- }
-}
-
-#[test]
-fn validate_ollama_url_rejects_public_registry_hosts() {
- // The bug: ollama.com is the website/registry, not a local server.
- // `/api/tags` against it returns HTTP 429 and floods Sentry.
- for url in [
- "https://ollama.com",
- "http://ollama.com",
- "https://ollama.com/",
- "https://www.ollama.com:443",
- "https://ollama.ai",
- "https://registry.ollama.ai",
- ] {
- let err = validate_ollama_url(url).unwrap_err();
- assert!(
- err.contains("ollama.com is the Ollama website"),
- "expected website rejection for {url}, got: {err}"
- );
- }
-}
-
-#[test]
-fn validate_ollama_url_still_accepts_self_hosted_subdomain() {
- assert_eq!(
- validate_ollama_url("https://ollama.mycompany.com:11434"),
- Ok("https://ollama.mycompany.com:11434".to_string())
- );
-}
-
-#[test]
-fn ollama_base_url_from_config_heals_registry_host_to_default() {
- // Existing users who saved ollama.com before validation rejected it
- // must stop hitting the website on the next launch.
- let _lock = test_lock();
- let _g = OllamaEnvGuard::clear();
- let config = make_config_with_base_url(Some("https://ollama.com"));
- assert_eq!(
- ollama_base_url_from_config(&config),
- DEFAULT_OLLAMA_BASE_URL
- );
-}
-
-#[test]
-fn ollama_base_url_heals_registry_host_from_env_override() {
- let _lock = test_lock();
- let _g = OllamaEnvGuard::set("https://ollama.com");
- assert_eq!(ollama_base_url(), DEFAULT_OLLAMA_BASE_URL);
-}
-
-#[test]
-fn ollama_base_url_heals_registry_host_from_ollama_host() {
- let _lock = test_lock();
- let _g1 = OllamaEnvGuard::clear();
- let _g2 = OllamaEnvGuard::set_var(OLLAMA_HOST_VAR, "ollama.com");
- assert_eq!(ollama_base_url(), DEFAULT_OLLAMA_BASE_URL);
-}
-
-// ── redact_ollama_base_url ────────────────────────────────────────
-
-#[test]
-fn redact_strips_userinfo_query_and_fragment() {
- assert_eq!(
- redact_ollama_base_url("http://user:pass@host:11434/api?token=abc#frag"),
- "http://host:11434/api"
- );
-}
-
-#[test]
-fn redact_keeps_plain_url() {
- assert_eq!(
- redact_ollama_base_url("http://127.0.0.1:11434/"),
- "http://127.0.0.1:11434/"
- );
-}
-
-#[test]
-fn redact_handles_invalid_url() {
- assert_eq!(redact_ollama_base_url("not a url"), "<invalid-endpoint>");
-}
diff --git a/crates/openhuman-core/src/inference/local/process_util.rs b/crates/openhuman-core/src/inference/local/process_util.rs
deleted file mode 100644
index 79e9d52fa4..0000000000
--- a/crates/openhuman-core/src/inference/local/process_util.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-//! Process-spawn helpers for local AI subsystems.
-//!
-//! On Windows every `Command::spawn` allocates a conhost for the child
-//! before stdio inheritance is applied — so a `Stdio::null()` redirect
-//! still flashes a console window. `apply_no_window` sets the
-//! `CREATE_NO_WINDOW` (0x0800_0000) process-creation flag which tells
-//! the OS to skip conhost allocation entirely.
-//!
-//! Mirrors the pattern established by #731 and #1338 for the Tauri-shell
-//! side (see `crates/openhuman-app/src/core_process.rs` and `process_kill.rs`).
-//! Without this every Ollama health-check / install attempt flashes a
-//! console on Windows; on a fresh install without Ollama present the
-//! flashes are continuous because the resolve-or-install loop retries.
-
-#[cfg(windows)]
-const CREATE_NO_WINDOW: u32 = 0x0800_0000;
-
-#[cfg(windows)]
-pub(crate) fn apply_no_window(cmd: &mut tokio::process::Command) {
- cmd.creation_flags(CREATE_NO_WINDOW);
-}
-
-#[cfg(not(windows))]
-pub(crate) fn apply_no_window(_cmd: &mut tokio::process::Command) {}
-
-#[cfg(test)]
-#[path = "process_util_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/process_util_tests.rs b/crates/openhuman-core/src/inference/local/process_util_tests.rs
deleted file mode 100644
index 16a5af741d..0000000000
--- a/crates/openhuman-core/src/inference/local/process_util_tests.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-use super::*;
-
-#[test]
-fn apply_no_window_is_callable_on_every_platform() {
- // The function is a no-op on non-Windows. On Windows it sets a
- // creation flag we cannot directly read back from
- // `tokio::process::Command`, so this test just guarantees the
- // helper compiles and is callable from generic code.
- let mut cmd = tokio::process::Command::new("does-not-need-to-exist");
- apply_no_window(&mut cmd);
-}
diff --git a/crates/openhuman-core/src/inference/local/profile.rs b/crates/openhuman-core/src/inference/local/profile.rs
deleted file mode 100644
index a8a58e4896..0000000000
--- a/crates/openhuman-core/src/inference/local/profile.rs
+++ /dev/null
@@ -1,243 +0,0 @@
-//! Local provider profiles — capability metadata for local inference runtimes.
-//!
-//! Instead of treating all local OpenAI-compatible providers identically, each
-//! provider type (Ollama, LM Studio, MLX-compatible, generic local OpenAI) gets
-//! a profile that declares its capabilities, quirks, and default context window.
-//! The factory and agent harness consult these profiles for:
-//!
-//! - Tool dispatch strategy (native vs prompt-guided)
-//! - Context window defaults for unknown model names
-//! - Request body extras (`options.num_ctx`, `think` field suppression)
-//! - Temperature handling
-
-use serde::{Deserialize, Serialize};
-
-/// Identifies a local provider type.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum LocalProviderKind {
- Ollama,
- LmStudio,
- /// MLX-compatible local server (e.g. `mlx_lm.server`).
- Mlx,
- /// OMLX — OpenAI v1-compatible MLX server that requires an API key.
- Omlx,
- /// Generic local OpenAI-compatible endpoint (llama.cpp, vLLM, etc.).
- LocalOpenai,
-}
-
-impl LocalProviderKind {
- pub fn as_str(self) -> &'static str {
- match self {
- Self::Ollama => "ollama",
- Self::LmStudio => "lmstudio",
- Self::Mlx => "mlx",
- Self::Omlx => "omlx",
- Self::LocalOpenai => "local-openai",
- }
- }
-
- pub fn display_name(self) -> &'static str {
- match self {
- Self::Ollama => "Ollama",
- Self::LmStudio => "LM Studio",
- Self::Mlx => "MLX",
- Self::Omlx => "OMLX",
- Self::LocalOpenai => "Local OpenAI",
- }
- }
-
- /// Parse a provider kind from a string, accepting common aliases.
- pub fn from_str_loose(s: &str) -> Option<Self> {
- match s.trim().to_ascii_lowercase().as_str() {
- "ollama" => Some(Self::Ollama),
- "lmstudio" | "lm-studio" | "lm_studio" => Some(Self::LmStudio),
- "mlx" | "mlx-server" | "mlx_lm" => Some(Self::Mlx),
- "omlx" | "omlx-server" => Some(Self::Omlx),
- "local-openai" | "local_openai" | "llamacpp" | "llama.cpp" | "vllm" => {
- Some(Self::LocalOpenai)
- }
- _ => None,
- }
- }
-}
-
-/// How the provider handles tool calling.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ToolSupport {
- /// Provider reliably supports native OpenAI-style tool calling.
- Native,
- /// Provider does NOT support native tools — use prompt-guided dispatch.
- PromptGuided,
- /// Support depends on the specific model; probe or consult model profile.
- ModelDependent,
-}
-
-/// Extra request body options for a local provider.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct RequestQuirks {
- /// Ollama `options.num_ctx` override. When set, injected into the
- /// request body as `{"options": {"num_ctx": <value>}}`.
- pub num_ctx: Option<u32>,
- /// When true, suppress reasoning/thinking fields in the request.
- /// Some Ollama models reject requests containing `think` parameters.
- pub suppress_thinking: bool,
- /// When true, omit the `temperature` field entirely (model uses its
- /// own default). Distinct from `temperature_unsupported_models` which
- /// is pattern-based — this is a blanket provider-level override.
- pub omit_temperature: bool,
- /// When true, merge system messages into user messages (provider
- /// rejects `role: system`).
- pub merge_system_into_user: bool,
-}
-
-/// Static capability profile for a local provider type.
-#[derive(Debug, Clone)]
-pub struct LocalProviderProfile {
- pub kind: LocalProviderKind,
- /// Default tool support level for this provider type.
- pub tool_support: ToolSupport,
- /// Default context window (tokens) when the model name is not
- /// recognized by `context_window_for_model`. `None` means "unknown,
- /// skip preflight trimming".
- pub default_context_window: Option<u64>,
- /// Whether the provider supports the Responses API (`/v1/responses`).
- pub supports_responses_api: bool,
- /// Whether the provider supports SSE streaming.
- pub supports_streaming: bool,
- /// Default request quirks for this provider type.
- pub default_quirks: RequestQuirks,
- /// Default base URL when none is configured.
- pub default_base_url: &'static str,
- /// Environment variable name for base URL override.
- pub base_url_env: &'static str,
-}
-
-/// Ollama profile: conservative defaults, no native tools.
-pub const OLLAMA_PROFILE: LocalProviderProfile = LocalProviderProfile {
- kind: LocalProviderKind::Ollama,
- tool_support: ToolSupport::PromptGuided,
- default_context_window: Some(8_192),
- supports_responses_api: false,
- supports_streaming: true,
- default_quirks: RequestQuirks {
- num_ctx: None,
- suppress_thinking: false,
- omit_temperature: false,
- merge_system_into_user: false,
- },
- default_base_url: "http://127.0.0.1:11434",
- base_url_env: "OLLAMA_HOST",
-};
-
-/// LM Studio profile: conservative defaults, no native tools.
-pub const LM_STUDIO_PROFILE: LocalProviderProfile = LocalProviderProfile {
- kind: LocalProviderKind::LmStudio,
- tool_support: ToolSupport::PromptGuided,
- default_context_window: Some(8_192),
- supports_responses_api: false,
- supports_streaming: true,
- default_quirks: RequestQuirks {
- num_ctx: None,
- suppress_thinking: false,
- omit_temperature: false,
- merge_system_into_user: false,
- },
- default_base_url: "http://127.0.0.1:1234/v1",
- base_url_env: "LM_STUDIO_URL",
-};
-
-/// MLX-compatible server profile (mlx_lm.server, etc.).
-pub const MLX_PROFILE: LocalProviderProfile = LocalProviderProfile {
- kind: LocalProviderKind::Mlx,
- tool_support: ToolSupport::PromptGuided,
- default_context_window: Some(4_096),
- supports_responses_api: false,
- supports_streaming: true,
- default_quirks: RequestQuirks {
- num_ctx: None,
- suppress_thinking: false,
- omit_temperature: false,
- merge_system_into_user: false,
- },
- default_base_url: "http://127.0.0.1:8080/v1",
- base_url_env: "MLX_SERVER_URL",
-};
-
-/// OMLX profile: OpenAI v1-compatible MLX server, default port 8000, key required.
-pub const OMLX_PROFILE: LocalProviderProfile = LocalProviderProfile {
- kind: LocalProviderKind::Omlx,
- tool_support: ToolSupport::PromptGuided,
- default_context_window: Some(4_096),
- supports_responses_api: false,
- supports_streaming: true,
- default_quirks: RequestQuirks {
- num_ctx: None,
- suppress_thinking: false,
- omit_temperature: false,
- merge_system_into_user: false,
- },
- default_base_url: "http://127.0.0.1:8000/v1",
- base_url_env: "OMLX_SERVER_URL",
-};
-
-/// Generic local OpenAI-compatible server (llama.cpp, vLLM, etc.).
-pub const LOCAL_OPENAI_PROFILE: LocalProviderProfile = LocalProviderProfile {
- kind: LocalProviderKind::LocalOpenai,
- tool_support: ToolSupport::PromptGuided,
- default_context_window: None,
- supports_responses_api: false,
- supports_streaming: true,
- default_quirks: RequestQuirks {
- num_ctx: None,
- suppress_thinking: false,
- omit_temperature: false,
- merge_system_into_user: false,
- },
- default_base_url: "http://127.0.0.1:8080/v1",
- base_url_env: "LOCAL_OPENAI_URL",
-};
-
-/// Look up the static profile for a provider kind.
-pub fn profile_for_kind(kind: LocalProviderKind) -> &'static LocalProviderProfile {
- match kind {
- LocalProviderKind::Ollama => &OLLAMA_PROFILE,
- LocalProviderKind::LmStudio => &LM_STUDIO_PROFILE,
- LocalProviderKind::Mlx => &MLX_PROFILE,
- LocalProviderKind::Omlx => &OMLX_PROFILE,
- LocalProviderKind::LocalOpenai => &LOCAL_OPENAI_PROFILE,
- }
-}
-
-/// Resolve the provider kind from a provider string prefix.
-///
-/// Returns `None` for cloud/openhuman/unknown providers.
-pub fn kind_from_provider_string(provider: &str) -> Option<LocalProviderKind> {
- let p = provider.trim().to_ascii_lowercase();
- if p.starts_with("ollama:") || p == "ollama" {
- Some(LocalProviderKind::Ollama)
- } else if p.starts_with("lmstudio:")
- || p.starts_with("lm-studio:")
- || p.starts_with("lm_studio:")
- {
- Some(LocalProviderKind::LmStudio)
- } else if p.starts_with("mlx:") {
- Some(LocalProviderKind::Mlx)
- } else if p.starts_with("omlx:") {
- Some(LocalProviderKind::Omlx)
- } else if p.starts_with("local-openai:") || p.starts_with("local_openai:") {
- Some(LocalProviderKind::LocalOpenai)
- } else {
- None
- }
-}
-
-/// Returns `true` when the provider string resolves to any local provider.
-pub fn is_local_provider_string(provider: &str) -> bool {
- kind_from_provider_string(provider).is_some()
-}
-
-#[cfg(test)]
-#[path = "profile_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/profile_tests.rs b/crates/openhuman-core/src/inference/local/profile_tests.rs
deleted file mode 100644
index d34084d636..0000000000
--- a/crates/openhuman-core/src/inference/local/profile_tests.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-use super::*;
-
-#[test]
-fn kind_from_str_loose_accepts_aliases() {
- assert_eq!(
- LocalProviderKind::from_str_loose("ollama"),
- Some(LocalProviderKind::Ollama)
- );
- assert_eq!(
- LocalProviderKind::from_str_loose("LM-Studio"),
- Some(LocalProviderKind::LmStudio)
- );
- assert_eq!(
- LocalProviderKind::from_str_loose("lm_studio"),
- Some(LocalProviderKind::LmStudio)
- );
- assert_eq!(
- LocalProviderKind::from_str_loose("mlx"),
- Some(LocalProviderKind::Mlx)
- );
- assert_eq!(
- LocalProviderKind::from_str_loose("mlx-server"),
- Some(LocalProviderKind::Mlx)
- );
- assert_eq!(
- LocalProviderKind::from_str_loose("llamacpp"),
- Some(LocalProviderKind::LocalOpenai)
- );
- assert_eq!(
- LocalProviderKind::from_str_loose("vllm"),
- Some(LocalProviderKind::LocalOpenai)
- );
- assert_eq!(LocalProviderKind::from_str_loose("unknown"), None);
-}
-
-#[test]
-fn kind_from_provider_string_parses_prefixes() {
- assert_eq!(
- kind_from_provider_string("ollama:qwen3:14b"),
- Some(LocalProviderKind::Ollama)
- );
- assert_eq!(
- kind_from_provider_string("lmstudio:mistral"),
- Some(LocalProviderKind::LmStudio)
- );
- assert_eq!(
- kind_from_provider_string("mlx:llama-3.1-8b"),
- Some(LocalProviderKind::Mlx)
- );
- assert_eq!(
- kind_from_provider_string("local-openai:qwen2"),
- Some(LocalProviderKind::LocalOpenai)
- );
- assert_eq!(kind_from_provider_string("openai:gpt-4o"), None);
- assert_eq!(kind_from_provider_string("openhuman"), None);
-}
-
-#[test]
-fn is_local_identifies_local_strings() {
- assert!(is_local_provider_string("ollama:phi3"));
- assert!(is_local_provider_string("mlx:model"));
- assert!(!is_local_provider_string("openai:gpt-4"));
- assert!(!is_local_provider_string("openhuman"));
-}
-
-#[test]
-fn profiles_have_correct_defaults() {
- let ollama = profile_for_kind(LocalProviderKind::Ollama);
- assert_eq!(ollama.tool_support, ToolSupport::PromptGuided);
- assert_eq!(ollama.default_context_window, Some(8_192));
- assert!(!ollama.supports_responses_api);
-
- let mlx = profile_for_kind(LocalProviderKind::Mlx);
- assert_eq!(mlx.default_context_window, Some(4_096));
-}
-
-#[test]
-fn ollama_profile_is_conservative_on_tools() {
- let profile = profile_for_kind(LocalProviderKind::Ollama);
- assert_eq!(profile.tool_support, ToolSupport::PromptGuided);
-}
-
-#[test]
-fn omlx_kind_and_profile() {
- assert_eq!(
- LocalProviderKind::from_str_loose("omlx"),
- Some(LocalProviderKind::Omlx)
- );
- assert_eq!(
- LocalProviderKind::from_str_loose("omlx-server"),
- Some(LocalProviderKind::Omlx)
- );
- assert_eq!(LocalProviderKind::Omlx.as_str(), "omlx");
- assert_eq!(LocalProviderKind::Omlx.display_name(), "OMLX");
- assert_eq!(
- profile_for_kind(LocalProviderKind::Omlx).default_base_url,
- "http://127.0.0.1:8000/v1"
- );
- assert_eq!(
- kind_from_provider_string("omlx:my-model"),
- Some(LocalProviderKind::Omlx)
- );
- assert!(is_local_provider_string("omlx:my-model"));
-}
diff --git a/crates/openhuman-core/src/inference/local/provider.rs b/crates/openhuman-core/src/inference/local/provider.rs
deleted file mode 100644
index 333f670e74..0000000000
--- a/crates/openhuman-core/src/inference/local/provider.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-//! Local AI provider selection helpers.
-
-use crate::config::Config;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum LocalAiProvider {
- Ollama,
- LmStudio,
-}
-
-impl LocalAiProvider {
- pub(crate) fn as_str(self) -> &'static str {
- match self {
- Self::Ollama => "ollama",
- Self::LmStudio => "lm_studio",
- }
- }
-
- pub(crate) fn display_name(self) -> &'static str {
- match self {
- Self::Ollama => "Ollama",
- Self::LmStudio => "LM Studio",
- }
- }
-}
-
-pub(crate) fn normalize_provider(value: &str) -> String {
- match value.trim().to_ascii_lowercase().as_str() {
- "lmstudio" | "lm-studio" | "lm_studio" => LocalAiProvider::LmStudio.as_str().to_string(),
- // OMLX is a keyed OpenAI-v1 local runtime handled by the provider factory
- // (`omlx:<model>`), not by `LocalAiProvider`. Preserve the slug so the
- // saved config keeps `provider = "omlx"` instead of collapsing to ollama.
- "omlx" | "omlx-server" => {
- log::trace!(
- "[local-provider] normalized provider '{}' -> omlx (factory-resolved local runtime)",
- value.trim()
- );
- "omlx".to_string()
- }
- _ => LocalAiProvider::Ollama.as_str().to_string(),
- }
-}
-
-pub(crate) fn provider_from_config(config: &Config) -> LocalAiProvider {
- match normalize_provider(&config.local_ai.provider).as_str() {
- "lm_studio" => LocalAiProvider::LmStudio,
- _ => LocalAiProvider::Ollama,
- }
-}
-
-/// How a local runtime exposes its installed-model catalog.
-///
-/// Ollama serves a native `GET /api/tags` listing; every OpenAI-compatible
-/// runtime (LM Studio, OMLX, `local-openai`, and any custom BYOK endpoint that
-/// speaks the OpenAI `/v1` surface) serves `GET /v1/models`. Sending an Ollama
-/// probe to an OpenAI-compatible server produces `GET /v1/api/tags`, which
-/// LM Studio logs as `Unexpected endpoint or method` and answers with an empty
-/// catalog — so model discovery silently fails and the model never appears as
-/// selectable (GH #5053).
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum ModelDiscoveryApi {
- /// Ollama-native `/api/tags`.
- OllamaTags,
- /// OpenAI-compatible `/v1/models`.
- OpenAiModels,
-}
-
-/// True when `base_url`'s path is the OpenAI-compatible `/v1` root — the
-/// canonical marker of an OpenAI-style server (LM Studio, OMLX, LiteLLM, …).
-///
-/// A genuine Ollama base URL is host-rooted (`http://localhost:11434`) with no
-/// `/v1` path segment, so this cleanly separates the two API shapes by
-/// **endpoint type**, not by "is it localhost" (which would misidentify a
-/// localhost LM Studio server as Ollama — the #5053 conflation).
-pub(crate) fn endpoint_is_openai_v1(base_url: &str) -> bool {
- if let Ok(url) = reqwest::Url::parse(base_url.trim()) {
- let path = url.path().trim_end_matches('/').to_ascii_lowercase();
- return path.ends_with("/v1");
- }
- // Fall back to a lexical check when the URL doesn't parse cleanly.
- base_url
- .trim()
- .trim_end_matches('/')
- .to_ascii_lowercase()
- .ends_with("/v1")
-}
-
-/// Select the model-discovery API for a local runtime from its provider slug
-/// and base URL — by provider **type**, never by "is it localhost".
-///
-/// Genuine Ollama (`provider = "ollama"` on a host-rooted base) uses
-/// `/api/tags`. Every OpenAI-compatible runtime uses `/v1/models`: an explicit
-/// `lm_studio` / `omlx` slug, OR any endpoint whose path is the OpenAI `/v1`
-/// root. The `/v1` endpoint clause is what rescues a custom BYOK localhost
-/// endpoint (e.g. LM Studio on `http://localhost:1234/v1`) whose provider tag
-/// still defaults to `ollama`: the endpoint type wins over the fallback slug
-/// (GH #5053).
-pub(crate) fn model_discovery_api(provider: &str, base_url: &str) -> ModelDiscoveryApi {
- if endpoint_is_openai_v1(base_url) {
- return ModelDiscoveryApi::OpenAiModels;
- }
- match normalize_provider(provider).as_str() {
- "ollama" => ModelDiscoveryApi::OllamaTags,
- // lm_studio, omlx, and any other OpenAI-compatible local runtime.
- _ => ModelDiscoveryApi::OpenAiModels,
- }
-}
-
-#[cfg(test)]
-#[path = "provider_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/provider_tests.rs b/crates/openhuman-core/src/inference/local/provider_tests.rs
deleted file mode 100644
index 627605dce4..0000000000
--- a/crates/openhuman-core/src/inference/local/provider_tests.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-use super::*;
-
-#[test]
-fn normalize_provider_accepts_lm_studio_aliases() {
- assert_eq!(normalize_provider("lmstudio"), "lm_studio");
- assert_eq!(normalize_provider("lm-studio"), "lm_studio");
- assert_eq!(normalize_provider("LM_Studio"), "lm_studio");
-}
-
-#[test]
-fn normalize_provider_falls_back_to_ollama() {
- assert_eq!(normalize_provider(""), "ollama");
- assert_eq!(normalize_provider("unknown"), "ollama");
-}
-
-#[test]
-fn normalize_provider_keeps_omlx() {
- assert_eq!(normalize_provider("omlx"), "omlx");
- assert_eq!(normalize_provider("omlx-server"), "omlx");
- assert_eq!(normalize_provider("OMLX"), "omlx");
-}
-
-#[test]
-fn endpoint_is_openai_v1_detects_v1_root() {
- assert!(endpoint_is_openai_v1("http://localhost:1234/v1"));
- assert!(endpoint_is_openai_v1("http://localhost:1234/v1/"));
- assert!(endpoint_is_openai_v1("https://box.local:1234/openai/v1"));
- // Genuine Ollama base is host-rooted with no /v1 path.
- assert!(!endpoint_is_openai_v1("http://localhost:11434"));
- assert!(!endpoint_is_openai_v1("http://localhost:11434/"));
- // A `/v1` embedded mid-path is not the OpenAI root.
- assert!(!endpoint_is_openai_v1("http://localhost:11434/v1/models"));
-}
-
-#[test]
-fn model_discovery_api_uses_tags_for_genuine_ollama() {
- // Ollama slug on its host-rooted native base -> /api/tags.
- assert_eq!(
- model_discovery_api("ollama", "http://localhost:11434"),
- ModelDiscoveryApi::OllamaTags
- );
- assert_eq!(
- model_discovery_api("", "http://localhost:11434"),
- ModelDiscoveryApi::OllamaTags
- );
-}
-
-#[test]
-fn model_discovery_api_uses_v1_models_for_openai_compatible() {
- // Explicit LM Studio / OMLX slugs are OpenAI-compatible.
- assert_eq!(
- model_discovery_api("lm_studio", "http://localhost:1234/v1"),
- ModelDiscoveryApi::OpenAiModels
- );
- assert_eq!(
- model_discovery_api("omlx", "http://localhost:8080/v1"),
- ModelDiscoveryApi::OpenAiModels
- );
- // The #5053 case: a custom BYOK OpenAI-compatible endpoint on localhost
- // whose provider tag still defaults to `ollama` must NOT be probed with
- // /api/tags — the `/v1` endpoint type wins.
- assert_eq!(
- model_discovery_api("ollama", "http://localhost:1234/v1"),
- ModelDiscoveryApi::OpenAiModels
- );
- assert_eq!(
- model_discovery_api("custom-byok", "http://localhost:1234/v1"),
- ModelDiscoveryApi::OpenAiModels
- );
-}
diff --git a/crates/openhuman-core/src/inference/local/service/spawn_marker.rs b/crates/openhuman-core/src/inference/local/service/spawn_marker.rs
deleted file mode 100644
index c48fc5b5d7..0000000000
--- a/crates/openhuman-core/src/inference/local/service/spawn_marker.rs
+++ /dev/null
@@ -1,132 +0,0 @@
-//! Spawn marker for openhuman-owned `ollama serve` processes.
-//!
-//! Every time `start_and_wait_for_server` actually spawns an Ollama daemon
-//! (i.e. didn't adopt a healthy external one), we write a small JSON file
-//! recording the PID, the binary we launched, and the openhuman process
-//! that owned it. On graceful shutdown the marker is cleared. If openhuman
-//! crashes before its shutdown hook fires, the marker survives — and on
-//! next launch we can reclaim the orphaned daemon (kill + respawn fresh)
-//! instead of either leaking it forever or running blanket `taskkill /IM
-//! ollama.exe` and hitting daemons we don't own.
-//!
-//! Liveness is checked via `sysinfo` (already a workspace dep) to match
-//! the cross-platform pattern in `install::is_ollama_installer_running`.
-
-use std::path::Path;
-
-use serde::{Deserialize, Serialize};
-
-use crate::config::Config;
-use crate::inference::paths::ollama_spawn_marker_path;
-
-/// On-disk record of an openhuman-spawned `ollama serve` process.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub(crate) struct OllamaSpawnMarker {
- pub pid: u32,
- pub started_at_unix: u64,
- pub binary_path: String,
- pub openhuman_pid: u32,
-}
-
-impl OllamaSpawnMarker {
- pub(crate) fn new(pid: u32, binary_path: &Path) -> Self {
- let started_at_unix = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
- Self {
- pid,
- started_at_unix,
- binary_path: binary_path.display().to_string(),
- openhuman_pid: std::process::id(),
- }
- }
-}
-
-// ---- Path-keyed helpers (testable without touching ~/.openhuman/) -------
-
-/// Write `marker` to `path`, replacing any existing file. Creates the
-/// parent directory if needed. Uses a tmp-and-rename so a crash mid-write
-/// can't leave truncated JSON.
-pub(crate) fn write_marker_at(path: &Path, marker: &OllamaSpawnMarker) -> Result<(), String> {
- if let Some(parent) = path.parent() {
- std::fs::create_dir_all(parent)
- .map_err(|e| format!("create marker dir {}: {e}", parent.display()))?;
- }
- let json =
- serde_json::to_string_pretty(marker).map_err(|e| format!("serialize spawn marker: {e}"))?;
-
- let tmp = path.with_extension("spawn.tmp");
- std::fs::write(&tmp, json).map_err(|e| format!("write marker tmp {}: {e}", tmp.display()))?;
- std::fs::rename(&tmp, path)
- .map_err(|e| format!("rename marker {} -> {}: {e}", tmp.display(), path.display()))?;
- Ok(())
-}
-
-pub(crate) fn read_marker_at(path: &Path) -> Option<OllamaSpawnMarker> {
- let content = std::fs::read_to_string(path).ok()?;
- match serde_json::from_str::<OllamaSpawnMarker>(&content) {
- Ok(m) => Some(m),
- Err(e) => {
- log::warn!(
- "[local_ai] ollama spawn marker at {} is unparseable, ignoring: {e}",
- path.display()
- );
- None
- }
- }
-}
-
-pub(crate) fn clear_marker_at(path: &Path) {
- match std::fs::remove_file(path) {
- Ok(()) => log::debug!(
- "[local_ai] cleared ollama spawn marker at {}",
- path.display()
- ),
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
- Err(e) => log::warn!(
- "[local_ai] failed to clear ollama spawn marker {}: {e}",
- path.display()
- ),
- }
-}
-
-// ---- Config-keyed conveniences (used by production code) ---------------
-
-pub(crate) fn write_marker(config: &Config, marker: &OllamaSpawnMarker) -> Result<(), String> {
- let path = ollama_spawn_marker_path(config);
- write_marker_at(&path, marker)?;
- log::debug!(
- "[local_ai] wrote ollama spawn marker pid={} bin={} at {}",
- marker.pid,
- marker.binary_path,
- path.display()
- );
- Ok(())
-}
-
-pub(crate) fn read_marker(config: &Config) -> Option<OllamaSpawnMarker> {
- read_marker_at(&ollama_spawn_marker_path(config))
-}
-
-pub(crate) fn clear_marker(config: &Config) {
- clear_marker_at(&ollama_spawn_marker_path(config));
-}
-
-/// True iff `pid` corresponds to a live process on this machine.
-///
-/// Uses `sysinfo` rather than libc/Win32 directly to stay consistent with
-/// the rest of the local_ai module (see `install::is_ollama_installer_running`).
-pub(crate) fn pid_is_alive(pid: u32) -> bool {
- use sysinfo::{Pid, ProcessesToUpdate, System};
- let mut sys = System::new();
- let target = Pid::from_u32(pid);
- // Refresh just the one PID we care about; cheap on Windows where a full
- // refresh can take ~tens of ms on a loaded machine.
- sys.refresh_processes(ProcessesToUpdate::Some(&[target]), true);
- sys.process(target).is_some()
-}
-
-#[cfg(test)]
-#[path = "spawn_marker_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/local/service/spawn_marker_tests.rs b/crates/openhuman-core/src/inference/local/service/spawn_marker_tests.rs
deleted file mode 100644
index 25dcf20d38..0000000000
--- a/crates/openhuman-core/src/inference/local/service/spawn_marker_tests.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-use super::*;
-use tempfile::TempDir;
-
-fn tmp_marker_path() -> (TempDir, std::path::PathBuf) {
- let tmp = TempDir::new().unwrap();
- let path = tmp.path().join("local-ai").join("ollama.spawn");
- (tmp, path)
-}
-
-#[test]
-fn marker_round_trips_through_disk() {
- let (_tmp, path) = tmp_marker_path();
- let m = OllamaSpawnMarker {
- pid: 4242,
- started_at_unix: 1_700_000_000,
- binary_path: "C:\\fake\\ollama.exe".to_string(),
- openhuman_pid: 9001,
- };
-
- write_marker_at(&path, &m).expect("write marker");
- let loaded = read_marker_at(&path).expect("read marker");
- assert_eq!(loaded, m);
-
- clear_marker_at(&path);
- assert!(
- read_marker_at(&path).is_none(),
- "marker must be gone after clear"
- );
-}
-
-#[test]
-fn read_marker_returns_none_when_file_missing() {
- let (_tmp, path) = tmp_marker_path();
- assert!(read_marker_at(&path).is_none());
-}
-
-#[test]
-fn read_marker_returns_none_on_corrupt_json() {
- let (_tmp, path) = tmp_marker_path();
- std::fs::create_dir_all(path.parent().unwrap()).unwrap();
- std::fs::write(&path, b"{ not valid json").unwrap();
-
- assert!(
- read_marker_at(&path).is_none(),
- "corrupt marker must be treated as absent"
- );
-}
-
-#[test]
-fn clear_marker_is_idempotent() {
- let (_tmp, path) = tmp_marker_path();
- clear_marker_at(&path);
- clear_marker_at(&path);
-}
-
-#[test]
-fn write_marker_creates_missing_parent_dir() {
- let (_tmp, path) = tmp_marker_path();
- // path.parent() does NOT exist yet — write should create it.
- assert!(!path.parent().unwrap().exists());
- let m = OllamaSpawnMarker::new(1234, std::path::Path::new("ollama"));
- write_marker_at(&path, &m).expect("write");
- assert!(path.exists());
-}
-
-#[test]
-fn new_marker_captures_current_process_id() {
- let m = OllamaSpawnMarker::new(4242, std::path::Path::new("ollama"));
- assert_eq!(m.openhuman_pid, std::process::id());
- assert_eq!(m.pid, 4242);
- assert_eq!(m.binary_path, "ollama");
-}
-
-#[test]
-fn pid_is_alive_recognises_self() {
- let me = std::process::id();
- assert!(
- pid_is_alive(me),
- "current process PID {me} should be reported alive"
- );
-}
-
-#[test]
-fn pid_is_alive_rejects_dead_pid() {
- // Spawn a short child, wait for it to exit, then check that its
- // recycled PID is no longer reported alive. Hardcoded sentinel PIDs
- // (0, u32::MAX) are unreliable cross-platform — on Windows PID 0 is
- // "System Idle Process" and registers as alive in sysinfo.
- let child = if cfg!(windows) {
- std::process::Command::new("cmd")
- .args(["/C", "exit 0"])
- .spawn()
- .expect("spawn cmd /C exit")
- } else {
- std::process::Command::new("true")
- .spawn()
- .expect("spawn /usr/bin/true")
- };
- let pid = child.id();
- let mut child = child;
- let _ = child.wait();
-
- // Give the OS a moment to fully reap so sysinfo doesn't catch a
- // lingering zombie entry.
- std::thread::sleep(std::time::Duration::from_millis(200));
-
- assert!(
- !pid_is_alive(pid),
- "exited child pid {pid} should not be reported alive"
- );
-}
diff --git a/crates/openhuman-core/src/inference/parse.rs b/crates/openhuman-core/src/inference/parse.rs
deleted file mode 100644
index d4cc43ffe4..0000000000
--- a/crates/openhuman-core/src/inference/parse.rs
+++ /dev/null
@@ -1,148 +0,0 @@
-//! Parse model output into inline completions.
-
-fn normalize_inline_text(value: &str) -> String {
- value
- .replace(['\u{200B}', '\u{200C}', '\u{200D}', '\u{FEFF}'], "")
- .replace(['\u{00A0}', '\u{2028}', '\u{2029}', '\t', '→'], " ")
-}
-
-fn trim_generation_prefixes(mut value: &str) -> &str {
- value = value.trim_start();
-
- // Common wrappers from LLM output formatting.
- for prefix in ["suffix:", "completion:", "result:", "output:"] {
- if value
- .get(..prefix.len())
- .is_some_and(|s| s.eq_ignore_ascii_case(prefix))
- {
- value = value.get(prefix.len()..).unwrap_or(value).trim_start();
- break;
- }
- }
-
- value
-}
-
-fn strip_inline_wrapper_prefix(value: &str) -> &str {
- fn strip_known_markers(input: &str) -> Option<&str> {
- for marker in ["- ", "* ", "> ", "→ "] {
- if let Some(rest) = input.strip_prefix(marker) {
- return Some(rest.trim_start());
- }
- }
- None
- }
-
- fn strip_numbered_token(input: &str) -> Option<&str> {
- let bytes = input.as_bytes();
- let mut i = 0usize;
- while i < bytes.len() && bytes[i].is_ascii_digit() {
- i += 1;
- }
- if i == 0 {
- return None;
- }
- let punctuation = bytes.get(i).copied();
- let following_space = bytes.get(i + 1).copied();
- if matches!(punctuation, Some(b'.' | b')')) && following_space == Some(b' ') {
- return input.get(i + 2..).map(str::trim_start);
- }
- None
- }
-
- let trimmed = value.trim_start();
- if let Some(stripped) = strip_known_markers(trimmed) {
- return stripped;
- }
- if let Some(stripped) = strip_numbered_token(trimmed) {
- return stripped;
- }
-
- // Quoted marker variants, e.g. "\"- item" or "\"1. item".
- if let Some(after_quote) = trimmed.strip_prefix('"') {
- if let Some(stripped) = strip_known_markers(after_quote) {
- return stripped;
- }
- if let Some(stripped) = strip_numbered_token(after_quote) {
- return stripped;
- }
- }
-
- trimmed
-}
-
-pub(crate) fn sanitize_inline_completion(raw: &str, context: &str) -> String {
- let raw_norm = normalize_inline_text(raw);
- let line = raw_norm
- .lines()
- .next()
- .unwrap_or_default()
- .trim()
- .to_string();
- if line.is_empty() {
- return String::new();
- }
-
- let unquoted = line.trim_matches('"');
- let mut cleaned = strip_inline_wrapper_prefix(unquoted).trim().to_string();
- cleaned = trim_generation_prefixes(&cleaned).to_string();
-
- cleaned = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
-
- if cleaned.eq_ignore_ascii_case("none") || cleaned.eq_ignore_ascii_case("n/a") {
- return String::new();
- }
-
- let context_norm = normalize_inline_text(context)
- .split_whitespace()
- .collect::<Vec<_>>()
- .join(" ");
-
- // Avoid overly aggressive overlap stripping for very short contexts.
- // Example: context="hello", model="hello world" should usually stay as
- // "hello world" instead of collapsing to "world".
- const MIN_CONTEXT_CHARS_FOR_DEDUP: usize = 6;
- let should_dedup_against_context = context_norm.chars().count() >= MIN_CONTEXT_CHARS_FOR_DEDUP;
-
- if !context_norm.is_empty() && should_dedup_against_context {
- // If model returned full text, keep suffix only.
- if cleaned.starts_with(&context_norm) {
- cleaned = cleaned[context_norm.len()..].trim_start().to_string();
- } else {
- // Remove overlap between end of context and start of prediction.
- let cleaned_chars: Vec<char> = cleaned.chars().collect();
- let max_overlap = context_norm
- .chars()
- .count()
- .min(cleaned_chars.len())
- .min(160);
- for overlap in (1..=max_overlap).rev() {
- let overlap_prefix: String = cleaned_chars.iter().take(overlap).collect();
- if context_norm.ends_with(&overlap_prefix) {
- cleaned = cleaned_chars
- .iter()
- .skip(overlap)
- .collect::<String>()
- .trim_start()
- .to_string();
- break;
- }
- }
- }
-
- // If "completion" is already part of the context tail, drop it.
- if !cleaned.is_empty() && context_norm.ends_with(&cleaned) {
- return String::new();
- }
- }
-
- if cleaned.chars().count() > 96 {
- cleaned = cleaned.chars().take(96).collect();
- }
-
- cleaned
-}
-
-#[cfg(test)]
-#[path = "parse_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/parse_tests.rs b/crates/openhuman-core/src/inference/parse_tests.rs
deleted file mode 100644
index 46923c7ef3..0000000000
--- a/crates/openhuman-core/src/inference/parse_tests.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-use super::*;
-
-#[test]
-fn sanitize_inline_completion_handles_placeholders_and_clamps_length() {
- assert_eq!(sanitize_inline_completion("none", "hello"), "");
- assert_eq!(sanitize_inline_completion("n/a", "hello"), "");
- assert_eq!(
- sanitize_inline_completion("\"- hello world\"", "hello"),
- "hello world"
- );
-
- let long = "a".repeat(256);
- let out = sanitize_inline_completion(&long, "hello");
- assert_eq!(out.chars().count(), 96);
-}
-
-#[test]
-fn sanitize_inline_completion_strips_arrow_and_extra_whitespace() {
- assert_eq!(
- sanitize_inline_completion("\t→ keep it concise\t", "hello"),
- "keep it concise"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_strips_quoted_generation_label() {
- assert_eq!(
- sanitize_inline_completion("\"suffix: hello\"", "context example"),
- "hello"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_returns_suffix_only_when_model_repeats_context() {
- let ctx = "Yesterday, I went";
- let raw = "Yesterday, I went to the garden";
- assert_eq!(sanitize_inline_completion(raw, ctx), "to the garden");
-}
-
-#[test]
-fn sanitize_inline_completion_drops_tabby_unicode_noise() {
- let ctx = "Yester";
- let raw = "Yester\tday, \u{2028}I went\t to garden";
- assert_eq!(
- sanitize_inline_completion(raw, ctx),
- "day, I went to garden"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_preserves_iso_date_prefix() {
- assert_eq!(
- sanitize_inline_completion("2026-04-07", "context example"),
- "2026-04-07"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_preserves_time_prefix() {
- assert_eq!(
- sanitize_inline_completion("3pm meeting", "context example"),
- "3pm meeting"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_preserves_double_dash_help_token() {
- assert_eq!(
- sanitize_inline_completion("--help", "context example"),
- "--help"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_preserves_task_marker_without_space() {
- assert_eq!(
- sanitize_inline_completion("-[ ] task", "context example"),
- "-[ ] task"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_strips_numbered_list_prefix_dot() {
- assert_eq!(
- sanitize_inline_completion("1. item", "context example"),
- "item"
- );
-}
-
-#[test]
-fn sanitize_inline_completion_strips_numbered_list_prefix_paren() {
- assert_eq!(
- sanitize_inline_completion("2) item", "context example"),
- "item"
- );
-}
diff --git a/crates/openhuman-core/src/inference/provider/billing_error.rs b/crates/openhuman-core/src/inference/provider/billing_error.rs
deleted file mode 100644
index 85d9ec561c..0000000000
--- a/crates/openhuman-core/src/inference/provider/billing_error.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-/// Returns true if a 400 response body indicates the user is out of
-/// budget / has insufficient balance / over their plan. These are
-/// deterministic user-state errors — already surfaced in the UI as a
-/// toast — and must not flow to Sentry as errors.
-///
-/// Match is case-insensitive against any of the known phrases. Keep the
-/// list deliberately tight: false positives demote real backend bugs.
-pub fn is_budget_exhausted_message(body: &str) -> bool {
- const PHRASES: &[&str] = &[
- "insufficient budget",
- "budget exceeded",
- "add credits",
- "insufficient balance",
- // abacus's out-of-credits 400 wording (TAURI-RUST-D6X): the managed
- // route-llm account is exhausted. The full body is
- // `"You have no remaining credits to use the LLM apis."`. Anchored on
- // the "no remaining credits" fragment (not the broader "remaining
- // credits", which a positive "you have N remaining credits" balance
- // message could trip) to keep the list tight per the rule above.
- "no remaining credits",
- // Anthropic's BYO-key out-of-credits 400 wording (TAURI-RUST-4MM):
- // the full body is `"Your credit balance is too low to access the
- // Anthropic API. Please go to Plans & Billing to upgrade or purchase
- // credits."` (direct provider, "anthropic API error", not the managed
- // "OpenHuman API error"). Anchored on the "credit balance is too low"
- // fragment — the "too low" qualifier keeps a positive-balance message
- // (e.g. "your credit balance is $50") from tripping, per the tight-list
- // rule above. OpenHuman has no lever over a third-party Anthropic
- // account's balance; budget toast already surfaced in the UI.
- "credit balance is too low",
- ];
-
- let lower = body.to_ascii_lowercase();
- PHRASES.iter().any(|phrase| lower.contains(phrase))
-}
-
-#[cfg(test)]
-#[path = "billing_error_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/billing_error_tests.rs b/crates/openhuman-core/src/inference/provider/billing_error_tests.rs
deleted file mode 100644
index d78c53f867..0000000000
--- a/crates/openhuman-core/src/inference/provider/billing_error_tests.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-use super::*;
-
-#[test]
-fn detects_known_budget_exhaustion_phrases() {
- for body in [
- "Insufficient budget",
- "Budget exceeded",
- "Insufficient balance",
- "Add credits to continue",
- ] {
- assert!(
- is_budget_exhausted_message(body),
- "{body:?} must be classified as budget-exhausted user-state"
- );
- }
-}
-
-#[test]
-fn detection_is_case_insensitive() {
- assert!(is_budget_exhausted_message("INSUFFICIENT BUDGET"));
- assert!(is_budget_exhausted_message("budget EXCEEDED — ADD credits"));
- assert!(is_budget_exhausted_message("Insufficient BALANCE"));
-}
-
-/// Verbatim abacus out-of-credits 400 body (Sentry TAURI-RUST-D6X). The
-/// classifier feeds the native_chat demotion, the `expected_error_kind`
-/// re-report demotion, the `is_budget_event` before_send net, AND the cron
-/// scheduler's terminal billing-halt (`is_budget_exhausted_failure`), so
-/// pinning the exact wire body makes an abacus phrasing drift fail CI
-/// rather than silently re-flood Sentry / re-fire the retry loop.
-#[test]
-fn detects_abacus_no_remaining_credits_400_body() {
- let body = "abacus API error (400 Bad Request): \
- {\"success\": false, \"error\": \"You have no remaining credits to use the LLM apis.\"}";
- assert!(
- is_budget_exhausted_message(body),
- "abacus no-remaining-credits 400 must classify as budget-exhausted user-state"
- );
- // Case-insensitive on the same phrase.
- assert!(is_budget_exhausted_message(
- "You have NO REMAINING CREDITS left"
- ));
-}
-
-/// Verbatim Anthropic BYO out-of-credits 400 body (Sentry TAURI-RUST-4MM).
-/// Direct provider — "anthropic API error", not the managed "OpenHuman API
-/// error". The classifier feeds the emit-site `classify_expected_error`
-/// demotion, the agent turn's billing gate, the `web_errors` net, the
-/// `is_budget_event` before_send filter, AND the cron billing-halt, so
-/// pinning the exact wire body makes an Anthropic phrasing drift fail CI
-/// rather than silently re-flood Sentry (3793 events leaked before this).
-#[test]
-fn detects_anthropic_credit_balance_too_low_400_body() {
- let body = "anthropic API error (400 Bad Request): \
- {\"error\":{\"code\":\"invalid_request_error\",\"message\":\"Your credit \
- balance is too low to access the Anthropic API. Please go to Plans & \
- Billing to upgrade or purchase credits.\",\"type\":\"invalid_request_error\"}}";
- assert!(
- is_budget_exhausted_message(body),
- "anthropic credit-balance-too-low 400 must classify as budget-exhausted user-state"
- );
- // Case-insensitive on the same phrase.
- assert!(is_budget_exhausted_message(
- "Your CREDIT BALANCE IS TOO LOW to access the Anthropic API"
- ));
-}
-
-#[test]
-fn ignores_non_budget_messages() {
- for body in [
- "Bad request: missing field",
- "Invalid request: model not found",
- "HTTP 400 Bad Request",
- // A positive-balance message must NOT be demoted: we anchor on the
- // "no remaining credits" fragment precisely so this doesn't trip.
- "You have 100 remaining credits this month",
- // Likewise the Anthropic matcher anchors on "too low", so a healthy
- // balance readout stays visible.
- "Your credit balance is $50.00",
- "",
- ] {
- assert!(
- !is_budget_exhausted_message(body),
- "{body:?} must not be classified as budget-exhausted"
- );
- }
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/mod.rs b/crates/openhuman-core/src/inference/provider/claude_agent_sdk/mod.rs
deleted file mode 100644
index 76c73e070f..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/mod.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-//! Provider that routes inference through the `claude -p` CLI subprocess.
-
-mod protocol;
-pub mod subprocess;
-
-pub use subprocess::ClaudeAgentSdkProvider;
diff --git a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/protocol.rs b/crates/openhuman-core/src/inference/provider/claude_agent_sdk/protocol.rs
deleted file mode 100644
index 3b48aae91a..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/protocol.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-//! Wire types for the `claude --output-format stream-json` NDJSON protocol.
-
-use serde::Deserialize;
-
-#[derive(Debug, Deserialize)]
-#[serde(tag = "type", rename_all = "snake_case")]
-pub enum SdkMessage {
- Text {
- text: String,
- },
- Result {
- result: Option<String>,
- #[serde(rename = "is_error")]
- is_error: bool,
- #[serde(default)]
- total_cost_usd: Option<f64>,
- },
- Error {
- error: SdkError,
- },
- #[serde(other)]
- Unknown,
-}
-
-#[derive(Debug, Deserialize)]
-pub struct SdkError {
- pub message: String,
-}
diff --git a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/subprocess.rs b/crates/openhuman-core/src/inference/provider/claude_agent_sdk/subprocess.rs
deleted file mode 100644
index 0abb3ab39e..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/subprocess.rs
+++ /dev/null
@@ -1,320 +0,0 @@
-//! Subprocess lifecycle for the Claude Agent SDK provider.
-
-use anyhow::Context;
-use async_trait::async_trait;
-use tinyagents_harness::tool::{coalesce_prompt_tool_results, with_prompt_tool_instructions};
-use tinyinference::message::Message;
-use tinyinference::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
-use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-use tokio::process::Command;
-use tokio::time::{timeout, Duration};
-
-use super::protocol::SdkMessage;
-use crate::config::schema::claude_agent_sdk::ClaudeAgentSdkConfig;
-
-pub struct ClaudeAgentSdkProvider {
- pub(super) config: ClaudeAgentSdkConfig,
- profile: ModelProfile,
-}
-
-struct ClaudeInvocation {
- args: Vec<String>,
- stdin: String,
-}
-
-fn build_invocation(
- system_prompt: Option<&str>,
- message: &str,
- model: &str,
- max_budget_usd: Option<f64>,
-) -> ClaudeInvocation {
- let stdin = match system_prompt {
- Some(system) if !system.trim().is_empty() => {
- format!("[SYSTEM]\n{system}\n[/SYSTEM]\n\n{message}")
- }
- _ => message.to_string(),
- };
- let mut args = vec![
- "-p".to_string(),
- "--model".to_string(),
- model.to_string(),
- "--output-format".to_string(),
- "stream-json".to_string(),
- "--no-color".to_string(),
- ];
- if let Some(budget) = max_budget_usd {
- args.push("--max-turns".to_string());
- args.push("10".to_string());
- args.push("--budget".to_string());
- args.push(format!("{budget:.4}"));
- }
- ClaudeInvocation { args, stdin }
-}
-
-fn spawn_error(binary: &str, source: std::io::Error) -> anyhow::Error {
- let message = format!("failed to spawn claude binary '{binary}': {source}");
- anyhow::Error::new(source).context(message)
-}
-
-impl ClaudeAgentSdkProvider {
- pub fn new(config: ClaudeAgentSdkConfig) -> Self {
- let model = config.default_model.clone();
- Self::for_model(config, model)
- }
-
- pub fn for_model(config: ClaudeAgentSdkConfig, model: impl Into<String>) -> Self {
- Self {
- config,
- profile: ModelProfile {
- provider: Some("claude-agent-sdk".to_string()),
- model: Some(model.into()),
- ..Default::default()
- },
- }
- }
-
- async fn invoke_cli(
- &self,
- system_prompt: Option<&str>,
- message: &str,
- model: &str,
- ) -> anyhow::Result<String> {
- let model = if model.is_empty() {
- &self.config.default_model
- } else {
- model
- };
-
- // `claude -p` reads stdin in non-interactive mode. Keep the full
- // request out of argv so large harness prompts can spawn on Windows.
- let invocation =
- build_invocation(system_prompt, message, model, self.config.max_budget_usd);
-
- let mut cmd = Command::new(&self.config.binary);
- cmd.args(&invocation.args)
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped())
- .stdin(std::process::Stdio::piped())
- .kill_on_drop(true);
-
- tracing::debug!(
- "[claude_agent_sdk] spawning claude binary={} model={} message_len={}",
- self.config.binary,
- model,
- invocation.stdin.len()
- );
-
- let mut child = cmd.spawn().map_err(|source| {
- tracing::warn!(
- error = %source,
- binary = %self.config.binary,
- "[claude_agent_sdk] failed to spawn claude binary"
- );
- spawn_error(&self.config.binary, source)
- })?;
-
- let mut stdin = child
- .stdin
- .take()
- .context("claude subprocess has no stdin")?;
- stdin
- .write_all(invocation.stdin.as_bytes())
- .await
- .context("failed to write claude request to stdin")?;
- stdin
- .shutdown()
- .await
- .context("failed to close claude subprocess stdin")?;
- drop(stdin);
-
- let stdout = child
- .stdout
- .take()
- .context("claude subprocess has no stdout")?;
- let stderr = child
- .stderr
- .take()
- .context("claude subprocess has no stderr")?;
-
- // Drain stderr concurrently to prevent pipe-buffer stalls and capture failure context.
- let stderr_task = tokio::spawn(async move {
- let mut err_lines = BufReader::new(stderr).lines();
- let mut buf = String::new();
- while let Ok(Some(line)) = err_lines.next_line().await {
- if !buf.is_empty() {
- buf.push('\n');
- }
- buf.push_str(&line);
- }
- buf
- });
-
- let mut lines = BufReader::new(stdout).lines();
- let mut text_parts: Vec<String> = Vec::new();
- let mut result_text: Option<String> = None;
- let mut error_message: Option<String> = None;
-
- let read_result = timeout(Duration::from_secs(120), async {
- while let Some(line) = lines.next_line().await? {
- let line = line.trim().to_string();
- if line.is_empty() {
- continue;
- }
- tracing::trace!(
- "[claude_agent_sdk] ndjson line received line_len={}",
- line.len()
- );
- match serde_json::from_str::<SdkMessage>(&line) {
- Ok(SdkMessage::Text { text }) => {
- text_parts.push(text);
- }
- Ok(SdkMessage::Result {
- result,
- is_error,
- total_cost_usd,
- }) => {
- if let Some(cost) = total_cost_usd {
- tracing::debug!(
- "[claude_agent_sdk] request completed total_cost_usd={:.6}",
- cost
- );
- }
- if is_error {
- error_message = Some(result.unwrap_or_else(|| {
- "claude subprocess returned an error".to_string()
- }));
- } else {
- result_text = result;
- }
- }
- Ok(SdkMessage::Error { error }) => {
- error_message = Some(error.message);
- }
- Ok(SdkMessage::Unknown) => {
- tracing::trace!("[claude_agent_sdk] unknown ndjson message type, skipping");
- }
- Err(e) => {
- tracing::warn!(
- error = %e,
- line_len = line.len(),
- "[claude_agent_sdk] failed to parse ndjson line"
- );
- }
- }
- }
- anyhow::Ok(())
- })
- .await;
-
- match read_result {
- Ok(inner) => inner?,
- Err(_) => {
- let _ = child.kill().await;
- anyhow::bail!("[claude_agent_sdk] subprocess timed out while reading output");
- }
- }
-
- let status = timeout(Duration::from_secs(30), child.wait())
- .await
- .map_err(|_| {
- anyhow::anyhow!("[claude_agent_sdk] subprocess timed out while waiting for exit")
- })??;
- let stderr_output = stderr_task.await.unwrap_or_default();
- tracing::debug!("[claude_agent_sdk] subprocess exited status={}", status);
-
- if let Some(err) = error_message {
- anyhow::bail!("[claude_agent_sdk] error from claude CLI: {err}");
- }
-
- // Use the final result message if present; otherwise join streaming text parts.
- let output = result_text
- .filter(|s| !s.is_empty())
- .unwrap_or_else(|| text_parts.join(""));
-
- if !status.success() && output.is_empty() {
- anyhow::bail!(
- "[claude_agent_sdk] claude subprocess exited with non-zero status {} and no output; stderr={}",
- status,
- stderr_output
- );
- }
-
- tracing::debug!(
- "[claude_agent_sdk] response collected output_len={}",
- output.len()
- );
-
- Ok(output)
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for ClaudeAgentSdkProvider {
- fn profile(&self) -> Option<&ModelProfile> {
- Some(&self.profile)
- }
-
- /// Identity for harness response-cache scoping: the SDK binary and the
- /// selected model. No credential is involved on this path.
- fn cache_identity(&self) -> Option<String> {
- Some(format!(
- "claude_agent_sdk:{}:{}",
- self.config.binary,
- self.profile
- .model
- .as_deref()
- .unwrap_or(&self.config.default_model)
- ))
- }
-
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference::Result<ModelResponse> {
- let messages = coalesce_prompt_tool_results(&request.messages);
- let messages = with_prompt_tool_instructions(&messages, &request.tools);
- let system = coalesce_system_prompt(&messages);
- let last_user = messages
- .iter()
- .rev()
- .find_map(|message| match message {
- Message::User(_) => Some(message.text()),
- _ => None,
- })
- .unwrap_or_default();
- let model = request
- .model
- .as_deref()
- .or(self.profile.model.as_deref())
- .unwrap_or(&self.config.default_model);
- let output = self
- .invoke_cli(system.as_deref(), &last_user, model)
- .await
- .map_err(|error| tinyinference::Error::Model(error.to_string()))?;
-
- Ok(crate::agent::tinyagents::model::prompt_guided_text_response(output, &request))
- }
-}
-
-/// Join every system message into the one system prompt the CLI accepts.
-///
-/// The CLI takes a single `--system-prompt`, and this used to `find_map` the
-/// first system message and drop the rest (codex on #6068). What gets dropped is
-/// not incidental: the artifact contents list and the turn-cap wrap-up are both
-/// appended as system messages *precisely because* a system message is the one
-/// thing compression and the trim will not remove. Taking only the first put
-/// them back to being removable — on this provider alone, and silently.
-fn coalesce_system_prompt(messages: &[Message]) -> Option<String> {
- let parts: Vec<String> = messages
- .iter()
- .filter(|message| matches!(message, Message::System(_)))
- .map(|message| message.text())
- .filter(|text| !text.trim().is_empty())
- .collect();
- (!parts.is_empty()).then(|| parts.join("\n\n"))
-}
-
-#[cfg(test)]
-#[path = "subprocess_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/subprocess_tests.rs b/crates/openhuman-core/src/inference/provider/claude_agent_sdk/subprocess_tests.rs
deleted file mode 100644
index 3bd4e8ce2c..0000000000
--- a/crates/openhuman-core/src/inference/provider/claude_agent_sdk/subprocess_tests.rs
+++ /dev/null
@@ -1,260 +0,0 @@
-use super::*;
-use crate::config::schema::claude_agent_sdk::ClaudeAgentSdkConfig;
-
-#[test]
-fn provider_constructs_with_default_config() {
- let config = ClaudeAgentSdkConfig::default();
- let provider = ClaudeAgentSdkProvider::new(config);
- assert_eq!(provider.config.binary, "claude");
- assert_eq!(provider.config.default_model, "claude-sonnet-4-6");
-}
-
-#[test]
-fn config_default_disabled() {
- let config = ClaudeAgentSdkConfig::default();
- assert!(!config.enabled);
- assert!(config.max_budget_usd.is_none());
-}
-
-#[test]
-fn large_request_is_delivered_over_stdin_instead_of_argv() {
- let system_prompt = "system instruction\n".repeat(2_500);
- assert!(system_prompt.len() > 32_767);
-
- let invocation = build_invocation(Some(&system_prompt), "hello", "claude-sonnet-4-6", None);
-
- assert_eq!(
- invocation.args,
- [
- "-p",
- "--model",
- "claude-sonnet-4-6",
- "--output-format",
- "stream-json",
- "--no-color"
- ]
- );
- assert!(!invocation
- .args
- .iter()
- .any(|arg| arg.contains(&system_prompt)));
- assert_eq!(
- invocation.stdin,
- format!("[SYSTEM]\n{system_prompt}\n[/SYSTEM]\n\nhello")
- );
-}
-
-#[test]
-fn invocation_preserves_plain_message_and_budget_flags() {
- let invocation = build_invocation(None, "hello", "claude-opus-4-6", Some(1.25));
-
- assert_eq!(invocation.stdin, "hello");
- assert_eq!(
- &invocation.args[6..],
- ["--max-turns", "10", "--budget", "1.2500"]
- );
-}
-
-#[test]
-fn spawn_error_message_includes_the_os_source() {
- let source = std::io::Error::from_raw_os_error(206);
- let error = spawn_error(r"C:\Users\test\.local\bin\claude.exe", source);
-
- assert!(error.to_string().contains("os error 206"));
- assert_eq!(
- error.chain().count(),
- 2,
- "io::Error source must be preserved"
- );
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn provider_pipes_large_request_to_cli_stdin() {
- use std::os::unix::fs::PermissionsExt;
-
- let dir = tempfile::tempdir().expect("tempdir");
- let script = dir.path().join("claude");
- std::fs::write(
- &script,
- r#"#!/bin/sh
-cat > "$0.stdin"
-printf '%s\n' '{"type":"result","result":"captured","is_error":false}'
-"#,
- )
- .expect("write fake claude");
- std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700))
- .expect("make fake claude executable");
-
- let mut config = ClaudeAgentSdkConfig::default();
- config.binary = script.display().to_string();
- let provider = ClaudeAgentSdkProvider::new(config);
- let system_prompt = "system instruction\n".repeat(2_500);
-
- let output = provider
- .invoke(
- &(),
- ModelRequest::new(vec![
- Message::system(&system_prompt),
- Message::user("hello"),
- ])
- .with_model("claude-sonnet-4-6"),
- )
- .await
- .expect("fake claude response")
- .text();
-
- assert_eq!(output, "captured");
- assert_eq!(
- std::fs::read_to_string(format!("{}.stdin", script.display())).expect("captured stdin"),
- format!("[SYSTEM]\n{system_prompt}\n[/SYSTEM]\n\nhello")
- );
-}
-
-#[tokio::test]
-async fn provider_spawn_error_includes_the_os_source() {
- let dir = tempfile::tempdir().expect("tempdir");
- let mut config = ClaudeAgentSdkConfig::default();
- config.binary = dir.path().join("missing-claude").display().to_string();
- let provider = ClaudeAgentSdkProvider::new(config);
-
- let error = provider
- .invoke_cli(None, "hello", "claude-sonnet-4-6")
- .await
- .expect_err("missing binary must fail");
-
- assert!(error.to_string().contains("failed to spawn claude binary"));
- assert!(error.to_string().contains("os error"));
- assert_eq!(
- error.chain().count(),
- 2,
- "io::Error source must be preserved"
- );
-}
-
-#[cfg(unix)]
-#[tokio::test]
-async fn chat_model_uses_prompt_guided_protocol_and_model_override() {
- use std::os::unix::fs::PermissionsExt;
- use tinyinference::tool::ToolSchema;
-
- let dir = tempfile::tempdir().expect("tempdir");
- let script = dir.path().join("claude");
- std::fs::write(
- &script,
- r#"#!/bin/sh
-cat > "$0.stdin"
-printf '%s\n' "$@" > "$0.args"
-printf '%s\n' '{"type":"result","result":"Calling.<tool_call>{\"name\":\"lookup\",\"arguments\":{\"query\":\"needle\"}}</tool_call>","is_error":false}'
-"#,
- )
- .expect("write fake claude");
- std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700))
- .expect("make fake claude executable");
-
- let mut config = ClaudeAgentSdkConfig::default();
- config.binary = script.display().to_string();
- let provider = ClaudeAgentSdkProvider::for_model(config, "profile-model");
- let request = ModelRequest {
- messages: vec![
- Message::system("Base system"),
- Message::user("original question"),
- Message::assistant("calling"),
- Message::tool("call-1", "first result"),
- Message::tool("call-2", "second result"),
- ],
- tools: vec![ToolSchema::new(
- "lookup",
- "looks up data",
- serde_json::json!({
- "type": "object",
- "properties": { "query": { "type": "string" } }
- }),
- )],
- model: Some("request-model".to_string()),
- ..Default::default()
- };
-
- let response = provider
- .invoke(&(), request)
- .await
- .expect("fake claude response");
-
- assert_eq!(response.text(), "Calling.");
- assert_eq!(response.message.tool_calls.len(), 1);
- assert_eq!(response.message.tool_calls[0].name, "lookup");
- assert_eq!(
- response.message.tool_calls[0].arguments,
- serde_json::json!({"query": "needle"})
- );
- let stdin =
- std::fs::read_to_string(format!("{}.stdin", script.display())).expect("captured stdin");
- assert!(stdin.contains("Base system"));
- assert!(stdin.contains("## Tool Use Protocol"));
- assert!(
- stdin.contains("[Tool results]\n<tool_result>\nfirst result\n</tool_result>"),
- "unexpected CLI stdin: {stdin:?}"
- );
- assert!(stdin.ends_with("<tool_result>\nsecond result\n</tool_result>"));
- let args =
- std::fs::read_to_string(format!("{}.args", script.display())).expect("captured args");
- assert!(args.contains("request-model"));
- assert_eq!(
- provider
- .profile()
- .and_then(|profile| profile.model.as_deref()),
- Some("profile-model")
- );
- assert_eq!(
- provider
- .profile()
- .and_then(|profile| profile.provider.as_deref()),
- Some("claude-agent-sdk")
- );
-}
-
-#[test]
-fn cache_identity_includes_selected_model() {
- let config = ClaudeAgentSdkConfig::default();
- let first = ClaudeAgentSdkProvider::for_model(config.clone(), "model-a");
- let second = ClaudeAgentSdkProvider::for_model(config, "model-b");
-
- assert_ne!(first.cache_identity(), second.cache_identity());
-}
-
-/// The CLI takes one `--system-prompt`, so every system message has to be
-/// folded into it. Taking only the first dropped the artifact contents list and
-/// the turn-cap wrap-up, which are appended as system messages exactly so the
-/// context ladder cannot remove them (codex on #6068).
-#[test]
-fn every_system_message_reaches_the_cli_prompt() {
- let messages = vec![
- Message::system("you are a helpful agent"),
- Message::user("fetch the issues"),
- Message::system("## Stored results from this turn\n\n- `file_read` → `a.json`"),
- ];
-
- let system = coalesce_system_prompt(&messages).expect("a system prompt");
-
- assert!(
- system.contains("you are a helpful agent"),
- "the persona must survive: {system}"
- );
- assert!(
- system.contains("Stored results from this turn"),
- "a later system message must not be dropped: {system}"
- );
- assert!(
- system.find("you are a helpful agent") < system.find("Stored results"),
- "order must be preserved so the persona still leads: {system}"
- );
-}
-
-#[test]
-fn a_conversation_with_no_system_message_yields_none() {
- let messages = vec![Message::user("hello")];
- assert!(coalesce_system_prompt(&messages).is_none());
- // Blank system messages are not a prompt either.
- let blank = vec![Message::system(" ")];
- assert!(coalesce_system_prompt(&blank).is_none());
-}
diff --git a/crates/openhuman-core/src/inference/provider/config_rejection.rs b/crates/openhuman-core/src/inference/provider/config_rejection.rs
deleted file mode 100644
index 5c50630308..0000000000
--- a/crates/openhuman-core/src/inference/provider/config_rejection.rs
+++ /dev/null
@@ -1,311 +0,0 @@
-//! Classifier for **provider configuration-rejection** errors.
-//!
-//! When OpenHuman talks to a user-configured custom cloud endpoint
-//! (`custom_openai` → DeepSeek / OpenRouter / Moonshot / …) the upstream
-//! API rejects requests whose model id or sampling params it doesn't
-//! understand:
-//!
-//! - `"The supported API model names are deepseek-v4-pro or
-//! deepseek-v4-flash, but you passed reasoning-v1."` (#2079 — an
-//! OpenHuman abstract tier alias leaked to a provider that only speaks
-//! its own native ids)
-//! - `"Model 'deepseek-v4-pro' is not available. Use GET
-//! /openai/v1/models to list available models."` (#2202)
-//! - `"invalid temperature: only 1 is allowed for this model"` (#2076 —
-//! Moonshot Kimi K2)
-//! - `"The model \`gpt-5.5\` does not exist or you do not have access to
-//! it."` / `"model_not_found"` (stale model pin)
-//! - `"This model is not available in your region."` (R1 — region-blocked
-//! model on a custom cloud provider)
-//! - `"ModelNotAllowed"` (R4 — Doubao/ChatGLM model-allowlist enforcement)
-//! - `"invalid_authentication_error"` (YC — user pasted a malformed /
-//! revoked API key into the provider config)
-//! - `"This request requires more credits"` (S5 — OpenRouter `402` when
-//! the user's account is out of credits)
-//! - `"Insufficient Balance"` (4ZF — DeepSeek custom BYO-key `402` when
-//! the user's DeepSeek account balance is exhausted)
-//! - `"Invalid model name passed in model="` (Y0 — litellm-style proxy
-//! rejecting a model id pre-routing)
-//! - `"No active credentials for provider:"` (JN / KB — user hasn't
-//! plugged in their API key for the selected provider yet)
-//! - `"litellm.BadRequestError"` (JK — litellm github_copilot proxy 400
-//! from a user OAuth/scope gap)
-//! - `"not_found_error"` (J2 / J5 / J4 — litellm-compatible envelope
-//! `type` field carrying "model 'X' not found")
-//!
-//! These are **deterministic user-configuration state**, not bugs the
-//! maintainers can act on: the user pointed OpenHuman at a custom
-//! provider with a model / temperature / region / credential that
-//! provider does not accept. The remediation is "fix the model, key, or
-//! routing in Settings", which the UI surfaces. Yet every agent turn
-//! produces a fresh Sentry event (OPENHUMAN-TAURI-WJ / -QW / -HB / -NH /
-//! -R1 / -R4 / -YC / -S5 / -Y0 / -JN / -KB / -JK / -J2 / -J5 / -J4 —
-//! ~250 additional events on top of the Wave 1-3 IDs). This is the
-//! same class as budget-exhaustion ([`super::billing_error`]) and must
-//! be demoted from Sentry to an info log the same way.
-//!
-//! ## Provider-aware polarity (important)
-//!
-//! Most of the phrases below are emitted by **third-party upstream APIs**
-//! (DeepSeek / OpenRouter / Moonshot). The OpenHuman hosted backend
-//! resolves tier aliases natively and never emits "supported API model
-//! names are deepseek-…" or "invalid temperature: only 1 is allowed" — so
-//! that phrase set is intrinsically scoped to custom providers. The
-//! HTTP-layer wrapper [`super::ops::is_provider_config_rejection_http`]
-//! polarity-guards those phrases on `provider !=
-//! openhuman_backend_model::PROVIDER_LABEL` so a model-rejection from our
-//! **own** backend that we did not expect (which would be a real
-//! regression we sent it a bad request) still reaches Sentry. The
-//! message-only predicate is consumed by
-//! [`crate::core::observability::expected_error_kind`] for the
-//! re-reported error that escapes the provider layer and is raised again
-//! by `agent.run_single` / `web_channel.run_chat_task`.
-//!
-//! **Exception: the OpenAI-compatible "unknown model" shape** (`Model 'X'
-//! is not available. Use GET /openai/v1/models …`) is now emitted by the
-//! OpenHuman hosted backend too, in response to user-configured model ids
-//! that aren't in the backend's registry. Pinned by
-//! [`is_openai_compatible_unknown_model_message`]. The HTTP-layer wrapper
-//! drops the polarity guard for that specific shape so the same body is
-//! treated as user-state regardless of provider — see TAURI-RUST-2Z1
-//! where a user-typed `MiniMax-M2.7-highspeed` model id (plus two
-//! `custom:` fallback variants from their own `model_fallbacks` config)
-//! was rejected with this wire shape and otherwise reached Sentry.
-//!
-//! Keep the list deliberately tight: a false positive demotes a real
-//! provider/backend bug to an info log.
-
-/// Returns true if a provider error body indicates the request was
-/// rejected because of the user's model / parameter **configuration**
-/// (unknown model id, abstract tier leaked to a custom provider,
-/// model-specific temperature constraint), as opposed to a transient
-/// failure or a server bug.
-///
-/// Case-insensitive substring match. See the module docs for the polarity
-/// contract and the OPENHUMAN-TAURI Sentry issues each phrase drops.
-pub fn is_provider_config_rejection_message(body: &str) -> bool {
- const PHRASES: &[&str] = &[
- // #2079 — an OpenHuman abstract tier alias (`reasoning-v1`,
- // `chat-v1`, …) reached a custom provider that lists its own
- // native ids back at us.
- "supported api model names are",
- // #2202 — OpenAI-compatible "unknown model" body. The
- // `/openai/v1/models` remediation hint is the stable, unique
- // anchor (the quoted model id varies per user).
- "/openai/v1/models",
- // OpenAI / OpenRouter stale-pin shape (`claude-opus-4-7`,
- // `gpt-5.5`, …) — model removed or no access.
- "does not exist or you do not have access",
- "model_not_found",
- // #2076 — Moonshot Kimi K2 only accepts `temperature: 1`.
- "invalid temperature",
- "only 1 is allowed for this model",
- // Our own actionable error once a proper tier→model resolution
- // is in place (keeps this classifier stable across that fix).
- "is an abstract tier",
- // OPENHUMAN-TAURI-R1 — custom_openai upstream 403 with body
- // `{"error":{"message":"This model is not available in your region.","code":403}}`.
- // User picked a model the provider blocks for their account's
- // region. Sentry has no remediation; user must switch model.
- "not available in your region",
- // OPENHUMAN-TAURI-R4 — Doubao / ChatGLM-style model allowlist
- // enforcement. Body: `{"reason":"ModelNotAllowed",...}`. Match
- // lowercased — the provider sends the camelCase token as a
- // sentinel `reason` value.
- "modelnotallowed",
- // OPENHUMAN-TAURI-YC — user-supplied custom_openai API key was
- // rejected by upstream with the OpenAI-compatible
- // `{"error":{"type":"invalid_authentication_error",...}}`
- // envelope. Anchored on the type token (stable across providers
- // that emit this OpenAI-compatible body).
- "invalid_authentication_error",
- // OPENHUMAN-TAURI-S5 — OpenRouter 402 when the user is out of
- // credits. Body always carries "requires more credits, or fewer
- // max_tokens"; pin to the unique-enough credits phrase. (The
- // separate `billing_error` classifier handles our own
- // OpenHuman-backend balance gate; this catches the third-party
- // OpenRouter shape that re-emits via `agent.run_single`.)
- "requires more credits",
- // TAURI-RUST-4ZF — DeepSeek (custom BYO-key) 402 when the user's
- // DeepSeek account balance is exhausted. Body carries the upstream
- // `{"error":{"message":"Insufficient Balance",...}}` envelope.
- // Same user-billing class as the OpenRouter S5 shape above.
- // NOTE: `is_budget_exhausted_message` (billing_error.rs) also
- // contains this phrase. In `expected_error_kind` (observability.rs)
- // this classifier is checked first (line 199 vs 205), so a re-
- // reported "Insufficient Balance" error routes to
- // `ProviderConfigRejection` rather than `BudgetExhausted`. Both
- // suppress Sentry at info-level — no event-volume regression — but
- // the telemetry `kind` tag becomes "provider_config_rejection".
- "insufficient balance",
- // OPENHUMAN-TAURI-Y0 — litellm-style proxy rejected the model
- // id pre-routing with `Invalid model name passed in model=…`.
- // Anchored on the `passed in model=` suffix so a stray "invalid
- // model name" log line elsewhere does not classify.
- "invalid model name passed in model=",
- // OPENHUMAN-TAURI-JN / -KB — custom provider proxy that fronts
- // multiple upstream APIs surfaces a "you haven't configured the
- // upstream provider yet" 401/404 as `{"error":{"message":"No
- // active credentials for provider: openai",...}}`. The
- // remediation is "add the upstream API key in Settings".
- "no active credentials for provider",
- // OPENHUMAN-TAURI-JK — litellm github_copilot proxy 400 driven
- // by the user's missing / expired Copilot OAuth scope. The body
- // always starts with the `litellm.BadRequestError:` envelope.
- // Anchor to that prefix-shaped substring so we don't catch
- // unrelated 400s that merely mention litellm in passing.
- "litellm.badrequesterror",
- // OPENHUMAN-TAURI-J2 / -J5 / -J4 — litellm-compatible
- // envelope with `"type":"not_found_error"` carrying "model 'X'
- // not found". Distinct from the existing `model_not_found`
- // phrase: that's the `code` field used by OpenAI-native bodies;
- // this is the `type` field used by litellm/Anthropic-style
- // envelopes for the same class of user-state error.
- "not_found_error",
- // TAURI-RUST-4NM — nvidia-nim (and compatible providers) return
- // `{"error":{"message":"model field is required","code":"missing_required_field"}}`
- // when the request body contains an empty `"model":""` field.
- "model field is required",
- // TAURI-RUST-GKV (~2.3k events / 1 user) — the LOCAL form of the
- // 4NM empty-model state, caught one layer earlier. The #2784 cloud-slug
- // resolution guard bails BEFORE any
- // provider HTTP call when a `<slug>` provider string carries no
- // model and the `cloud_providers` entry has no `default_model`:
- // "[chat-factory] no model configured: role '<r>' resolved to an
- // empty model id for slug '<s>'. Include a model in the provider
- // string (e.g. '<s>:<model-id>') or set default_model …".
- // User-state — the remediation is "add/pick a model in Settings →
- // LLM", which the user-facing copy surfaces; Sentry has no
- // remediation. Anchored on the role/slug-interpolation-free
- // substring, which IS `factory::NO_MODEL_CONFIGURED_ANCHOR` —
- // referenced directly so the two can never drift (the round-trip
- // test in `factory_tests.rs` remains as a belt-and-braces guard).
- super::factory::NO_MODEL_CONFIGURED_ANCHOR,
- // TAURI-RUST-2G (~2684 events) / TAURI-RUST-2F (~950 events) —
- // thinking-mode model (DeepSeek-R1 / Moonshot K2-thinking on
- // `provider=cloud` custom_openai) rejects a follow-up turn that
- // doesn't echo the prior assistant's `reasoning_content` field.
- // Body shape (backtick-quoted JSON literal in the upstream body):
- // `{"error":{"message":"The `reasoning_content` in the thinking
- // mode must be passed back to the API.",...}}`. The
- // provider-contract gap is on our side, but until the thinking-
- // mode round-tripping ships in the inference layer, every affected
- // turn fires a fresh Sentry event — and the UI already surfaces
- // the actionable error to the user. Anchor on the unique
- // `thinking mode must be passed back` substring so the match
- // doesn't depend on the upstream's backtick-quoting around
- // `reasoning_content` (some provider versions ship without them).
- "thinking mode must be passed back",
- // TAURI-RUST-4XK (~649 events) — Ollama Cloud subscription gate.
- // Body: `{"error":"this model requires a subscription, upgrade for
- // access: https://ollama.com/upgrade (ref: <uuid>)"}` on a 403
- // Forbidden from the OpenAI-compatible client with
- // `name = "ollama"`. User-state: the model picked in Settings is
- // a paid-tier Ollama Cloud model the user's account doesn't
- // cover. The UI surfaces an actionable upgrade link in the
- // remediation message itself.
- "requires a subscription, upgrade for access",
- // TAURI-RUST-1V / OPENHUMAN-TAURI-4JS —
- // `reliable.rs::format_failure_aggregate` (no-configured-fallbacks
- // branch) wraps every exhausted `reliable_chat_with_system` turn
- // with:
- //
- // "The model `<name>` may not be available on your provider.
- // Configure a fallback chain via `reliability.model_fallbacks`
- // in your OpenHuman config, or change your default model in
- // Connections → API keys → LLM.\n\nAll providers/models failed. Attempts:\n…"
- //
- // The aggregate fires once per turn regardless of the underlying
- // per-attempt cause (auth wall, unknown model, region block,
- // rate-limit cliff). All of those are user-actionable: pick a
- // different model, fix the credential, or configure fallbacks —
- // the message body literally tells the user how. Sentry has no
- // remediation path the per-attempt classifiers haven't already
- // covered at the lower layer (provider/ops.rs:486 publishes
- // SessionExpired, billing_error covers credit walls, etc.).
- //
- // Two anchors, both unique to this single emit site (verified via
- // grep across `src/`) and both present only in the no-configured-
- // fallbacks branch — the configured-fallbacks branch emits only
- // the bare "All providers/models failed. Attempts:\n…" dump, so
- // neither phrase fires on it (see the
- // `does_not_classify_reliable_aggregate_with_configured_fallbacks`
- // test). `may not be available on your provider` is the canonical
- // remediation-sentence phrase (TAURI-RUST-1V); the
- // `reliability.model_fallbacks` config path (OPENHUMAN-TAURI-4JS)
- // is kept as a redundant belt-and-braces anchor for the same line.
- "may not be available on your provider",
- "reliability.model_fallbacks",
- // TAURI-RUST-35 family — user picked a model that doesn't
- // implement tool calling, agent harness sent a tool spec
- // anyway, upstream rejected with `{"error":{"message":
- // "<model id> does not support tools",
- // "type":"invalid_request_error",...}}`. Same body across the
- // `cloud` / `ollama` / `custom_openai` provider prefixes — one
- // phrase drops all 10+ sibling Sentry issues currently
- // fragmented by model id (TAURI-RUST-35, -DF, -123, -4K7,
- // -4FS, -4F6, -2YA, -4KR, -4KH, -4KY — ~458 events). The user
- // must pick a tool-capable model; Sentry has no remediation.
- // NOTE: also pinned in the TAURI-RUST-4K7 capability-discovery
- // block above; both match the same phrase — the duplicate is
- // harmless (`.any()` short-circuits) and kept so each Sentry
- // family stays self-documenting.
- "does not support tools",
- // TAURI-RUST-ADC (~5.9k events / 10 users) — OpenRouter's
- // *router-level* phrasing of the same tool-capability user-state.
- // When the picked model has no provider endpoint that supports tool
- // calling, OpenRouter returns a 404 with `{"error":{"message":"No
- // endpoints found that support tool use. Try disabling \"<tool>\".
- // ..."}}`. The wording differs from the direct-provider `does not
- // support tools` body above ("tool use" vs "tools", prefixed with
- // "No endpoints found"), so it needs its own anchor. Same user-state
- // class: pick a tool-capable model. Surfaced most often by the
- // autonomous Subconscious loop, which additionally halts on this via
- // its own capability breaker (`subconscious/engine.rs`).
- "no endpoints found that support tool use",
- // TAURI-RUST-4P6 (~36.6k events / 2 users) — user picked an
- // *embedding* model (Ollama `bge-m3:latest`, OpenHuman's default
- // memory-tree embed model) as their chat model. Ollama rejects every
- // chat turn with `{"error":{"message":"\"bge-m3:latest\" does not
- // support chat","type":"invalid_request_error",...}}` on a 400. Same
- // user-state class as `does not support tools`: the model lacks the
- // chat capability and the user must pick a chat-capable model — Sentry
- // has no remediation. The 400 status bypasses the
- // `completion_only_404_guard` (404-only), so without this phrase the
- // raw body re-reports every turn. The companion `not_chat_capable_guard`
- // in `compatible.rs` rewrites the opaque upstream JSON into an
- // actionable "assign a chat-capable model" message that still carries
- // this substring, so it stays demoted.
- "does not support chat",
- ];
-
- let lower = body.to_ascii_lowercase();
- PHRASES.iter().any(|phrase| lower.contains(phrase))
-}
-
-/// Returns true if a provider error body matches the OpenAI-compatible
-/// "unknown model" shape — anchored on the `/openai/v1/models`
-/// remediation hint the upstream returns alongside `Model 'X' is not
-/// available.`.
-///
-/// This is a strict subset of [`is_provider_config_rejection_message`]:
-/// the same phrase already lives in that predicate's list. The narrower
-/// helper exists so the HTTP-layer wrapper
-/// ([`super::ops::is_provider_config_rejection_http`]) can drop its
-/// `provider != openhuman_backend_model::PROVIDER_LABEL` polarity guard for
-/// this specific body shape — the OpenHuman hosted backend now emits the
-/// same OpenAI-compatible "Model 'X' is not available" wire body in
-/// response to user-configured unknown model ids, so the original
-/// polarity assumption ("only third-party providers speak this dialect")
-/// no longer holds.
-///
-/// Drops TAURI-RUST-2Z1 (per-attempt) — the aggregate sibling
-/// TAURI-RUST-2Z2 is already covered by the message-only classifier in
-/// [`crate::core::observability::expected_error_kind`].
-pub fn is_openai_compatible_unknown_model_message(body: &str) -> bool {
- body.to_ascii_lowercase().contains("/openai/v1/models")
-}
-
-#[cfg(test)]
-#[path = "config_rejection_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/config_rejection_tests.rs b/crates/openhuman-core/src/inference/provider/config_rejection_tests.rs
deleted file mode 100644
index 899a6d7985..0000000000
--- a/crates/openhuman-core/src/inference/provider/config_rejection_tests.rs
+++ /dev/null
@@ -1,381 +0,0 @@
-use super::*;
-
-#[test]
-fn detects_real_sentry_bodies() {
- // The exact upstream bodies from OPENHUMAN-TAURI-WJ / -QW / -HB
- // / -NH and the stale-pin family.
- for body in [
- "The supported API model names are deepseek-v4-pro or deepseek-v4-flash, but you passed reasoning-v1.",
- "Model 'deepseek-v4-pro' is not available. Use GET /openai/v1/models to list available models.",
- "Model 'claude-opus-4-7' is not available. Use GET /openai/v1/models to list available models.",
- "invalid temperature: only 1 is allowed for this model",
- "The model `gpt-5.5` does not exist or you do not have access to it.",
- r#"{"error":{"message":"model not found","code":"model_not_found"}}"#,
- "Model 'reasoning-v1' is an abstract tier — configure a concrete model for your custom provider",
- ] {
- assert!(
- is_provider_config_rejection_message(body),
- "{body:?} must classify as a provider config-rejection user-state"
- );
- }
-}
-
-#[test]
-fn detects_wave4_sentry_bodies() {
- // Real wire bodies pulled from the OPENHUMAN-TAURI-* Sentry
- // events the Wave 4 phrases drop.
- for (sentry_id, body) in [
- (
- "R1",
- r#"custom_openai API error (403 Forbidden): {"error":{"message":"This model is not available in your region.","code":403}}"#,
- ),
- (
- "R4",
- r#"custom_openai API error (403 Forbidden): {"code":403,"reason":"ModelNotAllowed","message":"模型不允许访问","metadata":{"request_id":"2026051706431574423265420620337"}}"#,
- ),
- (
- "YC",
- r#"custom_openai API error (401 Unauthorized): {"error":{"message":"Invalid Authentication","type":"invalid_authentication_error"}}"#,
- ),
- (
- "S5",
- r#"custom_openai API error (402 Payment Required): {"error":{"message":"This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, but can only afford 597.","type":"insufficient_credits"}}"#,
- ),
- (
- "Y0",
- r#"custom_openai API error (400 Bad Request): {"error":{"message":"{'error': '/chat/completions: Invalid model name passed in model=reasoning-v1. Call `/v1/models` to view available models for your key.'}","type":"None"}}"#,
- ),
- (
- "JN",
- r#"custom_openai Responses API error: {"error":{"message":"No active credentials for provider: openai","type":"invalid_request_error","code":"model_not_found"}}"#,
- ),
- (
- "KB",
- r#"OpenHuman API error (404 Not Found): {"error":{"message":"No active credentials for provider: openai","type":"invalid_request_error","code":"model_not_found"}}"#,
- ),
- (
- "JK",
- r#"custom_openai API error (400 Bad Request): {"error":{"message":"litellm.BadRequestError: Github_copilotException - Bad Request. Received Model Group=github_copilot/claude-haiku-4.5\nAvailable Model Group Fallbacks=None","type":null}}"#,
- ),
- (
- "J2",
- r#"custom_openai Responses API error: {"error":{"message":"model 'llama3.3' not found","type":"not_found_error","param":null,"code":null}}"#,
- ),
- (
- "J5",
- r#"custom_openai API error (404 Not Found): {"error":{"message":"model 'llama3.3' not found","type":"not_found_error","param":null,"code":null}}"#,
- ),
- (
- "J4",
- r#"custom_openai streaming API error (404 Not Found): {"error":{"message":"model 'llama3.3' not found","type":"not_found_error","param":null,"code":null}}"#,
- ),
- // TAURI-RUST-ADC — OpenRouter router-level "no tool-use endpoint"
- // 404, surfaced by the autonomous Subconscious loop on a
- // content-safety model that supports no tools.
- (
- "ADC",
- r#"openrouter API error (404 Not Found): {"error":{"message":"No endpoints found that support tool use. Try disabling \"spawn_async_subagent\". To learn more about provider routing, visit: https://openrouter.ai/docs/guides/routing/provider-selection"}}"#,
- ),
- // TAURI-RUST-4NM — nvidia-nim (and compatible providers) return
- // this body when the request body has an empty `"model":""`.
- // This is user-configuration state: the provider string had no
- // model id and the config entry has no default_model set.
- (
- "4NM",
- r#"nvidia-nim API error (400 Bad Request): {"error":{"message":"model field is required","type":"invalid_request_error","param":null,"code":"missing_required_field"}}"#,
- ),
- (
- "TAURI-RUST-4XK",
- r#"ollama API error (403 Forbidden): {"error":"this model requires a subscription, upgrade for access: https://ollama.com/upgrade (ref: bc48f3c8-fba1-40b6-93a9-786a167d16f9)"}"#,
- ),
- (
- "TAURI-RUST-2G",
- r#"cloud API error (400 Bad Request): {"error":{"message":"The `reasoning_content` in the thinking mode must be passed back to the API.","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}"#,
- ),
- (
- "TAURI-RUST-2F",
- r#"cloud streaming API error (400 Bad Request): {"error":{"message":"The `reasoning_content` in the thinking mode must be passed back to the API.","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}"#,
- ),
- // TAURI-RUST-4P6 — user picked an embedding model
- // (`bge-m3:latest`) as their Ollama chat model. Ollama 400s every
- // chat turn. Verbatim wire body from Sentry issue 5338.
- (
- "TAURI-RUST-4P6",
- r#"ollama API error (400 Bad Request): {"error":{"message":"\"bge-m3:latest\" does not support chat","type":"invalid_request_error","param":null,"code":null}}"#,
- ),
- // Same shape after `not_chat_capable_guard` (compatible.rs)
- // rewrites it into the actionable message — must still classify so
- // the re-reported error stays demoted.
- (
- "TAURI-RUST-4P6-enriched",
- "ollama API error: model 'bge-m3:latest' does not support chat — it appears to be an embedding or non-chat model. Assign a chat-capable model to this provider (e.g. in Connections → API keys → LLM), or pick a different model.",
- ),
- ] {
- assert!(
- is_provider_config_rejection_message(body),
- "OPENHUMAN-TAURI-{sentry_id} body must classify as provider config-rejection: {body:?}"
- );
- }
-}
-
-/// TAURI-RUST-4ZF — a user's custom BYO-key DeepSeek provider returns
-/// HTTP 402 with `{"error":{"message":"… Insufficient Balance …"}}`
-/// when their DeepSeek account is out of credits. Same user-billing
-/// class as the OpenRouter S5 "requires more credits" 402 already in
-/// the list — the remediation is "top up the provider account", which
-/// Sentry cannot act on. The DeepSeek wire token is `Insufficient
-/// Balance` (vs OpenRouter's `requires more credits`).
-#[test]
-fn detects_insufficient_balance_402_family() {
- for (sentry_id, body) in [
- // TAURI-RUST-4ZF — verbatim (truncated) from issue 5679,
- // model=`ds/deepseek-v4-flash`, provider=custom, status=402.
- (
- "4ZF",
- r#"custom API error (402 Payment Required): {"error":{"message":"[deepseek/deepseek-v4-flash] [402]: {\"error\":{\"message\":\"Insufficient Balance\",\"type\":\"unknown_error\",\"param\":null,\"code\":\"invali (reset after 57s)"}}"#,
- ),
- // Bare upstream envelope — what a future caller might re-emit
- // after unwrapping one layer.
- (
- "bare",
- r#"{"error":{"message":"Insufficient Balance","type":"unknown_error"}}"#,
- ),
- ] {
- assert!(
- is_provider_config_rejection_message(body),
- "TAURI-RUST-{sentry_id} insufficient-balance 402 must classify as provider config-rejection: {body:?}"
- );
- }
-}
-
-#[test]
-fn detects_reliable_aggregate_no_fallbacks_envelope() {
- // OPENHUMAN-TAURI-4JS — `reliable::format_failure_aggregate`
- // (no-configured-fallbacks branch) wraps every exhausted turn.
- // Pin a few realistic shapes:
- //
- // 1. Verbatim Sentry 4JS payload (auth wall as the per-attempt cause).
- // 2. Same aggregate, unknown-model upstream body (proves the matcher
- // is per-emit-site, not per-underlying-cause).
- // 3. Same aggregate, region-block per-attempt body (R1-sibling cause).
- // 4. Bare two-line aggregate (only the literal prefix + an empty
- // attempts dump).
- //
- // All four must classify; the unique anchor is the
- // `reliability.model_fallbacks` config path the message literally
- // tells the user to set.
- for raw in [
- // 1) Verbatim 4JS payload.
- "The model `reasoning-quick-v1` may not be available on your provider. \
- Configure a fallback chain via `reliability.model_fallbacks` in your \
- OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
- All providers/models failed. Attempts:\n\
- provider=openhuman model=reasoning-quick-v1 attempt 1/3: non_retryable; \
- error=OpenHuman API error (401 Unauthorized): {\"success\":false,\"error\":\"Invalid token\"}",
- // 2) Unknown-model upstream cause.
- "The model `gpt-5.5` may not be available on your provider. \
- Configure a fallback chain via `reliability.model_fallbacks` in your \
- OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
- All providers/models failed. Attempts:\n\
- provider=custom_openai model=gpt-5.5 attempt 1/3: non_retryable; \
- error=custom_openai API error (404 Not Found): {\"error\":\"model not found\"}",
- // 3) Region-block (R1-sibling) per-attempt cause.
- "The model `gpt-4o` may not be available on your provider. \
- Configure a fallback chain via `reliability.model_fallbacks` in your \
- OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
- All providers/models failed. Attempts:\n\
- provider=custom_openai model=gpt-4o attempt 1/3: non_retryable; \
- error=custom_openai API error (403 Forbidden): {\"error\":{\"message\":\"This model is not available in your region.\"}}",
- // 4) Bare aggregate — minimal anchor surface.
- "The model `x` may not be available on your provider. \
- Configure a fallback chain via `reliability.model_fallbacks` in your \
- OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
- All providers/models failed. Attempts:\n",
- ] {
- assert!(
- is_provider_config_rejection_message(raw),
- "OPENHUMAN-TAURI-4JS aggregate must classify as provider config-rejection: {raw:?}"
- );
- }
-}
-
-#[test]
-fn does_not_classify_reliable_aggregate_with_configured_fallbacks() {
- // The configured-fallbacks branch of `format_failure_aggregate`
- // emits ONLY the attempts dump (`"All providers/models failed.
- // Attempts:\n…"`), with no `reliability.model_fallbacks`
- // remediation hint — the user has already engaged with the knob,
- // so the aggregate is closer to a real diagnostic surface than a
- // user-config nudge. Without the anchor phrase, this matcher
- // must NOT fire on its own — only the per-attempt body
- // classifiers (#2786 SessionExpired, config_rejection siblings,
- // …) can demote it on a per-shape basis.
- let aggregate_with_fallbacks = "All providers/models failed. Attempts:\n\
- provider=openhuman model=gpt-5.5 attempt 1/3: non_retryable; \
- error=OpenHuman API error (404 Not Found): {\"error\":\"unknown model\"}";
- assert!(
- !is_provider_config_rejection_message(aggregate_with_fallbacks),
- "configured-fallbacks aggregate (no `reliability.model_fallbacks` anchor) \
- must NOT classify on the aggregate phrase alone"
- );
-}
-
-#[test]
-fn detection_is_case_insensitive() {
- assert!(is_provider_config_rejection_message(
- "INVALID TEMPERATURE: ONLY 1 IS ALLOWED FOR THIS MODEL"
- ));
- assert!(is_provider_config_rejection_message(
- "The Supported API Model Names Are gpt-4o or gpt-4o-mini"
- ));
-}
-
-#[test]
-fn ignores_transient_and_server_and_unrelated() {
- // Must NOT demote: transient/server failures and generic 4xx
- // that carry no config-rejection signal — those stay Sentry
- // actionable. (A real backend bug must not be silenced.)
- for body in [
- "Internal server error",
- "503 Service Unavailable",
- "Bad request: missing field",
- "rate limit exceeded, retry after 1s",
- "insufficient budget — add credits",
- "",
- ] {
- assert!(
- !is_provider_config_rejection_message(body),
- "{body:?} must NOT classify as a provider config-rejection"
- );
- }
-}
-
-#[test]
-fn detects_reliable_chain_exhaustion_rollup() {
- // TAURI-RUST-1V — `reliable.rs:325` rolls every attempt into
- // `All providers/models failed. Attempts:\n…\nThe model `<id>`
- // may not be available on your provider. Configure a fallback
- // chain via `reliability.model_fallbacks` in …`. The wrapped err
- // bubbles to `memory_sync::composio::bus` which previously
- // emitted it as a raw `tracing::error!` — 10.7k events / 14d on
- // self-hosted Sentry. The remediation lives entirely in the
- // user's `reliability.model_fallbacks` config; Sentry has no
- // remediation path.
- let rollup = "All providers/models failed. Attempts:\n\
- provider=openhuman model=gemini-3-flash-preview attempt 1/3: \
- non_retryable; error=custom_openai API error (404 Not Found): \
- <html>...</html>\n\
- The model `gemini-3-flash-preview` may not be available on \
- your provider. Configure a fallback chain via \
- `reliability.model_fallbacks` in your config to route around \
- unavailable models.";
- assert!(
- is_provider_config_rejection_message(rollup),
- "TAURI-RUST-1V multi-line rollup must classify as provider config-rejection"
- );
-
- // Single-line `reliable.rs:332` emission (without the outer
- // rollup wrapper) also matches — defensive against callers that
- // surface only the inner remediation message.
- let bare = "The model `chat-v1` may not be available on your provider. \
- Configure a fallback chain via `reliability.model_fallbacks` in …";
- assert!(
- is_provider_config_rejection_message(bare),
- "bare `may not be available on your provider` phrase must classify"
- );
-}
-
-#[test]
-fn unknown_model_helper_matches_openai_compatible_bodies() {
- // TAURI-RUST-2Z1 — the OpenHuman hosted backend now emits the
- // OpenAI-compatible "Model 'X' is not available" wire body for
- // user-configured unknown model ids. The helper is anchored on
- // the `/openai/v1/models` remediation hint so the same body shape
- // matches whether it came from a third-party `custom_openai`
- // upstream or our own backend.
- for body in [
- r#"OpenHuman API error (400 Bad Request): {"success":false,"error":"Model 'MiniMax-M2.7-highspeed' is not available. Use GET /openai/v1/models to list available models."}"#,
- r#"OpenHuman API error (400 Bad Request): {"success":false,"error":"Model 'custom:MiniMax-M2.7' is not available. Use GET /openai/v1/models to list available models."}"#,
- "Model 'deepseek-v4-pro' is not available. Use GET /openai/v1/models to list available models.",
- ] {
- assert!(
- is_openai_compatible_unknown_model_message(body),
- "TAURI-RUST-2Z1 body must classify as openai-compatible unknown model: {body:?}"
- );
- // Sanity: must remain a member of the broader phrase set so
- // the message-only classifier in
- // `crate::core::observability::expected_error_kind` keeps
- // demoting the aggregate (TAURI-RUST-2Z2).
- assert!(
- is_provider_config_rejection_message(body),
- "broader classifier must continue to match: {body:?}"
- );
- }
-}
-
-#[test]
-fn detects_nvidia_nim_missing_model_body() {
- // TAURI-RUST-4NM — nvidia-nim rejects requests with model="" with
- // `{"error":{"message":"model field is required",...}}`.
- let body = r#"nvidia-nim API error (400 Bad Request): {"error":{"message":"model field is required","type":"invalid_request_error","code":"missing_required_field"}}"#;
- assert!(
- is_provider_config_rejection_message(body),
- "TAURI-RUST-4NM body must classify as provider config-rejection: {body:?}"
- );
- // Also verify the bare phrase on its own (defense-in-depth path).
- assert!(is_provider_config_rejection_message(
- "model field is required"
- ));
-}
-
-#[test]
-fn detects_chat_factory_empty_model_local_bail() {
- // TAURI-RUST-GKV — the #2784 cloud-slug resolution guard catches the
- // empty-model state
- // BEFORE the provider HTTP call (the local form of 4NM) and bails
- // with this body (role/slug interpolated). Verbatim from Sentry
- // issue 18482 (role='chat', slug='nvidia').
- let body = "[chat-factory] no model configured: role 'chat' resolved to an empty model id \
- for slug 'nvidia'. Include a model in the provider string (e.g. \
- 'nvidia:<model-id>') or set default_model on the cloud_providers entry for \
- slug 'nvidia'.";
- assert!(
- is_provider_config_rejection_message(body),
- "TAURI-RUST-GKV empty-model bail must classify as provider config-rejection: {body:?}"
- );
- // Bare anchor on its own (the literal shared with
- // `factory::NO_MODEL_CONFIGURED_ANCHOR`).
- assert!(is_provider_config_rejection_message(
- "resolved to an empty model id"
- ));
- // Negative: a near-miss model-resolution error that does NOT carry
- // the anchor (or any other phrase) must stay Sentry-actionable.
- assert!(
- !is_provider_config_rejection_message(
- "could not resolve the model registry for slug 'nvidia'"
- ),
- "unrelated model-resolution error must not classify on the GKV anchor"
- );
-}
-
-#[test]
-fn unknown_model_helper_rejects_other_config_rejection_phrases() {
- // Polarity exception must stay narrow: other config-rejection
- // shapes (DeepSeek `supported api model names are`, Moonshot
- // `invalid temperature`, OpenRouter `requires more credits`, …)
- // must still go through the provider-polarity guard so a
- // hypothetical regression where our own backend emits one of
- // those phrases reaches Sentry.
- for body in [
- "The supported API model names are deepseek-v4-pro or deepseek-v4-flash, but you passed reasoning-v1.",
- "invalid temperature: only 1 is allowed for this model",
- "The model `gpt-5.5` does not exist or you do not have access to it.",
- r#"{"error":{"message":"model not found","code":"model_not_found"}}"#,
- "This request requires more credits, or fewer max_tokens.",
- ] {
- assert!(
- !is_openai_compatible_unknown_model_message(body),
- "{body:?} must NOT match the narrow openai-compatible-unknown-model helper"
- );
- }
-}
diff --git a/crates/openhuman-core/src/inference/provider/error_code.rs b/crates/openhuman-core/src/inference/provider/error_code.rs
deleted file mode 100644
index b94a23695f..0000000000
--- a/crates/openhuman-core/src/inference/provider/error_code.rs
+++ /dev/null
@@ -1,220 +0,0 @@
-//! Backend `errorCode` extraction + Sentry-ownership decision.
-//!
-//! The OpenHuman **managed backend** (PR #870 / backend `tinyhumansai/backend#870`)
-//! stamps every inference error response with a stable machine-readable
-//! `errorCode` field in the JSON body, e.g.
-//!
-//! ```json
-//! {"error":{"message":"Rate limited","errorCode":"RATE_LIMITED","retryAfter":30}}
-//! ```
-//!
-//! That body is the only thing that distinguishes a **managed** failure (our
-//! operator key / account / quota / routing) from a **BYO** failure (the user
-//! runs their own provider key, no `errorCode` is present). The presence of an
-//! `errorCode` is therefore the single load-bearing signal for two decisions:
-//!
-//! 1. **Classification** ([`super::super::super::web_chat::web_errors::classify_inference_error`]):
-//! when an `errorCode` is present, branch on it FIRST and ignore the
-//! substring heuristics; when it is absent, fall back to the substring
-//! ladder (the BYO / direct-provider path, whose "check your API key" /
-//! "check your model settings" copy is correct there).
-//! 2. **Sentry ownership** (`api_error` / `before_send` / `expected_error_kind`):
-//! any response carrying an `errorCode` is owned by the backend (it already
-//! paged, or it is expected user-state) so the FE must **not** double-report
-//! — with the single exception of a backend-flagged **malformed**
-//! `BAD_REQUEST`, which means the client built a payload the backend
-//! couldn't parse (a client bug worth paging). See the spec's "golden rule"
-//! (F2) and the malformed-`BAD_REQUEST` carve-out (F8/B8).
-//!
-//! Everything in this module operates on the **already-flattened error string**
-//! (`"OpenHuman API error (429 …): {…errorCode…}"`) because the typed provider
-//! error is collapsed to a `String` at the native-bus boundary before it
-//! reaches the channel classifier or the higher-layer re-report sites.
-
-use super::openhuman_backend_model;
-
-/// A recognised backend `errorCode` token (PR #870).
-///
-/// Unknown / future tokens are intentionally NOT represented here — they are
-/// still detected as "an `errorCode` is present" by
-/// [`extract_backend_error_code_token`] (so the Sentry golden rule still
-/// applies), but they fall through to the substring ladder for *display*
-/// classification rather than guessing a bucket.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum BackendErrorCode {
- RateLimited,
- UserInsufficientCredits,
- UpstreamUnavailable,
- ModelUnavailable,
- PayloadTooLarge,
- ContextLengthExceeded,
- BadRequest,
- InternalError,
-}
-
-impl BackendErrorCode {
- /// Parse a canonical (upper-cased) token into a known variant.
- pub fn from_token(token: &str) -> Option<Self> {
- match token {
- "RATE_LIMITED" => Some(Self::RateLimited),
- "USER_INSUFFICIENT_CREDITS" => Some(Self::UserInsufficientCredits),
- "UPSTREAM_UNAVAILABLE" => Some(Self::UpstreamUnavailable),
- "MODEL_UNAVAILABLE" => Some(Self::ModelUnavailable),
- "PAYLOAD_TOO_LARGE" => Some(Self::PayloadTooLarge),
- "CONTEXT_LENGTH_EXCEEDED" => Some(Self::ContextLengthExceeded),
- "BAD_REQUEST" => Some(Self::BadRequest),
- "INTERNAL_ERROR" => Some(Self::InternalError),
- _ => None,
- }
- }
-}
-
-/// Extract the raw (upper-cased) `errorCode` token from a flattened error
-/// string, or `None` when the body carries no `errorCode` field.
-///
-/// Returns the token **even if it is not a recognised [`BackendErrorCode`]** —
-/// the mere presence of an `errorCode` means the error came through the managed
-/// backend, which is what the Sentry golden rule keys on. Display
-/// classification narrows further via [`BackendErrorCode::from_token`].
-///
-/// The key match is case-insensitive (`"errorCode"` / `"errorcode"` /
-/// `"ERRORCODE"`) so a re-cased or re-serialised body still resolves; the
-/// extracted **value** is upper-cased before return so callers can compare
-/// against the canonical tokens regardless of how the backend cased them.
-pub fn extract_backend_error_code_token(err: &str) -> Option<String> {
- // `to_ascii_lowercase` is byte-length preserving (it only remaps ASCII
- // bytes in place), so a byte index found in `lower` is also valid in the
- // original `err` — we search the lowercased copy for the key but read the
- // value out of the original to keep the token's casing intact for the
- // (defensive) upper-casing below.
- let lower = err.to_ascii_lowercase();
- const KEY: &str = "\"errorcode\"";
- let key_idx = lower.find(KEY)?;
- let after_key = &err[key_idx + KEY.len()..];
- // Skip ONLY the JSON separators (whitespace + the colon) and then require a
- // quoted string value. A non-string value (`"errorCode":null` / a number)
- // must NOT be treated as a present code — otherwise the old
- // `trim_start_matches(|c| c != '"')` skipped past the `null` and latched
- // onto the *next* key's opening quote, returning a bogus token and wrongly
- // marking the error backend-owned (CodeRabbit). `strip_prefix('"')` returns
- // `None` for a non-string value, so we bail correctly.
- let after_colon = after_key.trim_start_matches(|c: char| c.is_ascii_whitespace() || c == ':');
- let stripped = after_colon.strip_prefix('"')?;
- let end = stripped.find('"')?;
- let token = stripped[..end].trim().to_ascii_uppercase();
- if token.is_empty() {
- None
- } else {
- Some(token)
- }
-}
-
-/// Whether the flattened error string is a **managed-backend** envelope (the
-/// `errorCode` contract only holds for errors that came through the OpenHuman
-/// managed backend, `"OpenHuman API error (...)"` /
-/// `"OpenHuman streaming API error (...)"`).
-///
-/// Load-bearing for the managed-vs-BYO distinction: a BYO / direct-provider
-/// body that merely happens to carry an `errorCode`-shaped field must NOT be
-/// treated as backend-owned (CodeRabbit). The provider HTTP emit sites gate on
-/// the known `provider` value instead; this helper is for the string-only
-/// downstream sites (`expected_error_kind`, `before_send`) that no longer carry
-/// the typed provider.
-pub fn is_managed_backend_envelope(err: &str) -> bool {
- let label = openhuman_backend_model::PROVIDER_LABEL.to_ascii_lowercase();
- let lower = err.to_ascii_lowercase();
- lower.contains(&format!("{label} api error"))
- || lower.contains(&format!("{label} streaming api error"))
-}
-
-/// Managed-backend Sentry-ownership decision for **string-only** call sites:
-/// the error must both be a managed-backend envelope AND carry a backend
-/// `errorCode` the backend owns. Wraps [`backend_error_code_skips_sentry`] with
-/// the [`is_managed_backend_envelope`] gate so a BYO payload that contains an
-/// `errorCode` token can't suppress FE Sentry.
-pub fn managed_error_skips_sentry(err: &str) -> bool {
- is_managed_backend_envelope(err) && backend_error_code_skips_sentry(err)
-}
-
-/// Parse a recognised [`BackendErrorCode`] out of a flattened error string.
-pub fn extract_backend_error_code(err: &str) -> Option<BackendErrorCode> {
- extract_backend_error_code_token(err).and_then(|t| BackendErrorCode::from_token(&t))
-}
-
-/// Whether the managed backend explicitly flagged this `BAD_REQUEST` as a
-/// **malformed** payload (the client built a request the backend couldn't
-/// parse), as opposed to a user-parameter rejection (an unsupported model /
-/// parameter combination the user can fix).
-///
-/// Contract consumed from backend PR #870: the malformed variant carries a
-/// `"malformed": true` flag alongside `"errorCode":"BAD_REQUEST"`. Only this
-/// variant keeps paging the FE Sentry (F8/B8) — every other `errorCode` (the
-/// user-param `BAD_REQUEST` included) is owned by the backend and must not
-/// double-report.
-pub fn body_flags_malformed(err: &str) -> bool {
- let lower = err.to_ascii_lowercase();
- const KEY: &str = "\"malformed\"";
- let Some(key_idx) = lower.find(KEY) else {
- return false;
- };
- // Whitespace-tolerant: accept `"malformed":true`, `"malformed": true`, and
- // pretty-printed `"malformed" : true` (CodeRabbit) — skip arbitrary
- // whitespace and the colon before matching the boolean literal.
- let after_key = &lower[key_idx + KEY.len()..];
- let after_colon = after_key.trim_start_matches(|c: char| c.is_ascii_whitespace() || c == ':');
- after_colon.starts_with("true")
-}
-
-/// Whether the error is a backend-flagged malformed `BAD_REQUEST` — the single
-/// `errorCode` case the FE *does* page (a client-built payload the backend
-/// rejected as unparseable).
-pub fn is_backend_malformed_bad_request(err: &str) -> bool {
- matches!(
- extract_backend_error_code(err),
- Some(BackendErrorCode::BadRequest)
- ) && body_flags_malformed(err)
-}
-
-/// Whether the `errorCode` names a limit the **client enforces before sending**,
-/// so a backend rejection means our pre-send guard leaked — a client-side bug
-/// worth paging, not expected user-state.
-///
-/// - `PAYLOAD_TOO_LARGE`: the client gates attachment size up front
-/// (`app/src/lib/attachments.ts` — per-image / per-file byte caps + a
-/// `too_large` reject), so an over-limit request reaching the backend means
-/// the aggregate slipped past those gates.
-/// - `CONTEXT_LENGTH_EXCEEDED`: the client manages context before send (the
-/// context stats state's `context_window`, `crates/openhuman-core/src/agent/context/stats.rs`),
-/// so a backend rejection means that fitting / trimming failed.
-///
-/// The backend does not ops-alert either (they are 4xx, not 500), so if the FE
-/// also suppressed them the guard leak would be invisible to everyone. Display
-/// classification is unchanged — the user still sees the actionable copy.
-pub fn is_backend_client_guard_leak(err: &str) -> bool {
- matches!(
- extract_backend_error_code(err),
- Some(BackendErrorCode::PayloadTooLarge | BackendErrorCode::ContextLengthExceeded)
- )
-}
-
-/// Sentry-ownership decision (F2 golden rule): a response carrying any backend
-/// `errorCode` must **not** page the FE — the backend owns it (it already
-/// paged) or it is expected user-state — *except* errors the **client** caused
-/// and so still page:
-/// - a backend-flagged malformed `BAD_REQUEST` (unparseable client payload), and
-/// - a client-guard-leak code (`PAYLOAD_TOO_LARGE` / `CONTEXT_LENGTH_EXCEEDED`)
-/// the client should have caught before sending — see
-/// [`is_backend_client_guard_leak`].
-///
-/// Shared by the provider HTTP layer (`api_error`), the higher-layer re-report
-/// classifier (`observability::expected_error_kind`), and the Sentry
-/// `before_send` defense-in-depth filter so the three layers can't drift.
-pub fn backend_error_code_skips_sentry(err: &str) -> bool {
- extract_backend_error_code_token(err).is_some()
- && !is_backend_malformed_bad_request(err)
- && !is_backend_client_guard_leak(err)
-}
-
-#[cfg(test)]
-#[path = "error_code_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/error_code_tests.rs b/crates/openhuman-core/src/inference/provider/error_code_tests.rs
deleted file mode 100644
index a7830dcb48..0000000000
--- a/crates/openhuman-core/src/inference/provider/error_code_tests.rs
+++ /dev/null
@@ -1,131 +0,0 @@
-use super::*;
-
-#[test]
-fn extracts_known_tokens() {
- let body = r#"OpenHuman API error (429 Too Many Requests): {"error":{"message":"slow down","errorCode":"RATE_LIMITED","retryAfter":30}}"#;
- assert_eq!(
- extract_backend_error_code_token(body).as_deref(),
- Some("RATE_LIMITED")
- );
- assert_eq!(
- extract_backend_error_code(body),
- Some(BackendErrorCode::RateLimited)
- );
-}
-
-#[test]
-fn extraction_is_case_insensitive_on_key_and_normalises_value() {
- let body = r#"{"ErrorCode":"rate_limited"}"#;
- assert_eq!(
- extract_backend_error_code_token(body).as_deref(),
- Some("RATE_LIMITED")
- );
-}
-
-#[test]
-fn unknown_token_is_present_but_not_recognised() {
- let body = r#"{"errorCode":"SOME_FUTURE_CODE"}"#;
- assert_eq!(
- extract_backend_error_code_token(body).as_deref(),
- Some("SOME_FUTURE_CODE")
- );
- assert_eq!(extract_backend_error_code(body), None);
- // Golden rule still applies: an unknown code is a managed error.
- assert!(backend_error_code_skips_sentry(body));
-}
-
-#[test]
-fn no_error_code_means_byo_path() {
- let body =
- r#"custom_openai API error (401 Unauthorized): {"error":{"message":"invalid api key"}}"#;
- assert_eq!(extract_backend_error_code_token(body), None);
- assert!(!backend_error_code_skips_sentry(body));
-}
-
-#[test]
-fn malformed_bad_request_is_the_one_paging_exception() {
- let malformed = r#"OpenHuman API error (400 Bad Request): {"error":{"errorCode":"BAD_REQUEST","malformed":true}}"#;
- assert!(is_backend_malformed_bad_request(malformed));
- assert!(!backend_error_code_skips_sentry(malformed));
-
- let malformed_spaced = r#"{"errorCode":"BAD_REQUEST","malformed": true,"message":"bad"}"#;
- assert!(is_backend_malformed_bad_request(malformed_spaced));
-}
-
-#[test]
-fn user_param_bad_request_does_not_page() {
- let user_param = r#"OpenHuman API error (400 Bad Request): {"error":{"errorCode":"BAD_REQUEST","message":"unsupported parameter"}}"#;
- assert!(!is_backend_malformed_bad_request(user_param));
- assert!(backend_error_code_skips_sentry(user_param));
-}
-
-#[test]
-fn client_guard_leak_codes_page_but_other_state_codes_do_not() {
- // PAYLOAD_TOO_LARGE / CONTEXT_LENGTH_EXCEEDED are limits the client
- // enforces before sending, so a backend rejection is a guard leak that
- // must page the FE — unlike genuinely backend-owned / user-state codes.
- let payload = r#"OpenHuman API error (413 Payload Too Large): {"error":{"errorCode":"PAYLOAD_TOO_LARGE","message":"too big"}}"#;
- assert!(is_backend_client_guard_leak(payload));
- assert!(!backend_error_code_skips_sentry(payload));
- assert!(!managed_error_skips_sentry(payload));
-
- let context = r#"OpenHuman API error (400 Bad Request): {"error":{"errorCode":"CONTEXT_LENGTH_EXCEEDED","message":"start a new chat"}}"#;
- assert!(is_backend_client_guard_leak(context));
- assert!(!backend_error_code_skips_sentry(context));
-
- // Contrast: these remain backend-owned / expected user-state -> suppress.
- let rate = r#"OpenHuman API error (429): {"error":{"errorCode":"RATE_LIMITED"}}"#;
- let credits =
- r#"OpenHuman API error (402): {"error":{"errorCode":"USER_INSUFFICIENT_CREDITS"}}"#;
- assert!(!is_backend_client_guard_leak(rate));
- assert!(backend_error_code_skips_sentry(rate));
- assert!(backend_error_code_skips_sentry(credits));
-}
-
-#[test]
-fn malformed_flag_without_bad_request_is_ignored() {
- // A stray `malformed` flag on a non-BAD_REQUEST code must not turn a
- // backend-owned error into a paging one.
- let body = r#"{"errorCode":"INTERNAL_ERROR","malformed":true}"#;
- assert!(!is_backend_malformed_bad_request(body));
- assert!(backend_error_code_skips_sentry(body));
-}
-
-#[test]
-fn non_string_error_code_is_not_treated_as_present_code() {
- // `"errorCode":null` (or a numeric value) must NOT latch onto the next
- // quoted key and return a bogus token (CodeRabbit).
- let body = r#"{"error":{"errorCode":null,"message":"x"}}"#;
- assert_eq!(extract_backend_error_code_token(body), None);
- assert!(!backend_error_code_skips_sentry(body));
-}
-
-#[test]
-fn malformed_flag_with_spaced_colon_is_detected() {
- // Pretty-printed JSON `"malformed" : true` must still flag malformed.
- let body =
- r#"OpenHuman API error (400 Bad Request): {"errorCode":"BAD_REQUEST","malformed" : true}"#;
- assert!(is_backend_malformed_bad_request(body));
- assert!(!managed_error_skips_sentry(body));
-}
-
-#[test]
-fn managed_envelope_gate_rejects_byo_payload_carrying_error_code() {
- // A BYO / direct-provider envelope that merely contains an
- // `errorCode`-shaped field must NOT be treated as backend-owned —
- // otherwise it would wrongly suppress FE Sentry.
- let byo = r#"custom_openai API error (429 Too Many Requests): {"error":{"errorCode":"RATE_LIMITED"}}"#;
- assert!(!is_managed_backend_envelope(byo));
- assert!(!managed_error_skips_sentry(byo));
-
- // The same body under the managed envelope IS backend-owned.
- let managed =
- r#"OpenHuman API error (429 Too Many Requests): {"error":{"errorCode":"RATE_LIMITED"}}"#;
- assert!(is_managed_backend_envelope(managed));
- assert!(managed_error_skips_sentry(managed));
-
- // The streaming envelope variant is also recognised.
- let managed_stream = r#"OpenHuman streaming API error (500): {"errorCode":"INTERNAL_ERROR"}"#;
- assert!(is_managed_backend_envelope(managed_stream));
- assert!(managed_error_skips_sentry(managed_stream));
-}
diff --git a/crates/openhuman-core/src/inference/provider/fallback_diagnostics.rs b/crates/openhuman-core/src/inference/provider/fallback_diagnostics.rs
deleted file mode 100644
index 8be894da95..0000000000
--- a/crates/openhuman-core/src/inference/provider/fallback_diagnostics.rs
+++ /dev/null
@@ -1,187 +0,0 @@
-//! Actionable diagnostics for background-workload provider fallback (#5146 §2.1).
-//!
-//! ## The user-visible bug
-//!
-//! A user configures a local Ollama model for chat, attaches an image, and gets
-//! `failed to read API key for slug 'anthropic'` — naming a provider they never
-//! configured. The same shape appears for embeddings, memory and the other
-//! background workloads.
-//!
-//! ## Why it happens, and why the routing itself is correct
-//!
-//! [`super::factory::provider_for_role`] deliberately routes the background
-//! roles (`vision`, `embeddings`, `memory`, `heartbeat`, `learning`,
-//! `subconscious`, `agentic`, `burst`) to the primary cloud provider when their
-//! own route is unset: they run tier-specific models (`vision-v1`,
-//! `summarization-v1`, …) that local runtimes and BYOK slugs do not serve. A
-//! user on a local chat model with a managed subscription genuinely wants those
-//! workloads on the cloud, so the fallback must stay.
-//!
-//! What was wrong is that the fallback was **unexplained**. When it landed on a
-//! provider with no usable credentials, the failure surfaced as a raw slug-level
-//! auth error with no hint that (a) this was a background role, (b) it fell back
-//! because the local model cannot serve that capability, or (c) what to do about
-//! it. That is the whole of the fix here: the routing decision is unchanged, the
-//! *explanation* is not.
-//!
-//! Everything in this module is a pure string/predicate function so the wording
-//! and the routing rules can be unit-tested without a live provider.
-//!
-//! Users who want no cloud egress at all already have
-//! [`crate::config::schema::PrivacyMode::LocalOnly`], enforced at the
-//! inference chokepoint by `factory::enforce_local_only_inference`. This module
-//! deliberately does not duplicate that gate.
-
-/// Workload roles that inherit the primary cloud provider when their own route
-/// is unset — the set [`super::factory::provider_for_role`] does **not** include
-/// in chat-tier BYOK inheritance.
-///
-/// `chat`, `reasoning` and `coding` are absent on purpose: they inherit a
-/// configured BYOK slug instead, so they never produce the confusion this
-/// module exists to explain.
-const CLOUD_FALLBACK_ROLES: &[&str] = &[
- "vision",
- "embeddings",
- "memory",
- "summarization",
- "heartbeat",
- "learning",
- "subconscious",
- "agentic",
- "burst",
-];
-
-/// Whether `role` falls through to the primary cloud provider when its own
-/// route is unset.
-pub(crate) fn role_falls_back_to_cloud(role: &str) -> bool {
- CLOUD_FALLBACK_ROLES.contains(&role.trim())
-}
-
-/// The capability a background role provides, phrased for a user-facing
-/// sentence ("… does not support **vision**").
-///
-/// `None` for roles whose name is not a capability the user would recognise as
-/// a model feature (`heartbeat`, `burst`, …); callers fall back to the role
-/// name itself.
-pub(crate) fn role_capability_label(role: &str) -> Option<&'static str> {
- match role.trim() {
- "vision" => Some("vision (image input)"),
- "embeddings" => Some("embeddings"),
- "memory" | "summarization" => Some("summarization"),
- "agentic" | "burst" => Some("agentic tool use"),
- _ => None,
- }
-}
-
-/// How a role is described in a sentence — the capability when it maps to one,
-/// otherwise the bare role name.
-fn role_phrase(role: &str) -> String {
- match role_capability_label(role) {
- Some(capability) => capability.to_string(),
- None => role.trim().to_string(),
- }
-}
-
-/// Explanation logged when a background role runs on the cloud because the
-/// user's chat model is local and cannot serve that capability.
-///
-/// This is the informational, everything-is-working case: the user has a cloud
-/// route available and the workload will succeed. It exists so the routing
-/// decision is visible in logs and support transcripts rather than silent.
-pub(crate) fn cloud_fallback_notice(
- role: &str,
- local_chat_provider: &str,
- resolved_provider: &str,
-) -> String {
- format!(
- "{} is running via your managed/cloud provider ('{}') because your local chat model \
- ('{}') does not serve this workload. Set {}_provider explicitly in Connections to \
- override.",
- capitalize_first(&role_phrase(role)),
- resolved_provider.trim(),
- local_chat_provider.trim(),
- override_knob_for_role(role),
- )
-}
-
-/// The config knob a user sets to override a role's route.
-///
-/// `burst` has no knob of its own — it rides the agentic route — so it points
-/// the user at `agentic_provider` rather than a setting that does not exist.
-pub(crate) fn override_knob_for_role(role: &str) -> &str {
- match role.trim() {
- "burst" => "agentic",
- "summarization" => "memory",
- other => other,
- }
-}
-
-/// Actionable error for the failing case: a background role fell back to a
-/// cloud slug whose credentials cannot be read.
-///
-/// Replaces the bare `failed to read API key for slug 'anthropic'` that named a
-/// provider the user never chose. Mentions the local chat model when there is
-/// one, because that is the missing half of the story.
-pub(crate) fn missing_provider_credentials_message(
- role: &str,
- slug: &str,
- local_chat_provider: Option<&str>,
-) -> String {
- let role = role.trim();
- let slug = slug.trim();
- match local_chat_provider {
- Some(local) if !local.trim().is_empty() => format!(
- "No usable credentials for '{slug}', which OpenHuman selected for the {} workload. \
- Your chat model is local ('{}') and does not serve this workload, so it fell back \
- to your cloud provider — but '{slug}' has no API key configured. Add a key for \
- '{slug}' in Connections → LLM, set {}_provider to a provider that is configured, \
- or enable the managed OpenHuman backend.",
- role_phrase(role),
- local.trim(),
- override_knob_for_role(role),
- ),
- _ => format!(
- "No usable credentials for '{slug}', which OpenHuman selected for the {} workload. \
- Add a key for '{slug}' in Connections → LLM, set {}_provider to a provider that is \
- configured, or enable the managed OpenHuman backend.",
- role_phrase(role),
- override_knob_for_role(role),
- ),
- }
-}
-
-/// Actionable message for the vision pre-flight: the active model cannot accept
-/// images, so the caller should say so instead of stripping the image and
-/// producing a confusing blind answer.
-pub(crate) fn local_vision_unsupported_message(model: &str) -> String {
- format!(
- "The selected local model ('{}') does not support vision (image input). Switch to a \
- vision-capable model such as llava:7b (`ollama pull llava:7b`), or set vision_provider \
- in Connections → LLM to a provider that supports images.",
- model.trim()
- )
-}
-
-/// Pure pre-flight for image input: `Ok(())` when `model` accepts images,
-/// `Err(actionable message)` when it does not.
-///
-/// Split from the call sites so the wording is unit-testable and identical
-/// everywhere an image is about to be dropped.
-pub(crate) fn vision_preflight(model: &str, config: &crate::config::Config) -> Result<(), String> {
- if crate::inference::model_context::model_supports_vision(model, config) {
- return Ok(());
- }
- Err(local_vision_unsupported_message(model))
-}
-
-fn capitalize_first(s: &str) -> String {
- let mut chars = s.chars();
- match chars.next() {
- Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
- None => String::new(),
- }
-}
-
-#[cfg(test)]
-#[path = "fallback_diagnostics_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/fallback_diagnostics_tests.rs b/crates/openhuman-core/src/inference/provider/fallback_diagnostics_tests.rs
deleted file mode 100644
index f92f044aa1..0000000000
--- a/crates/openhuman-core/src/inference/provider/fallback_diagnostics_tests.rs
+++ /dev/null
@@ -1,141 +0,0 @@
-use super::*;
-
-#[test]
-fn chat_tier_roles_do_not_fall_back_to_cloud() {
- // These inherit a BYOK slug instead; including them would attach the
- // "your local model can't serve this" explanation to the very roles the
- // user did configure locally.
- for role in ["chat", "reasoning", "coding"] {
- assert!(
- !role_falls_back_to_cloud(role),
- "{role} must not be treated as a cloud-fallback role"
- );
- }
-}
-
-#[test]
-fn background_roles_fall_back_to_cloud() {
- for role in [
- "vision",
- "embeddings",
- "memory",
- "summarization",
- "heartbeat",
- "learning",
- "subconscious",
- "agentic",
- "burst",
- ] {
- assert!(
- role_falls_back_to_cloud(role),
- "{role} must be treated as a cloud-fallback role"
- );
- }
-}
-
-#[test]
-fn unknown_role_does_not_fall_back() {
- assert!(!role_falls_back_to_cloud("not-a-role"));
- assert!(!role_falls_back_to_cloud(""));
-}
-
-#[test]
-fn role_falls_back_to_cloud_ignores_surrounding_whitespace() {
- assert!(role_falls_back_to_cloud(" vision "));
-}
-
-#[test]
-fn burst_points_at_the_agentic_knob_that_actually_exists() {
- // There is no `burst_provider`; telling the user to set one would be a
- // dead end.
- assert_eq!(override_knob_for_role("burst"), "agentic");
- assert_eq!(override_knob_for_role("summarization"), "memory");
- assert_eq!(override_knob_for_role("vision"), "vision");
-}
-
-#[test]
-fn fallback_notice_names_capability_local_model_and_override() {
- let msg = cloud_fallback_notice("vision", "ollama:gemma3:1b", "anthropic:claude-sonnet-4");
- assert!(msg.contains("Vision (image input)"), "got: {msg}");
- assert!(msg.contains("ollama:gemma3:1b"), "got: {msg}");
- assert!(msg.contains("anthropic:claude-sonnet-4"), "got: {msg}");
- assert!(msg.contains("vision_provider"), "got: {msg}");
-}
-
-#[test]
-fn fallback_notice_for_role_without_capability_label_uses_role_name() {
- let msg = cloud_fallback_notice("heartbeat", "ollama:gemma3:1b", "openhuman");
- assert!(msg.contains("Heartbeat"), "got: {msg}");
- assert!(msg.contains("heartbeat_provider"), "got: {msg}");
-}
-
-#[test]
-fn missing_credentials_message_explains_the_local_fallback() {
- let msg = missing_provider_credentials_message("vision", "anthropic", Some("ollama:gemma3:1b"));
- // The whole point of #5146 §2.1: the user must learn *why* a provider
- // they never configured is being asked for a key.
- assert!(msg.contains("anthropic"), "got: {msg}");
- assert!(msg.contains("ollama:gemma3:1b"), "got: {msg}");
- assert!(msg.contains("vision (image input)"), "got: {msg}");
- assert!(msg.contains("Connections"), "got: {msg}");
- assert!(msg.contains("vision_provider"), "got: {msg}");
-}
-
-#[test]
-fn missing_credentials_message_without_local_chat_omits_the_local_clause() {
- let msg = missing_provider_credentials_message("embeddings", "openai", None);
- assert!(msg.contains("openai"), "got: {msg}");
- assert!(msg.contains("embeddings"), "got: {msg}");
- assert!(
- !msg.contains("Your chat model is local"),
- "must not claim a local chat model when there is none: {msg}"
- );
-}
-
-#[test]
-fn missing_credentials_message_treats_blank_local_provider_as_absent() {
- let msg = missing_provider_credentials_message("embeddings", "openai", Some(" "));
- assert!(
- !msg.contains("Your chat model is local"),
- "blank provider string is not a local model: {msg}"
- );
-}
-
-#[test]
-fn vision_unsupported_message_names_model_and_a_concrete_remedy() {
- let msg = local_vision_unsupported_message("gemma3:1b");
- assert!(msg.contains("gemma3:1b"), "got: {msg}");
- assert!(msg.contains("llava:7b"), "got: {msg}");
- assert!(msg.contains("vision_provider"), "got: {msg}");
-}
-
-#[test]
-fn vision_preflight_allows_a_vision_capable_model() {
- use crate::config::schema::ModelRegistryEntry;
- let mut config = crate::config::Config::default();
- config.model_registry = vec![ModelRegistryEntry {
- id: "llava:7b".into(),
- provider: "ollama".into(),
- cost_per_1m_output: 0.0,
- vision: true,
- ..Default::default()
- }];
- assert!(vision_preflight("llava:7b", &config).is_ok());
-}
-
-#[test]
-fn vision_preflight_rejects_a_text_only_model_with_an_actionable_message() {
- let config = crate::config::Config::default();
- let err = vision_preflight("gemma3:1b", &config)
- .expect_err("a text-only model must fail the vision pre-flight");
- assert!(err.contains("gemma3:1b"), "got: {err}");
- assert!(err.contains("llava:7b"), "got: {err}");
-}
-
-#[test]
-fn vision_preflight_allows_the_managed_vision_tier() {
- // `vision-v1` is multimodal per `oh_tier_supports_vision`; the
- // pre-flight must not fire for the managed vision sub-agent.
- let config = crate::config::Config::default();
- assert!(vision_preflight("vision-v1", &config).is_ok());
-}
diff --git a/crates/openhuman-core/src/inference/provider/openai_codex_tests.rs b/crates/openhuman-core/src/inference/provider/openai_codex_tests.rs
deleted file mode 100644
index f0ef7e7993..0000000000
--- a/crates/openhuman-core/src/inference/provider/openai_codex_tests.rs
+++ /dev/null
@@ -1,114 +0,0 @@
-use super::*;
-use tempfile::tempdir;
-
-struct EnvVarGuard {
- key: &'static str,
- previous: Option<std::ffi::OsString>,
-}
-
-impl EnvVarGuard {
- fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
- let previous = std::env::var_os(key);
- unsafe { std::env::set_var(key, value) };
- Self { key, previous }
- }
-
- fn remove(key: &'static str) -> Self {
- let previous = std::env::var_os(key);
- unsafe { std::env::remove_var(key) };
- Self { key, previous }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- unsafe {
- match self.previous.take() {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
-
-#[test]
-fn client_version_prefers_explicit_env_override() {
- let _env_lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let _version = EnvVarGuard::set("OPENAI_CODEX_CLIENT_VERSION", " 0.200.0 ");
- let _codex_home = EnvVarGuard::remove("CODEX_HOME");
-
- assert_eq!(openai_codex_client_version(), "0.200.0");
-}
-
-#[test]
-fn client_version_reads_codex_models_cache() {
- let _env_lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let tmp = tempdir().unwrap();
- std::fs::write(
- tmp.path().join("models_cache.json"),
- serde_json::json!({ "client_version": "0.137.0", "models": [] }).to_string(),
- )
- .unwrap();
- let _version = EnvVarGuard::remove("OPENAI_CODEX_CLIENT_VERSION");
- let _codex_home = EnvVarGuard::set("CODEX_HOME", tmp.path());
-
- assert_eq!(openai_codex_client_version(), "0.137.0");
-}
-
-#[test]
-fn client_version_models_cache_precedes_version_file() {
- let _env_lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let tmp = tempdir().unwrap();
- std::fs::write(
- tmp.path().join("models_cache.json"),
- serde_json::json!({ "client_version": "0.137.0", "models": [] }).to_string(),
- )
- .unwrap();
- std::fs::write(
- tmp.path().join("version.json"),
- serde_json::json!({ "latest_version": "0.140.0" }).to_string(),
- )
- .unwrap();
- let _version = EnvVarGuard::remove("OPENAI_CODEX_CLIENT_VERSION");
- let _codex_home = EnvVarGuard::set("CODEX_HOME", tmp.path());
-
- assert_eq!(openai_codex_client_version(), "0.137.0");
-}
-
-#[test]
-fn client_version_falls_back_to_codex_version_file() {
- let _env_lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let tmp = tempdir().unwrap();
- std::fs::write(
- tmp.path().join("version.json"),
- serde_json::json!({ "latest_version": "0.140.0" }).to_string(),
- )
- .unwrap();
- let _version = EnvVarGuard::remove("OPENAI_CODEX_CLIENT_VERSION");
- let _codex_home = EnvVarGuard::set("CODEX_HOME", tmp.path());
-
- assert_eq!(openai_codex_client_version(), "0.140.0");
-}
-
-#[test]
-fn client_version_uses_default_when_codex_files_are_missing() {
- let _env_lock = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let tmp = tempdir().unwrap();
- let _version = EnvVarGuard::remove("OPENAI_CODEX_CLIENT_VERSION");
- let _codex_home = EnvVarGuard::set("CODEX_HOME", tmp.path());
-
- assert_eq!(
- openai_codex_client_version(),
- OPENAI_CODEX_DEFAULT_CLIENT_VERSION
- );
-}
diff --git a/crates/openhuman-core/src/inference/provider/ops/sanitize.rs b/crates/openhuman-core/src/inference/provider/ops/sanitize.rs
deleted file mode 100644
index 78497e5a1f..0000000000
--- a/crates/openhuman-core/src/inference/provider/ops/sanitize.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-use crate::util;
-
-pub const MAX_API_ERROR_CHARS: usize = 200;
-const TRANSPORT_ERROR_MAX_CHARS: usize = 1200;
-
-fn is_secret_char(c: char) -> bool {
- c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':')
-}
-
-fn token_end(input: &str, from: usize) -> usize {
- let mut end = from;
- for (i, c) in input[from..].char_indices() {
- if is_secret_char(c) {
- end = from + i + c.len_utf8();
- } else {
- break;
- }
- }
- end
-}
-
-/// Scrub known secret-like token prefixes from provider error strings.
-pub fn scrub_secret_patterns(input: &str) -> String {
- const PREFIXES: [&str; 7] = [
- "sk-",
- "xoxb-",
- "xoxp-",
- "ghp_",
- "gho_",
- "ghu_",
- "github_pat_",
- ];
-
- let mut scrubbed = input.to_string();
-
- for prefix in PREFIXES {
- let mut search_from = 0;
- loop {
- let Some(rel) = scrubbed[search_from..].find(prefix) else {
- break;
- };
-
- let start = search_from + rel;
- let content_start = start + prefix.len();
- let end = token_end(&scrubbed, content_start);
-
- if end == content_start {
- search_from = content_start;
- continue;
- }
-
- scrubbed.replace_range(start..end, "[REDACTED]");
- search_from = start + "[REDACTED]".len();
- }
- }
-
- scrubbed
-}
-
-/// Sanitize API error text by scrubbing secrets and truncating length.
-pub fn sanitize_api_error(input: &str) -> String {
- let scrubbed = scrub_secret_patterns(input);
- util::truncate_with_ellipsis(&scrubbed, MAX_API_ERROR_CHARS)
-}
-
-/// Full `source()` chain for connection / TLS failures (scrubbed, longer than API body snippets).
-pub fn format_error_chain(err: &dyn std::error::Error) -> String {
- let mut parts: Vec<String> = vec![err.to_string()];
- let mut src = std::error::Error::source(err);
- while let Some(e) = src {
- parts.push(e.to_string());
- src = std::error::Error::source(e);
- }
- let joined = parts.join(" | ");
- let scrubbed = scrub_secret_patterns(&joined);
- util::truncate_with_suffix(&scrubbed, TRANSPORT_ERROR_MAX_CHARS, "…")
-}
-
-/// Cause chain from [`anyhow::Error`] (e.g. responses fallback), scrubbed and length-limited.
-pub fn format_anyhow_chain(err: &anyhow::Error) -> String {
- let joined = err
- .chain()
- .map(|e| e.to_string())
- .collect::<Vec<_>>()
- .join(" | ");
- let scrubbed = scrub_secret_patterns(&joined);
- util::truncate_with_suffix(&scrubbed, TRANSPORT_ERROR_MAX_CHARS, "…")
-}
diff --git a/crates/openhuman-core/src/inference/sentiment.rs b/crates/openhuman-core/src/inference/sentiment.rs
deleted file mode 100644
index 28c49f57af..0000000000
--- a/crates/openhuman-core/src/inference/sentiment.rs
+++ /dev/null
@@ -1,148 +0,0 @@
-//! Emotion / sentiment analysis via the bundled local AI model.
-
-use crate::config::Config;
-use crate::inference::local as local_ai;
-use crate::rpc::RpcOutcome;
-
-/// Result of sentiment / emotion analysis on a user message.
-#[derive(Debug, serde::Serialize)]
-pub struct SentimentResult {
- /// Primary emotion label.
- /// One of: joy, sadness, anger, surprise, fear, disgust, neutral.
- pub emotion: String,
- /// Overall valence: positive, negative, or neutral.
- pub valence: String,
- /// Model's self-reported confidence (0.0–1.0).
- pub confidence: f32,
-}
-
-impl SentimentResult {
- /// Safe default when analysis is skipped or parsing fails.
- fn neutral() -> Self {
- Self {
- emotion: "neutral".to_string(),
- valence: "neutral".to_string(),
- confidence: 1.0,
- }
- }
-}
-
-/// Known emotion labels the model is expected to produce.
-const VALID_EMOTIONS: &[&str] = &[
- "joy", "sadness", "anger", "surprise", "fear", "disgust", "neutral",
-];
-
-/// Known valence labels.
-const VALID_VALENCES: &[&str] = &["positive", "negative", "neutral"];
-
-/// Ask the local model to classify the emotion and sentiment of a user
-/// message. Designed to be called periodically (e.g. every hour), not on
-/// every single message. Lightweight: ~8 output tokens, fire-and-forget safe.
-pub async fn local_ai_analyze_sentiment(
- config: &Config,
- message: &str,
-) -> Result<RpcOutcome<SentimentResult>, String> {
- tracing::debug!(
- msg_len = message.len(),
- "[local_ai:sentiment] evaluating sentiment"
- );
-
- if message.trim().is_empty() {
- return Ok(RpcOutcome::single_log(
- SentimentResult::neutral(),
- "empty message — neutral sentiment",
- ));
- }
-
- let service = local_ai::global(config);
- let status = service.status();
- if !matches!(status.state.as_str(), "ready") {
- tracing::debug!("[local_ai:sentiment] local model not ready, returning neutral");
- return Ok(RpcOutcome::single_log(
- SentimentResult::neutral(),
- "local model not ready",
- ));
- }
-
- let prompt = format!(
- "Classify the emotion and sentiment of this user message.\n\
- Reply with EXACTLY three words separated by spaces:\n\
- EMOTION VALENCE CONFIDENCE\n\
- Where EMOTION is one of: joy, sadness, anger, surprise, fear, disgust, neutral\n\
- VALENCE is one of: positive, negative, neutral\n\
- CONFIDENCE is a number from 0.0 to 1.0\n\n\
- User message: {message}"
- );
-
- let output = service.prompt(config, &prompt, Some(8), true).await;
-
- let result = match output {
- Ok(raw) => {
- let trimmed = raw.trim().to_lowercase();
- tracing::debug!(
- raw = %trimmed,
- "[local_ai:sentiment] model response"
- );
- parse_sentiment_response(&trimmed)
- }
- Err(e) => {
- tracing::debug!(error = %e, "[local_ai:sentiment] inference failed, returning neutral");
- SentimentResult::neutral()
- }
- };
-
- tracing::debug!(
- emotion = %result.emotion,
- valence = %result.valence,
- confidence = result.confidence,
- "[local_ai:sentiment] analysis complete"
- );
- Ok(RpcOutcome::single_log(
- result,
- "sentiment analysis completed",
- ))
-}
-
-/// Parse the model's 3-word response into a `SentimentResult`.
-/// Falls back to neutral on any parsing error.
-fn parse_sentiment_response(text: &str) -> SentimentResult {
- let parts: Vec<&str> = text.split_whitespace().collect();
- if parts.len() < 3 {
- tracing::debug!(
- parts = parts.len(),
- "[local_ai:sentiment] unexpected token count, falling back to neutral"
- );
- return SentimentResult::neutral();
- }
-
- let emotion = parts[0].to_string();
- let valence = parts[1].to_string();
- let confidence: f32 = parts[2].parse().unwrap_or(0.5);
-
- // Validate labels, fall back to neutral for garbage
- let emotion = if VALID_EMOTIONS.contains(&emotion.as_str()) {
- emotion
- } else {
- tracing::debug!(raw = %emotion, "[local_ai:sentiment] unknown emotion label, defaulting to neutral");
- "neutral".to_string()
- };
-
- let valence = if VALID_VALENCES.contains(&valence.as_str()) {
- valence
- } else {
- tracing::debug!(raw = %valence, "[local_ai:sentiment] unknown valence label, defaulting to neutral");
- "neutral".to_string()
- };
-
- let confidence = confidence.clamp(0.0, 1.0);
-
- SentimentResult {
- emotion,
- valence,
- confidence,
- }
-}
-
-#[cfg(test)]
-#[path = "sentiment_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/sentiment_tests.rs b/crates/openhuman-core/src/inference/sentiment_tests.rs
deleted file mode 100644
index 260bfb66c4..0000000000
--- a/crates/openhuman-core/src/inference/sentiment_tests.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-use super::*;
-
-#[test]
-fn parse_valid_response() {
- let r = parse_sentiment_response("joy positive 0.9");
- assert_eq!(r.emotion, "joy");
- assert_eq!(r.valence, "positive");
- assert!((r.confidence - 0.9).abs() < 0.01);
-}
-
-#[test]
-fn parse_valid_negative() {
- let r = parse_sentiment_response("anger negative 0.75");
- assert_eq!(r.emotion, "anger");
- assert_eq!(r.valence, "negative");
- assert!((r.confidence - 0.75).abs() < 0.01);
-}
-
-#[test]
-fn parse_unknown_emotion_falls_back() {
- let r = parse_sentiment_response("excited positive 0.8");
- assert_eq!(r.emotion, "neutral");
- assert_eq!(r.valence, "positive");
-}
-
-#[test]
-fn parse_too_few_tokens() {
- let r = parse_sentiment_response("joy");
- assert_eq!(r.emotion, "neutral");
- assert_eq!(r.valence, "neutral");
-}
-
-#[test]
-fn parse_bad_confidence() {
- let r = parse_sentiment_response("sadness negative abc");
- assert_eq!(r.emotion, "sadness");
- assert_eq!(r.valence, "negative");
- assert!((r.confidence - 0.5).abs() < 0.01);
-}
-
-#[test]
-fn parse_clamps_confidence() {
- let r = parse_sentiment_response("joy positive 2.5");
- assert!((r.confidence - 1.0).abs() < 0.01);
-}
-
-#[test]
-fn parse_empty_returns_neutral() {
- let r = parse_sentiment_response("");
- assert_eq!(r.emotion, "neutral");
- assert_eq!(r.valence, "neutral");
-}
-
-#[test]
-fn parse_clamps_negative_confidence_to_zero() {
- let r = parse_sentiment_response("joy positive -0.5");
- assert!(r.confidence >= 0.0 && r.confidence <= 1.0);
- assert!((r.confidence - 0.0).abs() < 0.01);
-}
-
-#[test]
-fn parse_unknown_valence_falls_back_to_neutral() {
- let r = parse_sentiment_response("joy mixed 0.8");
- assert_eq!(r.emotion, "joy");
- assert_eq!(r.valence, "neutral");
-}
-
-#[test]
-fn parse_accepts_all_documented_emotions() {
- for e in [
- "joy", "sadness", "anger", "surprise", "fear", "disgust", "neutral",
- ] {
- let r = parse_sentiment_response(&format!("{e} positive 0.5"));
- assert_eq!(r.emotion, e, "emotion `{e}` should be accepted verbatim");
- }
-}
-
-#[test]
-fn parse_accepts_all_documented_valences() {
- for v in ["positive", "negative", "neutral"] {
- let r = parse_sentiment_response(&format!("joy {v} 0.5"));
- assert_eq!(r.valence, v, "valence `{v}` should be accepted verbatim");
- }
-}
-
-#[test]
-fn neutral_constructor_returns_documented_defaults() {
- let r = SentimentResult::neutral();
- assert_eq!(r.emotion, "neutral");
- assert_eq!(r.valence, "neutral");
- assert!((r.confidence - 1.0).abs() < 0.01);
-}
-
-#[tokio::test]
-async fn local_ai_analyze_sentiment_returns_neutral_for_empty_message() {
- let config = Config::default();
- let outcome = local_ai_analyze_sentiment(&config, " ").await.unwrap();
- assert_eq!(outcome.value.emotion, "neutral");
- assert_eq!(outcome.value.valence, "neutral");
- assert!(outcome.logs.iter().any(|l| l.contains("empty message")));
-}