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
refactor: consume inference crates directly
Steven Enamakel39e27c068f4a
diff --git a/Cargo.lock b/Cargo.lockindex c45cd84a5a..a5f6904b85 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6437,6 +6437,7 @@ dependencies = [name = "tinyagents-harness"version = "2.1.2"dependencies = [+ "anyhow","async-trait","base64 0.22.1","bytes",@@ -6693,6 +6694,7 @@ dependencies = [name = "tinyinference"version = "0.2.1"dependencies = [+ "anyhow","async-trait","bytes","futures",diff --git a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs b/crates/openhuman-core/src/agent/harness/session/builder/factory.rsindex 1712541329..aad38a170f 100644--- a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs+++ b/crates/openhuman-core/src/agent/harness/session/builder/factory.rs@@ -482,9 +482,10 @@ impl Agent {// engine silently strips them, and the user gets a confident answer// about an image the model never saw. Log the actionable reason (which// model, and what to switch to) at the moment the decision is made.- if let Err(reason) =- crate::inference::provider::fallback_diagnostics::vision_preflight(&model_name, config)- {+ if !model_vision {+ let reason = tinyinference::classification::fallback::local_vision_unsupported_message(+ &model_name,+ );log::info!("[vision-preflight] {reason}");}diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs b/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rsindex 161a07a9bf..9c498244d3 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs@@ -5,7 +5,7 @@ use super::super::types::Agent;use crate::agent::dispatcher::ParsedToolCall;use crate::agent::error::AgentError;use crate::agent::messages::ConversationMessage;-use crate::inference::provider::{self, ToolCall};+use crate::inference::provider::ToolCall;use crate::util::truncate_with_ellipsis;impl Agent {@@ -83,7 +83,7 @@ impl Agent {return kind.to_string();}- let scrubbed = provider::sanitize_api_error(&err.to_string())+ let scrubbed = tinyinference::sanitize::sanitize_api_error(&err.to_string()).replace(['\n', '\r', '\t'], " ").split_whitespace().collect::<Vec<_>>()diff --git a/crates/openhuman-core/src/agent/host_runtime.rs b/crates/openhuman-core/src/agent/host_runtime.rsindex 0cbc196b32..b976979523 100644--- a/crates/openhuman-core/src/agent/host_runtime.rs+++ b/crates/openhuman-core/src/agent/host_runtime.rs@@ -111,7 +111,7 @@ fn maybe_hide_window(cmd: &mut tokio::process::Command, hide: bool) {if !hide {return;}- crate::inference::local::process_util::apply_no_window(cmd);+ tinyinference::local::process::apply_no_window(cmd);#[cfg(windows)]tracing::debug!(creation_flags = "0x08000000",diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rsindex de2dbaca5b..2b29c274e0 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs@@ -159,14 +159,14 @@ pub(super) fn scout_failure_signal(err: &SubagentRunError) -> String {/// Two billing shapes reach here, both **user-state, not defects**:/// * the managed OpenHuman backend's budget-exhausted 400/// (`{"error":"Insufficient budget","errorCode":"USER_INSUFFICIENT_CREDITS"}`),-/// matched by [`crate::inference::provider::is_budget_exhausted_message`];+/// matched by [`tinyinference::classification::is_budget_exhausted_message`];/// * a BYO provider's insufficient-credits 402, matched by/// [`crate::core::observability::is_insufficient_credits_message`].////// Both delegate to the crate's single-source classifiers so the phrase sets/// can't drift from the cron halt / `before_send` nets that share them.pub(super) fn is_expected_billing_failure(message: &str) -> bool {- crate::inference::provider::is_budget_exhausted_message(message)+ tinyinference::classification::is_budget_exhausted_message(message)|| crate::core::observability::is_insufficient_credits_message(message)}diff --git a/crates/openhuman-core/src/agent/schemas.rs b/crates/openhuman-core/src/agent/schemas.rsindex edae566e09..b07f4639ab 100644--- a/crates/openhuman-core/src/agent/schemas.rs+++ b/crates/openhuman-core/src/agent/schemas.rs@@ -518,7 +518,7 @@ fn handle_graph_topologies(_params: Map<String, Value>) -> ControllerFuture {fn local_catalog_models_from_config(config: &crate::config::Config,) -> Vec<crate::platform::cost::catalog::LocalCatalogModel> {- use crate::inference::local::profile::{profile_for_kind, LocalProviderKind, ToolSupport};+ use tinyinference::local::profile::{profile_for_kind, LocalProviderKind, ToolSupport};config.model_registrydiff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rsindex 977da0dea6..2b1e5b2c23 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs@@ -113,7 +113,7 @@ fn has_inference_failure_envelope(result: &str) -> bool {/// the two tight provider classifiers. Budget takes precedence if both match./// Ported from legacy `tool_loop::terminal_inference_failure_kind` (#3104).pub(crate) fn terminal_inference_failure_kind(result: &str) -> Option<TerminalInferenceFailure> {- use crate::inference::provider::{+ use tinyinference::classification::{is_budget_exhausted_message, is_provider_config_rejection_message,};if !has_inference_failure_envelope(result) {diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rsindex f94c1883df..e2229d92db 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs@@ -331,7 +331,7 @@ impl TurnModelSource {});let local_kind = provider_string.as_deref()- .and_then(crate::inference::local::profile::kind_from_provider_string);+ .and_then(tinyinference::local::profile::kind_from_provider_string);crate::inference::model_context::context_window_for_model_with_local_fallback(model, local_kind,)@@ -351,7 +351,7 @@ impl TurnModelSource {let provider = source.primary_override.clone().unwrap_or_else(|| {crate::inference::provider::provider_for_role(&source.role, &source.config)});- crate::inference::local::profile::is_local_provider_string(&provider)+ tinyinference::local::profile::is_local_provider_string(&provider)})}@@ -400,7 +400,7 @@ impl TurnModelSource {crate::inference::provider::provider_for_role(&cn.role, &cn.config)});let is_local =- crate::inference::local::profile::is_local_provider_string(&provider_string);+ tinyinference::local::profile::is_local_provider_string(&provider_string);let provider_id = if provider_string == "openhuman"|| provider_string.is_empty()|| provider_string == "cloud"diff --git a/crates/openhuman-core/src/agent/triage/routing.rs b/crates/openhuman-core/src/agent/triage/routing.rsindex 78ffcffbd9..063ecf3a7b 100644--- a/crates/openhuman-core/src/agent/triage/routing.rs+++ b/crates/openhuman-core/src/agent/triage/routing.rs@@ -143,10 +143,10 @@ fn is_local_cli_route(provider_string: &str) -> bool {/// errors because a local model is down. Only a concrete BYOK **cloud** route is/// honoured as-is. A build failure also falls back to the managed backend.fn build_remote_provider(config: &Config) -> anyhow::Result<ResolvedProvider> {- use crate::inference::local::profile::is_local_provider_string;use crate::inference::provider::factory::{create_chat_model_from_string_with_model_id, PROVIDER_OPENHUMAN,};+ use tinyinference::local::profile::is_local_provider_string;let resolved = provider::provider_for_role("subconscious", config);let r = resolved.trim();diff --git a/crates/openhuman-core/src/api/rest.rs b/crates/openhuman-core/src/api/rest.rsindex 5e28eacba3..977931e8bd 100644--- a/crates/openhuman-core/src/api/rest.rs+++ b/crates/openhuman-core/src/api/rest.rs@@ -807,7 +807,7 @@ impl BackendOAuthClient {let is_transient_infra =crate::core::observability::is_transient_http_status_code(status_code);let is_budget_exhausted = status_code == 400- && crate::inference::provider::is_budget_exhausted_message(&text);+ && tinyinference::classification::is_budget_exhausted_message(&text);if is_budget_exhausted {tracing::info!(method = method.as_str(),diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rsindex 5261bf20eb..b68ca51460 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs@@ -16,7 +16,6 @@ use crate::channels::traits;use crate::channels::{ChannelSendExt, SendMessage};use crate::core::bus::BUS;use crate::core::events::DomainEvent;-use crate::inference::provider;use crate::util::truncate_with_ellipsis;use std::sync::Arc;use std::time::{Duration, Instant};@@ -136,7 +135,7 @@ pub(crate) async fn process_channel_runtime_message(("provider", route.provider.as_str()),],);- let safe_err = provider::sanitize_api_error(&err.to_string());+ let safe_err = tinyinference::sanitize::sanitize_api_error(&err.to_string());let message = format!("⚠️ Failed to initialize provider `{}`. Please run `/models` to choose another provider.\nDetails: {safe_err}",route.providerdiff --git a/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider.rs b/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider.rsindex 1949362f22..733ff4e9ff 100644--- a/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider.rs+++ b/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider.rs@@ -53,9 +53,9 @@use crate::config::Config;use crate::inference::embeddings::{- DEFAULT_CLOUD_EMBEDDING_DIMENSIONS, DEFAULT_CLOUD_EMBEDDING_MODEL, DEFAULT_OLLAMA_DIMENSIONS,- DEFAULT_OLLAMA_MODEL,+ DEFAULT_CLOUD_EMBEDDING_DIMENSIONS, DEFAULT_CLOUD_EMBEDDING_MODEL,};+use tinyinference::embeddings::{DEFAULT_OLLAMA_DIMENSIONS, DEFAULT_OLLAMA_MODEL};/// The removed provider value that must not reach the embedding factory.const REMOVED_PROVIDER: &str = "fastembed";diff --git a/crates/openhuman-core/src/config/migrations/mod.rs b/crates/openhuman-core/src/config/migrations/mod.rsindex 1c6cfb27a9..c56861185d 100644--- a/crates/openhuman-core/src/config/migrations/mod.rs+++ b/crates/openhuman-core/src/config/migrations/mod.rs@@ -380,7 +380,9 @@ pub async fn run_pending(config: &mut Config) {.trim().eq_ignore_ascii_case("fastembed"){- let base = crate::inference::local::ollama_base_url_from_config(config);+ let base = tinyinference::local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ );migrate_legacy_embedding_provider::local_ollama_reachable(&base).await} else {falsediff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rsindex cc386adbac..445cfa26b7 100644--- a/crates/openhuman-core/src/config/ops/model.rs+++ b/crates/openhuman-core/src/config/ops/model.rs@@ -422,7 +422,7 @@ pub async fn apply_local_ai_settings(config.local_ai.opt_in_confirmed = v;}if let Some(provider) = update.provider {- config.local_ai.provider = crate::inference::local::provider::normalize_provider(&provider);+ config.local_ai.provider = tinyinference::local::provider::normalize_provider(&provider);}if let Some(base_url) = update.base_url {config.local_ai.base_url = match base_url {@@ -430,15 +430,18 @@ pub async fn apply_local_ai_settings(Some(base_url) if base_url.trim().is_empty() => None,// OMLX is an OpenAI-v1 endpoint: the `/v1` suffix is significant, so it// must NOT go through `validate_ollama_url` (which strips the path).- // `provider_from_config` maps omlx → Ollama, so guard on the slug here.+ // `provider_from_name` maps omlx → Ollama, so guard on the slug here.Some(base_url)- if crate::inference::local::provider::normalize_provider(+ if tinyinference::local::provider::normalize_provider(&config.local_ai.provider,) != "omlx"- && crate::inference::local::provider::provider_from_config(config)- == crate::inference::local::provider::LocalAiProvider::Ollama =>+ && tinyinference::local::provider::provider_from_name(+ &config.local_ai.provider,+ ) == tinyinference::local::provider::LocalAiProvider::Ollama =>{- Some(crate::inference::local::validate_ollama_url(&base_url)?)+ Some(tinyinference::local::ollama::validate_ollama_url(+ &base_url,+ )?)}Some(base_url) => Some(base_url.trim().trim_end_matches('/').to_string()),};diff --git a/crates/openhuman-core/src/config/schema/claude_agent_sdk.rs b/crates/openhuman-core/src/config/schema/claude_agent_sdk.rsindex 8979791a05..cd8aa8d45d 100644--- a/crates/openhuman-core/src/config/schema/claude_agent_sdk.rs+++ b/crates/openhuman-core/src/config/schema/claude_agent_sdk.rs@@ -42,3 +42,16 @@ impl Default for ClaudeAgentSdkConfig {}}}++impl From<&ClaudeAgentSdkConfig>+ for tinyagents_harness::providers::claude_agent_sdk::ClaudeAgentSdkConfig+{+ fn from(config: &ClaudeAgentSdkConfig) -> Self {+ Self {+ enabled: config.enabled,+ binary: config.binary.clone(),+ default_model: config.default_model.clone(),+ max_budget_usd: config.max_budget_usd,+ }+ }+}diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay.rs b/crates/openhuman-core/src/config/schema/load/env_overlay.rsindex e3604977e8..739289c7b3 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay.rs@@ -59,9 +59,7 @@ impl Config {set_runtime_proxy_config(self.proxy.clone());- crate::inference::embeddings::rate_limit::set_embedding_rate_limit(- self.memory.embedding_rate_limit_per_min,- );+ tinyinference::embeddings::set_rate_limit(self.memory.embedding_rate_limit_per_min);// Launch flags are process-local and intentionally win over both the// persisted file and ordinary environment overlays. They are applieddiff --git a/crates/openhuman-core/src/core/jsonrpc.rs b/crates/openhuman-core/src/core/jsonrpc.rsindex 5da59c4b95..53a108652c 100644--- a/crates/openhuman-core/src/core/jsonrpc.rs+++ b/crates/openhuman-core/src/core/jsonrpc.rs@@ -180,8 +180,7 @@ pub async fn rpc_handler(State(state): State<AppState>, Json(req): Json<RpcReque// query params, or pasted-through provider error text that// includes tokens. `sanitize_api_error` runs the same scrub// used in the SessionExpired publish path below.- let redacted =- crate::inference::provider::ops::sanitize_api_error(&display_message);+ let redacted = tinyinference::sanitize::sanitize_api_error(&display_message);tracing::warn!(method = %method,elapsed_ms = ms as u64,@@ -278,7 +277,7 @@ pub async fn invoke_method(state: AppState, method: &str, params: Value) -> Resu// the UI. Generic downstream/provider 401s must stay recoverable errors;// otherwise a scoped integration failure can log the user out.if let Err(ref msg) = result {- let sanitized_reason = crate::inference::provider::ops::sanitize_api_error(msg);+ let sanitized_reason = tinyinference::sanitize::sanitize_api_error(msg);if is_session_expired_error(msg) {log::warn!("[jsonrpc] confirmed session expiry for method='{}' — publishing SessionExpired: {}",diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rsindex e648d62b4f..4097ae234d 100644--- a/crates/openhuman-core/src/core/observability.rs+++ b/crates/openhuman-core/src/core/observability.rs@@ -103,7 +103,7 @@ pub enum ExpectedErrorKind {/// Deterministic user-config state surfaced in the UI — Sentry has no/// remediation path (OPENHUMAN-TAURI-WJ / -QW / -HB / -NH, ~273/// events). See- /// [`crate::inference::provider::is_provider_config_rejection_message`]+ /// [`tinyinference::classification::is_provider_config_rejection_message`]/// for the polarity contract and exact body shapes.ProviderConfigRejection,LocalAiCapabilityUnavailable,@@ -299,7 +299,7 @@ pub enum ExpectedErrorKind {/// The single exception — a backend-flagged **malformed** `BAD_REQUEST` —/// is NOT classified here (it is a client-built payload the backend/// couldn't parse, and the FE *does* page for it, F8). See- /// [`crate::inference::provider::backend_error_code_skips_sentry`].+ /// [`tinyinference::classification::backend_error_code_skips_sentry`].BackendErrorCodeOwned,/// A provider embedding call (Cohere `/v2/embed`, OpenAI/Voyage embed,/// custom OpenAI-compatible embed) returned a **403/Forbidden gateway@@ -423,7 +423,7 @@ pub fn expected_error_kind(message: &str) -> Option<ExpectedErrorKind> {// decision is gated on the managed-backend envelope so a BYO payload// carrying an `errorCode`-shaped field is not wrongly suppressed// (CodeRabbit).- if crate::inference::provider::managed_error_skips_sentry(message) {+ if tinyinference::classification::managed_error_skips_sentry(message) {return Some(ExpectedErrorKind::BackendErrorCodeOwned);}// A managed-backend client-guard-leak code (`PAYLOAD_TOO_LARGE` /@@ -436,8 +436,8 @@ pub fn expected_error_kind(message: &str) -> Option<ExpectedErrorKind> {// `ContextWindowExceeded` bucket (CodeRabbit). Gated on the managed envelope// so a BYO provider's own context-overflow — genuine user-state, not our// guard — still flows to that matcher and stays demoted.- if crate::inference::provider::is_managed_backend_envelope(message)- && crate::inference::provider::is_backend_client_guard_leak(message)+ if tinyinference::classification::is_managed_backend_envelope(message)+ && tinyinference::classification::is_backend_client_guard_leak(message){return None;}@@ -642,13 +642,13 @@ pub fn expected_error_kind(message: &str) -> Option<ExpectedErrorKind> {// backend never emits these phrases. See the predicate's polarity// contract. Drops OPENHUMAN-TAURI-WJ / -QW / -HB / -NH re-reports// (#2079 / #2076 / #2202).- if crate::inference::provider::is_provider_config_rejection_message(message) {+ if tinyinference::classification::is_provider_config_rejection_message(message) {return Some(ExpectedErrorKind::ProviderConfigRejection);}if is_local_ai_capability_unavailable_message(&lower) {return Some(ExpectedErrorKind::LocalAiCapabilityUnavailable);}- if crate::inference::provider::is_budget_exhausted_message(message) {+ if tinyinference::classification::is_budget_exhausted_message(message) {return Some(ExpectedErrorKind::BudgetExhausted);}if is_prompt_injection_blocked_message(&lower) {@@ -2474,7 +2474,7 @@ fn report_expected_message(kind: ExpectedErrorKind, message: &str, domain: &str,// The FE surfaces actionable copy via `classify_inference_error`;// Sentry must not double-report (F2/F4). Demote at `warn!` so the// breadcrumb retains the code for triage without spawning an event.- let code = crate::inference::provider::extract_backend_error_code_token(message)+ let code = tinyinference::classification::extract_backend_error_code_token(message).unwrap_or_default();tracing::warn!(domain = domain,@@ -2757,7 +2757,7 @@ pub fn is_transient_provider_http_failure(event: &sentry::protocol::Event<'_>) -/// classifier (`expected_error_kind` → [`ExpectedErrorKind::BackendErrorCodeOwned`])./// This catches any future call site that re-emits the same flattened error/// without routing through those funnels. Delegates the decision to the-/// single-source [`crate::inference::provider::managed_error_skips_sentry`]+/// single-source [`tinyinference::classification::managed_error_skips_sentry`]/// (managed-envelope gated, so a BYO payload carrying an `errorCode`-shaped/// field is not wrongly dropped) so the layers can't drift.#[cfg(feature = "crash-reporting")]@@ -2768,7 +2768,7 @@ pub fn is_backend_error_code_event(event: &sentry::protocol::Event<'_>) -> bool[direct, from_logentry, from_exception].into_iter().flatten()- .any(crate::inference::provider::managed_error_skips_sentry)+ .any(tinyinference::classification::managed_error_skips_sentry)}/// Defense-in-depth `before_send` filter for transient streaming **transport**@@ -3494,7 +3494,7 @@ fn event_contains_budget_exhausted_message(event: &sentry::protocol::Event<'_>)if event.message.as_deref()- .is_some_and(crate::inference::provider::is_budget_exhausted_message)+ .is_some_and(tinyinference::classification::is_budget_exhausted_message){return true;}@@ -3503,7 +3503,7 @@ fn event_contains_budget_exhausted_message(event: &sentry::protocol::Event<'_>)exception.value.as_deref()- .is_some_and(crate::inference::provider::is_budget_exhausted_message)+ .is_some_and(tinyinference::classification::is_budget_exhausted_message)})}diff --git a/crates/openhuman-core/src/cron/scheduler/failure_classification.rs b/crates/openhuman-core/src/cron/scheduler/failure_classification.rsindex 18f8d9780a..041e88eb9e 100644--- a/crates/openhuman-core/src/cron/scheduler/failure_classification.rs+++ b/crates/openhuman-core/src/cron/scheduler/failure_classification.rs@@ -193,7 +193,7 @@ pub(super) fn is_budget_exhausted_failure(return false;}let signal = last_agent_error.unwrap_or(last_output);- crate::inference::provider::is_budget_exhausted_message(signal)+ tinyinference::classification::is_budget_exhausted_message(signal)}/// TAURI-RUST-HCK — a cron **agent** job pinned to a provider with nodiff --git a/crates/openhuman-core/src/inference/README.md b/crates/openhuman-core/src/inference/README.mdindex 2bc491fa69..735b584277 100644--- a/crates/openhuman-core/src/inference/README.md+++ b/crates/openhuman-core/src/inference/README.md@@ -29,39 +29,33 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.| `mod.rs` | Domain root; module decls + re-exports; wires `inference.*` controller schemas/controllers. || `ops.rs` | Canonical handler file — `inference_*` business logic returning `RpcOutcome<T>`; delegates to `local`, `provider`, `sentiment`, `device`, `presets`, `openai_oauth`. Includes Sentry-noise suppression for expected provider/user-config failures. || `schemas.rs` + `schemas/` (`catalog.rs`, `prompt_handlers.rs`, `oauth_handlers.rs`, `claude_code_handlers.rs`, `settings_handlers.rs`) | `inference.*` controller schemas + `handle_*` fns + param DTOs. |-| `auth_error_registry.rs` | Process-lived registry of rejected BYO keys (401/403): `record`/`clear`/`snapshot` feed `inference.provider_auth_errors` and the one-shot `DomainEvent::ProviderApiKeyRejected`. |+| `tinyinference::{auth_errors,classification,completion,device,sanitize,sentiment}` | Reusable inference state, parsing, hardware detection, diagnostics, and error sanitization called directly by the host. || `tinyinference::model::model_id_supports_vision` | Upstream capability hint used directly for local model ids when the runtime cannot return an authoritative profile. || `tinyinference::model::effective_temperature` | Applies unsupported-model glob patterns and overrides before provider serialization. || `types.rs` | Serde DTOs: `LocalAiStatus`, `LocalAiAssetsStatus`, `LocalAiDownloadsProgress`, `LocalAiEmbeddingResult`, `LocalAiSpeechResult`, `LocalAiTtsResult`, etc. |-| `device.rs` | `DeviceProfile` hardware detection (RAM/CPU/GPU/OS), cached. || `model_ids.rs` | Effective chat/vision/embedding/STT/TTS/quantization model id resolution from config. || `model_context.rs` | Known model context-window sizes (`context_window_for_model`) for pre-dispatch budgeting. || `presets.rs` | `ModelPreset`, `ModelTier`, `VisionMode`; tier recommendation + apply-to-config; MVP preset gating. |-| `sentiment.rs` | `SentimentResult` + emotion/valence analysis via the local model. |-| `parse.rs` / `paths.rs` | Output parsing helpers / on-disk model artifact paths. |+| `paths.rs` | Host-owned on-disk model artifact paths. Completion and sentiment parsing live in `tinyinference`. || `local/` | Local runtime manager (was `local_ai/`). See `local/README.md`. || `local/core.rs` | `LocalAiService` singleton (`global`/`try_global`), `model_artifact_path`. || `local/ops.rs` + `local/ops/` (`runtime_ops.rs`, `chat.rs`, `agent_chat.rs`, `reactions.rs`, `turn_guards.rs`) | Local RPC entrypoints (`local_ai_status/prompt/summarize/vision_prompt/embed/should_react`, `ReactionDecision`); re-exported as `local::rpc`. || `local/schemas.rs` | Local-runtime `inference.*` controller schemas + handlers. |-| `local/ollama.rs`, `local/lm_studio.rs` | Ollama / LM Studio HTTP wire types and base-url resolution (`ollama_base_url[_from_config]`, `validate_ollama_url`, `lm_studio_base_url`). || `local/install*.rs`, `local/voice_install_common.rs` | Ollama/Piper install + shared download logic. No Whisper install any more. |-| `local/model_requirements.rs` | `MIN_CONTEXT_TOKENS`, `evaluate_context`, `ContextEligibility`. |-| `local/profile.rs` | `LocalProviderProfile` capability metadata (tool-dispatch strategy, context defaults, request-body quirks) per local provider type. |-| `local/process_util.rs` | Shared subprocess helpers (e.g. Windows `CREATE_NO_WINDOW`), reused from `agent::host_runtime`. |-| `local/provider.rs` | `LocalAiProvider` (Ollama / LM Studio) selection helpers. |+| `tinyinference::local` | Ollama/LM Studio wire types, URL handling, model requirements, runtime profiles, provider selection, process flags, and spawn-marker persistence. || `local/service/` | `LocalAiService` impl split: `bootstrap`, `assets`, `lm_studio`, `model_rpc`, `public_infer`, `speech`, `transcription`, `vision_embed`, `spawn_marker`, `ollama_admin/`. || `local/service/ollama_admin/` | Ollama daemon lifecycle split by concern: `binary`, `diagnostics`, `health`, `model_pull`, `server`, `util` (`test_ollama_connection`). || `provider/` | Native TinyAgents model construction plus host provider configuration, auth, error taxonomy, DTOs, and RPC helpers (was `providers/`). See `provider/README.md`. || `provider/types.rs` | Host request/response, streaming delta, tool-call, and usage DTOs retained at product/RPC boundaries. || `provider/factory.rs` + `provider/factory/` (`routing.rs`, `tiers.rs`, `turn_model.rs`, `subprocess_providers.rs`, `access_gates.rs`, `chat_model.rs`, `cloud_slug.rs`, `credentials.rs`, `local_runtime.rs`, `managed_backend.rs`, `primary_cloud.rs`) | `create_chat_model*`, `provider_for_role`, provider-string grammar, access gates, and local/cloud/CLI model construction; `BYOK_INCOMPLETE_SENTINEL`. |-| `provider/crate_openai.rs`, `provider/crate_anthropic.rs` | TinyAgents OpenAI-compatible and Anthropic Messages API model builders (managed, BYOK, and local endpoints; prompt caching). |+| `tinyinference::providers::{openai,anthropic}` | OpenAI-compatible and Anthropic model builders, including Codex metadata and local-runtime construction. || `provider/openhuman_backend_model.rs` | Managed OpenHuman backend `ChatModel` with session JWT, billing metadata, and thread context. || `provider/openai_codex.rs` | `pub(crate)` Codex routing metadata (`OpenAiCodexRouting`, `resolve_openai_codex_routing`): re-targets the `openai` slug at the ChatGPT Codex backend with account/originator headers when Codex OAuth tokens exist. Not a `ChatModel` itself. |-| `provider/claude_agent_sdk/` | Claude Agent SDK subprocess provider (`protocol.rs`, `subprocess.rs`). |+| `tinyagents_harness::providers::claude_agent_sdk` | Claude Agent SDK subprocess provider and prompt-guided tool adapter. || `provider/claude_code/` | Claude Code CLI provider (`claude-code:<model>`). Drives the `claude` CLI over stream-json; see `provider/claude_code/README.md`. |-| `provider/config_rejection.rs`, `provider/billing_error.rs`, `provider/error_classify.rs`, `provider/error_code.rs`, `provider/fallback_diagnostics.rs`, `provider/chat_template.rs` | Error classifiers (unknown-model / config rejection / budget exhausted / chat-template rejection / backend error codes / background-workload fallback diagnostics). |+| `provider/error_classify.rs` | OpenHuman policy layered on the reusable classifiers in `tinyinference::classification`. || `tinyinference::providers::openai::AuthStyle` | Wire auth style consumed directly by crate-native builders. |-| `provider/ops/` | Split from a single `ops.rs`: `sanitize` (secret scrubbing), `http_error` (HTTP error classification, Sentry routing, `api_error`), `models` (`list_configured_models`), `provider_factory` (`ProviderRuntimeOptions`, `list_providers`). |+| `provider/ops/` | Host HTTP policy, model catalog RPC, and provider configuration; reusable sanitization lives in `tinyinference::sanitize`. || `provider/schemas.rs` | Defines a `providers.list_models` controller that is **not** wired into `core/all.rs`; the live method is `inference.list_models` (`openhuman.providers_list_models` survives only as a legacy alias). || `voice/` | Inference implementations imported by `crate::voice`. || `voice/cloud_transcribe.rs`, `voice/local_speech.rs` | Hosted STT and local Piper TTS. |@@ -75,10 +69,8 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.From `mod.rs` re-exports:-- `device::DeviceProfile`- `model_context::context_window_for_model`- `presets::{ModelPreset, ModelTier, VisionMode}`-- `sentiment::SentimentResult`- `types::{LocalAiStatus, LocalAiAssetStatus, LocalAiAssetsStatus, LocalAiDownloadProgressItem, LocalAiDownloadsProgress, LocalAiEmbeddingResult, LocalAiSpeechResult, LocalAiTtsResult}`- `local::all_local_inference_controller_schemas` / `local::all_local_inference_registered_controllers` (legacy export names; registered schemas are in the `inference` namespace)- `rpc` (alias for `ops`) and `all_inference_controller_schemas` / `all_inference_registered_controllers`@@ -98,7 +90,7 @@ Also exposes a non-RPC HTTP router (`http::router()`) nested at `/v1` by `crates## Events- Publishes `DomainEvent::SessionExpired` from `provider/ops/http_error/auth_failure.rs` (`publish_backend_session_expired`) and `provider/openhuman_backend_model.rs` when the managed backend rejects a session, so the credentials layer can clear/refresh it.-- Publishes `DomainEvent::ProviderApiKeyRejected` once per provider from `provider/ops/http_error/auth_failure.rs` the first time a BYO key is rejected (401/403), gated by `auth_error_registry::record`.+- Publishes `DomainEvent::ProviderApiKeyRejected` once per provider from `provider/ops/http_error/auth_failure.rs` the first time a BYO key is rejected (401/403), gated by `tinyinference::auth_errors::record`.- No `bus.rs` / `EventHandler` subscribers in this domain.## Persistencediff --git a/crates/openhuman-core/src/inference/embeddings/factory.rs b/crates/openhuman-core/src/inference/embeddings/factory.rsindex a4354a78a9..ced922e007 100644--- a/crates/openhuman-core/src/inference/embeddings/factory.rs+++ b/crates/openhuman-core/src/inference/embeddings/factory.rs@@ -109,7 +109,7 @@ pub fn create_embedding_provider(),)),"ollama" => {- let base_url = crate::inference::local::ollama_base_url();+ let base_url = tinyinference::local::ollama::ollama_base_url();Ok(TinyAgentsEmbeddingProvider::boxed(OllamaEmbeddingModel::try_new(&base_url, model, dims)?,))@@ -163,7 +163,7 @@ pub fn create_embedding_provider_with_credentials(),)),"ollama" => {- let base_url = crate::inference::local::ollama_base_url();+ let base_url = tinyinference::local::ollama::ollama_base_url();Ok(TinyAgentsEmbeddingProvider::boxed(OllamaEmbeddingModel::try_new(&base_url, model, dims)?,))@@ -241,7 +241,9 @@ pub fn create_embedding_provider_with_config(// is honoured — the credential-store path calls `ollama_base_url()`// (env-only) and diverges when the setting is set (#6032)."ollama" => {- let base_url = crate::inference::local::ollama_base_url_from_config(config);+ let base_url = tinyinference::local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ );Ok(TinyAgentsEmbeddingProvider::boxed(OllamaEmbeddingModel::try_new(&base_url, model, dims)?,))diff --git a/crates/openhuman-core/src/inference/embeddings/mod.rs b/crates/openhuman-core/src/inference/embeddings/mod.rsindex 6242f8edcd..bba3403c33 100644--- a/crates/openhuman-core/src/inference/embeddings/mod.rs+++ b/crates/openhuman-core/src/inference/embeddings/mod.rs@@ -18,22 +18,6 @@ pub mod cloud;mod factory;pub mod noop;mod provider_trait;-pub mod rate_limit {- pub use tinyinference::embeddings::{- rate_limit as embedding_rate_limit, set_rate_limit as set_embedding_rate_limit,- DEFAULT_REQUESTS_PER_MINUTE as DEFAULT_EMBEDDING_RATE_LIMIT_PER_MIN,- };-- pub async fn acquire_embedding_slot(base_url: &str) {- tinyinference::embeddings::acquire(base_url).await;- }-}-pub mod retry_after {- pub use tinyinference::embeddings::{- backoff_ms_for_attempt, parse_retry_after_ms, BASE_BACKOFF_MS, MAX_BACKOFF_MS,- MAX_RETRIES as MAX_429_RETRIES,- };-}mod rpc;mod schemas;@@ -63,9 +47,7 @@ pub use schemas::{all_controller_schemas as all_embeddings_controller_schemas,all_registered_controllers as all_embeddings_registered_controllers,};-pub use tinyinference::embeddings::{- DEFAULT_OLLAMA_DIMENSIONS, DEFAULT_OLLAMA_MODEL, DEFAULT_OLLAMA_URL,-};+use tinyinference::embeddings::{DEFAULT_OLLAMA_DIMENSIONS, DEFAULT_OLLAMA_MODEL};/// The **intended** embedding selection — `(provider, model, dimensions)`.///diff --git a/crates/openhuman-core/src/inference/embeddings/mod_tests.rs b/crates/openhuman-core/src/inference/embeddings/mod_tests.rsindex 3dbdada08e..764cac902a 100644--- a/crates/openhuman-core/src/inference/embeddings/mod_tests.rs+++ b/crates/openhuman-core/src/inference/embeddings/mod_tests.rs@@ -5,6 +5,7 @@//! `embeddings` module.use super::*;+use tinyinference::embeddings::{DEFAULT_OLLAMA_DIMENSIONS, DEFAULT_OLLAMA_MODEL};// ── Trait default method ─────────────────────────────────diff --git a/crates/openhuman-core/src/inference/local/README.md b/crates/openhuman-core/src/inference/local/README.mdindex 38ccaf0963..ede8589ee9 100644--- a/crates/openhuman-core/src/inference/local/README.md+++ b/crates/openhuman-core/src/inference/local/README.md@@ -9,17 +9,12 @@ single-crate layout); see `../README.md` for the wider `inference` domain.| File / dir | Role || --- | --- |-| `mod.rs` | Re-exports `super::{device, model_ids, parse, paths, presets, sentiment, types}` under `local::` (compatibility for files migrated from `local_ai/`); `pub use core::*`, `pub use ops as rpc`, `pub use service::LocalAiService`. |+| `mod.rs` | Exposes the host service and RPC surface; reusable local-runtime APIs are consumed directly from `tinyinference::local`. || `core.rs` | `LocalAiService` singleton (`global`/`try_global`), `model_artifact_path`. || `ops.rs` + `ops/` (`runtime_ops.rs`, `chat.rs`, `agent_chat.rs`, `reactions.rs`, `turn_guards.rs`) | RPC entry points: `local_ai_status/prompt/summarize/vision_prompt/embed/transcribe[_bytes]/tts/chat`, `agent_chat[_simple]`, `local_ai_should_react` (`ReactionDecision`), assets/downloads status. || `schemas.rs` | Local-runtime `inference.*` controller schemas + handlers (see RPC below); exported as `all_local_inference_controller_schemas` / `all_local_inference_registered_controllers`. |-| `ollama.rs` | Ollama HTTP JSON types, `DEFAULT_OLLAMA_BASE_URL`, `ollama_base_url[_from_config]`, `validate_ollama_url`. |-| `lm_studio.rs` | LM Studio OpenAI-compatible wire types, `lm_studio_base_url[_from_local_ai]`, URL normalisation and auth header; the daemon is only probed, never started. || `install.rs`, `install_piper.rs`, `voice_install_common.rs` | Ollama/Piper download and install; shared download-progress plumbing. No Whisper install any more — local STT was retired (`config/migrations/retire_local_whisper_stt.rs`). |-| `model_requirements.rs` | `MIN_CONTEXT_TOKENS`, `evaluate_context`, `ContextEligibility` — minimum-context-window floor enforcement. |-| `profile.rs` | `LocalProviderProfile` per-provider-type capability metadata (tool-dispatch strategy, context-window defaults, request-body extras like `options.num_ctx`, `think` suppression) consulted by the factory and agent harness. |-| `process_util.rs` | Shared subprocess helpers (`pub(crate)`, notably the Windows `CREATE_NO_WINDOW` flag) reused by `agent::host_runtime`. |-| `provider.rs` | `pub(crate)` `LocalAiProvider` (Ollama / LM Studio), `normalize_provider`, `provider_from_config`; `omlx` is preserved as a slug for the factory rather than collapsed to Ollama. |+| `tinyinference::local` | Ollama/LM Studio wire contracts, URL validation, model requirements, profiles, provider selection, subprocess flags, and spawn markers. || `service/` | `LocalAiService` impl, split by concern (below). |## `service/` split@@ -33,7 +28,6 @@ single-crate layout); see `../README.md` for the wider `inference` domain.| `speech.rs` | `transcribe`, `transcribe_with_prompt`, `tts` — delegates STT to `crate::voice::create_stt_provider` (cloud/engine-configurable) and TTS to the local Piper install. || `transcription.rs` | `TranscriptionResult` — provider-neutral transcription result type. It outlived the bundled whisper.cpp engine that introduced it; the shape is still the contract with `channels::host::adapters`. || `vision_embed.rs` | Vision-prompt and embedding entry points. |-| `spawn_marker.rs` | Writes a marker file (PID, binary, owning process) for each `ollama serve` this process spawned so a daemon orphaned by a crash can be reclaimed (`ollama_admin/server.rs::reclaim_orphan_if_ours`) instead of leaked or blanket-killed. || `assets.rs` + `assets/` (`status.rs`, `progress.rs`, `download.rs`, `tts_download.rs`) | Asset status and download-progress tracking. || `ollama_admin/` | Ollama daemon lifecycle, split by concern: `binary` (`resolve_or_install_ollama_binary`), `diagnostics`, `health` (`ollama_healthy*`, `has_model*`, `kill_ollama_server`, `shutdown_owned_ollama`), `model_pull`, `server` (`ensure_ollama_server[_fresh]`, `reclaim_orphan_if_ours`, `start_and_wait_for_server` — adopt vs own), `util` (`test_ollama_connection`, the only item re-exported from `ollama_admin/mod.rs`). |@@ -78,16 +72,16 @@ base-url resolution when routing into a local runtime), `inference/embeddings/fa`validate_ollama_url`), `agent/tinyagents/turn_models.rs` and `agent/triage/routing.rs`(`profile::is_local_provider_string`), `voice/ops.rs` (`model_ids`, `paths`), and`agent/host_runtime.rs`, `runtime/python/process.rs`, `runtime/python_server/{kompress,spacy}.rs`-(`process_util::apply_no_window`).+(`tinyinference::local::process::apply_no_window`).## Tests- Per-file `*_tests.rs` (`core_tests.rs`, `install_tests.rs`,`install_piper_tests.rs`, `lm_studio_tests.rs`, `model_requirements_tests.rs`,- `ollama_tests.rs`, `ops_tests.rs`, `process_util_tests.rs`, `profile_tests.rs`,- `provider_tests.rs`, `schemas_tests.rs`, `voice_install_common_tests.rs`).+ `ops_tests.rs`, `schemas_tests.rs`, `voice_install_common_tests.rs`). Reusable+ runtime-helper tests live in TinyInference.- `service/*_tests.rs` (`bootstrap_tests.rs`, `model_rpc_tests.rs`,- `public_infer_tests.rs`, `spawn_marker_tests.rs`, `vision_embed_tests.rs`,+ `public_infer_tests.rs`, `vision_embed_tests.rs`,`ollama_admin_tests*.rs`).- Tests that touch the runtime singleton or shared config serialize through`inference_test_guard()` (a process-global mutex defined in `mod.rs`,diff --git a/crates/openhuman-core/src/inference/local/install.rs b/crates/openhuman-core/src/inference/local/install.rsindex 1879e65035..79c7f5c08e 100644--- a/crates/openhuman-core/src/inference/local/install.rs+++ b/crates/openhuman-core/src/inference/local/install.rs@@ -124,7 +124,7 @@ fn build_install_command(install_dir: &Path) -> Result<tokio::process::Command,// crash-resume detection in `is_ollama_installer_running` picks it// up on the next OpenHuman launch and waits.cmd.kill_on_drop(true);- crate::inference::local::process_util::apply_no_window(&mut cmd);+ tinyinference::local::process::apply_no_window(&mut cmd);cmd.env("OPENHUMAN_OLLAMA_INSTALL_DIR", install_dir);cmd.args(["-NoProfile",diff --git a/crates/openhuman-core/src/inference/local/mod.rs b/crates/openhuman-core/src/inference/local/mod.rsindex 53732bcb1b..5db95eedc2 100644--- a/crates/openhuman-core/src/inference/local/mod.rs+++ b/crates/openhuman-core/src/inference/local/mod.rs@@ -22,26 +22,16 @@ mod schemas;// Re-expose inference-level modules under `local::` so that files that// were moved from `local_ai/` and used `super::model_ids` etc. continue// to compile without rewriting every callsite.-pub use super::device;pub use super::model_ids;-pub use super::parse;pub use super::paths;pub use super::presets;-pub use super::sentiment;pub use super::types;pub mod install;pub(crate) mod install_piper;-pub(crate) mod lm_studio;-pub(crate) mod model_requirements;-mod ollama;// `pub(crate)` so the shared `apply_no_window` helper can be reused from the// agent shell runtime (`agent::host_runtime`) — single source of truth for the// Windows `CREATE_NO_WINDOW` flag (#3727/#3728).-pub(crate) mod process_util;-pub mod profile;-pub(crate) mod provider;-pub(crate) use ollama::{ollama_base_url, ollama_base_url_from_config, validate_ollama_url};pub mod service;pub(crate) mod voice_install_common;diff --git a/crates/openhuman-core/src/inference/local/ops/chat.rs b/crates/openhuman-core/src/inference/local/ops/chat.rsindex 7e31c65088..b06c8d1e5d 100644--- a/crates/openhuman-core/src/inference/local/ops/chat.rs+++ b/crates/openhuman-core/src/inference/local/ops/chat.rs@@ -30,7 +30,7 @@ pub async fn local_ai_chat(return Err("messages must not be empty".to_string());}- let mut ollama_messages: Vec<crate::inference::local::ollama::OllamaChatMessage> =+ let mut ollama_messages: Vec<tinyinference::local::ollama::OllamaChatMessage> =Vec::with_capacity(messages.len());for msg in messages.into_iter() {@@ -48,7 +48,7 @@ pub async fn local_ai_chat(}}- ollama_messages.push(crate::inference::local::ollama::OllamaChatMessage {+ ollama_messages.push(tinyinference::local::ollama::OllamaChatMessage {role: normalized_role,content: msg.content,});diff --git a/crates/openhuman-core/src/inference/local/ops/runtime_ops.rs b/crates/openhuman-core/src/inference/local/ops/runtime_ops.rsindex c5b04eb896..6f2e76ff31 100644--- a/crates/openhuman-core/src/inference/local/ops/runtime_ops.rs+++ b/crates/openhuman-core/src/inference/local/ops/runtime_ops.rs@@ -30,9 +30,10 @@ pub async fn local_ai_status(config: &Config) -> Result<RpcOutcome<LocalAiStatus// (e.g. ollama → lm_studio) the cached value is stale, so we overlay// the current config's provider on the status snapshot before returning.let mut snapshot = service.status();- snapshot.provider = local_ai::provider::provider_from_config(config)- .as_str()- .to_string();+ snapshot.provider =+ tinyinference::local::provider::provider_from_name(&config.local_ai.provider)+ .as_str()+ .to_string();Ok(RpcOutcome::single_log(snapshot, "local ai status fetched"))}diff --git a/crates/openhuman-core/src/inference/local/service/assets/download.rs b/crates/openhuman-core/src/inference/local/service/assets/download.rsindex 636a35feb6..834078ab7c 100644--- a/crates/openhuman-core/src/inference/local/service/assets/download.rs+++ b/crates/openhuman-core/src/inference/local/service/assets/download.rs@@ -1,11 +1,11 @@//! Triggering model downloads: everything the profile needs, or one asset.use crate::config::Config;-use crate::inference::local::provider::{provider_from_config, LocalAiProvider};use crate::inference::local::service::LocalAiService;use crate::inference::model_ids;use crate::inference::presets::{self, VisionMode};use crate::inference::types::LocalAiAssetsStatus;+use tinyinference::local::provider::{provider_from_name, LocalAiProvider};impl LocalAiService {pub async fn download_all_models(&self, config: &Config) -> Result<(), String> {@@ -14,7 +14,7 @@ impl LocalAiService {}let _guard = self.bootstrap_lock.lock().await;- if provider_from_config(config) == LocalAiProvider::LmStudio {+ if provider_from_name(&config.local_ai.provider) == LocalAiProvider::LmStudio {self.ensure_lm_studio_available(config).await?;let mut embedding_state = None;if config.local_ai.preload_embedding_model {@@ -131,7 +131,7 @@ impl LocalAiService {let _guard = self.bootstrap_lock.lock().await;let capability = capability.trim().to_ascii_lowercase();- if provider_from_config(config) == LocalAiProvider::LmStudio+ if provider_from_name(&config.local_ai.provider) == LocalAiProvider::LmStudio&& matches!(capability.as_str(), "chat" | "vision"){return Err(diff --git a/crates/openhuman-core/src/inference/local/service/assets/status.rs b/crates/openhuman-core/src/inference/local/service/assets/status.rsindex 150a11411f..3226195fcb 100644--- a/crates/openhuman-core/src/inference/local/service/assets/status.rs+++ b/crates/openhuman-core/src/inference/local/service/assets/status.rs@@ -3,12 +3,12 @@use tracing::{debug, trace};use crate::config::Config;-use crate::inference::local::provider::{provider_from_config, LocalAiProvider};use crate::inference::local::service::LocalAiService;use crate::inference::model_ids;use crate::inference::paths::resolve_tts_voice_path;use crate::inference::presets::{self, VisionMode};use crate::inference::types::{LocalAiAssetStatus, LocalAiAssetsStatus};+use tinyinference::local::provider::{provider_from_name, LocalAiProvider};impl LocalAiService {pub async fn assets_status(&self, config: &Config) -> Result<LocalAiAssetsStatus, String> {@@ -17,7 +17,7 @@ impl LocalAiService {let embedding_model = model_ids::effective_embedding_model_id(config);let tts_voice = model_ids::effective_tts_voice_id(config);- let provider = provider_from_config(config);+ let provider = provider_from_name(&config.local_ai.provider);let correlation_id = uuid::Uuid::new_v4().to_string();trace!(target: "local_ai::assets",@@ -37,7 +37,9 @@ impl LocalAiService {LocalAiProvider::Ollama | LocalAiProvider::LmStudio);let ollama_available = if uses_ollama_assets {- let base_url = crate::inference::local::ollama_base_url_from_config(config);+ let base_url = tinyinference::local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ );let present = self.ollama_healthy_at(&base_url).await;debug!(target: "local_ai::assets",diff --git a/crates/openhuman-core/src/inference/local/service/bootstrap.rs b/crates/openhuman-core/src/inference/local/service/bootstrap.rsindex d28dca5e48..aafc2c4b2c 100644--- a/crates/openhuman-core/src/inference/local/service/bootstrap.rs+++ b/crates/openhuman-core/src/inference/local/service/bootstrap.rs@@ -1,9 +1,9 @@use crate::config::Config;-use crate::inference::device::DeviceProfile;-use crate::inference::local::provider::{provider_from_config, LocalAiProvider};use crate::inference::model_ids;use crate::inference::presets::{self, VisionMode};use crate::inference::types::LocalAiStatus;+use tinyinference::device::DeviceProfile;+use tinyinference::local::provider::{provider_from_name, LocalAiProvider};use super::LocalAiService;@@ -13,7 +13,7 @@ impl LocalAiService {let vision_model_id = model_ids::effective_vision_model_id(config);let embedding_model_id = model_ids::effective_embedding_model_id(config);let vision_mode = vision_mode_str(config);- let provider = provider_from_config(config);+ let provider = provider_from_name(&config.local_ai.provider);Self {status: parking_lot::Mutex::new(LocalAiStatus {state: "idle".to_string(),@@ -76,7 +76,7 @@ impl LocalAiService {pub fn reset_to_idle(&self, config: &Config) {let model_id = model_ids::effective_chat_model_id(config);let vision_mode = vision_mode_str(config);- let provider = provider_from_config(config);+ let provider = provider_from_name(&config.local_ai.provider);let mut status = self.status.lock();status.state = "idle".to_string();status.model_id = model_id.clone();@@ -127,7 +127,7 @@ impl LocalAiService {pub async fn bootstrap(&self, config: &Config) {let _guard = self.bootstrap_lock.lock().await;- let device = crate::inference::device::detect_device_profile();+ let device = tinyinference::device::detect_device_profile();let effective_config = config_with_recommended_tier_if_unselected(config, &device);if !effective_config.local_ai.runtime_enabled {@@ -144,7 +144,7 @@ impl LocalAiService {}{- let provider = provider_from_config(&effective_config);+ let provider = provider_from_name(&effective_config.local_ai.provider);let mut status = self.status.lock();status.model_id = model_ids::effective_chat_model_id(&effective_config);status.chat_model_id = model_ids::effective_chat_model_id(&effective_config);@@ -175,7 +175,7 @@ impl LocalAiService {status.model_path = Some(model_path_for_config(&effective_config));}- if provider_from_config(&effective_config) == LocalAiProvider::LmStudio {+ if provider_from_name(&effective_config.local_ai.provider) == LocalAiProvider::LmStudio {log::debug!("[local_ai] LM Studio bootstrap branch entry preload_embedding={} preload_tts={}",effective_config.local_ai.preload_embedding_model,@@ -410,7 +410,7 @@ fn vision_mode_str(config: &Config) -> String {fn model_path_for_config(config: &Config) -> String {let model_id = model_ids::effective_chat_model_id(config);- match provider_from_config(config) {+ match provider_from_name(&config.local_ai.provider) {LocalAiProvider::Ollama => format!("ollama://{model_id}"),LocalAiProvider::LmStudio => format!("lmstudio://{model_id}"),}diff --git a/crates/openhuman-core/src/inference/local/service/lm_studio.rs b/crates/openhuman-core/src/inference/local/service/lm_studio.rsindex 7c49ac7c7b..fc7536c04f 100644--- a/crates/openhuman-core/src/inference/local/service/lm_studio.rs+++ b/crates/openhuman-core/src/inference/local/service/lm_studio.rs@@ -1,8 +1,8 @@use crate::config::Config;-use crate::inference::local::lm_studio::{+use tinyinference::local::lm_studio::{apply_lm_studio_auth, lm_studio_base_url, ollama_tags_fallback_url, LmStudioModelsResponse,};-use crate::inference::local::ollama::{OllamaModelTag, OllamaTagsResponse};+use tinyinference::local::ollama::{OllamaModelTag, OllamaTagsResponse};use super::LocalAiService;@@ -33,7 +33,7 @@ impl LocalAiService {&self,config: &Config,) -> Result<Vec<OllamaModelTag>, String> {- let base = lm_studio_base_url(config);+ let base = lm_studio_base_url(config.local_ai.base_url.as_deref());let url = format!("{base}/models");// GH #5055: log the *resolved* discovery URL so a wrong base URL is// diagnosable from app logs alone, without reproducing against the@@ -50,7 +50,7 @@ impl LocalAiService {.http.get(&url).timeout(std::time::Duration::from_secs(5));- let response = apply_lm_studio_auth(request, config)+ let response = apply_lm_studio_auth(request, config.local_ai.api_key.as_deref()).send().await.map_err(|e| {@@ -158,7 +158,10 @@ impl LocalAiService {.http.get(&fallback_url).timeout(std::time::Duration::from_secs(5));- let response = match apply_lm_studio_auth(request, config).send().await {+ let response = match apply_lm_studio_auth(request, config.local_ai.api_key.as_deref())+ .send()+ .await+ {Ok(r) => r,Err(e) => {tracing::debug!(diff --git a/crates/openhuman-core/src/inference/local/service/mod.rs b/crates/openhuman-core/src/inference/local/service/mod.rsindex 65d00b271b..0033acda4f 100644--- a/crates/openhuman-core/src/inference/local/service/mod.rs+++ b/crates/openhuman-core/src/inference/local/service/mod.rs@@ -6,7 +6,6 @@ mod lm_studio;mod model_rpc;pub(crate) mod ollama_admin;mod public_infer;-pub(crate) mod spawn_marker;mod speech;pub(crate) mod transcription;mod vision_embed;diff --git a/crates/openhuman-core/src/inference/local/service/model_rpc.rs b/crates/openhuman-core/src/inference/local/service/model_rpc.rsindex fc9c705330..015ed997f2 100644--- a/crates/openhuman-core/src/inference/local/service/model_rpc.rs+++ b/crates/openhuman-core/src/inference/local/service/model_rpc.rs@@ -5,9 +5,9 @@//! neutral `ChatModel` interface.use crate::config::Config;-use crate::inference::local::lm_studio::lm_studio_base_url;-use crate::inference::local::ollama::{ollama_base_url_from_config, redact_ollama_base_url};-use crate::inference::local::provider::{provider_from_config, LocalAiProvider};+use tinyinference::local::lm_studio::lm_studio_base_url;+use tinyinference::local::ollama::{ollama_base_url_from_override, redact_ollama_base_url};+use tinyinference::local::provider::{provider_from_name, LocalAiProvider};use tinyinference::message::Message;use tinyinference::model::{ChatModel, ModelRequest};use tinyinference::providers::openai::OpenAiModel;@@ -25,14 +25,14 @@ fn throughput(raw: Option<&serde_json::Value>, count: &str, duration: &str) -> Olet raw = raw?;let count = raw.get(count)?.as_u64()?;let duration = raw.get(duration)?.as_u64()?;- crate::inference::local::ollama::ns_to_tps(count as f32, duration)+ tinyinference::local::ollama::ns_to_tps(count as f32, duration)}fn local_model(config: &Config, model_id: &str) -> Result<OpenAiModel, String> {- let provider = provider_from_config(config);+ let provider = provider_from_name(&config.local_ai.provider);let model = match provider {LocalAiProvider::LmStudio => {- let base = lm_studio_base_url(config);+ let base = lm_studio_base_url(config.local_ai.base_url.as_deref());tracing::debug!(provider = provider.as_str(),endpoint = %redact_ollama_base_url(&base),@@ -58,7 +58,7 @@ fn local_model(config: &Config, model_id: &str) -> Result<OpenAiModel, String> {)}LocalAiProvider::Ollama => {- let base = ollama_base_url_from_config(config);+ let base = ollama_base_url_from_override(config.local_ai.base_url.as_deref());tracing::debug!(provider = provider.as_str(),endpoint = %redact_ollama_base_url(&base),@@ -92,7 +92,7 @@ pub(super) async fn invoke(// HTTP client (connection pooling, proxy config) with local-inference// calls as a result; there is no replacement hook upstream.let model = local_model(config, &model_id)?;- let provider = provider_from_config(config);+ let provider = provider_from_name(&config.local_ai.provider);tracing::debug!(provider = provider.as_str(),model = %model_id,diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rsindex 327c22de30..99ea10f217 100644--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rs+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/binary.rs@@ -2,8 +2,8 @@ use std::path::{Path, PathBuf};use crate::config::Config;use crate::inference::local::install::{find_system_ollama_binary, run_ollama_install_script};-use crate::inference::local::process_util::apply_no_window;use crate::inference::paths::find_workspace_ollama_binary;+use tinyinference::local::process::apply_no_window;use super::super::LocalAiService;diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rsindex 3909e326c3..b2ee2d4e35 100644--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rs+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/diagnostics.rs@@ -1,17 +1,17 @@use crate::config::Config;-use crate::inference::local::lm_studio::lm_studio_base_url;-use crate::inference::local::model_requirements::{+use crate::inference::model_ids;+use crate::inference::presets::{self, VisionMode};+use tinyinference::local::lm_studio::lm_studio_base_url;+use tinyinference::local::model_requirements::{evaluate_context, ContextEligibility, MIN_CONTEXT_TOKENS,};-use crate::inference::local::ollama::{- ollama_base_url_from_config, OllamaModelShow, OllamaModelTag, OllamaShowRequest,+use tinyinference::local::ollama::{+ ollama_base_url_from_override, OllamaModelShow, OllamaModelTag, OllamaShowRequest,OllamaShowResponse, OllamaTagsResponse,};-use crate::inference::local::provider::{- model_discovery_api, provider_from_config, LocalAiProvider, ModelDiscoveryApi,+use tinyinference::local::provider::{+ model_discovery_api, provider_from_name, LocalAiProvider, ModelDiscoveryApi,};-use crate::inference::model_ids;-use crate::inference::presets::{self, VisionMode};use super::super::LocalAiService;use super::health::OllamaHealthStatus;@@ -21,14 +21,14 @@ impl LocalAiService {/// Run full diagnostics: check Ollama server health, list installed models,/// and verify expected models are present. Returns a JSON-serializable report.pub async fn diagnostics(&self, config: &Config) -> Result<serde_json::Value, String> {- if provider_from_config(config) == LocalAiProvider::LmStudio {+ if provider_from_name(&config.local_ai.provider) == LocalAiProvider::LmStudio {return self.lm_studio_diagnostics(config).await;}- let base_url = ollama_base_url_from_config(config);+ let base_url = ollama_base_url_from_override(config.local_ai.base_url.as_deref());// Route OpenAI-compatible local runtimes to the `/v1/models` probe.- // `provider_from_config` collapses everything that is not literally+ // `provider_from_name` collapses everything that is not literally// `lm_studio` onto `Ollama`, so an OMLX / `local-openai` / custom BYOK// endpoint on the OpenAI `/v1` surface (e.g. LM Studio at// `http://localhost:1234/v1`) would otherwise be probed at@@ -460,7 +460,7 @@ impl LocalAiService {}async fn lm_studio_diagnostics(&self, config: &Config) -> Result<serde_json::Value, String> {- let base_url = lm_studio_base_url(config);+ let base_url = lm_studio_base_url(config.local_ai.base_url.as_deref());let models_result = self.list_lm_studio_models(config).await;let (models, models_error, healthy) = match models_result {Ok(models) => (models, None, true),diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rsindex 4844d4fbbf..420b9d5cd5 100644--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rs+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/health.rs@@ -2,10 +2,9 @@ use std::path::PathBuf;use crate::config::Config;use crate::inference::local::install::find_system_ollama_binary;-use crate::inference::local::ollama::{ollama_base_url, ollama_base_url_from_config};use crate::inference::paths::{find_workspace_ollama_binary, workspace_ollama_binary};+use tinyinference::local::ollama::{ollama_base_url, ollama_base_url_from_override};-use super::super::spawn_marker;use super::super::LocalAiService;/// Fine-grained result of a health probe against an Ollama endpoint.@@ -215,7 +214,9 @@ impl LocalAiService {/// `RunEvent::ExitRequested` and window-close paths.pub async fn shutdown_owned_ollama(&self, config: &Config) {self.kill_ollama_server().await;- spawn_marker::clear_marker(config);+ tinyinference::local::spawn_marker::clear_marker_at(+ &crate::inference::paths::ollama_spawn_marker_path(config),+ );}pub(in crate::inference::local::service) fn resolve_binary_path(@@ -295,8 +296,11 @@ impl LocalAiService {config: &Config,model: &str,) -> Result<bool, String> {- self.has_model_at(&ollama_base_url_from_config(config), model)- .await+ self.has_model_at(+ &ollama_base_url_from_override(config.local_ai.base_url.as_deref()),+ model,+ )+ .await}pub(in crate::inference::local::service) async fn has_model_at(@@ -304,7 +308,7 @@ impl LocalAiService {base_url: &str,model: &str,) -> Result<bool, String> {- use crate::inference::local::ollama::OllamaTagsResponse;+ use tinyinference::local::ollama::OllamaTagsResponse;// Issue the /api/tags GET directly. We previously short-circuited via// ollama_healthy(), but that doubled the number of /api/tags round-trips// on healthy polls (one probe + one tags fetch). With three has_model()diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rsindex c0fda26db8..bf80ab0d0d 100644--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rs+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/model_pull.rs@@ -1,11 +1,11 @@use futures_util::StreamExt;use crate::config::Config;-use crate::inference::local::ollama::{- ollama_base_url_from_config, OllamaPullEvent, OllamaPullProgress, OllamaPullRequest,-};use crate::inference::model_ids;use crate::inference::presets::{self, VisionMode};+use tinyinference::local::ollama::{+ ollama_base_url_from_override, OllamaPullEvent, OllamaPullProgress, OllamaPullRequest,+};use super::super::LocalAiService;use super::util::interrupted_pull_settle_window_secs;@@ -102,7 +102,7 @@ impl LocalAiService {));}- let base_url = ollama_base_url_from_config(config);+ let base_url = ollama_base_url_from_override(config.local_ai.base_url.as_deref());if self.has_model_at(&base_url, model_id).await? {return Ok(());}diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/server.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/server.rsindex 79459aad56..e93a160f9d 100644--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/server.rs+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/server.rs@@ -1,10 +1,11 @@use std::path::Path;use crate::config::Config;-use crate::inference::local::ollama::ollama_base_url_from_config;-use crate::inference::local::process_util::apply_no_window;+use crate::inference::paths::ollama_spawn_marker_path;+use tinyinference::local::ollama::ollama_base_url_from_override;+use tinyinference::local::process::apply_no_window;+use tinyinference::local::spawn_marker::{self, OllamaSpawnMarker};-use super::super::spawn_marker::{self, OllamaSpawnMarker};use super::super::LocalAiService;use super::util::kill_pid_by_id;@@ -13,7 +14,7 @@ impl LocalAiService {&self,config: &Config,) -> Result<(), String> {- let base_url = ollama_base_url_from_config(config);+ let base_url = ollama_base_url_from_override(config.local_ai.base_url.as_deref());if self.ollama_healthy_at(&base_url).await {if self.ollama_runner_ok_at(&base_url).await {return Ok(());@@ -47,7 +48,8 @@ impl LocalAiService {&self,config: &Config,) {- let Some(marker) = spawn_marker::read_marker(config) else {+ let marker_path = ollama_spawn_marker_path(config);+ let Some(marker) = spawn_marker::read_marker_at(&marker_path) else {return;};if !spawn_marker::pid_is_alive(marker.pid) {@@ -55,10 +57,10 @@ impl LocalAiService {"[local_ai] stale ollama spawn marker (pid={} no longer alive); clearing",marker.pid);- spawn_marker::clear_marker(config);+ spawn_marker::clear_marker_at(&marker_path);return;}- let base_url = ollama_base_url_from_config(config);+ let base_url = ollama_base_url_from_override(config.local_ai.base_url.as_deref());if !self.ollama_healthy_at(&base_url).await {// PID is alive but :11434 isn't healthy — either Ollama is// mid-boot or the recorded PID was reused for an unrelated@@ -79,7 +81,7 @@ impl LocalAiService {marker.binary_path);kill_pid_by_id(marker.pid);- spawn_marker::clear_marker(config);+ spawn_marker::clear_marker_at(&marker_path);// Brief settle so the listener releases :11434 before we respawn.tokio::time::sleep(std::time::Duration::from_millis(500)).await;}@@ -89,7 +91,7 @@ impl LocalAiService {config: &Config,ollama_cmd: &Path,) -> Result<(), String> {- let base_url = ollama_base_url_from_config(config);+ let base_url = ollama_base_url_from_override(config.local_ai.base_url.as_deref());if self.ollama_healthy_at(&base_url).await {// A daemon is already up — adopt it. We did NOT spawn it (or any// prior spawn was already reclaimed in `reclaim_orphan_if_ours`),@@ -104,7 +106,7 @@ impl LocalAiService {// first pass), clear it before respawning. Without this, the new// child would replace the field and the old one would be leaked.self.kill_ollama_server().await;- spawn_marker::clear_marker(config);+ spawn_marker::clear_marker_at(&ollama_spawn_marker_path(config));let mut version_cmd = tokio::process::Command::new(ollama_cmd);version_cmd@@ -192,13 +194,21 @@ impl LocalAiService {);} else {let marker = OllamaSpawnMarker::new(pid, ollama_cmd);- if let Err(e) = spawn_marker::write_marker(config, &marker) {+ let marker_path = ollama_spawn_marker_path(config);+ if let Err(e) = spawn_marker::write_marker_at(&marker_path, &marker) {// Marker write failure is non-fatal — graceful shutdown// still kills via the in-memory `Child` handle. Only// crash-recovery on next launch is degraded.log::warn!("[local_ai] failed to write ollama spawn marker (pid={pid}): {e}");+ } else {+ log::debug!(+ "[local_ai] wrote ollama spawn marker pid={} bin={} at {}",+ marker.pid,+ marker.binary_path,+ marker_path.display()+ );}}*self.owned_ollama.lock() = Some(serve_child);diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin/util.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin/util.rsindex 64d396d33d..97f4b049bf 100644--- a/crates/openhuman-core/src/inference/local/service/ollama_admin/util.rs+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin/util.rs@@ -1,4 +1,4 @@-use crate::inference::local::ollama::{validate_ollama_url, OllamaTagsResponse};+use tinyinference::local::ollama::{validate_ollama_url, OllamaTagsResponse};pub(super) fn lm_studio_models_error_means_unreachable(error: &str) -> bool {error.starts_with("lm studio models request failed:")diff --git a/crates/openhuman-core/src/inference/local/service/ollama_admin_lm_studio_and_lifecycle_tests.rs b/crates/openhuman-core/src/inference/local/service/ollama_admin_lm_studio_and_lifecycle_tests.rsindex 0443a7cc09..dd04968309 100644--- a/crates/openhuman-core/src/inference/local/service/ollama_admin_lm_studio_and_lifecycle_tests.rs+++ b/crates/openhuman-core/src/inference/local/service/ollama_admin_lm_studio_and_lifecycle_tests.rs@@ -309,7 +309,7 @@ async fn kill_ollama_server_kills_owned_child() {// Sanity: child should be alive immediately after spawn.assert!(- crate::inference::local::service::spawn_marker::pid_is_alive(pid),+ tinyinference::local::spawn_marker::pid_is_alive(pid),"child pid {pid} should be alive right after spawn");@@ -325,7 +325,7 @@ async fn kill_ollama_server_kills_owned_child() {// update its process table — the kill is signalled but reap is async.let mut still_alive = true;for _ in 0..40 {- if !crate::inference::local::service::spawn_marker::pid_is_alive(pid) {+ if !tinyinference::local::spawn_marker::pid_is_alive(pid) {still_alive = false;break;}@@ -380,9 +380,9 @@ async fn shutdown_owned_ollama_clears_marker_and_kills_child() {let marker_path = crate::inference::paths::ollama_spawn_marker_path(&config);let marker_writable = marker_path.starts_with(tmp.path());if marker_writable {- crate::inference::local::service::spawn_marker::write_marker_at(+ tinyinference::local::spawn_marker::write_marker_at(&marker_path,- &crate::inference::local::service::spawn_marker::OllamaSpawnMarker::new(+ &tinyinference::local::spawn_marker::OllamaSpawnMarker::new(pid,std::path::Path::new("test-stub"),),@@ -406,7 +406,7 @@ async fn shutdown_owned_ollama_clears_marker_and_kills_child() {// And the spawned process is dead.let mut still_alive = true;for _ in 0..40 {- if !crate::inference::local::service::spawn_marker::pid_is_alive(pid) {+ if !tinyinference::local::spawn_marker::pid_is_alive(pid) {still_alive = false;break;}diff --git a/crates/openhuman-core/src/inference/local/service/public_infer.rs b/crates/openhuman-core/src/inference/local/service/public_infer.rsindex 57e056f4e0..9bca35d9de 100644--- a/crates/openhuman-core/src/inference/local/service/public_infer.rs+++ b/crates/openhuman-core/src/inference/local/service/public_infer.rs@@ -1,6 +1,6 @@use crate::config::Config;use crate::inference::model_ids;-use crate::inference::parse::sanitize_inline_completion;+use tinyinference::completion::sanitize_inline_completion;use tinyinference::message::Message;use super::LocalAiService;@@ -213,7 +213,7 @@ impl LocalAiService {pub(crate) async fn chat_with_history(&self,config: &Config,- messages: Vec<crate::inference::local::ollama::OllamaChatMessage>,+ messages: Vec<tinyinference::local::ollama::OllamaChatMessage>,max_tokens: Option<u32>,) -> Result<String, String> {self.chat_with_history_internal(config, messages, max_tokens, true)@@ -223,7 +223,7 @@ impl LocalAiService {pub(crate) async fn chat_with_history_interactive(&self,config: &Config,- messages: Vec<crate::inference::local::ollama::OllamaChatMessage>,+ messages: Vec<tinyinference::local::ollama::OllamaChatMessage>,max_tokens: Option<u32>,) -> Result<String, String> {log::trace!("[local_ai] chat_with_history_interactive bypasses scheduler_gate permit");@@ -234,7 +234,7 @@ impl LocalAiService {async fn chat_with_history_internal(&self,config: &Config,- messages: Vec<crate::inference::local::ollama::OllamaChatMessage>,+ messages: Vec<tinyinference::local::ollama::OllamaChatMessage>,max_tokens: Option<u32>,gated: bool,) -> Result<String, String> {diff --git a/crates/openhuman-core/src/inference/local/service/public_infer_tests.rs b/crates/openhuman-core/src/inference/local/service/public_infer_tests.rsindex d176fd1ab0..6312b55da2 100644--- a/crates/openhuman-core/src/inference/local/service/public_infer_tests.rs+++ b/crates/openhuman-core/src/inference/local/service/public_infer_tests.rs@@ -413,7 +413,7 @@ async fn chat_with_history_interactive_does_not_block_on_held_permit() {std::time::Duration::from_secs(2),service.chat_with_history_interactive(&config,- vec![crate::inference::local::ollama::OllamaChatMessage {+ vec![tinyinference::local::ollama::OllamaChatMessage {role: "user".to_string(),content: "hi".to_string(),}],diff --git a/crates/openhuman-core/src/inference/local/service/vision_embed.rs b/crates/openhuman-core/src/inference/local/service/vision_embed.rsindex 21da4cfd6a..c4fbaa1ddd 100644--- a/crates/openhuman-core/src/inference/local/service/vision_embed.rs+++ b/crates/openhuman-core/src/inference/local/service/vision_embed.rs@@ -1,9 +1,5 @@use crate::agent::multimodal;use crate::config::Config;-use crate::inference::local::ollama::{- ollama_base_url_from_config, redact_ollama_base_url, OllamaGenerateOptions,- OllamaGenerateRequest,-};use crate::inference::model_ids;use crate::inference::presets::{self, VisionMode};use crate::inference::types::LocalAiEmbeddingResult;@@ -11,6 +7,10 @@ use tinyinference::embeddings::{EmbeddingModel, OllamaEmbeddingModel, DEFAULT_OLLAMA_DIMENSIONS,RECOMMENDED_OLLAMA_CONTEXT_TOKENS,};+use tinyinference::local::ollama::{+ ollama_base_url_from_override, redact_ollama_base_url, OllamaGenerateOptions,+ OllamaGenerateRequest,+};use super::LocalAiService;@@ -142,7 +142,7 @@ impl LocalAiService {}),};- let base = ollama_base_url_from_config(config);+ let base = ollama_base_url_from_override(config.local_ai.base_url.as_deref());let url = format!("{base}/api/generate");let body_bytes = serde_json::to_vec(&body).map(|v| v.len()).unwrap_or(0);tracing::debug!(@@ -195,10 +195,11 @@ impl LocalAiService {));}- let payload: crate::inference::local::ollama::OllamaGenerateResponse = response- .json()- .await- .map_err(|e| format!("ollama vision response parse failed: {e}"))?;+ let payload: tinyinference::local::ollama::OllamaGenerateResponse =+ response+ .json()+ .await+ .map_err(|e| format!("ollama vision response parse failed: {e}"))?;if payload.response.trim().is_empty() {return Err("ollama vision returned empty content".to_string());}@@ -233,7 +234,7 @@ impl LocalAiService {// user's laptop when stacked with other Ollama work. Gate it.let _gate_permit = crate::cron::scheduler_gate::wait_for_capacity().await;- let embed_base = ollama_base_url_from_config(config);+ let embed_base = ollama_base_url_from_override(config.local_ai.base_url.as_deref());let dimensions = embedding_dimensions(&embedding_model);log::debug!("[local_ai:embed] embed: using model={} dimensions={} base_url={}",diff --git a/crates/openhuman-core/src/inference/mod.rs b/crates/openhuman-core/src/inference/mod.rsindex 09141e2a84..414ad36199 100644--- a/crates/openhuman-core/src/inference/mod.rs+++ b/crates/openhuman-core/src/inference/mod.rs@@ -24,8 +24,6 @@/// reports `Unknown`.pub const INFERENCE_COMPILED_IN: bool = cfg!(feature = "inference");-pub mod auth_error_registry;-pub mod device;pub mod embeddings;pub mod http;pub mod local;@@ -33,12 +31,10 @@ pub mod model_context;pub mod model_ids;pub mod openai_oauth;pub mod ops;-pub mod parse;pub mod paths;pub mod presets;pub mod provider;mod schemas;-pub mod sentiment;pub mod tokenjuice;pub mod types;pub mod voice;@@ -50,12 +46,10 @@ pub use schemas::{};// Re-export the types that external callers (voice, agent, etc.) import from inference-pub use device::DeviceProfile;pub use local::all_local_inference_controller_schemas;pub use local::all_local_inference_registered_controllers;pub use model_context::context_window_for_model;pub use presets::{ModelPreset, ModelTier, VisionMode};-pub use sentiment::SentimentResult;pub use types::{LocalAiAssetStatus, LocalAiAssetsStatus, LocalAiDownloadProgressItem, LocalAiDownloadsProgress,LocalAiEmbeddingResult, LocalAiSpeechResult, LocalAiStatus, LocalAiTtsResult,diff --git a/crates/openhuman-core/src/inference/model_context.rs b/crates/openhuman-core/src/inference/model_context.rsindex a5233f9370..565051cb40 100644--- a/crates/openhuman-core/src/inference/model_context.rs+++ b/crates/openhuman-core/src/inference/model_context.rs@@ -123,14 +123,14 @@ fn tier_context_window(model: &str) -> Option<u64> {/// where over-trimming a large window is worse than skipping the trim.pub fn context_window_for_model_with_local_fallback(model: &str,- local_kind: Option<crate::inference::local::profile::LocalProviderKind>,+ local_kind: Option<tinyinference::local::profile::LocalProviderKind>,) -> Option<u64> {if let Some(window) = context_window_for_model(model) {return Some(window);}// Fall back to the local provider profile's default context window.if let Some(kind) = local_kind {- let profile = crate::inference::local::profile::profile_for_kind(kind);+ let profile = tinyinference::local::profile::profile_for_kind(kind);if let Some(default_ctx) = profile.default_context_window {tracing::debug!(model,diff --git a/crates/openhuman-core/src/inference/model_context_tests.rs b/crates/openhuman-core/src/inference/model_context_tests.rsindex d6ec2c4a2f..20d8f3100d 100644--- a/crates/openhuman-core/src/inference/model_context_tests.rs+++ b/crates/openhuman-core/src/inference/model_context_tests.rs@@ -1,5 +1,5 @@use super::*;-use crate::inference::local::profile::LocalProviderKind;+use tinyinference::local::profile::LocalProviderKind;#[test]fn local_fallback_uses_profile_default() {diff --git a/crates/openhuman-core/src/inference/model_ids.rs b/crates/openhuman-core/src/inference/model_ids.rsindex 321a7ebc55..fc768acfbe 100644--- a/crates/openhuman-core/src/inference/model_ids.rs+++ b/crates/openhuman-core/src/inference/model_ids.rs@@ -10,7 +10,7 @@//! OpenHuman-managed Ollama assets.use crate::config::Config;-use crate::inference::local::provider::{provider_from_config, LocalAiProvider};+use tinyinference::local::provider::{provider_from_name, LocalAiProvider};const VISION_MODEL_SUGGESTIONS: &[&str] =&["moondream:1.8b-v2-q4_K_S", "llava:7b", "gemma3:4b-it-qat"];@@ -154,7 +154,7 @@ fn enforce_mvp_embedding_allowlist(resolved: &str) -> String {}pub(crate) fn effective_chat_model_id(config: &Config) -> String {- let provider = provider_from_config(config);+ let provider = provider_from_name(&config.local_ai.provider);if provider == LocalAiProvider::LmStudio {let model_id = raw_chat_model_id(config);tracing::debug!(@@ -290,7 +290,7 @@ pub(crate) fn effective_embedding_model_id(config: &Config) -> String {// exact served model instead of having it rewritten back to `bge-m3`// (#3920). The allowlist remains in force for the managed Ollama path// below, where the ids are OpenHuman-pulled assets.- if provider_from_config(config) == LocalAiProvider::LmStudio {+ if provider_from_name(&config.local_ai.provider) == LocalAiProvider::LmStudio {if raw.is_empty() {// No configured id — fall back to the canonical default so the// memory tree still has an embedder to request, rather thandiff --git a/crates/openhuman-core/src/inference/ops.rs b/crates/openhuman-core/src/inference/ops.rsindex 955ed6a55a..03e3ce2af1 100644--- a/crates/openhuman-core/src/inference/ops.rs+++ b/crates/openhuman-core/src/inference/ops.rs@@ -4,13 +4,15 @@ use crate::config::rpc as config_rpc;use crate::config::Config;use crate::inference::local as local_runtime;use crate::inference::local::ops::ReactionDecision;+use crate::inference::presets;use crate::inference::provider as providers;-use crate::inference::{device, presets, sentiment, SentimentResult};use crate::inference::{LocalAiEmbeddingResult, LocalAiStatus};use crate::rpc::RpcOutcome;use serde_json::{json, Value};+use tinyinference::device::detect_device_profile;use tinyinference::message::Message;use tinyinference::model::ModelRequest;+use tinyinference::sentiment::{parse_sentiment_response, SentimentResult};use tracing::{debug, error, warn};const LOG_PREFIX: &str = "[inference::ops]";@@ -240,7 +242,41 @@ pub async fn inference_analyze_sentiment(message_len = message.len(),"{LOG_PREFIX} analyze_sentiment:start");- let result = sentiment::local_ai_analyze_sentiment(config, message).await;+ if message.trim().is_empty() {+ return Ok(RpcOutcome::single_log(+ SentimentResult::neutral(),+ "empty message — neutral sentiment",+ ));+ }++ let service = local_runtime::global(config);+ if service.status().state != "ready" {+ 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 result = match service.prompt(config, &prompt, Some(8), true).await {+ Ok(raw) => parse_sentiment_response(&raw.trim().to_lowercase()),+ Err(error) => {+ debug!(%error, "{LOG_PREFIX} sentiment inference failed; returning neutral");+ SentimentResult::neutral()+ }+ };+ let result = Ok(RpcOutcome::single_log(+ result,+ "sentiment analysis completed",+ ));match &result {Ok(outcome) => {debug!(valence = %outcome.value.valence, "{LOG_PREFIX} analyze_sentiment:ok")@@ -344,7 +380,7 @@ pub async fn inference_list_models(provider_id: &str) -> Result<RpcOutcome<Valuepub async fn inference_device_profile() -> Result<RpcOutcome<Value>, String> {debug!("{LOG_PREFIX} device_profile:start");- let profile = device::detect_device_profile();+ let profile = detect_device_profile();let result = Ok(RpcOutcome::single_log(serde_json::to_value(profile).map_err(|e| format!("serialize: {e}"))?,"inference device profile fetched",@@ -360,7 +396,7 @@ pub async fn inference_device_profile() -> Result<RpcOutcome<Value>, String> {/// editor, not only in the notification center. Cleared when the user updates/// or removes the offending key.pub async fn inference_provider_auth_errors() -> Result<RpcOutcome<Value>, String> {- let errors = crate::inference::auth_error_registry::snapshot();+ let errors = tinyinference::auth_errors::snapshot();debug!(count = errors.len(), "{LOG_PREFIX} provider_auth_errors:ok");Ok(RpcOutcome::single_log(json!({ "errors": errors }),@@ -371,7 +407,7 @@ pub async fn inference_provider_auth_errors() -> Result<RpcOutcome<Value>, Strinpub async fn inference_presets() -> Result<RpcOutcome<Value>, String> {debug!("{LOG_PREFIX} presets:start");let config = config_rpc::load_config_with_timeout().await?;- let device = device::detect_device_profile();+ let device = detect_device_profile();let recommended = presets::recommend_tier(&device);let current = presets::current_tier_from_config(&config.local_ai);let selected_tier = config.local_ai.selected_tier.as_ref().and_then(|value| {diff --git a/crates/openhuman-core/src/inference/presets.rs b/crates/openhuman-core/src/inference/presets.rsindex bd41ec8ea9..d21371915d 100644--- a/crates/openhuman-core/src/inference/presets.rs+++ b/crates/openhuman-core/src/inference/presets.rs@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};use crate::config::schema::LocalAiConfig;-use super::device::DeviceProfile;+use tinyinference::device::DeviceProfile;/// Performance tier for local AI model selection.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]diff --git a/crates/openhuman-core/src/inference/provider/README.md b/crates/openhuman-core/src/inference/provider/README.mdindex b9d1bdb53e..1688d1f8e0 100644--- a/crates/openhuman-core/src/inference/provider/README.md+++ b/crates/openhuman-core/src/inference/provider/README.md@@ -19,25 +19,22 @@ domain.(`enforce_local_only_inference`), and managed-session (`verify_session_active`)gates before building a model.- **Models** — `OpenHumanBackendModel` + `PROVIDER_LABEL`- (`openhuman_backend_model.rs`), plus the OpenAI-compatible and Anthropic- crate-native builders (`crate_openai.rs`, `crate_anthropic.rs`).+ (`openhuman_backend_model.rs`); OpenAI-compatible and Anthropic builders live+ in `tinyinference::providers` and are called directly.- **DTOs** (`types.rs`) — `ChatRequest`, `ChatResponse`, `ProviderDelta`,`ToolCall`, `UsageInfo`, `AGENT_TURN_MAX_OUTPUT_TOKENS`.-- **Error classifiers** — `billing_error::is_budget_exhausted_message`,- `chat_template::is_chat_template_rejection_message`,- `config_rejection::{is_openai_compatible_unknown_model_message,- is_provider_config_rejection_message}`, `error_code::{BackendErrorCode,- extract_backend_error_code*, backend_error_code_skips_sentry, ...}`.+- **Error classifiers** — reusable classifiers live in+ `tinyinference::classification`; this directory retains only OpenHuman policy.## Transports| Transport | File | Provider-string prefix || --- | --- | --- || Managed OpenHuman backend | `openhuman_backend_model.rs` | `openhuman` / `cloud` (session JWT + billing metadata) |-| OpenAI-compatible (BYOK cloud slugs, local runtimes) | `crate_openai.rs` | `<slug>:<model>`, `ollama:<model>`, `lmstudio:<model>`, `mlx:<model>`, `omlx:<model>`, `local-openai:<model>` |-| Anthropic Messages API (prompt caching) | `crate_anthropic.rs` | `<slug>:<model>` whose endpoint is the first-party Messages API (`endpoint_is_anthropic_messages`) and native tool calling is on; other Anthropic-keyed endpoints stay on Chat Completions |-| Codex OAuth / Responses API | `openai_codex.rs` (`pub(crate)`, routing metadata only — `OpenAiCodexRouting` applied by the `crate_openai.rs` builder) | the `openai` cloud slug once Codex OAuth tokens exist in the auth-profile store |-| Claude Agent SDK subprocess | `claude_agent_sdk/` (`protocol.rs`, `subprocess.rs`) | `claude_agent_sdk` / `claude_agent_sdk:<model>` |+| OpenAI-compatible (BYOK cloud slugs, local runtimes) | `tinyinference::providers::openai` | `<slug>:<model>`, `ollama:<model>`, `lmstudio:<model>`, `mlx:<model>`, `omlx:<model>`, `local-openai:<model>` |+| Anthropic Messages API (prompt caching) | `tinyinference::providers::anthropic` | `<slug>:<model>` whose endpoint is the first-party Messages API and native tool calling is on |+| Codex OAuth / Responses API | `openai_codex.rs` host OAuth selection plus `tinyinference::providers::openai::codex` metadata | the `openai` cloud slug once Codex OAuth tokens exist |+| Claude Agent SDK subprocess | `tinyagents_harness::providers::claude_agent_sdk` | `claude_agent_sdk` / `claude_agent_sdk:<model>` || Claude Code CLI subprocess | `claude_code/` — see its own [README](claude_code/README.md) | `claude-code:<model>` |## Calls into@@ -55,7 +52,7 @@ domain.(`factory/access_gates.rs`).- `crate::inference::local` — `profile::is_local_provider_string`, Ollama /LM Studio base-url resolution for local provider strings.-- `crate::inference::auth_error_registry` — surfaces per-provider auth errors+- `tinyinference::auth_errors` — surfaces per-provider auth errorsback to the UI.- `crate::core::bus` (`BUS.publish`) / `crate::core::events::DomainEvent` —`ops/http_error/auth_failure.rs::publish_backend_session_expired` and@@ -83,14 +80,12 @@ consumers: the agent harness (`agent/harness/session/builder/factory.rs`,## Sub-modules-- `ops/` — `sanitize` (secret scrubbing), `http_error` (HTTP error+- `ops/` — `http_error` (HTTP errorclassification, Sentry routing, `api_error`), `models`(`list_configured_models`), `provider_factory` (`ProviderRuntimeOptions`,`list_providers`, `is_qwen_alias`-style China-provider alias helpers).Preserves the original `pub use ops::*` contract split out of a single `ops.rs`.- [`claude_code/`](claude_code/README.md) — Claude Code CLI provider.-- `claude_agent_sdk/` — `ClaudeAgentSdkProvider` (`subprocess.rs`, configured- from `Config::claude_agent_sdk`; `protocol.rs` wire types).- `schemas.rs` — a `providers.list_models` controller that is **not**registered in `core/all.rs`; the live method is `inference.list_models`(`openhuman.providers_list_models` survives only as a legacy alias in@@ -105,12 +100,10 @@ consumers: the agent harness (`agent/harness/session/builder/factory.rs`,- `ops_tests.rs`, `ops_tests_error_suppression_tests.rs`,`ops_tests_models_parsing_tests.rs`, `ops/http_error_tests.rs`, `ops/models_tests.rs` — errorclassification and model listing.-- `error_classify_tests.rs`, `error_code_tests.rs`, `config_rejection_tests.rs`,- `billing_error_tests.rs`, `fallback_diagnostics_tests.rs` — per-classifier- behavior.+- `error_classify_tests.rs` — OpenHuman-specific classifier policy; reusable+ classifier tests live in TinyInference.- `claude_code/*_tests.rs` — per-file coverage of the CC provider (auth,auth status, driver, event mapper, input builder, stream parser, sessionstore, settings, version check) plus `mod_tests.rs`.-- `crate_openai_tests.rs`, `crate_anthropic_tests.rs`,- `openhuman_backend_model_tests.rs`, `openai_codex_tests.rs` — per-transport- model builders.+- `openhuman_backend_model_tests.rs` — managed host transport; reusable provider+ builder and Codex tests live in TinyInference and TinyAgents.diff --git a/crates/openhuman-core/src/inference/provider/crate_anthropic.rs b/crates/openhuman-core/src/inference/provider/crate_anthropic.rsdeleted file mode 100644index c9f41454e4..0000000000--- a/crates/openhuman-core/src/inference/provider/crate_anthropic.rs+++ /dev/null@@ -1,73 +0,0 @@-//! Crate-native Anthropic Messages API client construction.-//!-//! A `cloud_providers` entry with `auth_style = "anthropic"` used to be served-//! by the crate `OpenAiModel` in its Anthropic-auth flavour — Chat Completions-//! against Anthropic's OpenAI-compatibility endpoint. That endpoint documents-//! prompt caching as **unsupported** and reports `prompt_tokens_details` as-//! always empty, so every turn on a BYOK Claude key re-billed the entire system-//! prompt, tool catalogue, and conversation at full price, and the host's-//! `[cache]` diagnostics could never show a hit.-//!-//! This module is the boundary where that entry becomes the crate's native-//! [`AnthropicModel`] instead: the Messages API with `cache_control`-//! breakpoints on the tool set, the system prompt, and the tail of the-//! conversation (see the crate adapter's docs for the placement rule), native-//! `tool_use` / `tool_result` blocks, signed thinking replay, and SSE streaming.-//! The harness's `PromptCacheSegmentMiddleware` already declares the stable-//! prefix on every request; this is what turns those declarations into wire-//! markers on the one provider that needs them explicitly.--use std::sync::Arc;--use tinyinference::model::ChatModel;-use tinyinference::providers::anthropic::AnthropicModel;--/// Whether an endpoint is known to speak the Anthropic Messages API.-///-/// Authentication style is not sufficient to select the wire protocol:-/// existing configurations may use an Anthropic key with an OpenAI-compatible-/// proxy. Keep those endpoints on Chat Completions unless the endpoint is the-/// first-party Messages API.-pub(crate) fn endpoint_is_anthropic_messages(endpoint: &str) -> bool {- crate::config::schema::cloud_providers::endpoint_host(endpoint)- .is_some_and(|host| host == "api.anthropic.com")-}--/// The resolved config for one Anthropic Messages API provider.-pub(crate) struct CrateAnthropicConfig<'a> {- /// Base URL (`https://api.anthropic.com/v1` for the hosted API; a- /// Messages-compatible proxy otherwise). `/messages` is appended unless- /// the URL already ends in it.- pub endpoint: &'a str,- /// API credential, sent as `x-api-key`.- pub api_key: &'a str,- /// Default model id baked onto the client (a per-call `ModelRequest.model`- /// still overrides it).- pub model: &'a str,- /// Fixed temperature override for every call, when set (the `@<temp>`- /// provider-string suffix).- pub temperature_override: Option<f64>,- /// Model-id `*`-glob patterns whose targets reject a `temperature` param.- pub temperature_unsupported_models: &'a [String],-}--/// Build a crate-native [`AnthropicModel`] (`ChatModel`) for the given config.-pub(crate) fn build_crate_anthropic_model(- config: CrateAnthropicConfig<'_>,-) -> Arc<dyn ChatModel<()>> {- log::debug!(- "[providers][chat-factory] building native Anthropic Messages client endpoint={} model={} temperature_override={:?}",- config.endpoint,- config.model,- config.temperature_override- );- let model = AnthropicModel::with_base_url(config.api_key, config.endpoint)- .with_model(config.model)- .with_temperature_override(config.temperature_override)- .with_temperature_unsupported_models(config.temperature_unsupported_models.iter().cloned());- Arc::new(model)-}--#[cfg(test)]-#[path = "crate_anthropic_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/inference/provider/crate_anthropic_tests.rs b/crates/openhuman-core/src/inference/provider/crate_anthropic_tests.rsdeleted file mode 100644index 22c41bf075..0000000000--- a/crates/openhuman-core/src/inference/provider/crate_anthropic_tests.rs+++ /dev/null@@ -1,35 +0,0 @@-use super::*;--#[test]-fn only_first_party_anthropic_endpoint_selects_messages_api() {- assert!(endpoint_is_anthropic_messages(- "https://api.anthropic.com/v1"- ));- assert!(!endpoint_is_anthropic_messages(- "https://anthropic-proxy.example/v1"- ));- assert!(!endpoint_is_anthropic_messages("https://api.openai.com/v1"));-}--#[test]-fn builds_a_native_anthropic_model_with_the_configured_profile() {- let model = build_crate_anthropic_model(CrateAnthropicConfig {- endpoint: "https://api.anthropic.com/v1",- api_key: "sk-ant-secret",- model: "claude-sonnet-4-6",- temperature_override: Some(0.2),- temperature_unsupported_models: &[],- });- let profile = model.profile().expect("anthropic models expose a profile");- assert_eq!(profile.provider.as_deref(), Some("anthropic"));- assert_eq!(profile.model.as_deref(), Some("claude-sonnet-4-6"));- assert!(profile.tool_calling, "the native adapter speaks tool_use");- assert!(profile.streaming, "the native adapter streams SSE");- // The identity the response cache scopes on names the endpoint + model and- // never the credential.- let identity = model- .cache_identity()- .expect("anthropic models identify themselves");- assert!(identity.contains("api.anthropic.com"));- assert!(!identity.contains("sk-ant-secret"));-}diff --git a/crates/openhuman-core/src/inference/provider/crate_openai.rs b/crates/openhuman-core/src/inference/provider/crate_openai.rsdeleted file mode 100644index 3562d13794..0000000000--- a/crates/openhuman-core/src/inference/provider/crate_openai.rs+++ /dev/null@@ -1,245 +0,0 @@-//! Crate-native OpenAI-compatible client construction (issue #4727, Motion B).-//!-//! The cutover replaced the in-house OpenAI-compatible wire client with the-//! vendored `tinyagents` crate's `OpenAiModel` — a `ChatModel` that speaks the-//! OpenAI Chat Completions wire and, since tinyagents #44/#47/#48, carries the-//! host-parity config the OpenHuman provider catalog needs: configurable auth-//! styles + static headers, per-model temperature suppression/override, and-//! system→user merging. `num_ctx` and other Ollama `options` ride-//! `ModelRequest.provider_options` (already supported upstream).-//!-//! This module is the **single boundary** where the host's resolved provider-//! config becomes a crate-native `ChatModel`. Bespoke providers that the crate-//! can't serve — the managed OpenHuman backend (session JWT + billing envelope),-//! `claude_code` / `claude_agent_sdk` (subprocess), and `openai_codex`-//! (`/v1/responses` + query-param auth) — stay as host `ChatModel` impls and do-//! **not** route through here.-//!-//! The builder is the factory's default construction path and consumes-//! TinyInference's auth style directly.--use std::sync::Arc;--use tinyinference::model::ChatModel;-use tinyinference::providers::openai::{AuthStyle as HostAuthStyle, OpenAiModel};--/// The resolved config for one OpenAI-compatible provider, mirroring the inputs-/// the host [`build_compatible_provider`](super::factory) helper takes. Kept as a-/// struct (rather than a long positional arg list) so the factory maps its-/// resolved provider string + credentials + catalog flags in one place.-pub(crate) struct CrateOpenAiConfig<'a> {- /// Provider family id (telemetry + normalized errors), e.g. `"openai"`.- pub provider_name: &'a str,- /// Base URL (no trailing slash needed; the crate trims it).- pub endpoint: &'a str,- /// API credential; empty is fine for [`AuthStyle::None`] (local runtimes).- pub api_key: &'a str,- /// How the credential is sent.- pub auth_style: HostAuthStyle,- /// Default model id baked onto the client (a per-call `ModelRequest.model`- /// still overrides it).- pub model: &'a str,- /// Model-id `*`-glob patterns whose targets reject a `temperature` param.- pub temperature_unsupported_models: &'a [String],- /// Fixed temperature override for every call, when set.- pub temperature_override: Option<f64>,- /// Fold system messages into the first user message (endpoints w/o a- /// `system` role).- pub merge_system_into_user: bool,- /// Static headers attached to every request (e.g. provider attribution).- pub extra_headers: &'a [(String, String)],- /// Override the model's advertised **native** tool-calling capability.- /// `None` keeps the crate default (`true`); `Some(false)` is required for- /// local runtimes (Ollama et al.) that reject the OpenAI `tools` parameter,- /// so the harness embeds tool specs in the prompt instead. Maps to the crate- /// `OpenAiModel::with_native_tool_calling`.- pub native_tool_calling: Option<bool>,- /// Override the model's advertised vision (image-in) capability. `None` keeps- /// the crate default; `Some(false)` marks a text-only local model. Maps to- /// `OpenAiModel::with_vision`.- pub vision: Option<bool>,- /// Provider options baked onto every request (e.g. Ollama's- /// `{"options": {"num_ctx": 8192}}`), merged under each call's own- /// `provider_options`. `None` bakes nothing. Maps to- /// `OpenAiModel::with_default_provider_options`.- pub default_provider_options: Option<serde_json::Value>,- /// Route calls to the OpenAI **Responses API** (`/v1/responses`) instead of- /// Chat Completions — the OpenAI Codex OAuth backend. Maps to- /// `OpenAiModel::with_responses_api_primary`.- pub responses_api_primary: bool,- /// (Responses path) omit `max_output_tokens`, which the Codex backend- /// rejects. Maps to `OpenAiModel::with_responses_omit_max_output_tokens`.- pub responses_omit_max_output_tokens: bool,- /// Static query parameters appended to every request URL (e.g. the Codex- /// `client_version`). Maps to `OpenAiModel::with_extra_query_param`.- pub extra_query_params: &'a [(String, String)],- /// `User-Agent` header override (e.g. the Codex CLI UA). Maps to- /// `OpenAiModel::with_user_agent`.- pub user_agent: Option<&'a str>,- /// Emit explicit `cache_control` breakpoints on the last system and user- /// messages. Only relays that forward them to an opt-in prompt cache- /// (OpenRouter → Anthropic / Gemini) should set this; hosted OpenAI- /// rejects unknown content-part fields. Maps to- /// `OpenAiModel::with_explicit_cache_control`.- pub explicit_cache_control: bool,-}--/// Whether `endpoint` is OpenRouter, the one relay in the catalog that-/// documents forwarding `cache_control` markers to its upstream providers.-pub(crate) fn endpoint_is_openrouter(endpoint: &str) -> bool {- url::Url::parse(endpoint.trim())- .ok()- .and_then(|url| {- url.host_str()- .map(|host| host.eq_ignore_ascii_case("openrouter.ai"))- })- .unwrap_or(false)-}--/// Build a crate-native `OpenAiModel` (`ChatModel`) for the given OpenAI-compatible-/// provider config.-pub(crate) fn build_crate_openai_model(config: CrateOpenAiConfig<'_>) -> Arc<dyn ChatModel<()>> {- let mut model = OpenAiModel::compatible_provider(- config.provider_name,- config.api_key,- config.endpoint,- config.model,- )- .with_auth_style(config.auth_style);-- if !config.temperature_unsupported_models.is_empty() {- model = model- .with_temperature_unsupported_models(config.temperature_unsupported_models.to_vec());- }- if config.temperature_override.is_some() {- model = model.with_temperature_override(config.temperature_override);- }- if config.merge_system_into_user {- model = model.with_merge_system_into_user();- }- for (name, value) in config.extra_headers {- model = model.with_header(name.clone(), value.clone());- }- // Capability toggles must be applied *after* provider/model are set (which- // `compatible_provider` above already did), because those re-derive the- // profile the toggles mutate.- if let Some(enabled) = config.native_tool_calling {- model = model.with_native_tool_calling(enabled);- }- if let Some(enabled) = config.vision {- model = model.with_vision(enabled);- }- if let Some(options) = config.default_provider_options {- model = model.with_default_provider_options(options);- }- for (name, value) in config.extra_query_params {- model = model.with_extra_query_param(name.clone(), value.clone());- }- if let Some(user_agent) = config.user_agent {- model = model.with_user_agent(user_agent);- }- if config.explicit_cache_control {- log::debug!(- "[providers][chat-factory] provider={} explicit cache_control breakpoints enabled",- config.provider_name- );- model = model.with_explicit_cache_control(true);- }- if config.responses_api_primary {- model = model.with_responses_api_primary();- }- if config.responses_omit_max_output_tokens {- model = model.with_responses_omit_max_output_tokens();- }-- Arc::new(model)-}--/// Factory-level native builder taking resolved provider slug, endpoint,-/// credential, host auth style, model, temperature-suppression list, and-/// per-workload override and returning a crate `ChatModel`.-///-/// The cutover swaps each generic OpenAI-compatible construction site over to-/// this. `merge_system_into_user` is threaded per-provider (the catalog knows-/// which endpoints reject a `system` role); `supports_responses_fallback` has no-/// crate equivalent — providers that need `/v1/responses` (only `openai_codex`)-/// stay host-side and never call here.-#[allow(clippy::too_many_arguments)]-pub(crate) fn make_crate_openai_chat_model(- provider_name: &str,- endpoint: &str,- api_key: &str,- auth_style: HostAuthStyle,- model: &str,- temperature_unsupported_models: &[String],- temperature_override: Option<f64>,- merge_system_into_user: bool,-) -> Arc<dyn ChatModel<()>> {- build_crate_openai_model(CrateOpenAiConfig {- provider_name,- endpoint,- api_key,- auth_style,- model,- temperature_unsupported_models,- temperature_override,- merge_system_into_user,- extra_headers: &[],- native_tool_calling: None,- vision: None,- default_provider_options: None,- responses_api_primary: false,- responses_omit_max_output_tokens: false,- extra_query_params: &[],- user_agent: None,- explicit_cache_control: false,- })-}--/// Build a crate-native `ChatModel` for a **local OpenAI-compatible runtime**-/// (Ollama, LM Studio, MLX, OMLX, local-openai). Local runtimes reject the-/// OpenAI `tools` parameter and are text-only, so native tool calling and vision-/// are forced off; `num_ctx` (Ollama) rides baked provider options as-/// `{"options": {"num_ctx": N}}`, matching the host provider's wire shape.-#[allow(clippy::too_many_arguments)]-pub(crate) fn make_crate_local_runtime_chat_model(- provider_name: &str,- endpoint: &str,- api_key: &str,- auth_style: HostAuthStyle,- model: &str,- temperature_unsupported_models: &[String],- temperature_override: Option<f64>,- num_ctx: Option<u32>,-) -> Arc<dyn ChatModel<()>> {- let default_provider_options = num_ctx.map(|n| {- serde_json::json!({- "options": { "num_ctx": n }- })- });- build_crate_openai_model(CrateOpenAiConfig {- provider_name,- endpoint,- api_key,- auth_style,- model,- temperature_unsupported_models,- temperature_override,- // Local runtimes have a native `system` role; no merge needed.- merge_system_into_user: false,- extra_headers: &[],- // Parity with the host local providers, which set these off.- native_tool_calling: Some(false),- vision: Some(false),- default_provider_options,- responses_api_primary: false,- responses_omit_max_output_tokens: false,- extra_query_params: &[],- user_agent: None,- explicit_cache_control: false,- })-}--#[cfg(test)]-#[path = "crate_openai_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/inference/provider/crate_openai_tests.rs b/crates/openhuman-core/src/inference/provider/crate_openai_tests.rsdeleted file mode 100644index 48873a78c9..0000000000--- a/crates/openhuman-core/src/inference/provider/crate_openai_tests.rs+++ /dev/null@@ -1,102 +0,0 @@-use super::*;--#[test]-fn builds_a_chat_model_with_the_configured_profile() {- let model = build_crate_openai_model(CrateOpenAiConfig {- provider_name: "deepseek",- endpoint: "https://api.deepseek.com/v1",- api_key: "secret",- auth_style: HostAuthStyle::Bearer,- model: "deepseek-chat",- temperature_unsupported_models: &[],- temperature_override: None,- merge_system_into_user: false,- extra_headers: &[],- native_tool_calling: None,- vision: None,- default_provider_options: None,- responses_api_primary: false,- responses_omit_max_output_tokens: false,- extra_query_params: &[],- user_agent: None,- explicit_cache_control: false,- });- // The built model carries the configured provider + model on its profile.- let profile = model.profile().expect("openai models expose a profile");- assert_eq!(profile.provider.as_deref(), Some("deepseek"));- assert_eq!(profile.model.as_deref(), Some("deepseek-chat"));- assert!(profile.tool_calling);-}--#[test]-fn factory_level_builder_carries_provider_and_model() {- let model = make_crate_openai_chat_model(- "groq",- "https://api.groq.com/openai/v1",- "secret",- HostAuthStyle::Bearer,- "llama-3.3-70b-versatile",- &["o1*".to_string()],- None,- false,- );- let profile = model.profile().expect("openai models expose a profile");- assert_eq!(profile.provider.as_deref(), Some("groq"));- assert_eq!(profile.model.as_deref(), Some("llama-3.3-70b-versatile"));-}--#[test]-fn builder_applies_local_none_auth_without_panicking() {- // Local runtime shape: no auth, empty key, merge-system on.- let _model = build_crate_openai_model(CrateOpenAiConfig {- provider_name: "ollama",- endpoint: "http://localhost:11434/v1",- api_key: "",- auth_style: HostAuthStyle::None,- model: "llama3.2",- temperature_unsupported_models: &["o1*".to_string()],- temperature_override: Some(0.0),- merge_system_into_user: true,- extra_headers: &[("X-Attr".to_string(), "openhuman".to_string())],- native_tool_calling: Some(false),- vision: Some(false),- default_provider_options: None,- responses_api_primary: false,- responses_omit_max_output_tokens: false,- extra_query_params: &[],- user_agent: None,- explicit_cache_control: false,- });-}--#[test]-fn local_runtime_builder_disables_native_tools_and_vision() {- let model = make_crate_local_runtime_chat_model(- "ollama",- "http://localhost:11434/v1",- "",- HostAuthStyle::None,- "qwen2.5",- &[],- None,- Some(8192),- );- let profile = model.profile().expect("openai models expose a profile");- assert_eq!(profile.provider.as_deref(), Some("ollama"));- assert_eq!(profile.model.as_deref(), Some("qwen2.5"));- // Local runtimes must not advertise native tools or vision.- assert!(!profile.tool_calling);- assert!(!profile.modalities.image_in);-}--#[test]-fn openrouter_endpoints_are_recognised_for_explicit_cache_control() {- assert!(endpoint_is_openrouter("https://openrouter.ai/api/v1"));- assert!(endpoint_is_openrouter("HTTPS://OpenRouter.ai/api/v1/"));- assert!(endpoint_is_openrouter("https://openrouter.ai:443/api/v1"));- assert!(!endpoint_is_openrouter("https://api.openai.com/v1"));- assert!(!endpoint_is_openrouter("https://notopenrouter.ai/api/v1"));- assert!(!endpoint_is_openrouter(- "https://example.com/openrouter.ai/"- ));-}diff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rsindex f87d38fe0c..fdad5071ad 100644--- a/crates/openhuman-core/src/inference/provider/factory.rs+++ b/crates/openhuman-core/src/inference/provider/factory.rs@@ -115,16 +115,17 @@ mod factory_tests;use crate::config::schema::cloud_providers::AuthStyle;use crate::config::Config;-use crate::inference::provider::claude_agent_sdk::subprocess::ClaudeAgentSdkProvider;-use crate::inference::provider::openai_codex::{- openai_codex_client_version, openai_codex_user_agent, resolve_openai_codex_routing,- OPENAI_CODEX_ACCOUNT_HEADER, OPENAI_CODEX_ORIGINATOR, OPENAI_CODEX_ORIGINATOR_HEADER,-};+use crate::inference::provider::openai_codex::resolve_openai_codex_routing;use crate::inference::provider::openhuman_backend_model::OpenHumanBackendModel;use crate::inference::provider::ProviderRuntimeOptions;use crate::security::credentials::AuthService;use std::sync::Arc;+use tinyagents_harness::providers::claude_agent_sdk::ClaudeAgentSdkProvider;use tinyinference::model::{ChatModel, ModelRequest, ModelResponse, ModelStream};+use tinyinference::providers::openai::codex::{+ openai_codex_client_version, openai_codex_user_agent, OPENAI_CODEX_ACCOUNT_HEADER,+ OPENAI_CODEX_ORIGINATOR, OPENAI_CODEX_ORIGINATOR_HEADER,+};use tinyinference::providers::openai::AuthStyle as CompatAuthStyle;/// Sentinel meaning "use the OpenHuman backend session JWT".@@ -149,13 +150,3 @@ pub const CLAUDE_AGENT_SDK_PROVIDER: &str = "claude_agent_sdk";/// `create_chat_model_from_string` to produce a clear configuration error/// instead of silently routing through the managed OpenHuman backend.pub const BYOK_INCOMPLETE_SENTINEL: &str = "__byok_incomplete__";--/// Interpolation-free substring of the empty-model bail emitted by-/// cloud-slug resolution when a `<slug>` provider string carries-/// no model and the `cloud_providers` entry has no `default_model` (the-/// #2784 guard). The Sentry-demotion + user-copy classifier-/// [`super::is_provider_config_rejection_message`] keys on this exact literal,-/// and a round-trip test in `factory_tests.rs` asserts the bail body still-/// contains it — so a wording drift fails CI instead of silently re-flooding-/// Sentry (TAURI-RUST-GKV).-pub(crate) const NO_MODEL_CONFIGURED_ANCHOR: &str = "resolved to an empty model id";diff --git a/crates/openhuman-core/src/inference/provider/factory/access_gates.rs b/crates/openhuman-core/src/inference/provider/factory/access_gates.rsindex c4cc718879..1fc2a585a7 100644--- a/crates/openhuman-core/src/inference/provider/factory/access_gates.rs+++ b/crates/openhuman-core/src/inference/provider/factory/access_gates.rs@@ -49,7 +49,7 @@ pub(super) fn local_only_violation(// Deferred: re-resolves to a concrete string on the recursive call.return None;}- if crate::inference::local::profile::is_local_provider_string(p) {+ if tinyinference::local::profile::is_local_provider_string(p) {return None;}Some(external_provider_label(p))@@ -104,7 +104,7 @@ pub(super) fn emit_inference_egress(role: &str, provider: &str) {// duplicate descriptor.return;}- let is_local = crate::inference::local::profile::is_local_provider_string(p);+ let is_local = tinyinference::local::profile::is_local_provider_string(p);let (slug, model) = match p.split_once(':') {Some((s, m)) if !s.trim().is_empty() => (s.trim().to_string(), m.trim().to_string()),_ => (p.to_string(), String::new()),diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rsindex 8cc2828a71..5d5584a207 100644--- a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs+++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs@@ -2,13 +2,15 @@//! abstract-tier remapping, credentials, codex routing) and the crate-native builders.use super::*;-use crate::inference::provider::crate_anthropic;-use crate::inference::provider::crate_openai;#[cfg(not(test))]use crate::inference::provider::factory::access_gates::verify_backend_session_active;#[cfg(not(test))]use crate::inference::provider::factory::access_gates::verify_session_active;-use crate::inference::provider::fallback_diagnostics;+use tinyinference::classification::fallback as fallback_diagnostics;+use tinyinference::providers::anthropic::{+ build_anthropic_model, endpoint_is_anthropic_messages, AnthropicConfig,+};+use tinyinference::providers::openai::{build_openai_model, endpoint_is_openrouter, OpenAiConfig};/// Look up a `cloud_providers` entry by slug and build the provider./// The shared resolution for a `<slug>:<model>` cloud provider — the cloud@@ -19,7 +21,7 @@ pub(super) struct CloudSlugResolution<'a> {entry: &'a crate::config::schema::cloud_providers::CloudProviderCreds,effective_model: String,key: String,- codex: crate::inference::provider::openai_codex::OpenAiCodexRouting,+ codex: tinyinference::providers::openai::codex::OpenAiCodexRouting,}pub(super) fn resolve_cloud_slug<'a>(@@ -130,7 +132,7 @@ pub(super) fn resolve_cloud_slug<'a>(config.chat_provider.as_deref()- .filter(|chat| crate::inference::local::profile::is_local_provider_string(chat))+ .filter(|chat| tinyinference::local::profile::is_local_provider_string(chat))} else {None};@@ -144,7 +146,12 @@ pub(super) fn resolve_cloud_slug<'a>(entry.auth_style.as_str(),implicit_fallback);- fallback_diagnostics::missing_provider_credentials_message(role, slug, local_chat)+ fallback_diagnostics::missing_provider_credentials_message(+ "OpenHuman",+ role,+ slug,+ local_chat,+ )};let key = lookup_key_for_slug(slug, config)@@ -314,7 +321,7 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(// places `cache_control` breakpoints. Text mode (prompt-guided// tools) is only implemented on the Chat Completions adapter, so// that rare case keeps the compat path.- if native_tool_calling && crate_anthropic::endpoint_is_anthropic_messages(&endpoint) {+ if native_tool_calling && endpoint_is_anthropic_messages(&endpoint) {crate::security::egress::emit_external_transfer(crate::security::egress::EgressDescriptor::inference(&slug,@@ -322,17 +329,15 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(true,),);- let chat = crate_anthropic::build_crate_anthropic_model(- crate_anthropic::CrateAnthropicConfig {- endpoint: endpoint.as_str(),- api_key: key.as_str(),- model: effective_model.as_str(),- temperature_override,- temperature_unsupported_models: config- .temperature_unsupported_models- .as_slice(),- },- );+ let chat = build_anthropic_model(AnthropicConfig {+ endpoint: endpoint.as_str(),+ api_key: key.as_str(),+ model: effective_model.as_str(),+ temperature_override,+ temperature_unsupported_models: config+ .temperature_unsupported_models+ .as_slice(),+ });return Some(Ok((chat, effective_model)));}log::debug!(@@ -373,7 +378,10 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(OPENAI_CODEX_ORIGINATOR_HEADER.to_string(),OPENAI_CODEX_ORIGINATOR.to_string(),));- user_agent = Some(openai_codex_user_agent());+ user_agent = Some(openai_codex_user_agent(+ "OpenHuman",+ env!("CARGO_PKG_VERSION"),+ ));extra_query_params.push(("client_version".to_string(), openai_codex_client_version()));responses_api_primary = true;@@ -392,7 +400,7 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools();let unsupported = config.temperature_unsupported_models.clone();- let chat = crate_openai::build_crate_openai_model(crate_openai::CrateOpenAiConfig {+ let chat = build_openai_model(OpenAiConfig {provider_name: slug.as_str(),endpoint: endpoint.as_str(),api_key: key.as_str(),@@ -415,7 +423,7 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(// and Gemini, which cache nothing through a Chat Completions relay// without them; hosted OpenAI rejects unknown part fields, so the// flag is keyed on the relay, not on by default.- explicit_cache_control: crate_openai::endpoint_is_openrouter(&endpoint),+ explicit_cache_control: endpoint_is_openrouter(&endpoint),});Some(Ok((chat, effective_model)))}diff --git a/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs b/crates/openhuman-core/src/inference/provider/factory/local_runtime.rsindex 8f8c41f8f6..9db41b056d 100644--- a/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs+++ b/crates/openhuman-core/src/inference/provider/factory/local_runtime.rs@@ -2,9 +2,9 @@//! local-openai) as crate-native `ChatModel`s.use super::*;-use crate::inference::provider::crate_openai;#[cfg(not(test))]use crate::inference::provider::factory::access_gates::verify_session_active;+use tinyinference::providers::openai::build_local_runtime_chat_model;/// Local OpenAI-compatible runtimes (Ollama / LM Studio / MLX / OMLX //// local-openai) as a crate-native [`ChatModel`] (issue #4727).@@ -13,7 +13,7 @@ use crate::inference::provider::factory::access_gates::verify_session_active;/// [`create_chat_model_with_model_id`] to try cloud/BYOK/CLI constructors.////// Endpoint/auth/`num_ctx` resolution uses the shared-/// `ollama_base_url_from_config` / `lm_studio_base_url` / profile helpers. It+/// `ollama_base_url_from_override` / `lm_studio_base_url` / profile helpers. It/// runs the host access gates for custom/local providers —/// [`enforce_local_only_inference`] (privacy mode) +/// [`verify_session_active`] (session requirement) — so routing a local runtime@@ -39,7 +39,7 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(config: &Config,require_session: bool,) -> OptionalChatModelResult {- use crate::inference::local::profile::{LOCAL_OPENAI_PROFILE, MLX_PROFILE, OMLX_PROFILE};+ use tinyinference::local::profile::{LOCAL_OPENAI_PROFILE, MLX_PROFILE, OMLX_PROFILE};let p = provider.trim().to_string();let is_local = p.starts_with(OLLAMA_PROVIDER_PREFIX)@@ -102,10 +102,12 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(return Some(Err(empty_model_err(&p, "ollama:<model-id>")));}// Ollama exposes the OpenAI-compatible endpoint at `/v1`.- let base_url = crate::inference::local::ollama_base_url_from_config(config);+ let base_url = tinyinference::local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ );let normalized = base_url.trim_end_matches('/').trim_end_matches("/v1");let endpoint = format!("{normalized}/v1");- let chat = crate_openai::make_crate_local_runtime_chat_model(+ let chat = build_local_runtime_chat_model("ollama",&endpoint,"",@@ -122,9 +124,11 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(if model.is_empty() {return Some(Err(empty_model_err(&p, "lmstudio:<model-id>")));}- let endpoint = crate::inference::local::lm_studio::lm_studio_base_url(config);+ let endpoint = tinyinference::local::lm_studio::lm_studio_base_url(+ config.local_ai.base_url.as_deref(),+ );let (api_key, auth) = keyed_auth();- let chat = crate_openai::make_crate_local_runtime_chat_model(+ let chat = build_local_runtime_chat_model("lmstudio",&endpoint,&api_key,@@ -142,7 +146,7 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(return Some(Err(empty_model_err(&p, "mlx:<model-id>")));}let endpoint = env_or_config_url("MLX_SERVER_URL", MLX_PROFILE.default_base_url);- let chat = crate_openai::make_crate_local_runtime_chat_model(+ let chat = build_local_runtime_chat_model("mlx",&endpoint,"",@@ -161,7 +165,7 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(}let endpoint = env_or_config_url("OMLX_SERVER_URL", OMLX_PROFILE.default_base_url);let (api_key, auth) = keyed_auth();- let chat = crate_openai::make_crate_local_runtime_chat_model(+ let chat = build_local_runtime_chat_model("omlx",&endpoint,&api_key,@@ -180,7 +184,7 @@ pub(super) fn try_create_local_runtime_chat_model_from_string(}let endpoint = env_or_config_url("LOCAL_OPENAI_URL", LOCAL_OPENAI_PROFILE.default_base_url);let (api_key, auth) = keyed_auth();- let chat = crate_openai::make_crate_local_runtime_chat_model(+ let chat = build_local_runtime_chat_model("local-openai",&endpoint,&api_key,diff --git a/crates/openhuman-core/src/inference/provider/factory/routing.rs b/crates/openhuman-core/src/inference/provider/factory/routing.rsindex 935d6b3ef2..92a69c1095 100644--- a/crates/openhuman-core/src/inference/provider/factory/routing.rs+++ b/crates/openhuman-core/src/inference/provider/factory/routing.rs@@ -2,7 +2,7 @@//! managed-credits bypass check and the `<model>[@<temp>]` suffix parser.use super::*;-use crate::inference::provider::fallback_diagnostics;+use tinyinference::classification::fallback as fallback_diagnostics;/// The provider route a role has **explicitly** configured, before any/// fallback.@@ -102,7 +102,7 @@ pub fn provider_for_role(role: &str, config: &Config) -> String {// visible in logs and support transcripts before anything goes wrong.if fallback_diagnostics::role_falls_back_to_cloud(role) {if let Some(chat) = config.chat_provider.as_deref() {- if crate::inference::local::profile::is_local_provider_string(chat) {+ if tinyinference::local::profile::is_local_provider_string(chat) {log::info!("[providers][local-fallback] role={} {}",role,@@ -155,7 +155,7 @@ pub(super) fn route_has_usable_credentials(resolved: &str, config: &Config) -> blet r = resolved.trim();// Local runtimes (ollama/lmstudio/mlx/local-openai) and the local CLI// delegates carry their own credentials / run on-device.- if crate::inference::local::profile::is_local_provider_string(r)+ if tinyinference::local::profile::is_local_provider_string(r)|| r.starts_with(crate::inference::provider::claude_code::PROVIDER_PREFIX)|| r == CLAUDE_AGENT_SDK_PROVIDER|| r.starts_with(CLAUDE_AGENT_SDK_PREFIX)diff --git a/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rsindex 14ee47aeeb..9b6b0cce13 100644--- a/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs+++ b/crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs@@ -26,7 +26,7 @@ pub(super) fn try_create_claude_agent_sdk_chat_model_from_string(};emit_inference_egress(role, &format!("{CLAUDE_AGENT_SDK_PREFIX}{model}"));let chat: Arc<dyn ChatModel<()>> = Arc::new(ClaudeAgentSdkProvider::for_model(- config.claude_agent_sdk.clone(),+ (&config.claude_agent_sdk).into(),model.clone(),));Some(Ok((chat, model)))diff --git a/crates/openhuman-core/src/inference/provider/factory/turn_model.rs b/crates/openhuman-core/src/inference/provider/factory/turn_model.rsindex d150d551f8..9e11249a99 100644--- a/crates/openhuman-core/src/inference/provider/factory/turn_model.rs+++ b/crates/openhuman-core/src/inference/provider/factory/turn_model.rs@@ -121,7 +121,7 @@ pub(super) fn create_turn_chat_model_with_native_tools_and_route_inner(emit_inference_egress(role, &format!("{CLAUDE_AGENT_SDK_PREFIX}{model}"));return Ok((Arc::new(ClaudeAgentSdkProvider::for_model(- config.claude_agent_sdk.clone(),+ (&config.claude_agent_sdk).into(),model,)),provider_name,diff --git a/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs b/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rsindex 1ce2e19612..b9489c959e 100644--- a/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs+++ b/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs@@ -228,7 +228,7 @@ fn implicit_cloud_fallback_is_claimed_only_when_the_role_has_no_route_of_its_ownfn cloud_fallback_roles_match_the_roles_provider_for_role_actually_falls_back() {// `factory_tests` is a child module of `factory`, so `super` is `factory`,// not `provider` — reach the sibling module by its crate path.- use crate::inference::provider::fallback_diagnostics::role_falls_back_to_cloud;+ use tinyinference::classification::fallback::role_falls_back_to_cloud;let mut config = Config::default();config.chat_provider = Some("ollama:gemma3:1b".to_string());diff --git a/crates/openhuman-core/src/inference/provider/factory_route_resolution_tests.rs b/crates/openhuman-core/src/inference/provider/factory_route_resolution_tests.rsindex 0716330676..8a64994675 100644--- a/crates/openhuman-core/src/inference/provider/factory_route_resolution_tests.rs+++ b/crates/openhuman-core/src/inference/provider/factory_route_resolution_tests.rs@@ -233,7 +233,7 @@ fn agentic_route_is_neither_donor_nor_beneficiary() {#[test]fn local_provider_string_detection() {- use crate::inference::local::profile::is_local_provider_string;+ use tinyinference::local::profile::is_local_provider_string;assert!(is_local_provider_string("ollama:phi3"));assert!(is_local_provider_string("lmstudio:model"));assert!(is_local_provider_string("mlx:llama"));diff --git a/crates/openhuman-core/src/inference/provider/mod.rs b/crates/openhuman-core/src/inference/provider/mod.rsindex 304aea3e12..366a23b6cc 100644--- a/crates/openhuman-core/src/inference/provider/mod.rs+++ b/crates/openhuman-core/src/inference/provider/mod.rs@@ -5,19 +5,9 @@//! inference concerns (local runtime, cloud providers, HTTP endpoint) share//! a single domain root.-pub mod billing_error;-pub mod claude_agent_sdk;pub mod claude_code;-pub mod config_rejection;-/// Crate-native Anthropic Messages API client construction (prompt caching).-pub mod crate_anthropic;-/// Crate-native OpenAI-compatible client construction (issue #4727, Motion B).-pub mod crate_openai;pub mod error_classify;-pub mod error_code;pub mod factory;-/// Actionable diagnostics for background-workload provider fallback (#5146 §2.1).-pub(crate) mod fallback_diagnostics;pub(crate) mod openai_codex;/// Crate-native managed OpenHuman backend as a host `ChatModel` (issue #4727).pub mod openhuman_backend_model;@@ -30,16 +20,6 @@ pub use types::{ChatRequest, ChatResponse, ProviderDelta, ToolCall, UsageInfo, AGENT_TURN_MAX_OUTPUT_TOKENS,};-pub use billing_error::is_budget_exhausted_message;-pub use config_rejection::{- is_openai_compatible_unknown_model_message, is_provider_config_rejection_message,-};-pub use error_code::{- backend_error_code_skips_sentry, body_flags_malformed, extract_backend_error_code,- extract_backend_error_code_token, is_backend_client_guard_leak,- is_backend_malformed_bad_request, is_managed_backend_envelope, managed_error_skips_sentry,- BackendErrorCode,-};#[cfg(feature = "flows")]pub(crate) use factory::is_raw_passthrough_model;pub use factory::{diff --git a/crates/openhuman-core/src/inference/provider/openai_codex.rs b/crates/openhuman-core/src/inference/provider/openai_codex.rsindex a52c1eb15a..2e8b7d878f 100644--- a/crates/openhuman-core/src/inference/provider/openai_codex.rs+++ b/crates/openhuman-core/src/inference/provider/openai_codex.rs@@ -1,145 +1,5 @@-use std::path::{Path, PathBuf};-use crate::config::Config;--pub(crate) const OPENAI_CODEX_ACCOUNT_HEADER: &str = "ChatGPT-Account-ID";-pub(crate) const OPENAI_CODEX_BACKEND_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";-pub(crate) const OPENAI_CODEX_ORIGINATOR_HEADER: &str = "originator";-pub(crate) const OPENAI_CODEX_ORIGINATOR: &str = "codex_cli_rs";-pub(crate) const OPENAI_CODEX_MODEL_HINTS: &[&str] =- &["gpt-5.5", "gpt-5.4", "gpt-5.3-codex-spark", "gpt-5.3-codex"];-// Conservative Codex CLI release known to work with the ChatGPT Codex backend.-// Bump this when field reports show the backend rejecting older client versions.-const OPENAI_CODEX_DEFAULT_CLIENT_VERSION: &str = "0.130.0";--pub(crate) fn openai_codex_user_agent() -> String {- format!(- "codex_cli_rs/0.0.0 (OpenHuman {})",- env!("CARGO_PKG_VERSION")- )-}--#[derive(Debug, Clone)]-pub(crate) struct OpenAiCodexRouting {- pub endpoint: String,- pub using_oauth: bool,- pub account_id: Option<String>,-}--impl OpenAiCodexRouting {- pub fn standard(endpoint: &str) -> Self {- Self {- endpoint: endpoint.trim_end_matches('/').to_string(),- using_oauth: false,- account_id: None,- }- }-}--pub(crate) fn openai_codex_client_version() -> String {- log::trace!("[providers][openai-codex] client_version resolve start");- let (version, source) = resolve_openai_codex_client_version();- log::debug!(- "[providers][openai-codex] resolved client_version source={source} value={version}"- );- version-}--fn resolve_openai_codex_client_version() -> (String, &'static str) {- if let Some(version) = std::env::var("OPENAI_CODEX_CLIENT_VERSION")- .ok()- .and_then(non_empty_trimmed)- {- log::trace!("[providers][openai-codex] client_version source=env");- return (version, "env");- }-- if let Some(home) = codex_home_dir() {- log::trace!(- "[providers][openai-codex] client_version probing codex home={}",- home.display()- );- if let Some(version) =- read_json_string_field(&home.join("models_cache.json"), "client_version")- {- log::trace!("[providers][openai-codex] client_version source=models_cache");- return (version, "models_cache");- }- if let Some(version) = read_json_string_field(&home.join("version.json"), "latest_version")- {- log::trace!("[providers][openai-codex] client_version source=version_json");- return (version, "version_json");- }- } else {- log::trace!("[providers][openai-codex] client_version codex home unresolved");- }-- log::trace!("[providers][openai-codex] client_version source=default");- (OPENAI_CODEX_DEFAULT_CLIENT_VERSION.to_string(), "default")-}--fn non_empty_trimmed(value: String) -> Option<String> {- let trimmed = value.trim().to_string();- (!trimmed.is_empty()).then_some(trimmed)-}--fn codex_home_dir() -> Option<PathBuf> {- if let Some(codex_home) = std::env::var_os("CODEX_HOME") {- let path = PathBuf::from(codex_home);- if !path.as_os_str().is_empty() {- return Some(path);- }- }-- home_dir_from_env().map(|home| home.join(".codex"))-}--fn home_dir_from_env() -> Option<PathBuf> {- for key in ["HOME", "USERPROFILE"] {- if let Some(value) = std::env::var_os(key) {- let path = PathBuf::from(value);- if !path.as_os_str().is_empty() {- return Some(path);- }- }- }-- match (std::env::var_os("HOMEDRIVE"), std::env::var_os("HOMEPATH")) {- (Some(drive), Some(path))- if !drive.as_os_str().is_empty() && !path.as_os_str().is_empty() =>- {- Some(PathBuf::from(drive).join(path))- }- _ => None,- }-}--fn read_json_string_field(path: &Path, field: &str) -> Option<String> {- let file = path- .file_name()- .and_then(|s| s.to_str())- .unwrap_or("<unknown>");- let bytes = match std::fs::read(path) {- Ok(bytes) => bytes,- Err(err) => {- log::trace!("[providers][openai-codex] client_version read miss file={file} err={err}");- return None;- }- };- let json: serde_json::Value = match serde_json::from_slice(&bytes) {- Ok(json) => json,- Err(err) => {- log::trace!(- "[providers][openai-codex] client_version parse miss file={file} err={err}"- );- return None;- }- };- json.get(field)- .and_then(|value| value.as_str())- .map(str::to_string)- .and_then(non_empty_trimmed)-}+use tinyinference::providers::openai::codex::{OpenAiCodexRouting, OPENAI_CODEX_BACKEND_BASE_URL};pub(crate) fn resolve_openai_codex_routing(config: &Config,@@ -157,24 +17,13 @@ pub(crate) fn resolve_openai_codex_routing(Ok(credentials) => credentials,Err(err) if !bearer_key.trim().is_empty() => {log::warn!(- "[providers][openai-codex] oauth metadata unavailable; continuing with standard bearer key: {err}"- );+ "[providers][openai-codex] oauth metadata unavailable; continuing with standard bearer key: {err}"+ );None}Err(err) => return Err(format!("[chat-factory] openai oauth lookup failed: {err}")),};- // Route to the Codex subscription backend when the resolved openai bearer is- // an OAuth (Codex-CLI) credential — decided by the effective profile's *kind*- // (`bearer_is_oauth`, from the credential store), not by string-comparing two- // independently resolved OAuth tokens. The old- // `credentials.access_token == bearer_key` check silently fell back to- // api.openai.com and failed with HTTP 400 "Stream must be set to true"- // (#5353): each read of the OAuth credential can trigger a refresh, OpenAI- // rotates the access token on every refresh, so the two reads diverged- // whenever they straddled a refresh — even though OAuth was the only cred.- // Still require resolved `credentials` so we have the account id / endpoint;- // if the metadata lookup failed we fall back to the standard path.let using_oauth = bearer_is_oauth && credentials.is_some();let account_id = credentials.filter(|_| using_oauth)@@ -192,7 +41,3 @@ pub(crate) fn resolve_openai_codex_routing(OpenAiCodexRouting::standard(endpoint)})}--#[cfg(test)]-#[path = "openai_codex_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rsindex 3596c083de..1c67cee986 100644--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs@@ -431,7 +431,7 @@ fn maybe_publish_local_session_expiry() {fn maybe_publish_session_expired(err: &TiError, operation: &str) {if let TiError::Provider(pe) = err {if pe.provider.as_str() == "OpenHuman" && matches!(pe.status, Some(401 | 403)) {- let reason = crate::inference::provider::ops::sanitize_api_error(&pe.message);+ let reason = tinyinference::sanitize::sanitize_api_error(&pe.message);crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {source: format!("openhuman_backend_model.{}({})",@@ -462,13 +462,13 @@ fn log_managed_dispatch_error(err: &TiError, operation: &str) {pe.code,pe.provider,pe.retryable,- crate::inference::provider::ops::sanitize_api_error(&pe.message),+ tinyinference::sanitize::sanitize_api_error(&pe.message),);}other => {log::warn!("[providers][openhuman-backend] managed {operation} failed (non-provider error): {}",- crate::inference::provider::ops::sanitize_api_error(&other.to_string()),+ tinyinference::sanitize::sanitize_api_error(&other.to_string()),);}}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error.rs b/crates/openhuman-core/src/inference/provider/ops/http_error.rsindex 63df698901..85f84e7d03 100644--- a/crates/openhuman-core/src/inference/provider/ops/http_error.rs+++ b/crates/openhuman-core/src/inference/provider/ops/http_error.rs@@ -27,8 +27,8 @@ mod quota_and_credits;// Shared imports every classifier submodule reaches through `use super::*;`// (mirrors the pre-split `include!`-shared scope).-use super::sanitize::sanitize_api_error;use crate::inference::provider::openhuman_backend_model;+use tinyinference::sanitize::sanitize_api_error;pub use auth_failure::{is_backend_auth_failure, is_byo_provider_auth_failure_http,diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rsindex e89f528e8c..9af6fb05d0 100644--- a/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rs+++ b/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rs@@ -136,13 +136,10 @@ pub fn log_byo_provider_auth_failure(// TAURI-RUST-4RC), so the registry latch is what keeps this from// re-flooding the notification center the way the raw error flooded Sentry.let status_code = status.as_u16();- if crate::inference::auth_error_registry::record(provider, status_code) {+ if tinyinference::auth_errors::record(provider, status_code) {crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ProviderApiKeyRejected {provider: provider.to_string(),- message: crate::inference::auth_error_registry::auth_error_message(- provider,- status_code,- ),+ message: tinyinference::auth_errors::auth_error_message(provider, status_code),});}}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/policy_rejection.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/policy_rejection.rsindex b63c8badd7..0ce393b0c6 100644--- a/crates/openhuman-core/src/inference/provider/ops/http_error/policy_rejection.rs+++ b/crates/openhuman-core/src/inference/provider/ops/http_error/policy_rejection.rs@@ -87,12 +87,12 @@ pub fn log_provider_access_policy_denied_http_403(/// Returns `false` for a backend-flagged **malformed** `BAD_REQUEST`: that one/// `errorCode` case is a client-built payload the backend couldn't parse, and/// the FE *does* page for it (F8). Delegates to the single-source decision in-/// [`crate::inference::provider::backend_error_code_skips_sentry`]+/// [`tinyinference::classification::backend_error_code_skips_sentry`]/// so the provider layer, the higher-layer re-report classifier, and the/// Sentry `before_send` filter can't drift.pub fn is_backend_error_code_owned(provider: &str, body: &str) -> bool {provider == openhuman_backend_model::PROVIDER_LABEL- && crate::inference::provider::backend_error_code_skips_sentry(body)+ && tinyinference::classification::backend_error_code_skips_sentry(body)}pub fn log_backend_error_code_owned(@@ -103,7 +103,7 @@ pub fn log_backend_error_code_owned(body: &str,) {let code =- crate::inference::provider::extract_backend_error_code_token(body).unwrap_or_default();+ tinyinference::classification::extract_backend_error_code_token(body).unwrap_or_default();tracing::info!(domain = "llm_provider",operation = operation,@@ -210,14 +210,14 @@ pub fn is_provider_config_rejection_http(if !matches!(status.as_u16(), 400 | 403 | 404 | 422) {return false;}- if !crate::inference::provider::is_provider_config_rejection_message(body) {+ if !tinyinference::classification::is_provider_config_rejection_message(body) {return false;}// OpenAI-compatible "unknown model" body is user-state regardless of// provider — both third-party `custom_openai` upstreams and our own// OpenHuman backend now emit it for user-configured model ids that// aren't in the registry (TAURI-RUST-2Z1).- if crate::inference::provider::is_openai_compatible_unknown_model_message(body) {+ if tinyinference::classification::is_openai_compatible_unknown_model_message(body) {return true;}// Remaining config-rejection phrases (DeepSeek `supported api modeldiff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/quota_and_credits.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/quota_and_credits.rsindex e9be8f7152..801c3d09f4 100644--- a/crates/openhuman-core/src/inference/provider/ops/http_error/quota_and_credits.rs+++ b/crates/openhuman-core/src/inference/provider/ops/http_error/quota_and_credits.rs@@ -5,7 +5,7 @@/// user-state error that should be demoted from Sentry to an info log.pub fn is_budget_exhausted_http_400(status: reqwest::StatusCode, body: &str) -> bool {status == reqwest::StatusCode::BAD_REQUEST- && crate::inference::provider::is_budget_exhausted_message(body)+ && tinyinference::classification::is_budget_exhausted_message(body)}pub fn log_budget_exhausted_http_400(diff --git a/crates/openhuman-core/src/inference/provider/ops/mod.rs b/crates/openhuman-core/src/inference/provider/ops/mod.rsindex f0509059d0..6136125e3b 100644--- a/crates/openhuman-core/src/inference/provider/ops/mod.rs+++ b/crates/openhuman-core/src/inference/provider/ops/mod.rs@@ -9,15 +9,9 @@mod http_error;mod models;mod provider_factory;-mod sanitize;// ── public surface (preserves the original `pub use ops::*` contract) ──-pub use sanitize::{- format_anyhow_chain, format_error_chain, sanitize_api_error, scrub_secret_patterns,- MAX_API_ERROR_CHARS,-};-pub use http_error::{api_error, body_indicates_insufficient_credits, body_indicates_quota_exhausted,is_backend_auth_failure, is_backend_error_code_owned, is_budget_exhausted_http_400,@@ -52,8 +46,6 @@ pub use provider_factory::{// ── test re-exports for ops_tests.rs ──-#[cfg(test)]-pub(crate) use super::openai_codex::openai_codex_client_version;#[cfg(test)]pub(crate) use super::openhuman_backend_model;diff --git a/crates/openhuman-core/src/inference/provider/ops/models.rs b/crates/openhuman-core/src/inference/provider/ops/models.rsindex 658c91eedd..8962185d48 100644--- a/crates/openhuman-core/src/inference/provider/ops/models.rs+++ b/crates/openhuman-core/src/inference/provider/ops/models.rs@@ -13,12 +13,13 @@//! - [`parsing`] — parsing the `/models` response envelope into//! [`ModelInfo`] entries.-use super::super::openai_codex::{- openai_codex_client_version, openai_codex_user_agent, resolve_openai_codex_routing,- OpenAiCodexRouting, OPENAI_CODEX_ACCOUNT_HEADER, OPENAI_CODEX_MODEL_HINTS,- OPENAI_CODEX_ORIGINATOR, OPENAI_CODEX_ORIGINATOR_HEADER,+use super::super::openai_codex::resolve_openai_codex_routing;+use tinyinference::providers::openai::codex::{+ openai_codex_client_version, openai_codex_user_agent, OpenAiCodexRouting,+ OPENAI_CODEX_ACCOUNT_HEADER, OPENAI_CODEX_MODEL_HINTS, OPENAI_CODEX_ORIGINATOR,+ OPENAI_CODEX_ORIGINATOR_HEADER,};-use super::sanitize::sanitize_api_error;+use tinyinference::sanitize::sanitize_api_error;mod catalog_listing;mod local_runtime;diff --git a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rsindex ef34de2561..b4118565b2 100644--- a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs+++ b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs@@ -206,7 +206,10 @@ pub async fn list_configured_models_from_config(let mut request = client.get(&models_url);if routing.using_oauth {request = request- .header(reqwest::header::USER_AGENT, openai_codex_user_agent())+ .header(+ reqwest::header::USER_AGENT,+ openai_codex_user_agent("OpenHuman", env!("CARGO_PKG_VERSION")),+ ).header(OPENAI_CODEX_ORIGINATOR_HEADER, OPENAI_CODEX_ORIGINATOR);}diff --git a/crates/openhuman-core/src/inference/provider/ops/models/local_runtime.rs b/crates/openhuman-core/src/inference/provider/ops/models/local_runtime.rsindex a205aeb25c..0456ad7acb 100644--- a/crates/openhuman-core/src/inference/provider/ops/models/local_runtime.rs+++ b/crates/openhuman-core/src/inference/provider/ops/models/local_runtime.rs@@ -31,11 +31,15 @@ pub fn synthesize_local_runtime_entry(// the same `{"data": [...]}` shape the existing parser handles, so// we route through that rather than the native `/api/tags`."ollama" => {- let base = crate::inference::local::ollama_base_url_from_config(config);+ let base = tinyinference::local::ollama::ollama_base_url_from_override(+ config.local_ai.base_url.as_deref(),+ );format!("{}/v1", base.trim_end_matches('/'))}// `lm_studio_base_url` already ends in `/v1`.- "lmstudio" => crate::inference::local::lm_studio::lm_studio_base_url(config),+ "lmstudio" => {+ tinyinference::local::lm_studio::lm_studio_base_url(config.local_ai.base_url.as_deref())+ }_ => return None,};diff --git a/crates/openhuman-core/src/inference/provider/ops_tests.rs b/crates/openhuman-core/src/inference/provider/ops_tests.rsindex b928132a26..bfb426f1a5 100644--- a/crates/openhuman-core/src/inference/provider/ops_tests.rs+++ b/crates/openhuman-core/src/inference/provider/ops_tests.rs@@ -15,6 +15,8 @@ use std::sync::{Arc, Mutex,};use tempfile::TempDir;+use tinyinference::providers::openai::codex::openai_codex_client_version;+use tinyinference::sanitize::{sanitize_api_error, MAX_API_ERROR_CHARS};#[derive(Clone)]struct ModelProbeState {diff --git a/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rs b/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rsindex 792f418b83..e84f131078 100644--- a/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rs+++ b/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rs@@ -554,7 +554,7 @@ async fn publish_backend_session_expired_emits_sanitized_session_expired() {#[test]fn synthesize_local_runtime_entry_ollama_respects_config_base_url() {// The synth must honor `config.local_ai.base_url` (the same- // priority `ollama_base_url_from_config` uses for chat routing).+ // priority `ollama_base_url_from_override` uses for chat routing).// This is the path users hit when they point Ollama at a non-loopback// host (e.g. a LAN box at 192.168.1.5).let mut config = Config::default();diff --git a/crates/openhuman-core/src/inference/types.rs b/crates/openhuman-core/src/inference/types.rsindex a327af61ed..e469460609 100644--- a/crates/openhuman-core/src/inference/types.rs+++ b/crates/openhuman-core/src/inference/types.rs@@ -3,9 +3,9 @@use crate::config::Config;use serde::{Deserialize, Serialize};-use super::local::provider::provider_from_config;use super::model_ids;use super::presets;+use tinyinference::local::provider::provider_from_name;#[derive(Debug, Clone, Serialize, Deserialize)]pub struct LocalAiStatus {@@ -44,7 +44,7 @@ pub struct LocalAiStatus {impl LocalAiStatus {pub(crate) fn disabled(config: &Config) -> Self {let vision_mode = presets::vision_mode_for_config(&config.local_ai);- let provider = provider_from_config(config);+ let provider = provider_from_name(&config.local_ai.provider);Self {state: "disabled".to_string(),model_id: model_ids::effective_chat_model_id(config),diff --git a/crates/openhuman-core/src/inference/types_tests.rs b/crates/openhuman-core/src/inference/types_tests.rsindex 67df183a81..7ccfb9b3a4 100644--- a/crates/openhuman-core/src/inference/types_tests.rs+++ b/crates/openhuman-core/src/inference/types_tests.rs@@ -16,7 +16,7 @@ fn disabled_status_marks_all_capabilities_disabled() {#[test]fn disabled_status_reflects_lm_studio_provider() {- use crate::inference::local::provider::LocalAiProvider;+ use tinyinference::local::provider::LocalAiProvider;let mut config = Config::default();config.local_ai.provider = LocalAiProvider::LmStudio.as_str().to_string();diff --git a/crates/openhuman-core/src/integrations/client/errors.rs b/crates/openhuman-core/src/integrations/client/errors.rsindex 68c38176ad..1e8a917e58 100644--- a/crates/openhuman-core/src/integrations/client/errors.rs+++ b/crates/openhuman-core/src/integrations/client/errors.rs@@ -137,7 +137,7 @@ fn handle_session_jwt_unauthorized(method: &str, path: &str, url: &str, detail:// subscriber's logs.crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {source: format!("integrations.{method}:{path}"),- reason: crate::inference::provider::ops::sanitize_api_error(&message),+ reason: tinyinference::sanitize::sanitize_api_error(&message),});messagediff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rsindex 31a3aec663..875c19ff19 100644--- a/crates/openhuman-core/src/modules/ops.rs+++ b/crates/openhuman-core/src/modules/ops.rs@@ -495,7 +495,7 @@ fn module_config(config: &Config, id: &str) -> serde_json::Value {"memory_sources": config.memory_sources,"embedding_routes": config.embedding_routes,"storage_provider": config.storage.provider.config,- "ollama_base_url": crate::inference::local::ollama_base_url_from_config(config),+ "ollama_base_url": tinyinference::local::ollama::ollama_base_url_from_override(config.local_ai.base_url.as_deref()),// The module's `EmbeddingHost::default_cloud_embedding_model`: what the// engine switches to when the opted-in local model is unreachable// (`store::factories`). That is the host's managed-cloud default, thediff --git a/crates/openhuman-core/src/platform/doctor/core/memory_agent_checks.rs b/crates/openhuman-core/src/platform/doctor/core/memory_agent_checks.rsindex d08c677984..02aa85d594 100644--- a/crates/openhuman-core/src/platform/doctor/core/memory_agent_checks.rs+++ b/crates/openhuman-core/src/platform/doctor/core/memory_agent_checks.rs@@ -111,7 +111,7 @@ pub(super) fn check_embedding_model_health(config: &Config, items: &mut Vec<Diag}// Ollama path: probe reachability then model availability.- let base_url = crate::inference::local::ollama_base_url();+ let base_url = tinyinference::local::ollama::ollama_base_url();let tags_url = format!("{}/api/tags", base_url.trim_end_matches('/'));log::debug!("[doctor] probing ollama at {tags_url} for embedding model {model}");diff --git a/crates/openhuman-core/src/runtime/python/process.rs b/crates/openhuman-core/src/runtime/python/process.rsindex ea1971cabd..26c978f317 100644--- a/crates/openhuman-core/src/runtime/python/process.rs+++ b/crates/openhuman-core/src/runtime/python/process.rs@@ -60,7 +60,7 @@ pub fn spawn_stdio_process(// Suppress the Windows conhost flash. This process is (re)spawned on every// launch to run the runtime python server, so without CREATE_NO_WINDOW a// CMD window blinks up each time the app starts (GH-4814).- crate::inference::local::process_util::apply_no_window(&mut cmd);+ tinyinference::local::process::apply_no_window(&mut cmd);let child = cmd.spawn().with_context(|| {format!(diff --git a/crates/openhuman-core/src/runtime/python_server/kompress.rs b/crates/openhuman-core/src/runtime/python_server/kompress.rsindex d46992d3ef..eb8ab006ad 100644--- a/crates/openhuman-core/src/runtime/python_server/kompress.rs+++ b/crates/openhuman-core/src/runtime/python_server/kompress.rs@@ -260,7 +260,7 @@ async fn run_step(cmd.kill_on_drop(true);// Re-provisioning can run mid-session if the venv is missing/corrupted, so// suppress the Windows conhost flash here too (GH-4814).- crate::inference::local::process_util::apply_no_window(&mut cmd);+ tinyinference::local::process::apply_no_window(&mut cmd);let output = match tokio::time::timeout(timeout, cmd.output()).await {Ok(Ok(o)) => o,diff --git a/crates/openhuman-core/src/runtime/python_server/spacy.rs b/crates/openhuman-core/src/runtime/python_server/spacy.rsindex 4802c02ac5..2dd65beeda 100644--- a/crates/openhuman-core/src/runtime/python_server/spacy.rs+++ b/crates/openhuman-core/src/runtime/python_server/spacy.rs@@ -168,7 +168,7 @@ async fn run_step(python_bin: &Path, args: &[&str], timeout: Duration, label: &scmd.kill_on_drop(true);// spaCy venv provisioning can re-run mid-session if the venv is missing or// its ready marker is stale, so suppress the Windows conhost flash (GH-4814).- crate::inference::local::process_util::apply_no_window(&mut cmd);+ tinyinference::local::process::apply_no_window(&mut cmd);let output = match tokio::time::timeout(timeout, cmd.output()).await {Ok(Ok(output)) => output,diff --git a/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs b/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rsindex 644a1dc59e..e9280abfc6 100644--- a/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs+++ b/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs@@ -63,7 +63,7 @@ pub async fn store_provider_credentials(/// bare slug (`openrouter`) the inference classifier records under.fn clear_provider_auth_error(provider: &str) {let slug = provider.strip_prefix("provider:").unwrap_or(provider);- crate::inference::auth_error_registry::clear(slug);+ tinyinference::auth_errors::clear(slug);}pub async fn remove_provider_credentials(diff --git a/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rs b/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rsindex 47595034c1..12823a9237 100644--- a/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rs+++ b/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rs@@ -24,7 +24,7 @@ pub(super) fn classify_by_backend_error_code(provider: Option<String>,fallback_available: Option<bool>,) -> Option<ClassifiedError> {- use crate::inference::provider::{+ use tinyinference::classification::{body_flags_malformed, extract_backend_error_code, is_managed_backend_envelope,BackendErrorCode,};diff --git a/crates/openhuman-core/src/web_chat/web_errors/budget.rs b/crates/openhuman-core/src/web_chat/web_errors/budget.rsindex afbc328c68..75decfc38f 100644--- a/crates/openhuman-core/src/web_chat/web_errors/budget.rs+++ b/crates/openhuman-core/src/web_chat/web_errors/budget.rs@@ -34,7 +34,7 @@ pub(crate) fn is_inference_budget_exceeded_error(message: &str) -> bool {// (issue #3088). Without this, an Ollama user with zero credits and// routing still on Managed sees an opaque "provider error" and has no// way to self-diagnose that they must top up or switch routing.- crate::inference::provider::is_budget_exhausted_message(message)+ tinyinference::classification::is_budget_exhausted_message(message)}pub(crate) fn inference_budget_exceeded_user_message() -> &'static str {diff --git a/crates/openhuman-core/src/web_chat/web_errors/classify.rs b/crates/openhuman-core/src/web_chat/web_errors/classify.rsindex a947c73550..a879f49902 100644--- a/crates/openhuman-core/src/web_chat/web_errors/classify.rs+++ b/crates/openhuman-core/src/web_chat/web_errors/classify.rs@@ -424,7 +424,7 @@ pub(crate) fn classify_inference_error(err: &str) -> ClassifiedError {provider,fallback_available: None,}- } else if crate::inference::provider::is_provider_config_rejection_message(err) {+ } else if tinyinference::classification::is_provider_config_rejection_message(err) {// #2079 / #2076 / #2202: an OpenHuman abstract tier alias leaked to// a custom provider, a stale model pin, or a model-specific// temperature constraint. Checked BEFORE the genericdiff --git a/crates/openhuman-core/src/web_chat/web_errors/provider_detail.rs b/crates/openhuman-core/src/web_chat/web_errors/provider_detail.rsindex 705a36420b..ee70d18655 100644--- a/crates/openhuman-core/src/web_chat/web_errors/provider_detail.rs+++ b/crates/openhuman-core/src/web_chat/web_errors/provider_detail.rs@@ -37,7 +37,7 @@ pub(crate) fn extract_provider_error_detail(err: &str) -> Option<String> {if trimmed.is_empty() {return None;}- let sanitized = crate::inference::provider::sanitize_api_error(trimmed);+ let sanitized = tinyinference::sanitize::sanitize_api_error(trimmed);return Some(crate::util::truncate_with_ellipsis(&sanitized,MAX_DETAIL_CHARS,diff --git a/vendor/tinyagents b/vendor/tinyagentsindex d5539df36d..ef811531d3 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit d5539df36d8a64b67912fe20bf7a0d9387e17251+Subproject commit ef811531d3a8d69ab022c8b79f9fdd3e155d317f