The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(config): inline cloud provider, local AI, and scheduler gate schemas
Steven Enamakel3957cdf7246e
diff --git a/crates/openhuman-core/src/config/schema/cloud_providers.rs b/crates/openhuman-core/src/config/schema/cloud_providers.rsindex 79e57bc824..0d77e9da2b 100644--- a/crates/openhuman-core/src/config/schema/cloud_providers.rs+++ b/crates/openhuman-core/src/config/schema/cloud_providers.rs@@ -1,15 +1,593 @@//! Cloud provider credential schema.//!-//! Definitions moved to [`tinymemory_api::host`] — the extracted memory-//! subsystem reads the provider table when it resolves an embedding backend.-//! Re-exported here so existing paths keep resolving.+//! Each entry in `Config::cloud_providers` represents one configured LLM+//! backend. Providers are keyed by a user-chosen `slug` (e.g. `"openai"`,+//! `"my-deepseek"`). The factory in `inference::provider::factory`+//! resolves workload-to-provider strings against this list at runtime using+//! the grammar `"<slug>:<model>"`.//!-//! Like [`super::local_ai`], this is a host-owned section parked in the memory-//! contract crate for mechanical reasons, not because memory owns it.--pub use tinymemory_api::host::cloud_providers::{- builtin_cloud_supports_responses_api, endpoint_host, endpoint_host_is_chat_completions_only,- generate_provider_id, host_is_builtin_cloud_provider, is_builtin_cloud_slug, is_slug_reserved,- migrate_legacy_fields, AuthStyle, BuiltinCloudProvider, CloudProviderCreds, CloudProviderType,- BUILTIN_CLOUD_PROVIDERS,-};+//! Legacy configs that use `type`/`default_model` are migrated in-memory on+//! load via `migrate_legacy_fields()`.++use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct BuiltinCloudProvider {+ pub slug: &'static str,+ pub label: &'static str,+ pub endpoint: &'static str,+ pub auth_style: AuthStyle,+}++pub const BUILTIN_CLOUD_PROVIDERS: &[BuiltinCloudProvider] = &[+ BuiltinCloudProvider {+ slug: "openhuman",+ label: "OpenHuman",+ endpoint: "https://api.openhuman.ai/v1",+ auth_style: AuthStyle::OpenhumanJwt,+ },+ BuiltinCloudProvider {+ slug: "openai",+ label: "OpenAI",+ endpoint: "https://api.openai.com/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "anthropic",+ label: "Anthropic",+ endpoint: "https://api.anthropic.com/v1",+ auth_style: AuthStyle::Anthropic,+ },+ BuiltinCloudProvider {+ slug: "openrouter",+ label: "OpenRouter",+ endpoint: "https://openrouter.ai/api/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "orcarouter",+ label: "OrcaRouter",+ endpoint: "https://api.orcarouter.ai/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "gmi",+ label: "GMI",+ endpoint: "https://api.gmi-serving.com/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "fireworks",+ label: "Fireworks",+ endpoint: "https://api.fireworks.ai/inference/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "moonshot",+ label: "Kimi (Moonshot)",+ endpoint: "https://api.moonshot.ai/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "groq",+ label: "Groq",+ endpoint: "https://api.groq.com/openai/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "mistral",+ label: "Mistral",+ endpoint: "https://api.mistral.ai/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "deepseek",+ label: "DeepSeek",+ endpoint: "https://api.deepseek.com/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "together",+ label: "Together AI",+ endpoint: "https://api.together.xyz/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "google",+ label: "Google Gemini",+ endpoint: "https://generativelanguage.googleapis.com/v1beta/openai",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "cerebras",+ label: "Cerebras",+ endpoint: "https://api.cerebras.ai/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "xai",+ label: "xAI",+ endpoint: "https://api.x.ai/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "huggingface",+ label: "Hugging Face",+ endpoint: "https://router.huggingface.co/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "nvidia",+ label: "NVIDIA",+ endpoint: "https://integrate.api.nvidia.com/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "zai",+ label: "Z.AI",+ endpoint: "https://api.z.ai/api/paas/v4",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "minimax",+ label: "MiniMax",+ // MiniMax exposes a full OpenAI-compatible surface at `/v1`+ // (`/v1/chat/completions`, `/v1/models`). The previous `/anthropic`+ // base + Anthropic auth pointed at MiniMax's Messages-protocol API,+ // which OpenHuman does not speak — it only builds OpenAI-style+ // `/chat/completions` and `/models` — so both chat and model-listing+ // 404'd (`/anthropic/chat/completions`, `/anthropic/models`). The+ // 404 on model-listing was Sentry TAURI-RUST-8X3. Use the `/v1`+ // OpenAI surface with Bearer auth so both paths resolve.+ endpoint: "https://api.minimax.io/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "stepfun",+ label: "StepFun",+ endpoint: "https://api.stepfun.ai/step_plan/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "kilocode",+ label: "Kilo Code",+ endpoint: "https://api.kilo.ai/api/gateway",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "deepinfra",+ label: "DeepInfra",+ endpoint: "https://api.deepinfra.com/v1/openai",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "novita",+ label: "Novita",+ endpoint: "https://api.novita.ai/v3/openai",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "venice",+ label: "Venice",+ endpoint: "https://api.venice.ai/api/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "vercel-ai-gateway",+ label: "Vercel AI Gateway",+ endpoint: "https://ai-gateway.vercel.sh/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "sumopod",+ label: "SumoPod",+ endpoint: "https://ai.sumopod.com/v1",+ auth_style: AuthStyle::Bearer,+ },+ BuiltinCloudProvider {+ slug: "modelscope",+ label: "ModelScope",+ endpoint: "https://api-inference.modelscope.cn/v1",+ auth_style: AuthStyle::Bearer,+ },+];++fn builtin_cloud_provider(type_str: &str) -> Option<&'static BuiltinCloudProvider> {+ BUILTIN_CLOUD_PROVIDERS+ .iter()+ .find(|provider| provider.slug == type_str)+}++/// Whether `slug` matches a built-in cloud provider preset.+///+/// The chat factory uses this to decide capability defaults (e.g. whether the+/// provider exposes the OpenAI Responses API) only for providers we ship and+/// therefore know the API surface of. Custom / user-defined slugs are treated+/// as unknown and keep the permissive defaults.+pub fn is_builtin_cloud_slug(slug: &str) -> bool {+ builtin_cloud_provider(slug).is_some()+}++/// Whether a built-in cloud provider exposes the OpenAI **Responses API**+/// (`/v1/responses`).+///+/// Only OpenAI's first-party endpoint serves `/responses`; every other built-in+/// preset (DeepSeek, Groq, Mistral, Fireworks, …) is chat-completions-only.+/// Enabling the chat-completions-404 → `/responses` fallback for those+/// guarantees a second 404 against an endpoint that does not exist, which floods+/// Sentry with an empty-body `"<provider> Responses API error:"` event+/// (TAURI-RUST-5EN — same class as the local-provider TAURI-RUST-59Y fix). The+/// factory consults this to build chat-completions-only built-ins with+/// `new_no_responses_fallback`.+///+/// Custom / unknown slugs are intentionally NOT covered here (see+/// [`is_builtin_cloud_slug`]): a user-defined OpenAI-compatible endpoint may be+/// a genuine OpenAI proxy that does support `/responses`, so the factory keeps+/// the fallback for those.+pub fn builtin_cloud_supports_responses_api(slug: &str) -> bool {+ matches!(slug, "openai")+}++/// Extract the lowercased authority host from an endpoint URL, dropping the+/// scheme, any userinfo, the port, and the path. Returns `None` when no host+/// can be parsed. Tolerant of a missing scheme and of IPv6 literals.+pub fn endpoint_host(endpoint: &str) -> Option<String> {+ let s = endpoint.trim();+ // Drop the scheme (`https://…`); tolerate a bare `host/path` form.+ let after_scheme = s.split_once("://").map(|(_, rest)| rest).unwrap_or(s);+ // The authority ends at the first path / query / fragment delimiter.+ let authority = after_scheme+ .split(['/', '?', '#'])+ .next()+ .unwrap_or(after_scheme);+ // Strip any `user:pass@` userinfo prefix.+ let host_port = authority+ .rsplit_once('@')+ .map(|(_, host)| host)+ .unwrap_or(authority);+ // Strip the port, handling bracketed IPv6 literals (`[::1]:8080`).+ let host = if let Some(rest) = host_port.strip_prefix('[') {+ rest.split_once(']').map(|(h, _)| h).unwrap_or(rest)+ } else {+ host_port+ .rsplit_once(':')+ .map(|(h, _)| h)+ .unwrap_or(host_port)+ };+ let host = host.trim().to_ascii_lowercase();+ (!host.is_empty()).then_some(host)+}++/// Whether `host` is the authority host of any built-in cloud **inference**+/// provider (e.g. `openrouter.ai`, `api.openai.com`, `api.groq.com`).+///+/// Derived entirely from [`BUILTIN_CLOUD_PROVIDERS`] so the set stays in sync+/// with the provider registry. `host` is compared case-insensitively against+/// each preset's [`endpoint_host`].+///+/// # Why this exists+///+/// `config.api_url` is overloaded: it is the chat/inference endpoint, but+/// `api::config::effective_backend_api_url` also reuses it as the+/// OpenHuman **backend** base for team/billing/auth calls. A BYO user who+/// points `api_url` at a provider's canonical base (`https://openrouter.ai/api/v1`)+/// would otherwise have every backend domain call routed to the inference host+/// → 400/404 (TAURI-RUST-HW1: 4932 `GET /teams/me/usage` 400s from `openrouter.ai`).+/// The backend-URL resolver uses this to treat such hosts as non-backend and+/// fall back to the default backend chain — the cloud analogue of the local-AI+/// guard that fixed the Ollama case (OPENHUMAN-TAURI-51/-80/-7Z).+pub fn host_is_builtin_cloud_provider(host: &str) -> bool {+ let host = host.trim().to_ascii_lowercase();+ if host.is_empty() {+ return false;+ }+ BUILTIN_CLOUD_PROVIDERS+ .iter()+ .any(|p| endpoint_host(p.endpoint).as_deref() == Some(host.as_str()))+}++/// Whether an endpoint **host** is a known cloud host that does NOT serve the+/// OpenAI Responses API (`/v1/responses`) — i.e. it is chat-completions-only,+/// regardless of which user slug points at it.+///+/// Derived entirely from [`BUILTIN_CLOUD_PROVIDERS`]: a host is chat-only when+/// some built-in preset uses it AND no preset at that host advertises the+/// Responses API (only OpenAI's `api.openai.com` does). This closes the+/// custom-slug gap behind the builtin-slug gate+/// ([`builtin_cloud_supports_responses_api`]): a user slug pointed at, e.g.,+/// `integrate.api.nvidia.com` must never attempt `/responses` (TAURI-RUST-5A1),+/// while a genuinely unknown proxy host keeps the permissive fallback so a real+/// OpenAI proxy still gets `/responses`.+pub fn endpoint_host_is_chat_completions_only(endpoint: &str) -> bool {+ let Some(host) = endpoint_host(endpoint) else {+ return false;+ };+ let mut matched_chat_only = false;+ for provider in BUILTIN_CLOUD_PROVIDERS {+ if endpoint_host(provider.endpoint).as_deref() == Some(host.as_str()) {+ if builtin_cloud_supports_responses_api(provider.slug) {+ // A Responses-capable built-in lives at this host → not chat-only.+ return false;+ }+ matched_chat_only = true;+ }+ }+ matched_chat_only+}++/// Authentication header style for a cloud provider.+///+/// Wire format is lowercase (e.g. `"bearer"`). Determines which HTTP headers+/// are attached when calling the provider's API.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]+#[serde(rename_all = "lowercase")]+pub enum AuthStyle {+ /// OpenAI-compatible: `Authorization: Bearer <key>`+ #[default]+ Bearer,+ /// Anthropic: `x-api-key: <key>` + `anthropic-version: 2023-06-01`+ Anthropic,+ /// OpenHuman session JWT (injected by the backend provider, not stored here).+ OpenhumanJwt,+ /// No auth header — e.g. local Ollama.+ None,+}++impl AuthStyle {+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Bearer => "bearer",+ Self::Anthropic => "anthropic",+ Self::OpenhumanJwt => "openhuman_jwt",+ Self::None => "none",+ }+ }+}++/// Endpoint config for one cloud LLM provider.+///+/// **Note on secrets**: API keys are NOT stored on this struct. They live in+/// `auth-profiles.json` via `security::credentials::AuthService`,+/// keyed by `provider:<slug>` (falling back to bare `<slug>` for legacy+/// entries). The factory looks up the token at call time via+/// `inference::provider::factory::auth_key_for_slug`.+///+/// ## Back-compat+///+/// Old configs may have `type` and `default_model` fields. These are+/// tolerated on read (via `legacy_type` / `default_model`) but never written.+/// Call `migrate_legacy_fields()` after deserialising.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]+#[serde(default)]+pub struct CloudProviderCreds {+ /// Opaque stable id, e.g. `"p_openai_a8c3f"`. Never shown in the UI.+ /// Generated once by [`generate_provider_id`] and never changes.+ pub id: String,+ /// Routing key chosen by the user or seeded from the legacy type.+ /// Lower-case alphanumeric + `-`. Must be unique per config and not in the+ /// reserved list (see [`is_slug_reserved`]). The factory resolves+ /// `"<slug>:<model>"` strings against this field.+ pub slug: String,+ /// Human-readable display label, supplied by the frontend. Not used in routing.+ pub label: String,+ /// OpenAI-compatible base URL (`/models`, `/chat/completions` etc. are appended).+ pub endpoint: String,+ /// Authentication header style.+ pub auth_style: AuthStyle,++ // ── Back-compat: old `type` field ───────────────────────────────────────+ /// Legacy discriminator written by older builds. Read-only; never emitted.+ #[serde(rename = "type", default, skip_serializing)]+ pub legacy_type: Option<String>,++ // ── Back-compat: old `default_model` field ──────────────────────────────+ /// Legacy default model written by older builds. Read-only; never emitted.+ #[serde(default, skip_serializing)]+ pub default_model: Option<String>,+}++impl Default for CloudProviderCreds {+ fn default() -> Self {+ Self {+ id: String::new(),+ slug: String::new(),+ label: String::new(),+ endpoint: String::new(),+ auth_style: AuthStyle::Bearer,+ legacy_type: None,+ default_model: None,+ }+ }+}++/// Reserved slugs that may not be used for user-configured providers.+/// These are sentinels in the factory's routing grammar.+///+/// `ollama` is deliberately NOT reserved: the AI settings panel registers an+/// `ollama` `cloud_providers` entry so `list_configured_models` can resolve+/// the user's chosen base_url for the model dropdown. The factory's chat+/// routing is unaffected — the `ollama:<model>` prefix branch in+/// `factory::create_chat_provider_from_string` fires before the+/// `<slug>:<model>` cloud-provider lookup, so a synthetic `ollama` entry+/// never reaches `make_cloud_provider_by_slug`. When no `cloud_providers`+/// row exists (config drift, upgrade from a build that only persisted+/// `config.local_ai.base_url`, flush-vs-probe race),+/// `inference::provider::ops::list_configured_models`+/// falls back to a synthetic entry via `synthesize_local_runtime_entry`+/// (Sentry TAURI-RUST-28Z fix). The same fallback applies to `lmstudio`.+pub fn is_slug_reserved(s: &str) -> bool {+ matches!(s.trim(), "" | "cloud" | "openhuman" | "pid")+}++/// Apply legacy field migration in-place.+///+/// Idempotent: only fills in empty fields from the legacy `type`/`default_model`+/// values. Safe to call on already-migrated entries.+pub fn migrate_legacy_fields(entry: &mut CloudProviderCreds) {+ let legacy_type = entry.legacy_type.clone().unwrap_or_default();+ let lt = legacy_type.trim();++ // Slug from legacy type when missing.+ if entry.slug.is_empty() && !lt.is_empty() {+ entry.slug = lt.to_string();+ log::debug!(+ "[config][cloud_providers] migrated slug from legacy type='{}' id={}",+ lt,+ entry.id+ );+ }++ // Label from static map when missing.+ if entry.label.is_empty() {+ entry.label = legacy_label_for(if entry.slug.is_empty() {+ lt+ } else {+ &entry.slug+ })+ .to_string();+ log::debug!(+ "[config][cloud_providers] migrated label='{}' for slug='{}' id={}",+ entry.label,+ entry.slug,+ entry.id+ );+ }++ // Endpoint from legacy defaults when missing.+ if entry.endpoint.is_empty() {+ let ep = legacy_default_endpoint(lt);+ if !ep.is_empty() {+ entry.endpoint = ep.to_string();+ }+ }++ // Auth style from legacy type when still at default Bearer.+ if entry.auth_style == AuthStyle::Bearer {+ if let Some(provider) = builtin_cloud_provider(lt) {+ entry.auth_style = provider.auth_style;+ }+ }+}++/// Map a legacy type string (or slug) to a human-readable label.+fn legacy_label_for(type_str: &str) -> &'static str {+ builtin_cloud_provider(type_str)+ .map(|provider| provider.label)+ .unwrap_or("Custom")+}++/// Map a legacy type string to its well-known default endpoint.+fn legacy_default_endpoint(type_str: &str) -> &'static str {+ builtin_cloud_provider(type_str)+ .map(|provider| provider.endpoint)+ .unwrap_or("")+}++/// Generate a short opaque id for a new provider entry.+///+/// Format: `"p_<slug>_<5 random alphanumerics>"`, e.g. `"p_openai_a8c3f"`.+/// The random suffix is not cryptographically strong — it only needs to be+/// unique within a single user's config file.+pub fn generate_provider_id(slug: &str) -> String {+ use std::time::{SystemTime, UNIX_EPOCH};+ // Cheap pseudo-random from timestamp nanoseconds — adequate for local+ // config uniqueness without pulling in a PRNG crate.+ let nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .subsec_nanos();+ let chars: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";+ let mut suffix = String::with_capacity(5);+ let mut seed = nanos as usize;+ for _ in 0..5 {+ suffix.push(chars[seed % chars.len()] as char);+ seed = seed+ .wrapping_mul(6364136223846793005)+ .wrapping_add(1442695040888963407);+ seed = (seed >> 33) ^ seed;+ }+ // Sanitise slug to only alphanumeric + '-' for the id prefix.+ let safe_slug: String = slug+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' {+ c+ } else {+ '_'+ }+ })+ .take(20)+ .collect();+ format!("p_{}_{}", safe_slug, suffix)+}++// ── Back-compat type alias ──────────────────────────────────────────────────+// Kept so existing code that imports `CloudProviderType` compiles without+// sweeping changes. New code should use `AuthStyle` directly.++/// Legacy discriminator enum. **Deprecated**: use `AuthStyle` on new entries.+/// Retained only to satisfy callers that still pattern-match on+/// `CloudProviderType` (e.g. the migration module). Will be removed once all+/// call sites are updated to slug-keyed lookups.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum CloudProviderType {+ Openhuman,+ Openai,+ Anthropic,+ Openrouter,+ Orcarouter,+ Custom,+}++impl CloudProviderType {+ /// Well-known default base URL for each provider type.+ pub fn default_endpoint(&self) -> &'static str {+ match self {+ Self::Openhuman => "https://api.openhuman.ai/v1",+ Self::Openai => "https://api.openai.com/v1",+ Self::Anthropic => "https://api.anthropic.com/v1",+ Self::Openrouter => "https://openrouter.ai/api/v1",+ Self::Orcarouter => "https://api.orcarouter.ai/v1",+ Self::Custom => "",+ }+ }++ /// Human-readable label used in logs and error messages.+ pub fn label(&self) -> &'static str {+ match self {+ Self::Openhuman => "OpenHuman",+ Self::Openai => "OpenAI",+ Self::Anthropic => "Anthropic",+ Self::Openrouter => "OpenRouter",+ Self::Orcarouter => "OrcaRouter",+ Self::Custom => "Custom",+ }+ }++ /// Lowercase wire-format string (matches JSON serialisation).+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Openhuman => "openhuman",+ Self::Openai => "openai",+ Self::Anthropic => "anthropic",+ Self::Openrouter => "openrouter",+ Self::Orcarouter => "orcarouter",+ Self::Custom => "custom",+ }+ }++ /// Corresponding `AuthStyle`.+ pub fn auth_style(&self) -> AuthStyle {+ match self {+ Self::Openhuman => AuthStyle::OpenhumanJwt,+ Self::Anthropic => AuthStyle::Anthropic,+ _ => AuthStyle::Bearer,+ }+ }+}++#[cfg(test)]+#[path = "cloud_providers_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rsnew file mode 100644index 0000000000..b3ad190fc2--- /dev/null+++ b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs@@ -0,0 +1,371 @@+//! Tests for the surrounding module.++use super::{+ builtin_cloud_supports_responses_api, endpoint_host, endpoint_host_is_chat_completions_only,+ host_is_builtin_cloud_provider, is_builtin_cloud_slug, is_slug_reserved, migrate_legacy_fields,+ AuthStyle, CloudProviderCreds, CloudProviderType, BUILTIN_CLOUD_PROVIDERS,+};++#[test]+fn reserved_slugs() {+ for s in ["", " ", "cloud", "openhuman", "pid"] {+ assert!(is_slug_reserved(s), "{s:?} must stay reserved");+ }+}++// Regression: `ollama` was previously reserved, which made the AI settings+// panel unable to persist an `ollama` cloud_providers entry — so the+// model-list dropdown failed with "no cloud provider with id or slug+// 'ollama' found". The factory's chat routing is unaffected by this+// change because the `ollama:<model>` prefix branch fires before any+// cloud_providers lookup.+#[test]+fn ollama_and_lmstudio_are_not_reserved() {+ assert!(+ !is_slug_reserved("ollama"),+ "ollama must be usable as a cloud_providers slug for the /models probe"+ );+ assert!(+ !is_slug_reserved("lmstudio"),+ "lmstudio is a free-form OpenAI-compatible slug"+ );+}++#[test]+fn builtin_cloud_provider_defaults_cover_phase_one_presets() {+ for (slug, label, endpoint, auth_style) in [+ (+ "groq",+ "Groq",+ "https://api.groq.com/openai/v1",+ AuthStyle::Bearer,+ ),+ (+ "deepseek",+ "DeepSeek",+ "https://api.deepseek.com/v1",+ AuthStyle::Bearer,+ ),+ (+ "minimax",+ "MiniMax",+ "https://api.minimax.io/v1",+ AuthStyle::Bearer,+ ),+ (+ "sumopod",+ "SumoPod",+ "https://ai.sumopod.com/v1",+ AuthStyle::Bearer,+ ),+ (+ "modelscope",+ "ModelScope",+ "https://api-inference.modelscope.cn/v1",+ AuthStyle::Bearer,+ ),+ ] {+ let mut entry = CloudProviderCreds {+ id: format!("p_{slug}"),+ legacy_type: Some(slug.to_string()),+ ..Default::default()+ };+ migrate_legacy_fields(&mut entry);++ assert_eq!(entry.slug, slug);+ assert_eq!(entry.label, label);+ assert_eq!(entry.endpoint, endpoint);+ assert_eq!(entry.auth_style, auth_style);+ }+}++#[test]+fn builtin_cloud_provider_slugs_are_unique() {+ let mut slugs = std::collections::HashSet::new();+ for provider in BUILTIN_CLOUD_PROVIDERS {+ assert!(+ slugs.insert(provider.slug),+ "duplicate built-in cloud provider slug {}",+ provider.slug+ );+ }+}++#[test]+fn is_builtin_cloud_slug_matches_presets_only() {+ for slug in ["openai", "deepseek", "groq", "mistral"] {+ assert!(is_builtin_cloud_slug(slug), "{slug} is a built-in preset");+ }+ for slug in ["my-proxy", "custom-openai", "totally-unknown", ""] {+ assert!(+ !is_builtin_cloud_slug(slug),+ "{slug:?} is not a built-in preset"+ );+ }+}++#[test]+fn only_openai_builtin_exposes_responses_api() {+ assert!(builtin_cloud_supports_responses_api("openai"));+ for slug in ["deepseek", "groq", "mistral", "fireworks", "together"] {+ assert!(+ !builtin_cloud_supports_responses_api(slug),+ "{slug} is chat-completions-only and must not advertise the Responses API"+ );+ }+}++/// Drift guard (TAURI-RUST-5EN): couple the capability helper to the+/// preset list so adding a new built-in that wrongly claims the Responses+/// API — or renaming `openai` — fails CI rather than silently re-enabling+/// the guaranteed-404 `/responses` fallback. OpenAI's first-party endpoint+/// is the only built-in that serves `/v1/responses`.+#[test]+fn responses_api_capability_is_coupled_to_the_preset_list() {+ for provider in BUILTIN_CLOUD_PROVIDERS {+ let expected = provider.slug == "openai";+ assert_eq!(+ builtin_cloud_supports_responses_api(provider.slug),+ expected,+ "built-in {} Responses-API capability drifted from the openai-only invariant",+ provider.slug+ );+ }+}++#[test]+fn endpoint_host_parses_scheme_path_and_port() {+ assert_eq!(+ endpoint_host("https://integrate.api.nvidia.com/v1").as_deref(),+ Some("integrate.api.nvidia.com")+ );+ // Missing scheme, mixed case, trailing path.+ assert_eq!(+ endpoint_host("API.OpenAI.com/v1/chat").as_deref(),+ Some("api.openai.com")+ );+ // Userinfo + explicit port are stripped.+ assert_eq!(+ endpoint_host("https://user:[email protected]:443/openai/v1").as_deref(),+ Some("api.groq.com")+ );+ // Bracketed IPv6 literal with port.+ assert_eq!(+ endpoint_host("http://[::1]:8080/v1").as_deref(),+ Some("::1")+ );+ assert_eq!(endpoint_host(" ").as_deref(), None);+}++/// TAURI-RUST-HW1: the backend-URL resolver uses this to reroute backend+/// domain calls away from a BYO inference host. Every built-in provider host+/// must be recognised; OpenHuman backend hosts and unknown proxies must not.+#[test]+fn host_is_builtin_cloud_provider_recognises_inference_hosts() {+ for host in [+ "openrouter.ai",+ "api.openai.com",+ "api.anthropic.com",+ "api.groq.com",+ "generativelanguage.googleapis.com",+ "API.OPENAI.COM", // case-insensitive+ ] {+ assert!(+ host_is_builtin_cloud_provider(host),+ "{host} is a built-in cloud inference host"+ );+ }+ for host in [+ "api.tinyhumans.ai",+ "staging-api.tinyhumans.ai",+ "my-backend.example",+ "",+ ] {+ assert!(+ !host_is_builtin_cloud_provider(host),+ "{host:?} is not a built-in cloud inference host"+ );+ }+ // Every registry endpoint's own host must classify as builtin.+ for provider in BUILTIN_CLOUD_PROVIDERS {+ let host = endpoint_host(provider.endpoint).expect("preset endpoint has a host");+ assert!(+ host_is_builtin_cloud_provider(&host),+ "{} ({host}) must be recognised",+ provider.slug+ );+ }+}++/// TAURI-RUST-5A1: a *custom* slug pointed at a known chat-only host (NVIDIA)+/// must be classified chat-only so the factory disables the guaranteed-404+/// `/responses` fallback — the builtin-slug gate alone misses this because+/// the slug is not builtin.+#[test]+fn nvidia_host_is_chat_completions_only_regardless_of_slug() {+ assert!(endpoint_host_is_chat_completions_only(+ "https://integrate.api.nvidia.com/v1"+ ));+ // Other chat-only built-in hosts too.+ for endpoint in [+ "https://api.deepseek.com/v1",+ "https://api.groq.com/openai/v1",+ "https://api.mistral.ai/v1",+ ] {+ assert!(+ endpoint_host_is_chat_completions_only(endpoint),+ "{endpoint} is a chat-completions-only built-in host"+ );+ }+}++#[test]+fn openai_host_and_unknown_proxies_keep_the_responses_fallback() {+ // OpenAI's first-party host serves /responses — must NOT be gated off,+ // even via a custom proxy slug pointed at it.+ assert!(!endpoint_host_is_chat_completions_only(+ "https://api.openai.com/v1"+ ));+ // Genuinely unknown proxy hosts keep the permissive default (they may be+ // real OpenAI proxies that implement /responses).+ for endpoint in [+ "https://my-llm-proxy.internal.example/v1",+ "https://litellm.mycorp.dev/v1",+ "",+ ] {+ assert!(+ !endpoint_host_is_chat_completions_only(endpoint),+ "{endpoint:?} is an unknown host and must keep the fallback"+ );+ }+}++/// Drift guard: the host-based gate must agree with the slug-based+/// capability for every built-in preset's own endpoint, so adding a preset+/// can't silently desync the two gates.+#[test]+fn host_gate_agrees_with_slug_capability_for_every_builtin() {+ for provider in BUILTIN_CLOUD_PROVIDERS {+ // OpenhumanJwt / Anthropic presets never route through the+ // OpenAI-compatible Responses fallback; the gate only matters for+ // the Bearer OpenAI-compatible hosts.+ if provider.auth_style != AuthStyle::Bearer {+ continue;+ }+ let host_chat_only = endpoint_host_is_chat_completions_only(provider.endpoint);+ let slug_supports = builtin_cloud_supports_responses_api(provider.slug);+ assert_eq!(+ host_chat_only, !slug_supports,+ "host gate for built-in {} disagrees with its slug capability",+ provider.slug+ );+ }+}++#[test]+fn auth_styles_and_legacy_provider_types_expose_stable_wire_properties() {+ let styles = [+ (AuthStyle::Bearer, "bearer"),+ (AuthStyle::Anthropic, "anthropic"),+ (AuthStyle::OpenhumanJwt, "openhuman_jwt"),+ (AuthStyle::None, "none"),+ ];+ for (style, expected) in styles {+ assert_eq!(style.as_str(), expected);+ }++ let types = [+ (+ CloudProviderType::Openhuman,+ "https://api.openhuman.ai/v1",+ "OpenHuman",+ "openhuman",+ AuthStyle::OpenhumanJwt,+ ),+ (+ CloudProviderType::Openai,+ "https://api.openai.com/v1",+ "OpenAI",+ "openai",+ AuthStyle::Bearer,+ ),+ (+ CloudProviderType::Anthropic,+ "https://api.anthropic.com/v1",+ "Anthropic",+ "anthropic",+ AuthStyle::Anthropic,+ ),+ (+ CloudProviderType::Openrouter,+ "https://openrouter.ai/api/v1",+ "OpenRouter",+ "openrouter",+ AuthStyle::Bearer,+ ),+ (+ CloudProviderType::Orcarouter,+ "https://api.orcarouter.ai/v1",+ "OrcaRouter",+ "orcarouter",+ AuthStyle::Bearer,+ ),+ (+ CloudProviderType::Custom,+ "",+ "Custom",+ "custom",+ AuthStyle::Bearer,+ ),+ ];+ for (provider, endpoint, label, slug, auth) in types {+ assert_eq!(provider.default_endpoint(), endpoint);+ assert_eq!(provider.label(), label);+ assert_eq!(provider.as_str(), slug);+ assert_eq!(provider.auth_style(), auth);+ }+}++#[test]+fn migration_is_idempotent_and_unknown_types_remain_custom() {+ let mut custom = CloudProviderCreds {+ id: "custom-id".into(),+ legacy_type: Some("my-provider".into()),+ ..Default::default()+ };+ migrate_legacy_fields(&mut custom);+ assert_eq!(custom.slug, "my-provider");+ assert_eq!(custom.label, "Custom");+ assert!(custom.endpoint.is_empty());+ assert_eq!(custom.auth_style, AuthStyle::Bearer);++ let once = custom.clone();+ migrate_legacy_fields(&mut custom);+ assert_eq!(custom, once);++ let mut preserved = CloudProviderCreds {+ id: "preserved".into(),+ slug: "chosen".into(),+ label: "Chosen Label".into(),+ endpoint: "https://proxy.example/v1".into(),+ auth_style: AuthStyle::None,+ legacy_type: Some("openai".into()),+ default_model: Some("legacy-model".into()),+ };+ migrate_legacy_fields(&mut preserved);+ assert_eq!(preserved.slug, "chosen");+ assert_eq!(preserved.label, "Chosen Label");+ assert_eq!(preserved.endpoint, "https://proxy.example/v1");+ assert_eq!(preserved.auth_style, AuthStyle::None);+}++#[test]+fn generated_provider_ids_sanitize_and_bound_the_slug_prefix() {+ let id = super::generate_provider_id("provider with spaces/and_symbols!");+ assert!(id.starts_with("p_provider_with_spaces_"));+ let suffix = id.rsplit('_').next().expect("suffix");+ assert_eq!(suffix.len(), 5);+ assert!(suffix+ .chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));+}diff --git a/crates/openhuman-core/src/config/schema/local_ai.rs b/crates/openhuman-core/src/config/schema/local_ai.rsindex 8174b31fd9..a772417a61 100644--- a/crates/openhuman-core/src/config/schema/local_ai.rs+++ b/crates/openhuman-core/src/config/schema/local_ai.rs@@ -1,11 +1,324 @@//! Local AI runtime configuration.-//!-//! Definitions moved to [`tinymemory_api::host`] — the extracted memory-//! subsystem reads `local_ai` when it resolves an embedding backend. Re-exported-//! here so existing paths keep resolving.-//!-//! This is a host-owned section living in the memory contract crate for purely-//! mechanical reasons; moving embedding *construction* back into the host would-//! let it come home.--pub use tinymemory_api::host::local_ai::{LocalAiConfig, LocalAiUsage};++use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++/// Per-feature flags controlling which subsystems route through the selected+/// local runtime. All default to `false` (use cloud instead). Guarded by+/// `LocalAiConfig::runtime_enabled` — when that is `false` every helper+/// method below returns `false` regardless of these values.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]+#[serde(default)]+#[derive(Default)]+pub struct LocalAiUsage {+ /// When true (and `runtime_enabled`), use the local model for embedding+ /// generation instead of the cloud backend.+ #[serde(default)]+ pub embeddings: bool,+ /// When true (and `runtime_enabled`), use the local model inside the+ /// heartbeat loop.+ #[serde(default)]+ pub heartbeat: bool,+ /// When true (and `runtime_enabled`), use the local model for+ /// learning/reflection passes.+ #[serde(default)]+ pub learning_reflection: bool,+ /// When true (and `runtime_enabled`), use the local model for+ /// subconscious evaluation and execution.+ #[serde(default)]+ pub subconscious: bool,+}++#[derive(Clone, Serialize, Deserialize, JsonSchema)]+#[serde(default)]+pub struct LocalAiConfig {+ /// Master runtime switch. Defaults to `false` — local AI is OFF by default.+ /// Note: the old on-disk field was `enabled`; that key is now unknown to+ /// serde and will be silently ignored on load (intentional forced reset).+ #[serde(default = "default_runtime_enabled")]+ pub runtime_enabled: bool,+ /// Local provider identifier. Supported values are `ollama`, `lm_studio`,+ /// and `omlx`; unknown values normalize to `ollama` at runtime.+ #[serde(default = "default_provider")]+ pub provider: String,+ /// Optional provider base URL. For LM Studio this defaults to+ /// `http://localhost:1234/v1`.+ #[serde(default)]+ pub base_url: Option<String>,+ #[serde(default)]+ pub api_key: Option<String>,+ #[serde(default = "default_model_id")]+ pub model_id: String,+ #[serde(default = "default_chat_model_id")]+ pub chat_model_id: String,+ #[serde(default = "default_vision_model_id")]+ pub vision_model_id: String,+ #[serde(default = "default_embedding_model_id")]+ pub embedding_model_id: String,+ #[serde(default = "default_stt_model_id")]+ pub stt_model_id: String,+ #[serde(default = "default_stt_download_url")]+ pub stt_download_url: Option<String>,+ /// Legacy voice STT routing string. `"cloud"` (the default) means "use+ /// `voice_server.stt_engine`"; a third-party `"<slug>[:<model>]"` overrides+ /// the engine outright. The local `"whisper"` value it once accepted is+ /// dead — `config::migrations` rewrites it back to `"cloud"`.+ #[serde(default = "default_stt_provider")]+ pub stt_provider: String,+ #[serde(default = "default_tts_voice_id")]+ pub tts_voice_id: String,+ /// Voice TTS provider selector. `"cloud"` (default) routes through the+ /// backend ElevenLabs proxy and returns rich visemes; `"piper"` runs+ /// local Piper via the `PIPER_BIN` env var.+ #[serde(default = "default_tts_provider")]+ pub tts_provider: String,+ #[serde(default = "default_tts_download_url")]+ pub tts_download_url: Option<String>,+ #[serde(default = "default_tts_config_download_url")]+ pub tts_config_download_url: Option<String>,+ #[serde(default = "default_quantization")]+ pub quantization: String,+ #[serde(default = "default_preload_vision_model")]+ pub preload_vision_model: bool,+ #[serde(default = "default_preload_embedding_model")]+ pub preload_embedding_model: bool,+ #[serde(default = "default_preload_stt_model")]+ pub preload_stt_model: bool,+ #[serde(default = "default_preload_tts_voice")]+ pub preload_tts_voice: bool,+ #[serde(default = "default_download_url")]+ pub download_url: Option<String>,+ #[serde(default = "default_autosummary_debounce_ms")]+ pub autosummary_debounce_ms: u64,+ #[serde(default)]+ pub selected_tier: Option<String>,+ /// Explicit MVP opt-in marker. Bootstrap disables local AI unless this is+ /// `true`, regardless of any prior `selected_tier` value. Existing installs+ /// (upgrading from pre-MVP) default to `false` and must re-opt-in from+ /// Settings. Set by `apply_preset` on any non-disabled tier.+ #[serde(default)]+ pub opt_in_confirmed: bool,+ /// Optional path to a manually-installed Ollama binary.+ #[serde(default)]+ pub ollama_binary_path: Option<String>,+ /// When true and Ollama is available, pass raw transcription through a+ /// local LLM to fix grammar/punctuation using conversation context.+ #[serde(default = "default_voice_llm_cleanup_enabled")]+ pub voice_llm_cleanup_enabled: bool,+ /// Ollama `options.num_ctx` override. When set, every chat request to+ /// an Ollama provider includes `"options": {"num_ctx": <value>}` so+ /// the model allocates at least this much KV-cache. Ollama defaults+ /// to 2048 for many models which is too small for agentic use.+ #[serde(default)]+ pub num_ctx: Option<u32>,+ /// Per-feature flags. Each gate is AND-ed with `runtime_enabled`.+ /// All default to `false` (cloud path).+ #[serde(default)]+ pub usage: LocalAiUsage,+}++impl std::fmt::Debug for LocalAiConfig {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("LocalAiConfig")+ .field("runtime_enabled", &self.runtime_enabled)+ .field("provider", &self.provider)+ .field("base_url", &self.base_url)+ .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))+ .field("model_id", &self.model_id)+ .field("chat_model_id", &self.chat_model_id)+ .field("vision_model_id", &self.vision_model_id)+ .field("embedding_model_id", &self.embedding_model_id)+ .field("stt_model_id", &self.stt_model_id)+ .field("stt_download_url", &self.stt_download_url)+ .field("stt_provider", &self.stt_provider)+ .field("tts_voice_id", &self.tts_voice_id)+ .field("tts_provider", &self.tts_provider)+ .field("tts_download_url", &self.tts_download_url)+ .field("tts_config_download_url", &self.tts_config_download_url)+ .field("quantization", &self.quantization)+ .field("preload_vision_model", &self.preload_vision_model)+ .field("preload_embedding_model", &self.preload_embedding_model)+ .field("preload_stt_model", &self.preload_stt_model)+ .field("preload_tts_voice", &self.preload_tts_voice)+ .field("download_url", &self.download_url)+ .field("autosummary_debounce_ms", &self.autosummary_debounce_ms)+ .field("selected_tier", &self.selected_tier)+ .field("opt_in_confirmed", &self.opt_in_confirmed)+ .field("ollama_binary_path", &self.ollama_binary_path)+ .field("voice_llm_cleanup_enabled", &self.voice_llm_cleanup_enabled)+ .field("num_ctx", &self.num_ctx)+ .field("usage", &self.usage)+ .finish()+ }+}++fn default_runtime_enabled() -> bool {+ false+}++fn default_provider() -> String {+ "ollama".to_string()+}++fn default_model_id() -> String {+ "gemma3:1b-it-qat".to_string()+}++fn default_chat_model_id() -> String {+ "gemma3:1b-it-qat".to_string()+}++fn default_vision_model_id() -> String {+ String::new()+}++fn default_embedding_model_id() -> String {+ // bge-m3 (1024 dims, 8192-token context). Required by the memory tree's+ // fixed on-disk embedding format (EMBEDDING_DIM=1024) — `all-minilm`+ // (384 dims) and `nomic-embed-text` (768 dims) would fail the+ // post-call dim validator at `memory::tree::score::embed::mod::embed`.+ "bge-m3".to_string()+}++fn default_stt_model_id() -> String {+ "ggml-base-q5_1.bin".to_string()+}++fn default_tts_voice_id() -> String {+ "en_US-lessac-medium".to_string()+}++fn default_stt_provider() -> String {+ "cloud".to_string()+}++fn default_tts_provider() -> String {+ "cloud".to_string()+}++fn default_stt_download_url() -> Option<String> {+ Some(+ "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base-q5_1.bin?download=true"+ .to_string(),+ )+}++fn default_tts_download_url() -> Option<String> {+ Some(+ "https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/lessac/medium/en_US-lessac-medium.onnx?download=true"+ .to_string(),+ )+}++fn default_tts_config_download_url() -> Option<String> {+ Some(+ "https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/lessac/medium/en_US-lessac-medium.onnx.json?download=true"+ .to_string(),+ )+}++fn default_quantization() -> String {+ "q4".to_string()+}++fn default_preload_vision_model() -> bool {+ false+}++fn default_preload_embedding_model() -> bool {+ true+}++fn default_preload_stt_model() -> bool {+ false+}++fn default_preload_tts_voice() -> bool {+ false+}++fn default_download_url() -> Option<String> {+ None+}++fn default_autosummary_debounce_ms() -> u64 {+ 2500+}++fn default_voice_llm_cleanup_enabled() -> bool {+ true+}++impl LocalAiConfig {+ /// Returns `true` when the local Ollama runtime is active.+ /// This is the primary gate; all per-feature helpers below AND with this.+ pub fn is_active(&self) -> bool {+ self.runtime_enabled+ }++ /// **Deprecated** — read from `Config::workload_uses_local("embeddings")`+ /// instead. This helper only consults the legacy `usage.*` booleans, which+ /// are no longer the source of truth after the unified AI settings+ /// migration (schema_version >= 2).+ #[deprecated(note = "Use Config::workload_uses_local(\"embeddings\")")]+ pub fn use_local_for_embeddings(&self) -> bool {+ self.runtime_enabled && self.usage.embeddings+ }++ /// **Deprecated** — read from `Config::workload_uses_local("heartbeat")`.+ #[deprecated(note = "Use Config::workload_uses_local(\"heartbeat\")")]+ pub fn use_local_for_heartbeat(&self) -> bool {+ self.runtime_enabled && self.usage.heartbeat+ }++ /// **Deprecated** — read from `Config::workload_uses_local("learning")`.+ #[deprecated(note = "Use Config::workload_uses_local(\"learning\")")]+ pub fn use_local_for_learning(&self) -> bool {+ self.runtime_enabled && self.usage.learning_reflection+ }++ /// **Deprecated** — read from `Config::workload_uses_local("subconscious")`.+ #[deprecated(note = "Use Config::workload_uses_local(\"subconscious\")")]+ pub fn use_local_for_subconscious(&self) -> bool {+ self.runtime_enabled && self.usage.subconscious+ }+}++impl Default for LocalAiConfig {+ fn default() -> Self {+ Self {+ runtime_enabled: default_runtime_enabled(),+ provider: default_provider(),+ base_url: None,+ api_key: None,+ model_id: default_model_id(),+ chat_model_id: default_chat_model_id(),+ vision_model_id: default_vision_model_id(),+ embedding_model_id: default_embedding_model_id(),+ stt_model_id: default_stt_model_id(),+ stt_download_url: default_stt_download_url(),+ stt_provider: default_stt_provider(),+ tts_voice_id: default_tts_voice_id(),+ tts_provider: default_tts_provider(),+ tts_download_url: default_tts_download_url(),+ tts_config_download_url: default_tts_config_download_url(),+ quantization: default_quantization(),+ preload_vision_model: default_preload_vision_model(),+ preload_embedding_model: default_preload_embedding_model(),+ preload_stt_model: default_preload_stt_model(),+ preload_tts_voice: default_preload_tts_voice(),+ download_url: default_download_url(),+ autosummary_debounce_ms: default_autosummary_debounce_ms(),+ selected_tier: None,+ opt_in_confirmed: false,+ ollama_binary_path: None,+ voice_llm_cleanup_enabled: default_voice_llm_cleanup_enabled(),+ num_ctx: None,+ usage: LocalAiUsage::default(),+ }+ }+}++#[cfg(test)]+#[path = "local_ai_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/config/schema/local_ai_tests.rs b/crates/openhuman-core/src/config/schema/local_ai_tests.rsnew file mode 100644index 0000000000..c0e65cb979--- /dev/null+++ b/crates/openhuman-core/src/config/schema/local_ai_tests.rs@@ -0,0 +1,36 @@+//! Tests for the surrounding module.++use super::*;++#[test]+fn defaults_keep_local_runtime_and_every_usage_gate_off() {+ let cfg = LocalAiConfig::default();+ assert!(!cfg.is_active());+ #[allow(deprecated)]+ {+ assert!(!cfg.use_local_for_embeddings());+ assert!(!cfg.use_local_for_heartbeat());+ assert!(!cfg.use_local_for_learning());+ assert!(!cfg.use_local_for_subconscious());+ }+ assert_eq!(cfg.embedding_model_id, "bge-m3");+}++#[test]+fn debug_output_redacts_the_api_key() {+ let cfg = LocalAiConfig {+ api_key: Some("secret-key".into()),+ ..Default::default()+ };+ let debug = format!("{cfg:?}");+ assert!(!debug.contains("secret-key"));+ assert!(debug.contains("<redacted>"));+ assert!(debug.contains("voice_llm_cleanup_enabled: true"));+ assert!(debug.contains("usage: LocalAiUsage"));+}++#[test]+fn legacy_enabled_key_does_not_reenable_the_runtime() {+ let cfg: LocalAiConfig = toml::from_str("enabled = true").unwrap();+ assert!(!cfg.runtime_enabled);+}diff --git a/crates/openhuman-core/src/config/schema/routes.rs b/crates/openhuman-core/src/config/schema/routes.rsindex e9a41f6241..3bb9c88d75 100644--- a/crates/openhuman-core/src/config/schema/routes.rs+++ b/crates/openhuman-core/src/config/schema/routes.rs@@ -9,7 +9,13 @@ pub struct ModelRouteConfig {pub model: String,}-/// A per-workload embedding provider override. Defined in the contract crate —-/// the memory store's embedder factory reads it. See-/// [`tinymemory_api::host::EmbeddingRouteConfig`].-pub use tinymemory_api::host::EmbeddingRouteConfig;+/// A per-workload embedding provider override (`[[embedding_routes]]`).+/// Inert serde data; its serde form is persisted in users' `config.toml`.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]+pub struct EmbeddingRouteConfig {+ pub hint: String,+ pub provider: String,+ pub model: String,+ #[serde(default)]+ pub dimensions: Option<usize>,+}diff --git a/crates/openhuman-core/src/config/schema/scheduler_gate.rs b/crates/openhuman-core/src/config/schema/scheduler_gate.rsindex fdbaf819b4..7493e3bc3c 100644--- a/crates/openhuman-core/src/config/schema/scheduler_gate.rs+++ b/crates/openhuman-core/src/config/schema/scheduler_gate.rs@@ -1,8 +1,194 @@//! Scheduler-gate configuration — controls when background AI work runs.//!-//! Consumed by [`crate::cron::scheduler_gate`]. The definitions moved-//! to [`tinymemory_api::host`] alongside the rest of the memory-adjacent config-//! sections, because `tinymemory-core`'s sync and summarizer loops consult the-//! gate directly. Re-exported here so existing paths keep resolving.+//! Consumed by `tinymemory-gate` and, through it, the host's scheduler gate.-pub use tinymemory_api::host::scheduler_gate::{SchedulerGateConfig, SchedulerGateMode};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+#[derive(Default)]+pub enum SchedulerGateMode {+ /// Decide based on power + CPU + deployment-mode signals.+ #[default]+ Auto,+ /// Always run background AI flat-out (server / power-user setting).+ AlwaysOn,+ /// Never run background AI. User can still trigger work explicitly.+ Off,+}++impl SchedulerGateMode {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Auto => "auto",+ Self::AlwaysOn => "always_on",+ Self::Off => "off",+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]+#[serde(default)]+pub struct SchedulerGateConfig {+ /// Top-level mode — `auto` (default), `always_on`, or `off`.+ #[serde(default)]+ pub mode: SchedulerGateMode,++ /// Battery charge floor in `auto` mode, 0.0..=1.0. Below this and not on+ /// AC, the gate throttles. Default: 0.80.+ #[serde(default = "default_battery_floor")]+ pub battery_floor: f32,++ /// CPU busy threshold (recent global usage, 0..100). Above this, the gate+ /// throttles even when plugged in. Default: 70.0 (i.e. <30% headroom).+ #[serde(default = "default_cpu_busy_threshold")]+ pub cpu_busy_threshold_pct: f32,++ /// In `Throttled` mode, sleep this many ms before each LLM-bound job to+ /// serialise workers and let the host catch up. Default: 30_000 (30s).+ #[serde(default = "default_throttled_backoff_ms")]+ pub throttled_backoff_ms: u64,++ /// In `Paused` mode, re-check the policy every this many ms so workers+ /// resume promptly when the user toggles the gate back on. Default:+ /// 60_000 (60s).+ #[serde(default = "default_paused_poll_ms")]+ pub paused_poll_ms: u64,++ /// Hard CPU ceiling (recent global usage, 0..100). When the host CPU+ /// climbs above this in `auto` mode, the gate flips to+ /// `Paused { CpuPressure }` rather than just `Throttled` — every+ /// background LLM call is held until the host calms down. Distinct+ /// from `cpu_busy_threshold_pct`, which only triggers `Throttled`.+ /// Default: 95.0.+ #[serde(default = "default_cpu_severe_pct")]+ pub cpu_severe_pct: f32,++ /// When `true`, `auto` mode only runs background LLM work while the+ /// laptop is on AC power. On battery the gate flips to+ /// `Paused { OnBattery }` — no background inference at all,+ /// regardless of charge level.+ ///+ /// Default `false` to preserve the prior behavior (battery-floor+ /// based throttling). Power-conscious users who never want+ /// background inference on battery can flip this on.+ #[serde(default)]+ pub require_ac_power: bool,+}++fn default_battery_floor() -> f32 {+ 0.80+}+fn default_cpu_busy_threshold() -> f32 {+ 70.0+}+fn default_throttled_backoff_ms() -> u64 {+ 30_000+}+fn default_paused_poll_ms() -> u64 {+ 60_000+}+fn default_cpu_severe_pct() -> f32 {+ 95.0+}++impl Default for SchedulerGateConfig {+ fn default() -> Self {+ Self {+ mode: SchedulerGateMode::default(),+ battery_floor: default_battery_floor(),+ cpu_busy_threshold_pct: default_cpu_busy_threshold(),+ throttled_backoff_ms: default_throttled_backoff_ms(),+ paused_poll_ms: default_paused_poll_ms(),+ cpu_severe_pct: default_cpu_severe_pct(),+ require_ac_power: false,+ }+ }+}++// ── Gate decision vocabulary ────────────────────────────────────────────────+//+// `Policy` and `PauseReason` moved here from the host's+// `cron::scheduler_gate::policy` because the extracted sync loops read them on+// every tick to decide whether to back off. They are inert `Copy` enums with no+// dependencies. The pure *decision function* that produces a `Policy` from+// sampled signals lives beside them in `scheduler_gate_decide`; the+// sampling of those signals and the cooperative wait live in `tinymemory-gate`+// (which needs a runtime and hardware probes this crate forbids).++/// Why the gate is currently paused. Carried by [`Policy::Paused`] so+/// downstream consumers (UI, logging, observability) can surface a+/// specific user-facing reason instead of a generic "paused" label.+///+/// New variants will land alongside #1073's full power-aware work+/// (`OnBattery`, `CpuPressure`); `UserDisabled` covers the existing+/// `SchedulerGateMode::Off` path and `Unknown` is the safe fallback for+/// callers that don't have specific context yet.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PauseReason {+ /// User explicitly turned the gate off in config.+ UserDisabled,+ /// Host on battery and gate's power-aware mode kicked in (#1073).+ OnBattery,+ /// CPU pressure exceeded the gate threshold (#1073).+ CpuPressure,+ /// No active app session — background AI work is suspended until the+ /// user signs in again. Trumps every other signal: while signed out+ /// the host should do *no* LLM-bound work, period. Set by+ /// `gate::set_signed_out(true)` from the credentials lifecycle and+ /// from 401-detection sites.+ SignedOut,+ /// Pause reason not yet classified — placeholder while #1073 is in flight.+ Unknown,+}++impl PauseReason {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::UserDisabled => "user_disabled",+ Self::OnBattery => "on_battery",+ Self::CpuPressure => "cpu_pressure",+ Self::SignedOut => "signed_out",+ Self::Unknown => "unknown",+ }+ }+}++/// Background-AI scheduling tier. See module docs in `mod.rs` for semantics.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Policy {+ Aggressive,+ Normal,+ Throttled,+ /// Gate paused. The `reason` is rendered to users in the memory-sync+ /// status UI (#1136) and recorded in observability.+ Paused {+ reason: PauseReason,+ },+}++impl Policy {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Aggressive => "aggressive",+ Self::Normal => "normal",+ Self::Throttled => "throttled",+ Self::Paused { .. } => "paused",+ }+ }++ /// `Some(reason)` when paused, `None` otherwise. Convenience for+ /// callers that only need the reason and don't want to pattern-match+ /// the whole enum (UI badges, log line construction).+ pub fn pause_reason(self) -> Option<PauseReason> {+ match self {+ Self::Paused { reason } => Some(reason),+ _ => None,+ }+ }+}++#[cfg(test)]+#[path = "scheduler_gate_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/config/schema/scheduler_gate_tests.rs b/crates/openhuman-core/src/config/schema/scheduler_gate_tests.rsnew file mode 100644index 0000000000..09b89cbf6d--- /dev/null+++ b/crates/openhuman-core/src/config/schema/scheduler_gate_tests.rs@@ -0,0 +1,29 @@+//! Tests for the surrounding module.++use super::*;++#[test]+fn scheduler_defaults_are_pinned_to_safe_auto_limits() {+ let config = SchedulerGateConfig::default();+ assert_eq!(config.mode, SchedulerGateMode::Auto);+ assert_eq!(config.battery_floor, 0.80);+ assert_eq!(config.cpu_busy_threshold_pct, 70.0);+ assert_eq!(config.cpu_severe_pct, 95.0);+ assert_eq!(config.throttled_backoff_ms, 30_000);+ assert_eq!(config.paused_poll_ms, 60_000);+ assert!(!config.require_ac_power);+}++#[test]+fn scheduler_mode_serde_and_policy_strings_are_stable() {+ let config: SchedulerGateConfig = toml::from_str("mode = \"always_on\"").unwrap();+ assert_eq!(config.mode, SchedulerGateMode::AlwaysOn);+ assert_eq!(config.mode.as_str(), "always_on");+ let paused = Policy::Paused {+ reason: PauseReason::SignedOut,+ };+ assert_eq!(paused.as_str(), "paused");+ assert_eq!(paused.pause_reason(), Some(PauseReason::SignedOut));+ assert_eq!(PauseReason::SignedOut.as_str(), "signed_out");+ assert_eq!(Policy::Normal.pause_reason(), None);+}diff --git a/crates/openhuman-core/src/inference/embedding_host/embedding_trait.rs b/crates/openhuman-core/src/inference/embedding_host/embedding_trait.rsnew file mode 100644index 0000000000..17cf69711b--- /dev/null+++ b/crates/openhuman-core/src/inference/embedding_host/embedding_trait.rs@@ -0,0 +1,129 @@+//! [`EmbeddingProvider`] — text → vector, supplied by the host.+//!+//! The memory subsystem embeds chunks, summaries and queries, but it does not+//! decide *how*: which provider, which credentials, which rate limit and which+//! fallback are host policy. So the core takes an `Arc<dyn EmbeddingProvider>`+//! and never constructs one.+//!+//! This trait deliberately lives in the contract crate rather than in+//! `tinymemory-core`, so that a host implementing it does not have to depend on+//! the engine. It carries nothing heavier than `async-trait` and `anyhow`.++use async_trait::async_trait;++/// Formats the canonical embedding-space signature string.+///+/// This is the **single source of truth** for the signature format. Both the+/// live-provider [`EmbeddingProvider::signature`] and any config-derived+/// signature must route through here, so a signature computed from+/// configuration is byte-identical to one computed from an instantiated+/// provider. Drift between the two silently splits one embedding space into+/// two, and every vector written on the wrong side of the split becomes+/// unsearchable without a re-embed.+/// # Delimiters in a component+///+/// A component containing `;`, `=` or `%` is percent-encoded, because without+/// that the format is ambiguous: `("a;model=b", "c")` and `("a", "b;model=c")`+/// are different embedding spaces that would otherwise produce one identical+/// key, and vectors from both would then be compared as though they came from+/// the same model.+///+/// Encoding only those three characters is what keeps this from being a+/// migration. Every provider and model identifier actually in use is+/// alphanumeric plus `-`, `_`, `.`, `/` or `:`, and each of those passes+/// through untouched — so every signature already on disk still formats to the+/// same bytes. Only a name that could have collided changes, and such a name+/// has never been written.+#[must_use]+pub fn format_embedding_signature(name: &str, model_id: &str, dims: usize) -> String {+ let name = escape_component(name);+ let model_id = escape_component(model_id);+ format!("provider={name};model={model_id};dims={dims}")+}++/// Percent-encode the three characters that carry structure in a signature.+///+/// `%` goes first and must: encoding it afterwards would re-encode the `%` this+/// function just introduced, and `a;b` would arrive as `a%3Bb` from one path+/// and `a%253Bb` from another.+fn escape_component(value: &str) -> String {+ if !value.contains(['%', ';', '=']) {+ // The overwhelmingly common path, and the one that guarantees existing+ // keys are untouched: no allocation beyond the copy, no rewriting.+ return value.to_string();+ }+ value+ .replace('%', "%25")+ .replace(';', "%3B")+ .replace('=', "%3D")+}++#[cfg(test)]+#[path = "embeddings_embedding_signature_tests.rs"]+mod embedding_signature_tests;++/// Converts text into numerical vectors.+#[async_trait]+pub trait EmbeddingProvider: Send + Sync {+ /// Provider name, e.g. `"ollama"`, `"openai"`.+ fn name(&self) -> &str;++ /// Stable model identifier used to generate embeddings.+ fn model_id(&self) -> &str;++ /// Number of dimensions in the generated embeddings.+ fn dimensions(&self) -> usize;++ /// Stable signature for the embedding space.+ ///+ /// Changing any component means existing vectors are no longer comparable+ /// with newly generated ones and must be stored and queried separately+ /// until a migration re-embeds them.+ fn signature(&self) -> String {+ format_embedding_signature(self.name(), self.model_id(), self.dimensions())+ }++ /// Generates embeddings for a batch of strings.+ ///+ /// # Errors+ /// Propagates transport, authentication and quota failures from the+ /// underlying provider.+ async fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>>;++ /// Generates an embedding for a single string.+ ///+ /// # Errors+ /// As [`Self::embed`], plus an error when the provider returns no vector.+ async fn embed_one(&self, text: &str) -> anyhow::Result<Vec<f32>> {+ let mut results = self.embed(&[text]).await?;+ results+ .pop()+ .ok_or_else(|| anyhow::anyhow!("Empty embedding result"))+ }+}++/// The inert provider bound when semantic search is switched off or no+/// embedding backend is configured. Reports zero dimensions and returns one+/// empty vector per input, so keyword-only retrieval keeps working while+/// vector rerank degrades to a no-op rather than an error.+#[derive(Debug, Clone, Copy, Default)]+pub struct NoopEmbedding;++#[async_trait]+impl EmbeddingProvider for NoopEmbedding {+ fn name(&self) -> &str {+ "none"+ }++ fn model_id(&self) -> &str {+ "none"+ }++ fn dimensions(&self) -> usize {+ 0+ }++ async fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {+ Ok(vec![Vec::new(); texts.len()])+ }+}diff --git a/crates/openhuman-core/src/inference/embedding_host/embeddings_embedding_signature_tests.rs b/crates/openhuman-core/src/inference/embedding_host/embeddings_embedding_signature_tests.rsnew file mode 100644index 0000000000..89392756dd--- /dev/null+++ b/crates/openhuman-core/src/inference/embedding_host/embeddings_embedding_signature_tests.rs@@ -0,0 +1,105 @@+//! Tests for the surrounding module.++use async_trait::async_trait;++use super::{format_embedding_signature, EmbeddingProvider, NoopEmbedding};++/// The signature format is a **persisted key**, pinned to literal values.+///+/// Written against golden strings rather than against another copy of the+/// function on purpose: the host used to hold a byte-identical duplicate of+/// this file and the two silently diverged once already. A guard that+/// compares two implementations stops protecting anything the moment one of+/// them goes away — which is exactly what happened when the duplicate was+/// removed. Literals outlive that.+///+/// Every vector on disk is keyed by one of these strings, so a change here+/// is a migration, never an edit.+#[test]+fn signature_format_is_pinned_to_its_persisted_form() {+ assert_eq!(+ format_embedding_signature("ollama", "nomic-embed-text", 768),+ "provider=ollama;model=nomic-embed-text;dims=768"+ );+ assert_eq!(+ format_embedding_signature("none", "none", 0),+ "provider=none;model=none;dims=0"+ );+}++/// Two distinct embedding spaces must never share one signature.+///+/// Without escaping these two collide exactly: both format to+/// `provider=a;model=b;model=c;dims=3`. A collision here is not a cosmetic+/// problem — the signature is what decides which vectors are comparable, so+/// two models' vectors would be scored against each other as though they+/// came from one space.+#[test]+fn delimiter_characters_cannot_make_distinct_spaces_collide() {+ let first = format_embedding_signature("a;model=b", "c", 3);+ let second = format_embedding_signature("a", "b;model=c", 3);+ assert_ne!(first, second);+}++/// Escaping `%` last would make the encoding itself ambiguous.+#[test]+fn an_already_percent_encoded_name_does_not_collide_with_a_literal_one() {+ assert_ne!(+ format_embedding_signature("a%3Bb", "m", 3),+ format_embedding_signature("a;b", "m", 3)+ );+}++/// The escaping is not a migration: every identifier shaped like the ones+/// actually in use formats to the same bytes it always did.+#[test]+fn identifiers_in_real_use_are_untouched_by_the_escaping() {+ for (provider, model) in [+ ("ollama", "nomic-embed-text"),+ ("openai", "text-embedding-3-small"),+ ("huggingface", "sentence-transformers/all-MiniLM-L6-v2"),+ ("local", "bge_base.en-v1.5"),+ ("backend", "tinyhumans:default"),+ ] {+ assert_eq!(+ format_embedding_signature(provider, model, 768),+ format!("provider={provider};model={model};dims=768"),+ "{provider}/{model} must not be rewritten — it is a persisted key"+ );+ }+}++#[tokio::test]+async fn noop_returns_one_empty_vector_per_input() {+ let provider = NoopEmbedding;+ assert_eq!(provider.signature(), "provider=none;model=none;dims=0");+ assert_eq!(+ provider.embed(&["a", "b"]).await.unwrap(),+ vec![Vec::<f32>::new(), Vec::<f32>::new()]+ );+ assert!(provider.embed_one("a").await.unwrap().is_empty());+}++struct EmptyProvider;++#[async_trait]+impl EmbeddingProvider for EmptyProvider {+ fn name(&self) -> &str {+ "empty"+ }+ fn model_id(&self) -> &str {+ "empty"+ }+ fn dimensions(&self) -> usize {+ 0+ }+ async fn embed(&self, _: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {+ Ok(Vec::new())+ }+}++#[tokio::test]+async fn embed_one_rejects_a_provider_that_returns_no_vectors() {+ let error = EmptyProvider.embed_one("text").await.unwrap_err();+ assert!(error.to_string().contains("Empty embedding result"));+}diff --git a/crates/openhuman-core/src/inference/embedding_host/provider_trait.rs b/crates/openhuman-core/src/inference/embedding_host/provider_trait.rsindex 496658fbfb..487f96d70c 100644--- a/crates/openhuman-core/src/inference/embedding_host/provider_trait.rs+++ b/crates/openhuman-core/src/inference/embedding_host/provider_trait.rs@@ -41,7 +41,7 @@use async_trait::async_trait;use tinyinference_embeddings::EmbeddingModel;-pub use tinymemory_api::host::{format_embedding_signature, EmbeddingProvider};+pub use super::embedding_trait::{format_embedding_signature, EmbeddingProvider};/// Adapts the canonical TinyInference model to the memory-host contract.pub struct TinyInferenceEmbeddingProvider {