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: move embedding implementation to tinyinference
Steven Enamakel4d27585b2454
diff --git a/Cargo.lock b/Cargo.lockindex 88f3f28ea8..9717f77c84 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6623,7 +6623,7 @@ dependencies = [[[package]]name = "tinyconnectors-bus"-version = "0.10.0"+version = "0.9.0"dependencies = ["serde","serde_json",@@ -6735,6 +6735,8 @@ name = "tinyinference-embeddings"version = "0.2.1"dependencies = ["async-trait",+ "once_cell",+ "regex","reqwest","serde","serde_json",diff --git a/app/src/services/__tests__/rpcMethods.test.ts b/app/src/services/__tests__/rpcMethods.test.tsindex e4d32c68f5..69088f869e 100644--- a/app/src/services/__tests__/rpcMethods.test.ts+++ b/app/src/services/__tests__/rpcMethods.test.ts@@ -163,7 +163,7 @@ describe('rpcMethods catalog', () => {readWithParts('../../../../crates/openhuman-core/src/inference/provider/schemas.rs'),readWithParts('../../../../crates/openhuman-core/src/inference/schemas.rs'),readWithParts('../../../../crates/openhuman-core/src/inference/local/schemas.rs'),- readWithParts('../../../../crates/openhuman-core/src/inference/embeddings/schemas.rs'),+ readWithParts('../../../../crates/openhuman-core/src/embeddings/schemas.rs'),// The MCP registry split its schemas module into a directory. Controller// definitions (and therefore the mcp_clients literals this guard owns)// live in `registry.rs`; keep this path explicit so another move failsdiff --git a/app/test/playwright/specs/embeddings-setup-modal.spec.ts b/app/test/playwright/specs/embeddings-setup-modal.spec.tsindex e2e3aa2626..4d3b382df6 100644--- a/app/test/playwright/specs/embeddings-setup-modal.spec.ts+++ b/app/test/playwright/specs/embeddings-setup-modal.spec.ts@@ -27,7 +27,7 @@ import {* assertion that matches the fix's own reasoning.** `custom` is a real catalog provider- * (`crates/openhuman-core/src/inference/embeddings/catalog.rs` — `PROVIDER_CUSTOM`, label+ * (`crates/openhuman-core/src/embeddings/catalog.rs` — `PROVIDER_CUSTOM`, label* "Custom (OpenAI-compatible)"), so it is served by the real core this lane* runs against and needs no fixture.*/diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex adfb02c500..aef1998528 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -7212,7 +7212,7 @@ dependencies = [[[package]]name = "tinyconnectors-bus"-version = "0.10.0"+version = "0.9.0"dependencies = ["serde","serde_json",@@ -7324,6 +7324,8 @@ name = "tinyinference-embeddings"version = "0.2.1"dependencies = ["async-trait",+ "once_cell",+ "regex","reqwest 0.12.28","serde","serde_json",diff --git a/crates/openhuman-core/src/agent/harness/archivist/boundary.rs b/crates/openhuman-core/src/agent/harness/archivist/boundary.rsindex 7cad79b67f..47ba04c446 100644--- a/crates/openhuman-core/src/agent/harness/archivist/boundary.rs+++ b/crates/openhuman-core/src/agent/harness/archivist/boundary.rs@@ -162,7 +162,7 @@ pub fn detect_boundary((current_segment.embedding.as_deref(), new_turn_embedding){if !segment_emb.is_empty() && segment_emb.len() == turn_emb.len() {- let similarity = cosine_similarity(segment_emb, turn_emb);+ let similarity = tinyinference_embeddings::cosine_similarity(segment_emb, turn_emb);if similarity < config.min_cosine_similarity {tracing::debug!("[segments] boundary: embedding drift (sim={similarity:.3} < {})",@@ -199,21 +199,7 @@ pub struct SegmentBoundaryState {/// Returns `new_embedding` unchanged when there is no usable centroid yet or/// the dimensions disagree — the same guard as the drift check, for the same/// reason.-#[must_use]-pub fn incremental_mean_embedding(- current_centroid: &[f32],- new_embedding: &[f32],- count: usize,-) -> Vec<f32> {- if current_centroid.is_empty() || current_centroid.len() != new_embedding.len() {- return new_embedding.to_vec();- }- current_centroid- .iter()- .zip(new_embedding.iter())- .map(|(c, n)| c + (n - c) / (count as f32 + 1.0))- .collect()-}+pub use tinyinference_embeddings::incremental_mean_embedding;/// A summary composed from the segment's first and last turns.///@@ -229,27 +215,6 @@ pub fn fallback_summary(first_content: &str, last_content: &str, turn_count: i32)}-/// Cosine similarity, clamped to `[-1, 1]`.-///-/// Zero when either vector has no magnitude, which is the honest answer: an-/// all-zero embedding has no direction to compare.-fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {- let mut dot = 0.0_f32;- let mut norm_a = 0.0_f32;- let mut norm_b = 0.0_f32;- for (x, y) in a.iter().zip(b.iter()) {- dot += x * y;- norm_a += x * x;- norm_b += y * y;- }- let denom = norm_a.sqrt() * norm_b.sqrt();- if denom < f32::EPSILON {- 0.0- } else {- (dot / denom).clamp(-1.0, 1.0)- }-}-/// Truncate at a char boundary, appending an ellipsis when anything was cut.////// Counts **characters**, not bytes, so a multi-byte string is never splitdiff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.mdindex a55ff0613e..33ddf79b0a 100644--- a/crates/openhuman-core/src/agent/tinyagents/README.md+++ b/crates/openhuman-core/src/agent/tinyagents/README.md@@ -46,7 +46,7 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../| `steering_forwarder.rs` | `SteeringForwarderGuard`: forwards `RunQueue` steer/collect messages into the harness `SteeringHandle`; abort-on-drop so drop-based cancellation always deregisters it (issue #4456). || `stop_hooks.rs` | `StopHookMiddleware`: evaluates OpenHuman `StopHook`s after each model call and pauses the run via steering on the first `Stop` decision. || `summarize.rs` | `ModelSummarizer` / `FaultTolerantCachingSummarizer` plus a context-window-aware `SummarizationPolicy` driving the crate's `ContextCompressionMiddleware`. |-| `embeddings.rs` | `ProviderEmbeddingModel`: adapts `crate::inference::embeddings::EmbeddingProvider` onto the crate's `EmbeddingModel` trait. |+| `embeddings.rs` | `ProviderEmbeddingModel`: adapts `crate::embeddings::EmbeddingProvider` onto the crate's `EmbeddingModel` trait. || `retriever.rs` | `recall_through_facade` / `build_retriever`: wraps `Memory::recall`, projects onto the crate's `ScoredDoc`, applies the `path_scope` dedupe rule, emits `MemoryLoaded`. || `thread_context.rs` | Task-local ambient `thread_id` (`with_thread_id`, `current_thread_id`) read by the OpenAI-compatible provider when serialising request bodies. || `todos.rs` | `todos_store` / `scratch_todos_store` (the crate `Store` behind per-thread task boards, `tinyagents_graph::todos`) and `migrate_legacy_task_boards`, the one-shot import run at startup. |diff --git a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs b/crates/openhuman-core/src/agent/tinyagents/embeddings.rsindex 45a0779565..876a77e985 100644--- a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs+++ b/crates/openhuman-core/src/agent/tinyagents/embeddings.rs@@ -25,7 +25,7 @@ use async_trait::async_trait;use tinyinference_embeddings::EmbeddingModel as TaEmbeddingModel;use tinyinference_embeddings::{Error as TiError, Result as TaResult};-use crate::inference::embeddings::EmbeddingProvider;+use crate::embeddings::EmbeddingProvider;/// Wraps an OpenHuman [`EmbeddingProvider`] as a `tinyagents`/// [`EmbeddingModel`](TaEmbeddingModel).@@ -109,8 +109,8 @@ impl TaEmbeddingModel for ProviderEmbeddingModel {// exact value only affects the catalog price when an embedding rate// exists; embedding models are usually uncatalogued, in which case// the recorded cost is zero regardless.- let total_chars: usize = texts.iter().map(|t| t.chars().count()).sum();- let approx_input_tokens = (total_chars as u64).div_ceil(4);+ let approx_input_tokens =+ tinyinference_embeddings::estimate_embedding_input_tokens(texts);crate::platform::cost::record_embedding_usage(self.provider.name(),self.provider.model_id(),diff --git a/crates/openhuman-core/src/agent/tinyagents/retriever.rs b/crates/openhuman-core/src/agent/tinyagents/retriever.rsindex 8a582b8fea..2afd7b478a 100644--- a/crates/openhuman-core/src/agent/tinyagents/retriever.rs+++ b/crates/openhuman-core/src/agent/tinyagents/retriever.rs@@ -49,7 +49,7 @@ use tinyinference_embeddings::{};use super::ProviderEmbeddingModel;-use crate::inference::embeddings::EmbeddingProvider;+use crate::embeddings::EmbeddingProvider;use crate::memory::{Memory, MemoryEntry, RecallOpts};/// Process-global [`EventSink`] the facade emits [`AgentEvent::MemoryLoaded`]diff --git a/crates/openhuman-core/src/api/README.md b/crates/openhuman-core/src/api/README.mdindex 7c18177cb6..17c3420c41 100644--- a/crates/openhuman-core/src/api/README.md+++ b/crates/openhuman-core/src/api/README.md@@ -176,7 +176,7 @@ announcements, team), `medulla/client/`, `integrations/` andre-exports; consumes `BackendOAuthClient`, `flatten_authed_error`,`decode_jwt_exp`, and re-exports the OAuth types), `voice/`,`agent/progress_tracing/` (Langfuse ingestion URL and `x-sdk-name`), and-`inference/provider/`, `inference/embeddings/`, `inference/voice/` (backend+`inference/provider/`, `embeddings/`, `inference/voice/` (backendinference proxy and cloud transcription/embeddings).## Testsdiff --git a/crates/openhuman-core/src/config/migrations/README.md b/crates/openhuman-core/src/config/migrations/README.mdindex 36144993cf..0eb72fa88f 100644--- a/crates/openhuman-core/src/config/migrations/README.md+++ b/crates/openhuman-core/src/config/migrations/README.md@@ -66,7 +66,7 @@ Does not own a `store.rs`. Its effects are written through other layers:- `crate::config` (`Config`, `HttpRequestConfig`, `schema::cloud_providers::{CloudProviderCreds, AuthStyle, CloudProviderType, generate_provider_id}`, `schema::LlmBackend`, `MODEL_CHAT_V1`, `MODEL_REASONING_V1`, `MODEL_REASONING_QUICK_V1`) — the migrations read and mutate the config struct; `schema_version` is the gating field.- `crate::agent::harness::session::transcript` (`transcript`, `SessionTranscript`, `write_transcript`) — `phase_out_profile_md` parses and rewrites persisted session transcripts byte-compatibly.- `crate::inference::provider::factory` — `reconcile_orphaned_providers` mirrors the factory's exact, case-sensitive provider-string grammar so "resolvable here" matches "resolvable at inference time"; `unify_ai_provider_settings` references the factory's provider-string format.-- `crate::inference::local::ollama_base_url_from_config` — the runner's Ollama reachability probe for the 6→7 step. That step and the 9→10 step mirror, by hand, the provider-string grammar of `inference::embeddings::factory::create_embedding_provider` and `voice::factory::create_stt_provider` respectively (doc-linked, not imported), so keep them in sync when those factories change.+- `crate::inference::local::ollama_base_url_from_config` — the runner's Ollama reachability probe for the 6→7 step. That step and the 9→10 step mirror, by hand, the provider-string grammar of `embeddings::factory::create_embedding_provider` and `voice::factory::create_stt_provider` respectively (doc-linked, not imported), so keep them in sync when those factories change.- `crate::agent::messages::ChatMessage`, `schema::{LocalAiConfig, LocalAiUsage, ModelRouteConfig, SttEngine}` and `voice::factory::effective_stt_provider` are imported only by tests.## Used bydiff --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 b992281226..7a53e60cbf 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@@ -5,7 +5,7 @@//! Older builds shipped a local `"fastembed"` embedding provider (BGE models,//! 384 dims). It has since been removed from the binary entirely — it is not a//! cargo feature, it simply no longer exists in-//! [`crate::inference::embeddings::factory::create_embedding_provider`], which+//! [`crate::embeddings::factory::create_embedding_provider`], which//! hard-errors on any unknown provider string.//!//! Users who selected (or defaulted to) `"fastembed"` on an older build keep@@ -52,9 +52,7 @@//! - Never touches keys/secrets or any other config field.use crate::config::Config;-use crate::inference::embeddings::{- DEFAULT_CLOUD_EMBEDDING_DIMENSIONS, DEFAULT_CLOUD_EMBEDDING_MODEL,-};+use crate::embeddings::{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.diff --git a/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider_tests.rs b/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider_tests.rsindex a63df7db3a..d2a3715287 100644--- a/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider_tests.rs+++ b/crates/openhuman-core/src/config/migrations/migrate_legacy_embedding_provider_tests.rs@@ -1,5 +1,5 @@use super::*;-use crate::inference::embeddings::{+use crate::embeddings::{DEFAULT_CLOUD_EMBEDDING_DIMENSIONS, DEFAULT_CLOUD_EMBEDDING_MODEL, DEFAULT_OLLAMA_DIMENSIONS,DEFAULT_OLLAMA_MODEL,};diff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rsindex 15dab434fc..ad2360e5cb 100644--- a/crates/openhuman-core/src/config/ops/model.rs+++ b/crates/openhuman-core/src/config/ops/model.rs@@ -317,10 +317,8 @@ pub async fn apply_memory_settings(// `embeddings::rpc::update_settings`), so a chat model id pasted here// would otherwise be stored unchecked and 400 "does not exist" on every// memory re-embed (2205 events from one user). Conservative check — see- // `inference::embeddings::catalog::non_embedding_model_reason`.- if let Some(reason) =- crate::inference::embeddings::catalog::non_embedding_model_reason(&model)- {+ // `embeddings::catalog::non_embedding_model_reason`.+ if let Some(reason) = crate::embeddings::catalog::non_embedding_model_reason(&model) {return Err(format!("invalid embeddings model `{model}`: {reason}"));}config.memory.embedding_model = model;diff --git a/crates/openhuman-core/src/config/schema/load/mod.rs b/crates/openhuman-core/src/config/schema/load/mod.rsindex a8f9352ddd..2a116d3227 100644--- a/crates/openhuman-core/src/config/schema/load/mod.rs+++ b/crates/openhuman-core/src/config/schema/load/mod.rs@@ -36,7 +36,7 @@ pub(crate) use dirs::default_root_dir_name_pub as default_root_dir_name;// re-export; only the load_tests module needs it visible at this level.#[cfg(test)]pub(crate) use dirs::read_active_user_id_checked;-// Non-test: the keyless cloud embedder (`inference::embeddings::cloud_adapter`)+// Non-test: the keyless cloud embedder (`embeddings::cloud_adapter`)// resolves its `OPENHUMAN_WORKSPACE` credential scope through the same// workspace→config-dir mapping `config::load` uses, so a legacy `.../workspace`// override lands on the sibling `.openhuman` root that holds `auth-profiles.json`.diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rsindex 72a296518e..8d2dd405d7 100644--- a/crates/openhuman-core/src/core/all.rs+++ b/crates/openhuman-core/src/core/all.rs@@ -630,7 +630,7 @@ fn build_registered_controllers() -> Vec<GroupedController> {push(&mut controllers,DomainGroup::Inference,- crate::inference::embeddings::all_embeddings_registered_controllers(),+ crate::embeddings::all_embeddings_registered_controllers(),);// People resolution and interaction scoringpush_cap(diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rsindex ce753c1aa0..c8893c3b86 100644--- a/crates/openhuman-core/src/core/observability.rs+++ b/crates/openhuman-core/src/core/observability.rs@@ -911,15 +911,13 @@ fn is_subconscious_schema_unavailable_message(lower: &str) -> bool {}fn is_embedding_backend_auth_failure(lower: &str) -> bool {- lower.contains("embedding api error")- && lower.contains("401")- && lower.contains("invalid token")+ tinyinference_embeddings::probe::is_embedding_backend_auth_failure(lower)}/// Detect a custom embeddings endpoint that exposes **no embeddings API** —/// the `OpenAiEmbedding` client POSTed `/embeddings` and the host answered/// `404 Not Found` (route absent) or `405 Method Not Allowed`. Canonical wire-/// shape from `crates/openhuman-core/src/inference/embeddings/openai.rs`:+/// shape from `crates/openhuman-core/src/embeddings/openai.rs`:////// ```text/// Embedding API error (404 Not Found): <body>@@ -939,15 +937,13 @@ fn is_embedding_backend_auth_failure(lower: &str) -> bool {/// `embeddings::rpc::update_settings` as the save-time hard-block signal so the/// two never drift.pub(crate) fn is_embedding_endpoint_absent(lower: &str) -> bool {- (lower.contains("embedding api error") && (lower.contains("(404") || lower.contains("(405")))- || (lower.contains("embeddings returned http")- && (lower.contains("http 404") || lower.contains("http 405")))+ tinyinference_embeddings::probe::is_embedding_endpoint_absent(lower)}/// Detect a custom/cloud embeddings endpoint that IS an embeddings API but/// **rejected the configured model id** — the user pasted a non-embedding/// (chat/reasoning) model into the embeddings model field. Canonical wire shape-/// from `crates/openhuman-core/src/inference/embeddings/openai.rs` (TAURI-RUST-9SK, ~2205 events):+/// from `crates/openhuman-core/src/embeddings/openai.rs` (TAURI-RUST-9SK, ~2205 events):////// ```text/// Embedding API error (400 Bad Request): {"error":{"message":"Model nvidia/nemotron-3-super-120b-a12b does not exist","code":400}}@@ -967,22 +963,7 @@ pub(crate) fn is_embedding_endpoint_absent(lower: &str) -> bool {/// from a valid embeddings endpoint is a real fault and must keep reaching/// Sentry, so this never fires on them.fn is_embedding_model_rejected(lower: &str) -> bool {- lower.contains("embedding api error")- && lower.contains("(400")- && (lower.contains("does not exist")- || lower.contains("does not support embeddings")- // Gemini's OpenAI-compat shim (generativelanguage.googleapis.com)- // maps `/v1/embeddings` → `BatchEmbedContents` and rejects a bare- // model id with `BatchEmbedContentsRequest.model: unexpected model- // name format` / `INVALID_ARGUMENT` on every re-embed (TAURI-RUST-4SA,- // 4,494 events / 1 user). The Custom-endpoint path now normalizes the- // id to `models/<name>` at the source; this demotes any that slip- // through (already-stored bad state, older releases, other compat- // hosts) so the per-embed flood stays out of Sentry. Distinct cause- // from the #4070/9SK `"does not exist"` family.- || lower.contains("unexpected model name format")- || (lower.contains("invalid_argument")- && lower.contains("batchembedcontentsrequest.model")))+ tinyinference_embeddings::probe::is_embedding_model_rejected(lower)}/// Detect the memory-store chunk DB's circuit-breaker-open message that@@ -1033,7 +1014,7 @@ fn is_memory_store_breaker_open(lower: &str) -> bool {/// - `"Embedding API error (401 Unauthorized): {…\"error\":\"Invalid token\"…}"`/// — TAURI-RUST-4K5 (~118 events, escalating on 0.56.0). Same OpenHuman/// backend session-expired envelope as 4P0, but the embedding client at-/// `crates/openhuman-core/src/inference/embeddings/openai.rs:139` wraps it with the+/// `crates/openhuman-core/src/embeddings/openai.rs:139` wraps it with the/// `"Embedding API error"` prefix instead of `"OpenHuman API error"`./// Uses the same conjunctive-anchor pattern so BYO-key embedding 401s/// from third-party providers (OpenAI / Voyage / Cohere) still escalate@@ -1076,7 +1057,7 @@ pub fn is_session_expired_message(msg: &str) -> bool {|| (msg.contains("OpenHuman API error (401")&& msg.contains("\"error\":\"Invalid token\""))// TAURI-RUST-4K5 — same OpenHuman backend "Invalid token" envelope- // wrapped by `crates/openhuman-core/src/inference/embeddings/openai.rs:139` with the+ // wrapped by `crates/openhuman-core/src/embeddings/openai.rs:139` with the// `"Embedding API error"` prefix instead of `"OpenHuman API error"`.// Same conjunctive-anchor pattern as 4P0: the embedding-scoped// prefix gates the match so a third-party BYO-key embedding 401diff --git a/crates/openhuman-core/src/core/observability_error_classification_session_tests.rs b/crates/openhuman-core/src/core/observability_error_classification_session_tests.rsindex b636458873..dbb923456d 100644--- a/crates/openhuman-core/src/core/observability_error_classification_session_tests.rs+++ b/crates/openhuman-core/src/core/observability_error_classification_session_tests.rs@@ -275,7 +275,7 @@ fn classifies_openhuman_invalid_token_401_as_session_expired() {}/// TAURI-RUST-4K5 (118 events, escalating on 0.56.0): the embedding-/// client at `crates/openhuman-core/src/inference/embeddings/openai.rs:139` wraps the same+/// client at `crates/openhuman-core/src/embeddings/openai.rs:139` wraps the same/// OpenHuman backend `{"success":false,"error":"Invalid token"}` 401/// envelope as 4P0, but with the `"Embedding API error"` prefix/// instead of `"OpenHuman API error"` (different emit-site formatdiff --git a/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs b/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rsindex 62ab1b39ae..aa90a6e0a3 100644--- a/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs+++ b/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs@@ -291,7 +291,7 @@ fn classifies_provider_config_rejection() {fn classifies_embedding_endpoint_absent_as_config_rejection() {// TAURI-RUST-5JR — custom embeddings provider pointed at a chat-only// base URL (DeepSeek) that has no `/embeddings` route. Verbatim shape- // produced by `crates/openhuman-core/src/inference/embeddings/openai.rs` (prefix preserved+ // produced by `crates/openhuman-core/src/embeddings/openai.rs` (prefix preserved// even after the actionable-hint suffix is appended).assert_eq!(expected_error_kind(diff --git a/crates/openhuman-core/src/inference/embeddings/README.md b/crates/openhuman-core/src/embeddings/README.mdsimilarity index 80%rename from crates/openhuman-core/src/inference/embeddings/README.mdrename to crates/openhuman-core/src/embeddings/README.mdindex 20a76a3b50..11bd02b8d7 100644--- a/crates/openhuman-core/src/inference/embeddings/README.md+++ b/crates/openhuman-core/src/embeddings/README.md@@ -8,9 +8,9 @@ those models for OpenHuman.## Host-owned responsibilities-- `factory.rs`: provider slug/model/dimension selection and construction of- `tinyinference` embedding models. Also owns `MODELS_SUPPORTING_DIMENSIONS`,- the list of models allowed to request a non-default dimension.+- `factory.rs`: resolves OpenHuman credentials, local-runtime URL overrides,+ and managed-cloud session scope before delegating model construction to+ `tinyinference_embeddings::factory`.- `provider_trait.rs`: re-exports the `EmbeddingProvider` contract and`format_embedding_signature` from `tinymemory_api::host`, and defines`TinyAgentsEmbeddingProvider`, the one adapter from a `tinyinference`@@ -18,12 +18,12 @@ those models for OpenHuman.- `cloud_adapter.rs` (module `cloud`): `OpenHumanCloudEmbedding`, which wraps`tinyinference`'s `CloudEmbeddingModel` with OpenHuman session-tokenresolution, egress disclosure, and local-only privacy enforcement.-- `catalog.rs`, `rpc.rs`, `schemas.rs`: Settings catalog, credentials, JSON-RPC,- connection tests, and re-embed/wipe policy.+- `rpc.rs`, `schemas.rs`: OpenHuman credentials, JSON-RPC, config persistence,+ and re-embed/wipe policy. Provider catalogs, endpoint verification, secret+ redaction, model-list discovery, and dimension helpers live in+ `tinyinference-embeddings`.- `noop.rs`: re-export of `tinymemory_api::host::NoopEmbedding` so the host andthe memory module share one type when embeddings are switched off.-- `rate_limit` and `retry_after` (in `mod.rs`): thin re-exports of the- `tinyinference` limiter and 429 backoff helpers under their older names.Provider HTTP behavior and its tests belong in `tinyinference`. Do not add newper-provider clients here.@@ -49,7 +49,7 @@ stores fixed 1024-dimension vectors (`EMBEDDING_DIM` in tinymemory-core's- `schemas.rs` declares the `embeddings` namespace functions (`get_settings`,`update_settings`, `set_api_key`, `clear_api_key`, `embed`,`test_connection`) and dispatches to the handlers in `rpc.rs`- (`rpc/settings.rs`, `rpc/api_keys.rs`, `rpc/embed.rs`, `rpc/probe.rs`, `rpc/served_models.rs`).+ (`rpc/settings.rs`, `rpc/api_keys.rs`, `rpc/embed.rs`).- See `mod.rs` for the current provider set (Managed default via the backend's`POST /openai/v1/embeddings`, Voyage, OpenAI, Cohere, Ollama, Custom, Noop)and `tinyinference_embeddings` for their concrete implementations.diff --git a/crates/openhuman-core/src/inference/embeddings/cloud_adapter.rs b/crates/openhuman-core/src/embeddings/cloud_adapter.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/cloud_adapter.rsrename to crates/openhuman-core/src/embeddings/cloud_adapter.rsdiff --git a/crates/openhuman-core/src/inference/embeddings/cloud_adapter_tests.rs b/crates/openhuman-core/src/embeddings/cloud_adapter_tests.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/cloud_adapter_tests.rsrename to crates/openhuman-core/src/embeddings/cloud_adapter_tests.rsdiff --git a/crates/openhuman-core/src/inference/embeddings/factory.rs b/crates/openhuman-core/src/embeddings/factory.rssimilarity index 68%rename from crates/openhuman-core/src/inference/embeddings/factory.rsrename to crates/openhuman-core/src/embeddings/factory.rsindex 918421b121..6714cba1f7 100644--- a/crates/openhuman-core/src/inference/embeddings/factory.rs+++ b/crates/openhuman-core/src/embeddings/factory.rs@@ -8,73 +8,26 @@ use super::cloud::{};use super::provider_trait::{EmbeddingProvider, TinyAgentsEmbeddingProvider};use crate::config::Config;-use tinyinference_embeddings::{- model_supports_dimensions, CohereEmbeddingModel, NoopEmbeddingModel, OllamaEmbeddingModel,- OpenAiEmbeddingModel, VoyageEmbeddingModel,-};+use tinyinference_embeddings::factory::{create_embedding_model, validate_custom_endpoint};+use tinyinference_embeddings::OllamaEmbeddingModel;-/// Build the provider for an OpenAI-compatible custom endpoint.-///-/// `dims == 0` is the TinyInference dimension-discovery mode (issue #4056):-/// send no `dimensions` parameter, accept the returned vector length, and let-/// the caller adopt it.-fn custom_openai_provider(- base_url: &str,- api_key: &str,+fn standard_provider(+ provider: &str,model: &str,dims: usize,-) -> anyhow::Result<Box<dyn EmbeddingProvider>> {- let base_url = validate_custom_endpoint(base_url, !api_key.is_empty())?;- Ok(TinyAgentsEmbeddingProvider::boxed(openai_model(- &base_url, api_key, model, dims, false,- )))-}--fn openai_model(- base_url: &str,api_key: &str,- model: &str,- dims: usize,- required_key: bool,-) -> OpenAiEmbeddingModel {- OpenAiEmbeddingModel::new(api_key)- .with_base_url(base_url)- .with_model(model)- .with_dimensions(dims)- .with_send_dimensions(model_supports_dimensions(model))- .with_required_api_key(required_key)-}--/// Validate a custom endpoint before a provider can send credentials to it.-fn validate_custom_endpoint(endpoint: &str, has_credentials: bool) -> anyhow::Result<String> {- let endpoint = endpoint.trim().trim_end_matches('/');- if endpoint.is_empty() {- anyhow::bail!("custom embedding provider endpoint must not be empty");- }-- let parsed = reqwest::Url::parse(endpoint)- .map_err(|_| anyhow::anyhow!("custom embedding provider endpoint is invalid"))?;- if !matches!(parsed.scheme(), "http" | "https") {- anyhow::bail!("custom embedding provider endpoint must use HTTP or HTTPS");- }-- if has_credentials {- let loopback = parsed- .host()- .map(|host| match host {- url::Host::Domain(domain) => domain.eq_ignore_ascii_case("localhost"),- url::Host::Ipv4(address) => address.is_loopback(),- url::Host::Ipv6(address) => address.is_loopback(),- })- .unwrap_or(false);- if parsed.scheme() != "https" && !(parsed.scheme() == "http" && loopback) {- anyhow::bail!(- "credentialed custom embedding provider endpoints must use HTTPS or loopback HTTP"- );- }- }-- Ok(endpoint.to_owned())+ custom_endpoint: Option<&str>,+ ollama_base_url: &str,+) -> anyhow::Result<Box<dyn EmbeddingProvider>> {+ let model = create_embedding_model(+ provider,+ model,+ dims,+ api_key,+ custom_endpoint,+ ollama_base_url,+ )?;+ Ok(Box::new(TinyAgentsEmbeddingProvider::from_boxed(model)))}/// Creates an embedding provider based on the specified name and configuration.@@ -100,42 +53,14 @@ pub fn create_embedding_provider("cloud" | "managed" => Ok(Box::new(OpenHumanCloudEmbedding::new(None, None, true, model, dims,))),- "voyage" => Ok(TinyAgentsEmbeddingProvider::boxed(- VoyageEmbeddingModel::with_options(- "",- model,- dims,- tinyinference_embeddings::VOYAGE_API_BASE,- ),- )),- "ollama" => {- let base_url = tinyinference_local::ollama::ollama_base_url();- Ok(TinyAgentsEmbeddingProvider::boxed(- OllamaEmbeddingModel::try_new(&base_url, model, dims)?,- ))- }- "openai" => Ok(TinyAgentsEmbeddingProvider::boxed(openai_model(- "https://api.openai.com",- "",+ other => standard_provider(+ other,model,dims,- true,- ))),- "cohere" => Ok(TinyAgentsEmbeddingProvider::boxed(- CohereEmbeddingModel::new("")- .with_model(model)- .with_dimensions(dims),- )),- name if name.starts_with("custom:") => {- let base_url = name.strip_prefix("custom:").unwrap_or("");- custom_openai_provider(base_url, "", model, dims)- }- "none" => Ok(TinyAgentsEmbeddingProvider::boxed(NoopEmbeddingModel)),- unknown => Err(anyhow::anyhow!(- "unknown embedding provider: \"{unknown}\". \- Supported: \"managed\", \"voyage\", \"openai\", \"cohere\", \- \"ollama\", \"custom:<url>\", \"none\""- )),+ "",+ other.strip_prefix("custom:"),+ &tinyinference_local::ollama::ollama_base_url(),+ ),}}@@ -154,46 +79,14 @@ pub fn create_embedding_provider_with_credentials("cloud" | "managed" => Ok(Box::new(OpenHumanCloudEmbedding::new(None, None, true, model, dims,))),- "voyage" => Ok(TinyAgentsEmbeddingProvider::boxed(- VoyageEmbeddingModel::with_options(- api_key,- model,- dims,- tinyinference_embeddings::VOYAGE_API_BASE,- ),- )),- "ollama" => {- let base_url = tinyinference_local::ollama::ollama_base_url();- Ok(TinyAgentsEmbeddingProvider::boxed(- OllamaEmbeddingModel::try_new(&base_url, model, dims)?,- ))- }- "openai" => Ok(TinyAgentsEmbeddingProvider::boxed(openai_model(- "https://api.openai.com",- api_key,+ other => standard_provider(+ other,model,dims,- true,- ))),- "cohere" => Ok(TinyAgentsEmbeddingProvider::boxed(- CohereEmbeddingModel::new(api_key)- .with_model(model)- .with_dimensions(dims),- )),- "custom" => {- let url = custom_endpoint.unwrap_or("");- custom_openai_provider(url, api_key, model, dims)- }- name if name.starts_with("custom:") => {- let url = custom_endpoint.unwrap_or_else(|| name.strip_prefix("custom:").unwrap_or(""));- custom_openai_provider(url, api_key, model, dims)- }- "none" => Ok(TinyAgentsEmbeddingProvider::boxed(NoopEmbeddingModel)),- unknown => Err(anyhow::anyhow!(- "unknown embedding provider: \"{unknown}\". \- Supported: \"managed\", \"voyage\", \"openai\", \"cohere\", \- \"ollama\", \"custom\", \"none\""- )),+ api_key,+ custom_endpoint,+ &tinyinference_local::ollama::ollama_base_url(),+ ),}}@@ -244,9 +137,7 @@ pub fn create_embedding_provider_with_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)?,- ))+ standard_provider("ollama", model, dims, api_key, None, &base_url)}// Every other provider is credential-store-agnostic (BYO key or local// endpoint), so the existing construction is correct unchanged.@@ -303,7 +194,9 @@ pub fn default_embedding_provider_with_config(config: &Config) -> Arc<dyn Embedd};let api_key = super::rpc::resolve_api_key(config, provider_slug);let custom_endpoint = match raw_custom_endpoint {- Some(endpoint) => validate_custom_endpoint(endpoint, !api_key.is_empty()).map(Some),+ Some(endpoint) => validate_custom_endpoint(endpoint, !api_key.is_empty())+ .map(Some)+ .map_err(anyhow::Error::from),None if provider_slug == "custom" => Err(anyhow::anyhow!("custom embedding provider endpoint is missing")),diff --git a/crates/openhuman-core/src/inference/embeddings/factory_tests.rs b/crates/openhuman-core/src/embeddings/factory_tests.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/factory_tests.rsrename to crates/openhuman-core/src/embeddings/factory_tests.rsdiff --git a/crates/openhuman-core/src/inference/embeddings/mod.rs b/crates/openhuman-core/src/embeddings/mod.rssimilarity index 83%rename from crates/openhuman-core/src/inference/embeddings/mod.rsrename to crates/openhuman-core/src/embeddings/mod.rsindex ed32dc822b..359296c6e3 100644--- a/crates/openhuman-core/src/inference/embeddings/mod.rs+++ b/crates/openhuman-core/src/embeddings/mod.rs@@ -12,7 +12,6 @@//! - **Custom**: Any OpenAI-compatible endpoint.//! - **Noop**: A fallback provider for keyword-only search.-pub mod catalog;#[path = "cloud_adapter.rs"]pub mod cloud;mod factory;@@ -46,6 +45,7 @@ pub use schemas::{all_controller_schemas as all_embeddings_controller_schemas,all_registered_controllers as all_embeddings_registered_controllers,};+pub use tinyinference_embeddings::catalog;pub use tinyinference_embeddings::{DEFAULT_OLLAMA_DIMENSIONS, DEFAULT_OLLAMA_MODEL};/// The **intended** embedding selection — `(provider, model, dimensions)`.@@ -67,22 +67,11 @@ pub fn effective_embedding_settings(memory: &crate::config::schema::MemoryConfig,local_embedding_model: Option<&str>,) -> (String, String, usize) {- if let Some(raw) = local_embedding_model {- // Trim once and reuse — the emptiness check and the final model- // string must agree, otherwise a value like " bge-m3 " would pass- // through to Ollama with surrounding whitespace and 404.- let trimmed = raw.trim();- let model = if trimmed.is_empty() {- DEFAULT_OLLAMA_MODEL.to_string()- } else {- trimmed.to_string()- };- return ("ollama".to_string(), model, DEFAULT_OLLAMA_DIMENSIONS);- }- (- memory.embedding_provider.clone(),- memory.embedding_model.clone(),+ tinyinference_embeddings::catalog::effective_embedding_settings(+ &memory.embedding_provider,+ &memory.embedding_model,memory.embedding_dimensions,+ local_embedding_model,)}diff --git a/crates/openhuman-core/src/inference/embeddings/mod_tests.rs b/crates/openhuman-core/src/embeddings/mod_tests.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/mod_tests.rsrename to crates/openhuman-core/src/embeddings/mod_tests.rsdiff --git a/crates/openhuman-core/src/inference/embeddings/noop.rs b/crates/openhuman-core/src/embeddings/noop.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/noop.rsrename to crates/openhuman-core/src/embeddings/noop.rsdiff --git a/crates/openhuman-core/src/inference/embeddings/provider_trait.rs b/crates/openhuman-core/src/embeddings/provider_trait.rssimilarity index 95%rename from crates/openhuman-core/src/inference/embeddings/provider_trait.rsrename to crates/openhuman-core/src/embeddings/provider_trait.rsindex 758222f549..0a4e1b47b3 100644--- a/crates/openhuman-core/src/inference/embeddings/provider_trait.rs+++ b/crates/openhuman-core/src/embeddings/provider_trait.rs@@ -7,7 +7,7 @@//! structurally identical ones, or the trait objects would not be//! interchangeable.//!-//! Every existing `inference::embeddings::EmbeddingProvider` path in this crate+//! Every existing `embeddings::EmbeddingProvider` path in this crate//! keeps resolving, and keeps naming the same type.//!//! # [`TinyAgentsEmbeddingProvider`] is the host's, not the engine's (#5560)@@ -58,6 +58,10 @@ impl TinyAgentsEmbeddingProvider {pub fn boxed(model: impl EmbeddingModel + 'static) -> Box<dyn EmbeddingProvider> {Box::new(Self::new(model))}++ pub fn from_boxed(model: Box<dyn EmbeddingModel>) -> Self {+ Self { model }+ }}#[async_trait]diff --git a/crates/openhuman-core/src/inference/embeddings/rpc.rs b/crates/openhuman-core/src/embeddings/rpc.rssimilarity index 93%rename from crates/openhuman-core/src/inference/embeddings/rpc.rsrename to crates/openhuman-core/src/embeddings/rpc.rsindex ad622f9778..d780307984 100644--- a/crates/openhuman-core/src/inference/embeddings/rpc.rs+++ b/crates/openhuman-core/src/embeddings/rpc.rs@@ -6,8 +6,6 @@ mod tests;mod api_keys;mod embed;-mod probe;-mod served_models;mod settings;pub use api_keys::{clear_api_key, set_api_key};@@ -15,17 +13,17 @@ pub use embed::{embed, test_connection};pub use settings::{get_settings, update_settings};#[cfg(test)]-use probe::redact_secrets;+use tinyinference_embeddings::probe::redact_secrets;#[cfg(test)]-use probe::{classify_embed_probe, EmbedProbe};+use settings::remember_active_custom_profile;+#[cfg(test)]+use tinyinference_embeddings::probe::{classify_embed_probe, EmbedProbe};#[cfg(test)]-use served_models::{+use tinyinference_embeddings::served_models::{check_requested_model_served, fetch_served_model_ids, normalize_embed_model_id,reject_model_not_served,};-#[cfg(test)]-use settings::remember_active_custom_profile;use crate::config::Config;use crate::security::credentials::AuthService;diff --git a/crates/openhuman-core/src/inference/embeddings/rpc/api_keys.rs b/crates/openhuman-core/src/embeddings/rpc/api_keys.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/rpc/api_keys.rsrename to crates/openhuman-core/src/embeddings/rpc/api_keys.rsdiff --git a/crates/openhuman-core/src/inference/embeddings/rpc/embed.rs b/crates/openhuman-core/src/embeddings/rpc/embed.rssimilarity index 96%rename from crates/openhuman-core/src/inference/embeddings/rpc/embed.rsrename to crates/openhuman-core/src/embeddings/rpc/embed.rsindex dac6e54454..eace1b0b73 100644--- a/crates/openhuman-core/src/inference/embeddings/rpc/embed.rs+++ b/crates/openhuman-core/src/embeddings/rpc/embed.rs@@ -3,9 +3,9 @@use crate::config::Config;use crate::rpc::RpcOutcome;-use super::probe::probe_custom_embeddings;use super::{resolve_api_key, LOG_PREFIX};-use crate::inference::embeddings::factory::create_embedding_provider_with_config;+use crate::embeddings::factory::create_embedding_provider_with_config;+use tinyinference_embeddings::probe::probe_custom_embeddings;/// Generates embeddings for the given input texts using the currently/// configured provider.diff --git a/crates/openhuman-core/src/inference/embeddings/rpc/settings.rs b/crates/openhuman-core/src/embeddings/rpc/settings.rssimilarity index 93%rename from crates/openhuman-core/src/inference/embeddings/rpc/settings.rsrename to crates/openhuman-core/src/embeddings/rpc/settings.rsindex 6f06e9d27b..ad3ffaa574 100644--- a/crates/openhuman-core/src/inference/embeddings/rpc/settings.rs+++ b/crates/openhuman-core/src/embeddings/rpc/settings.rs@@ -5,10 +5,36 @@ use crate::config::Config;use crate::rpc::RpcOutcome;use crate::security::credentials::AuthService;-use super::probe::{classify_embed_probe, final_probe_dims, probe_custom_embeddings, EmbedProbe};-use super::served_models::{check_requested_model_served, fetch_served_model_ids};use super::{resolve_api_key, LOG_PREFIX};-use crate::inference::embeddings::catalog;+use tinyinference_embeddings::catalog;+use tinyinference_embeddings::probe::{+ classify_embed_probe, final_probe_dims, probe_custom_embeddings, EmbedProbe,+ EmbeddingProbeRejection,+};+use tinyinference_embeddings::served_models::{+ check_requested_model_served, fetch_served_model_ids, ModelNotServed,+};++fn probe_rejection_outcome(reject: EmbeddingProbeRejection) -> RpcOutcome<serde_json::Value> {+ let mut body = serde_json::json!({ "error": reject.error, "message": reject.message });+ if let Some(detail) = reject.detail {+ body["detail"] = serde_json::Value::String(detail);+ }+ RpcOutcome::new(body, vec![reject.summary.to_string()])+}++fn model_rejection_outcome(reject: ModelNotServed) -> RpcOutcome<serde_json::Value> {+ let mut body = serde_json::json!({+ "error": reject.error,+ "message": reject.message,+ "requested_model": reject.requested_model,+ "available_models": reject.available_models,+ });+ if let Some(suggestion) = reject.suggested_model {+ body["suggested_model"] = serde_json::Value::String(suggestion);+ }+ RpcOutcome::new(body, vec![reject.summary.to_string()])+}/// Slug naming the embedder ingestion will actually use, resolved host-side/// from the `Config` fields the resolution ladder reads.@@ -198,7 +224,7 @@ pub async fn update_settings(confirm_wipe: bool,) -> Result<RpcOutcome<serde_json::Value>, String> {use crate::config::ops as config_rpc;- use crate::inference::embeddings::format_embedding_signature;+ use crate::embeddings::format_embedding_signature;let mut config = config_rpc::load_config_with_timeout().await?;@@ -286,11 +312,7 @@ pub async fn update_settings(// Log the classified error code (never the raw detail — it can// carry endpoint response bodies) so support can distinguish// auth vs wrong-model vs unreachable failures (issue #5017).- let reject_code = reject- .value- .get("error")- .and_then(|v| v.as_str())- .unwrap_or("EMBEDDINGS_VERIFICATION_FAILED");+ let reject_code = reject.error;tracing::warn!(provider = effective_provider.as_str(),reject_code,@@ -327,7 +349,7 @@ pub async fn update_settings(served = served.len(),"{LOG_PREFIX} update_settings: model not in served list — returning name-mismatch guidance");- return Ok(better);+ return Ok(model_rejection_outcome(better));}None => {tracing::debug!(@@ -346,7 +368,7 @@ pub async fn update_settings(}}}- return Ok(reject);+ return Ok(probe_rejection_outcome(reject));}// Passed. Adopt the endpoint's real vector length for every model// we probed dimension-agnostically — the user can't be expected todiff --git a/crates/openhuman-core/src/inference/embeddings/rpc_tests.rs b/crates/openhuman-core/src/embeddings/rpc_tests.rssimilarity index 95%rename from crates/openhuman-core/src/inference/embeddings/rpc_tests.rsrename to crates/openhuman-core/src/embeddings/rpc_tests.rsindex 14f5bd3f83..4696e9c9f6 100644--- a/crates/openhuman-core/src/inference/embeddings/rpc_tests.rs+++ b/crates/openhuman-core/src/embeddings/rpc_tests.rs@@ -1,6 +1,6 @@use super::*;-use crate::inference::embeddings::rpc::probe::final_probe_dims;use std::collections::HashMap;+use tinyinference_embeddings::probe::final_probe_dims;// Production code now routes managed construction through// `create_embedding_provider_with_config`; this low-level custom-endpoint// regression test still drives the credentialed factory directly.@@ -165,9 +165,12 @@ fn reject_model_not_served_suggests_normalized_match() {// the feedback names the exact served id to select (issue #3761).let served = vec!["text-embedding-bge-m3".to_string(), "qwen-chat".to_string()];let out = reject_model_not_served("bge-m3", &served);- assert_eq!(out.value["error"], "EMBEDDINGS_NO_MODEL_LOADED");- assert_eq!(out.value["suggested_model"], "text-embedding-bge-m3");- let msg = out.value["message"].as_str().unwrap();+ assert_eq!(out.error, "EMBEDDINGS_NO_MODEL_LOADED");+ assert_eq!(+ out.suggested_model.as_deref(),+ Some("text-embedding-bge-m3")+ );+ let msg = &out.message;assert!(msg.contains("text-embedding-bge-m3"));}@@ -175,9 +178,9 @@ fn reject_model_not_served_suggests_normalized_match() {fn reject_model_not_served_without_match_lists_available() {let served = vec!["qwen-chat".to_string(), "llama-3".to_string()];let out = reject_model_not_served("bge-m3", &served);- assert_eq!(out.value["error"], "EMBEDDINGS_NO_MODEL_LOADED");- assert!(out.value.get("suggested_model").is_none());- let msg = out.value["message"].as_str().unwrap();+ assert_eq!(out.error, "EMBEDDINGS_NO_MODEL_LOADED");+ assert!(out.suggested_model.is_none());+ let msg = &out.message;assert!(msg.contains("qwen-chat") && msg.contains("llama-3"));}@@ -193,7 +196,7 @@ fn check_requested_model_served_decisions() {assert!(check_requested_model_served("bge-m3", &[]).is_none());// Non-empty list without the model → reject with feedback.let reject = check_requested_model_served("bge-m3", &["text-embedding-bge-m3".to_string()]);- assert_eq!(reject.unwrap().value["error"], "EMBEDDINGS_NO_MODEL_LOADED");+ assert_eq!(reject.unwrap().error, "EMBEDDINGS_NO_MODEL_LOADED");}#[tokio::test]@@ -223,13 +226,7 @@ async fn fetch_served_model_ids_parses_openai_models_list() {/// Helper: pull the `error` code out of a reject payload.fn reject_code(outcome: EmbedProbe) -> Option<String> {- classify_embed_probe(outcome).map(|rpc| {- rpc.value- .get("error")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string()- })+ classify_embed_probe(outcome).map(|reject| reject.error.to_string())}/// A usable vector is the ONLY thing that passes the setup-time gate — the@@ -263,12 +260,9 @@ fn classify_embed_probe_rejects_empty_vectors() {fn classify_embed_probe_rejects_no_model_loaded() {let body = r#"Embedding API error (400 Bad Request): {"error":"No models loaded. Please load a model in the developer page or use the 'lms load' command."}"#;let rpc = classify_embed_probe(EmbedProbe::Failed(body.to_string())).unwrap();- assert_eq!(- rpc.value.get("error").and_then(|v| v.as_str()),- Some("EMBEDDINGS_NO_MODEL_LOADED")- );+ assert_eq!(Some(rpc.error), Some("EMBEDDINGS_NO_MODEL_LOADED"));// The raw provider detail is preserved for the UI.- assert_eq!(rpc.value.get("detail").and_then(|v| v.as_str()), Some(body));+ assert_eq!(rpc.detail.as_deref(), Some(body));}/// A 404/405 (no `/embeddings` route) keeps its dedicated code.@@ -370,20 +364,19 @@ fn classify_embed_probe_401_bad_key_is_auth_and_redacts_key() {let rpc = classify_embed_probe(EmbedProbe::Failed(detail.into())).expect("bad key must reject the save");assert_eq!(- rpc.value.get("error").and_then(|v| v.as_str()),+ Some(rpc.error),Some("EMBEDDINGS_AUTH_FAILED"),"a genuine 401 bad key must stay classified as auth");// Nothing in the surfaced payload may leak the key.- let surfaced = serde_json::to_string(&rpc.value).unwrap();+ let surfaced = format!("{} {} {:?}", rpc.error, rpc.message, rpc.detail);assert!(!surfaced.contains("sk-"),"surfaced payload must not contain any sk- key material: {surfaced}");assert!(- rpc.value- .get("detail")- .and_then(|v| v.as_str())+ rpc.detail+ .as_deref().map(|d| d.contains("[redacted-key]")).unwrap_or(false),"the detail should keep a redaction marker for support diagnosis"diff --git a/crates/openhuman-core/src/inference/embeddings/schemas.rs b/crates/openhuman-core/src/embeddings/schemas.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/schemas.rsrename to crates/openhuman-core/src/embeddings/schemas.rsdiff --git a/crates/openhuman-core/src/inference/embeddings/schemas_tests.rs b/crates/openhuman-core/src/embeddings/schemas_tests.rssimilarity index 100%rename from crates/openhuman-core/src/inference/embeddings/schemas_tests.rsrename to crates/openhuman-core/src/embeddings/schemas_tests.rsdiff --git a/crates/openhuman-core/src/inference/README.md b/crates/openhuman-core/src/inference/README.mdindex 1c87d06248..5f565c78ac 100644--- a/crates/openhuman-core/src/inference/README.md+++ b/crates/openhuman-core/src/inference/README.md@@ -118,7 +118,7 @@ Also exposes a non-RPC HTTP router (`http::router()`) nested at `/v1` by `crates## Used by-Widely depended on by the agent layer (`agent/harness`, `agent/harness/session`, `agent/tools`, `agent/triage`, `agent/harness/subagent_runner`, `agent/learning`, `agent/context`, `agent/tinyagents`), `voice`, `memory/tree/tree_runtime`, `channels`, `web_chat`, `flows/tinyflows/caps`, `cron/scheduler`, `inference/embeddings` (Ollama base-url resolution from `local`), `threads`, `security/credentials` (`local::global`), `core/runtime/builder` (`local::try_global` on shutdown), and `config/migrations`/`config/schema`. `grep -rn 'inference::provider::\|inference::local::' crates/openhuman-core/src` is the authoritative list.+Widely depended on by the agent layer (`agent/harness`, `agent/harness/session`, `agent/tools`, `agent/triage`, `agent/harness/subagent_runner`, `agent/learning`, `agent/context`, `agent/tinyagents`), `voice`, `memory/tree/tree_runtime`, `channels`, `web_chat`, `flows/tinyflows/caps`, `cron/scheduler`, `embeddings` (Ollama base-url resolution from `local`), `threads`, `security/credentials` (`local::global`), `core/runtime/builder` (`local::try_global` on shutdown), and `config/migrations`/`config/schema`. `grep -rn 'inference::provider::\|inference::local::' crates/openhuman-core/src` is the authoritative list.## Notes / gotchasdiff --git a/crates/openhuman-core/src/inference/embeddings/catalog.rs b/crates/openhuman-core/src/inference/embeddings/catalog.rsdeleted file mode 100644index 6043c7adba..0000000000--- a/crates/openhuman-core/src/inference/embeddings/catalog.rs+++ /dev/null@@ -1,203 +0,0 @@-//! Static catalog of supported embedding providers.-//!-//! Each entry declares its slug, display label, whether it requires an API key,-//! and the models + dimension presets it supports. The frontend reads this via-//! `openhuman.embeddings_get_settings` to populate the provider picker.--use serde::Serialize;--#[derive(Debug, Clone, Serialize)]-pub struct EmbeddingModelPreset {- pub id: &'static str,- pub label: &'static str,- pub default_dimensions: usize,- pub allowed_dimensions: &'static [usize],-}--#[derive(Debug, Clone, Serialize)]-pub struct EmbeddingProviderEntry {- pub slug: &'static str,- pub label: &'static str,- pub description: &'static str,- pub requires_api_key: bool,- pub requires_endpoint: bool,- pub models: &'static [EmbeddingModelPreset],-}--pub const PROVIDER_MANAGED: &str = "managed";-pub const PROVIDER_VOYAGE: &str = "voyage";-pub const PROVIDER_OPENAI: &str = "openai";-pub const PROVIDER_COHERE: &str = "cohere";-pub const PROVIDER_OLLAMA: &str = "ollama";-pub const PROVIDER_CUSTOM: &str = "custom";-pub const PROVIDER_NONE: &str = "none";--static MANAGED_MODELS: &[EmbeddingModelPreset] = &[EmbeddingModelPreset {- id: "embedding-v1",- label: "Embedding v1 (Voyage-backed)",- default_dimensions: 1024,- allowed_dimensions: &[1024],-}];--static VOYAGE_MODELS: &[EmbeddingModelPreset] = &[- EmbeddingModelPreset {- id: "voyage-3-large",- label: "Voyage 3 Large",- default_dimensions: 1024,- allowed_dimensions: &[256, 512, 1024, 2048],- },- EmbeddingModelPreset {- id: "voyage-3",- label: "Voyage 3",- default_dimensions: 1024,- allowed_dimensions: &[1024],- },- EmbeddingModelPreset {- id: "voyage-code-3",- label: "Voyage Code 3",- default_dimensions: 1024,- allowed_dimensions: &[1024],- },-];--static OPENAI_MODELS: &[EmbeddingModelPreset] = &[- EmbeddingModelPreset {- id: "text-embedding-3-small",- label: "Embedding 3 Small",- default_dimensions: 1536,- allowed_dimensions: &[512, 1536],- },- EmbeddingModelPreset {- id: "text-embedding-3-large",- label: "Embedding 3 Large",- default_dimensions: 3072,- allowed_dimensions: &[256, 1024, 3072],- },-];--static COHERE_MODELS: &[EmbeddingModelPreset] = &[- EmbeddingModelPreset {- id: "embed-english-v3.0",- label: "Embed English v3",- default_dimensions: 1024,- allowed_dimensions: &[1024],- },- EmbeddingModelPreset {- id: "embed-multilingual-v3.0",- label: "Embed Multilingual v3",- default_dimensions: 1024,- allowed_dimensions: &[1024],- },-];--static OLLAMA_MODELS: &[EmbeddingModelPreset] = &[EmbeddingModelPreset {- id: "bge-m3",- label: "BGE-M3",- default_dimensions: 1024,- allowed_dimensions: &[1024],-}];--static CATALOG: &[EmbeddingProviderEntry] = &[- EmbeddingProviderEntry {- slug: PROVIDER_MANAGED,- label: "Managed (OpenHuman)",- description: "Routes through the OpenHuman backend. No API key needed.",- requires_api_key: false,- requires_endpoint: false,- models: MANAGED_MODELS,- },- EmbeddingProviderEntry {- slug: PROVIDER_VOYAGE,- label: "Voyage AI",- description: "Direct Voyage AI API with your own key.",- requires_api_key: true,- requires_endpoint: false,- models: VOYAGE_MODELS,- },- EmbeddingProviderEntry {- slug: PROVIDER_OPENAI,- label: "OpenAI",- description: "OpenAI embeddings API with your own key.",- requires_api_key: true,- requires_endpoint: false,- models: OPENAI_MODELS,- },- EmbeddingProviderEntry {- slug: PROVIDER_COHERE,- label: "Cohere",- description: "Cohere embed API with your own key.",- requires_api_key: true,- requires_endpoint: false,- models: COHERE_MODELS,- },- EmbeddingProviderEntry {- slug: PROVIDER_OLLAMA,- label: "Ollama (Local)",- description: "Local Ollama server. No API key needed.",- requires_api_key: false,- requires_endpoint: false,- models: OLLAMA_MODELS,- },- EmbeddingProviderEntry {- slug: PROVIDER_CUSTOM,- label: "Custom (OpenAI-compatible)",- description: "Any OpenAI-compatible embedding endpoint.",- requires_api_key: true,- requires_endpoint: true,- models: &[],- },- EmbeddingProviderEntry {- slug: PROVIDER_NONE,- label: "Disabled",- description: "Disable semantic search. Keyword search only.",- requires_api_key: false,- requires_endpoint: false,- models: &[],- },-];--pub fn all_providers() -> &'static [EmbeddingProviderEntry] {- CATALOG-}--pub fn find_provider(slug: &str) -> Option<&'static EmbeddingProviderEntry> {- CATALOG.iter().find(|e| e.slug == slug)-}--pub fn find_model(provider_slug: &str, model_id: &str) -> Option<&'static EmbeddingModelPreset> {- find_provider(provider_slug).and_then(|p| p.models.iter().find(|m| m.id == model_id))-}--pub fn default_model_for(provider_slug: &str) -> Option<&'static EmbeddingModelPreset> {- find_provider(provider_slug).and_then(|p| p.models.first())-}--/// Returns `Some(reason)` when `model` is unmistakably **not** an embeddings-/// model and must be rejected before it is persisted as the embeddings model.-///-/// Conservative by design (zero false positives on real embedding ids): the-/// only hard signal is the OpenRouter `:free` chat/reasoning tier suffix — no-/// embeddings model is served under it, and a chat model id pasted into the-/// free-text custom-model field is exactly how TAURI-RUST-9SK happened-/// (`nvidia/nemotron-3-super-120b-a12b:free` saved as the embeddings model,-/// then 400 "does not exist" on every memory re-embed — 2205 events).-///-/// This is a source-gate for the persist paths that have **no** live verify-/// probe (`config::ops::model::apply_memory_settings`); the Custom-provider-/// setup flow already runs a save-time test embed (`embeddings::rpc::-/// update_settings`), and the broad long tail of chat ids is caught at runtime-/// by the 400 "does not exist" classifier in `core::observability`. Kept-/// deliberately tight: a false positive blocks a user's valid embeddings model.-pub fn non_embedding_model_reason(model: &str) -> Option<&'static str> {- if model.trim().to_ascii_lowercase().ends_with(":free") {- return Some(- "`:free` denotes an OpenRouter chat/reasoning tier, not an embeddings model — \- pick an embeddings-capable model in Settings → Memory",- );- }- None-}--#[cfg(test)]-#[path = "catalog_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/inference/embeddings/catalog_tests.rs b/crates/openhuman-core/src/inference/embeddings/catalog_tests.rsdeleted file mode 100644index 8030aa4b30..0000000000--- a/crates/openhuman-core/src/inference/embeddings/catalog_tests.rs+++ /dev/null@@ -1,112 +0,0 @@-use super::*;--#[test]-fn catalog_is_non_empty() {- assert!(!all_providers().is_empty());-}--#[test]-fn managed_is_first() {- assert_eq!(all_providers()[0].slug, PROVIDER_MANAGED);-}--#[test]-fn find_voyage_model() {- let m = find_model(PROVIDER_VOYAGE, "voyage-3-large").unwrap();- assert!(m.allowed_dimensions.contains(&1024));-}--#[test]-fn default_model_for_openai() {- let m = default_model_for(PROVIDER_OPENAI).unwrap();- assert_eq!(m.id, "text-embedding-3-small");-}--#[test]-fn none_has_no_models() {- let p = find_provider(PROVIDER_NONE).unwrap();- assert!(p.models.is_empty());-}--#[test]-fn unknown_provider_returns_none() {- assert!(find_provider("unknown").is_none());-}--#[test]-fn all_providers_have_unique_slugs() {- let providers = all_providers();- let mut seen = std::collections::HashSet::new();- for entry in providers {- assert!(- seen.insert(entry.slug),- "duplicate slug in CATALOG: \"{}\"",- entry.slug- );- }-}--#[test]-fn all_models_have_valid_dimensions() {- for entry in all_providers() {- for model in entry.models {- assert!(- model.allowed_dimensions.contains(&model.default_dimensions),- "provider \"{}\" model \"{}\" has default_dimensions {} not in allowed_dimensions {:?}",- entry.slug,- model.id,- model.default_dimensions,- model.allowed_dimensions- );- }- }-}--#[test]-fn non_embedding_model_reason_rejects_openrouter_free_tier() {- // TAURI-RUST-9SK — the exact incident id and case/whitespace variants.- for id in [- "nvidia/nemotron-3-super-120b-a12b:free",- "meta-llama/llama-3-70b-instruct:FREE",- " some-chat-model:free ",- ] {- assert!(- non_embedding_model_reason(id).is_some(),- "{id:?} (`:free` chat tier) must be rejected as an embeddings model"- );- }-}--#[test]-fn non_embedding_model_reason_accepts_real_embedding_ids() {- // Must NOT false-positive on genuine embedding model ids across providers.- for id in [- "text-embedding-3-small",- "text-embedding-3-large",- "voyage-3-large",- "embed-english-v3.0",- "nomic-embed-text:latest",- "bge-m3",- "mxbai-embed-large",- "",- ] {- assert!(- non_embedding_model_reason(id).is_none(),- "{id:?} is a valid embeddings model and must not be rejected"- );- }-}--#[test]-fn default_model_for_all_providers_with_models() {- for entry in all_providers() {- if !entry.models.is_empty() {- assert!(- default_model_for(entry.slug).is_some(),- "default_model_for({:?}) returned None but provider has {} models",- entry.slug,- entry.models.len()- );- }- }-}diff --git a/crates/openhuman-core/src/inference/embeddings/rpc/probe.rs b/crates/openhuman-core/src/inference/embeddings/rpc/probe.rsdeleted file mode 100644index 6ccae0f7eb..0000000000--- a/crates/openhuman-core/src/inference/embeddings/rpc/probe.rs+++ /dev/null@@ -1,322 +0,0 @@-//! The setup-time embed probe: sending one width-agnostic request to a custom-//! endpoint and classifying what came back into an accept-or-reject verdict.--use crate::rpc::RpcOutcome;--use tinyinference_embeddings::model_supports_dimensions;--/// Send one OpenAI-compatible embedding request without requesting or-/// validating a vector width. This is intentionally separate from the live-/// provider: a setup probe must discover a custom endpoint's native width,-/// while a live provider must enforce the width persisted after that probe.-pub(super) async fn probe_custom_embeddings(- endpoint: &str,- api_key: &str,- model: &str,-) -> Result<Vec<Vec<f32>>, String> {- let base = endpoint.trim_end_matches('/');- let url = if base.ends_with("/embeddings") {- base.to_string()- } else if base.ends_with("/v1") {- format!("{base}/embeddings")- } else {- format!("{base}/v1/embeddings")- };- let mut request = reqwest::Client::new()- .post(&url)- .json(&serde_json::json!({ "model": model, "input": ["connection test"] }));- if !api_key.trim().is_empty() {- request = request.bearer_auth(api_key.trim());- }- let response = request- .send()- .await- .map_err(|e| format!("custom embeddings request to {url} failed: {e}"))?;- let status = response.status();- let body = response- .text()- .await- .map_err(|e| format!("custom embeddings response read failed: {e}"))?;- if !status.is_success() {- return Err(format!("custom embeddings returned HTTP {status}: {body}"));- }- let data = serde_json::from_str::<serde_json::Value>(&body)- .map_err(|e| format!("custom embeddings response was not JSON: {e}"))?- .get("data")- .and_then(serde_json::Value::as_array)- .cloned()- .ok_or_else(|| "custom embeddings response missing data array".to_string())?;- data.into_iter()- .map(|item| {- item.get("embedding")- .and_then(serde_json::Value::as_array)- .ok_or_else(|| "custom embeddings response missing embedding array".to_string())?- .iter()- .map(|value| {- value.as_f64().map(|value| value as f32).ok_or_else(|| {- "custom embeddings response contains a non-numeric vector".to_string()- })- })- .collect()- })- .collect()-}--/// Dimension to persist after a successful Custom verification probe.-///-/// For a `text-embedding-3-*` model the endpoint honoured the requested size,-/// so keep the user's `configured` value (Matryoshka). For every other model we-/// probed dimension-agnostically, so adopt the endpoint's actual returned-/// length (`actual`) — the user can't be expected to know it, and storing the-/// real size is what lets the live embed path's length guard pass afterwards.-/// Falls back to `configured` if the probe somehow reported a zero-length-/// vector (defensive — `classify_embed_probe` already rejects empty vectors).-pub(super) fn final_probe_dims(model: &str, configured: usize, actual: usize) -> usize {- if model_supports_dimensions(model) || actual == 0 {- configured- } else {- actual- }-}--/// Normalized result of the setup-time test embed in [`update_settings`].-/// Collapses the `Result<Result<_, _>, Elapsed>` timeout shape into one enum so-/// the verification policy can be expressed (and unit-tested) as a pure-/// function over it.-pub(super) enum EmbedProbe {- /// The endpoint returned vectors (may still be empty/zero-dim — checked).- Returned(Vec<Vec<f32>>),- /// The embed call returned an error; the string is the provider detail.- Failed(String),- /// The probe didn't complete within the time box.- TimedOut,-}--/// Setup-time embeddings verification policy. Returns `None` when the endpoint-/// is verified (accept + persist the config) or `Some(reject)` — the-/// "not saved" RPC payload — otherwise.-///-/// The endpoint must prove it can embed before we accept it: only a non-empty-/// vector passes; every failure mode (no model loaded, no `/embeddings` route,-/// 5xx/auth/network, timeout, empty vector) rejects the save. We do NOT try to-/// classify-and-suppress the resulting embed flood in code — residual floods-/// (e.g. the user unloads the model after a good save) are handled Sentry-side.-/// The known shapes only get a friendlier remediation message.-pub(super) fn classify_embed_probe(outcome: EmbedProbe) -> Option<RpcOutcome<serde_json::Value>> {- let reject = |error: &str, message: &str, summary: &str, detail: Option<&str>| {- let mut body = serde_json::json!({ "error": error, "message": message });- if let Some(d) = detail {- // The probe detail is the raw endpoint response body. It can carry the- // API key (OpenAI's 401 echoes `Incorrect API key provided: sk-…`), and- // the frontend appends `detail` to the surfaced message — so redact any- // key/bearer material before it ever leaves the core, for both the UI- // and logs (#5116). The clean classified `message` is the primary text;- // the sanitized detail only adds a self-diagnosis hint.- body["detail"] = serde_json::Value::String(redact_secrets(d));- }- Some(RpcOutcome::new(body, vec![summary.to_string()]))- };-- match outcome {- // Pass only when the endpoint returns a usable vector.- EmbedProbe::Returned(vectors)- if vectors.first().map(|v| !v.is_empty()).unwrap_or(false) =>- {- None- }- // Reachable but produced no usable vector — not a valid embedder.- EmbedProbe::Returned(_) => reject(- "EMBEDDINGS_VERIFICATION_FAILED",- "The embeddings endpoint responded but returned no vector. Choose an \- embeddings-capable provider or endpoint, then save again.",- "test embed returned no vectors — not saved",- None,- ),- EmbedProbe::Failed(detail) => {- let lower = detail.to_ascii_lowercase();- // The endpoint IS reachable and correctly shaped (POST /v1/embeddings- // with the user's model + key — verified conformant by the mock-endpoint- // regression test). The failures below are all *distinct causes*; issue- // #5017 was that they collapsed into one generic "test embed failed"- // message, so a user whose endpoint works for chat couldn't tell that- // (e.g.) their chosen model isn't an embeddings model, their key was- // rejected, or the host was unreachable. Order matters: check the- // specific shapes before the generic fallback.- if lower.contains("no models loaded") {- // Reachable but no model loaded (e.g. LM Studio idle).- reject(- "EMBEDDINGS_NO_MODEL_LOADED",- "Your local embeddings server (e.g. LM Studio) is running but has no \- model loaded. Load an embedding model — in LM Studio use the developer \- page or the `lms load` command — then save again.",- "embeddings server has no model loaded — not saved",- Some(&detail),- )- } else if crate::core::observability::is_embedding_endpoint_absent(&lower) {- // Endpoint exposes no embeddings API (404/405).- reject(- "EMBEDDINGS_ENDPOINT_NO_API",- "This endpoint has no embeddings API. Choose an embeddings-capable \- provider (Managed, Voyage, OpenAI, Cohere, Ollama) or a different \- custom endpoint.",- "embeddings endpoint has no embeddings API — not saved",- Some(&detail),- )- } else if is_embedding_dimension_mismatch(&lower) {- // Endpoint embedded fine but returned a different vector length than- // the (Matryoshka) size we requested — a `text-embedding-3-*` model- // name pointed at a host that ignores the `dimensions` param.- reject(- "EMBEDDINGS_DIMENSION_MISMATCH",- "The endpoint returned a vector with a different length than the \- dimensions you entered. Set dimensions to match the model's native \- output, then save again.",- "embeddings endpoint returned mismatched dimensions — not saved",- Some(&detail),- )- } else if is_embedding_model_incompatible(&lower) {- // Reachable, authenticated embeddings API that rejected the model —- // the user pasted a chat/reasoning model (e.g. `gpt-5-mini`) into the- // embeddings model field. This is the #5017 reporter's exact case:- // the same model works for chat but is not an embeddings model.- reject(- "EMBEDDINGS_MODEL_INCOMPATIBLE",- "That model isn't an embeddings model on this endpoint. A chat model \- (the one that works in Chat settings) can't produce embeddings — \- enter an embeddings model id (e.g. text-embedding-3-small, bge-m3), \- then save again.",- "embeddings model is not an embeddings model — not saved",- Some(&detail),- )- } else if embed_error_mentions_status(&lower, 401)- || embed_error_mentions_status(&lower, 403)- {- // Auth failure — key missing/wrong/lacking embeddings scope. The- // embeddings key is stored separately from the chat BYOK key, so- // "works for chat" does not imply the embeddings key is set.- reject(- "EMBEDDINGS_AUTH_FAILED",- "The endpoint rejected the API key (401/403). Enter a valid key for \- this endpoint — note the embeddings key is stored separately from the \- Chat provider key — then save again.",- "embeddings endpoint rejected the API key — not saved",- Some(&detail),- )- } else if is_embedding_endpoint_unreachable(&lower) {- // Transport-level failure — DNS, refused connection, TLS. The base- // URL is wrong or the host is down.- reject(- "EMBEDDINGS_ENDPOINT_UNREACHABLE",- "Couldn't reach the embeddings endpoint (network/DNS/connection \- error). Check the base URL and that the host is reachable, then save \- again.",- "embeddings endpoint unreachable — not saved",- Some(&detail),- )- } else {- // Any other failure (5xx, unclassified) — didn't pass verification.- reject(- "EMBEDDINGS_VERIFICATION_FAILED",- "Couldn't verify the embeddings endpoint — the test embed failed. Make \- sure the endpoint is reachable and serving an embedding model, then \- save again.",- "embeddings endpoint failed verification — not saved",- Some(&detail),- )- }- }- EmbedProbe::TimedOut => reject(- "EMBEDDINGS_ENDPOINT_UNREACHABLE",- "Couldn't verify the embeddings endpoint — the test embed timed out. Make sure \- the endpoint is running and reachable, then save again.",- "embeddings endpoint timed out during verification — not saved",- None,- ),- }-}--/// Whether a lowercased embed-error detail names the given HTTP status, tolerant-/// of the wire shapes the embeddings stack emits:-/// `openai embeddings returned HTTP 401 Unauthorized: …` (tinyagents adapter)-/// `Embedding API error (401 Unauthorized): …` (parenthesized host shape)-/// `Embedding API error 401 Unauthorized: …` (bare-status host shape)-/// The bare-status `Embedding API error {code}` form is the one the observability-/// classifier in `crates/openhuman-core/src/core/observability.rs` covers; without it, setup-time-/// verification for those hosts fell through to the generic failure code (#5017).-fn embed_error_mentions_status(lower: &str, code: u16) -> bool {- let code = code.to_string();- lower.contains(&format!("http {code}"))- || lower.contains(&format!("({code}"))- || lower.contains(&format!("embedding api error {code}"))-}--/// A reachable, authenticated embeddings API that **rejected the model id** — the-/// user pointed the embeddings model field at a chat/reasoning model.-///-/// Two tiers of phrasing:-///-/// - **Strong, status-independent phrasings** unambiguously name a model that-/// can't embed. OpenAI returns *HTTP 403* "You are not allowed to generate-/// embeddings from this model" when a chat model (e.g. `gpt-4o-mini`) is used-/// as the embeddings model — a MODEL problem, not an auth problem. Because-/// `classify_embed_probe` checks this **before** the 401/403 auth branch, that-/// 403 must be caught here or it falls through and misreports "enter a valid-/// key" (issue #5116). None of these phrases appear in a genuine auth rejection-/// (`Incorrect API key provided …`), so matching them ahead of auth is safe.-/// - **Weak phrasings** (a stray "does not exist" / odd model-name format) are-/// only unambiguous alongside a 400/422 bad-request, so a genuine 5xx or an-/// oversized-input 400 still falls through to the generic failure (issue #5017).-fn is_embedding_model_incompatible(lower: &str) -> bool {- let strong_model_rejection = lower.contains("not allowed to generate embeddings")- || lower.contains("does not support embeddings")- || lower.contains("not an embedding model")- || lower.contains("is not an embedding")- || lower.contains("not supported for embeddings")- || (lower.contains("unsupported") && lower.contains("embedding"));- if strong_model_rejection {- return true;- }- let bad_request =- embed_error_mentions_status(lower, 400) || embed_error_mentions_status(lower, 422);- bad_request- && (lower.contains("does not exist") || lower.contains("unexpected model name format"))-}--/// Strip API-key / bearer-token material from any text before it reaches the UI-/// or logs. Matches OpenAI-style keys (`sk-…`, including the modern `sk-proj-…`-/// form with embedded hyphens/underscores) and `Bearer <token>` headers, and-/// replaces each **whole** match — the replacements deliberately contain no `sk-`-/// substring, so not even a key *prefix* can surface (#5116).-pub(super) fn redact_secrets(input: &str) -> String {- use once_cell::sync::Lazy;- use regex::Regex;- static SK_KEY_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bsk-[A-Za-z0-9_-]+").unwrap());- static BEARER_RE: Lazy<Regex> =- Lazy::new(|| Regex::new(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+").unwrap());- let redacted = SK_KEY_RE.replace_all(input, "[redacted-key]");- BEARER_RE- .replace_all(&redacted, "Bearer [redacted]")- .into_owned()-}--/// The post-response length guard fired: the endpoint embedded but returned a-/// vector whose length differs from the requested (Matryoshka) `dimensions`.-/// Canonical shape from the tinyagents adapter:-/// `openai embed dimension mismatch: expected 1024, got 3072`.-fn is_embedding_dimension_mismatch(lower: &str) -> bool {- lower.contains("dimension mismatch")-}--/// A transport-level failure (DNS, refused connection, TLS, connect timeout) —-/// the endpoint was never reached, so the base URL is wrong or the host is down.-/// The tinyagents adapter wraps these as-/// `openai embeddings request to <url> failed: <reqwest error>`.-fn is_embedding_endpoint_unreachable(lower: &str) -> bool {- lower.contains("request to") && lower.contains("failed")- || lower.contains("connection refused")- || lower.contains("error sending request")- || lower.contains("error trying to connect")- || lower.contains("dns error")- || lower.contains("failed to lookup address")- || lower.contains("tcp connect error")-}diff --git a/crates/openhuman-core/src/inference/embeddings/rpc/served_models.rs b/crates/openhuman-core/src/inference/embeddings/rpc/served_models.rsdeleted file mode 100644index e9cad2b3ff..0000000000--- a/crates/openhuman-core/src/inference/embeddings/rpc/served_models.rs+++ /dev/null@@ -1,104 +0,0 @@-//! Checking a requested embedding model against the ids an OpenAI-compatible-//! endpoint reports on `/models`.--use crate::rpc::RpcOutcome;--/// GET `{endpoint}/models` (OpenAI-compatible) and return the served model ids.-/// Time-boxed and best-effort — any failure returns `Err` and the caller falls-/// back to the live test-embed probe (issue #3761).-pub(super) async fn fetch_served_model_ids(- endpoint: &str,- api_key: &str,-) -> Result<Vec<String>, String> {- #[derive(serde::Deserialize)]- struct ModelEntry {- id: String,- }- #[derive(serde::Deserialize)]- struct ModelsResponse {- #[serde(default)]- data: Vec<ModelEntry>,- }-- let url = format!("{}/models", endpoint.trim_end_matches('/'));- let client = reqwest::Client::new();- let mut req = client.get(&url).timeout(std::time::Duration::from_secs(5));- if !api_key.trim().is_empty() {- req = req.bearer_auth(api_key.trim());- }- let resp = req- .send()- .await- .map_err(|e| format!("models request failed: {e}"))?;- if !resp.status().is_success() {- return Err(format!("models request returned status {}", resp.status()));- }- let parsed: ModelsResponse = resp- .json()- .await- .map_err(|e| format!("models parse failed: {e}"))?;- Ok(parsed.data.into_iter().map(|m| m.id).collect())-}--/// Normalize an embedding model id for tolerant *suggestion* matching:-/// lowercase, drop a leading `text-embedding-`, drop a trailing `:tag`. Used-/// only to suggest the right served name — never to silently rewrite the id.-pub(super) fn normalize_embed_model_id(name: &str) -> String {- let lower = name.trim().to_ascii_lowercase();- let stripped = lower.strip_prefix("text-embedding-").unwrap_or(&lower);- stripped.split(':').next().unwrap_or(stripped).to_string()-}--/// Decide whether the requested model is acceptable given the endpoint's served-/// list. Returns `Some(reject)` only when the endpoint reports a non-empty list-/// that does NOT contain the requested id — i.e. we have positive evidence the-/// model isn't loaded. An empty/unknown list returns `None` (defer to the live-/// test-embed probe) so we never block on a server that doesn't expose-/// `/models` (issue #3761).-pub(super) fn check_requested_model_served(- requested: &str,- served: &[String],-) -> Option<RpcOutcome<serde_json::Value>> {- if served.is_empty() || served.iter().any(|m| m == requested) {- return None;- }- Some(reject_model_not_served(requested, served))-}--/// Build the "model not served" rejection: names what the endpoint actually-/// serves and, when a normalized match exists, suggests the exact name to pick-/// (e.g. `bge-m3` → `text-embedding-bge-m3`). Reuses the-/// `EMBEDDINGS_NO_MODEL_LOADED` error code so the existing Embeddings setup-/// dialog surfaces `message` and keeps the config unsaved (issue #3761).-pub(super) fn reject_model_not_served(- requested: &str,- served: &[String],-) -> RpcOutcome<serde_json::Value> {- let want = normalize_embed_model_id(requested);- let suggestion = served- .iter()- .find(|m| normalize_embed_model_id(m) == want)- .cloned();- let served_list = served.join(", ");- let message = match suggestion.as_deref() {- Some(s) => format!(- "`{requested}` isn't loaded on this embeddings server — but the same model appears to be served as `{s}`. Select `{s}` (the exact name your server reports), then save again. Available models: {served_list}."- ),- None => format!(- "`{requested}` isn't loaded on this embeddings server. Select one of the loaded models (the exact name your server reports), then save again. Available models: {served_list}."- ),- };- let mut body = serde_json::json!({- "error": "EMBEDDINGS_NO_MODEL_LOADED",- "message": message,- "requested_model": requested,- "available_models": served,- });- if let Some(s) = suggestion {- body["suggested_model"] = serde_json::Value::String(s);- }- RpcOutcome::new(- body,- vec!["embedding model not served by endpoint — not saved".to_string()],- )-}diff --git a/crates/openhuman-core/src/inference/local/README.md b/crates/openhuman-core/src/inference/local/README.mdindex 9d8c1a1067..045467ea16 100644--- a/crates/openhuman-core/src/inference/local/README.md+++ b/crates/openhuman-core/src/inference/local/README.md@@ -65,7 +65,7 @@ into `local::rpc` (`ops.rs`).callers outside this module: `agent/schemas.rs` (registers `agent.chat` /`agent.chat_simple` over `local::rpc::agent_chat*`), `inference/ops.rs` and`inference/provider/factory/` (`profile::is_local_provider_string`,-base-url resolution when routing into a local runtime), `inference/embeddings/factory.rs`+base-url resolution when routing into a local runtime), `embeddings/factory.rs`(Ollama embedding base url), `agent/learning/reflection.rs` and`security/credentials/ops/login_services.rs` (`local::global`), `core/runtime/builder.rs`(`local::try_global` on shutdown), `config/ops/model.rs` (`provider::normalize_provider`,diff --git a/crates/openhuman-core/src/inference/local/service/vision_embed.rs b/crates/openhuman-core/src/inference/local/service/vision_embed.rsindex a43e690ff2..c5affeb87e 100644--- a/crates/openhuman-core/src/inference/local/service/vision_embed.rs+++ b/crates/openhuman-core/src/inference/local/service/vision_embed.rs@@ -3,7 +3,7 @@ use crate::config::ops::local_ai_presets;use crate::config::Config;use crate::inference::types::LocalAiEmbeddingResult;use tinyinference_embeddings::{- EmbeddingModel, OllamaEmbeddingModel, DEFAULT_OLLAMA_DIMENSIONS,+ known_ollama_embedding_dimensions, EmbeddingModel, OllamaEmbeddingModel,RECOMMENDED_OLLAMA_CONTEXT_TOKENS,};use tinyinference_local::models as model_ids;@@ -15,19 +15,6 @@ use tinyinference_local::presets::VisionMode;use super::LocalAiService;-fn embedding_dimensions(model_id: &str) -> Option<usize> {- let normalized = model_id.trim().to_ascii_lowercase();- if normalized.starts_with("all-minilm") {- Some(384)- } else if normalized.contains("bge-m3") || normalized.starts_with("mxbai-embed-large") {- Some(DEFAULT_OLLAMA_DIMENSIONS)- } else if normalized.starts_with("nomic-embed-text") {- Some(768)- } else {- None- }-}-impl LocalAiService {pub async fn vision_prompt(&self,@@ -235,7 +222,7 @@ impl LocalAiService {let _gate_permit = crate::cron::scheduler_gate::wait_for_capacity().await;let embed_base = ollama_base_url_from_override(config.local_ai.base_url.as_deref());- let dimensions = embedding_dimensions(&embedding_model);+ let dimensions = known_ollama_embedding_dimensions(&embedding_model);log::debug!("[local_ai:embed] embed: using model={} dimensions={} base_url={}",embedding_model,diff --git a/crates/openhuman-core/src/inference/local/service/vision_embed_tests.rs b/crates/openhuman-core/src/inference/local/service/vision_embed_tests.rsindex 15c32613d8..ca4ceeded2 100644--- a/crates/openhuman-core/src/inference/local/service/vision_embed_tests.rs+++ b/crates/openhuman-core/src/inference/local/service/vision_embed_tests.rs@@ -99,14 +99,6 @@ async fn embed_disabled_returns_error() {assert!(err.contains("local ai is disabled"));}-#[test]-fn embedding_dimensions_match_supported_legacy_models() {- assert_eq!(embedding_dimensions("bge-m3"), Some(1024));- assert_eq!(embedding_dimensions("all-minilm:latest"), Some(384));- assert_eq!(embedding_dimensions("nomic-embed-text"), Some(768));- assert_eq!(embedding_dimensions("user-managed-model"), None);-}-#[tokio::test]async fn vision_prompt_disabled_returns_error() {let mut config = Config::default();diff --git a/crates/openhuman-core/src/inference/mod.rs b/crates/openhuman-core/src/inference/mod.rsindex d5e893b43a..4d96f67541 100644--- a/crates/openhuman-core/src/inference/mod.rs+++ b/crates/openhuman-core/src/inference/mod.rs@@ -10,7 +10,6 @@//! (moved from `voice/`; audio I/O and the voice RPC surface//! stay in `crate::voice`)//! - `http/` — OpenAI-compatible `/v1/chat/completions` endpoint-//! - `embeddings/` — embedding provider selection and RPC//! - `tokenjuice/` — host adapter for the `tinyjuice` token-compression module//!//! The RPC surface is `inference.*`; old `local_ai_*` RPC names are resolved@@ -25,7 +24,6 @@pub const INFERENCE_COMPILED_IN: bool = cfg!(feature = "inference");pub mod auth_error_registry;-pub mod embeddings;pub mod http;pub mod local;pub mod model_context;diff --git a/crates/openhuman-core/src/integrations/composio/client/factory.rs b/crates/openhuman-core/src/integrations/composio/client/factory.rsindex fe62950b4d..c8960ea39d 100644--- a/crates/openhuman-core/src/integrations/composio/client/factory.rs+++ b/crates/openhuman-core/src/integrations/composio/client/factory.rs@@ -36,7 +36,7 @@ pub(crate) fn build_composio_client(config: &crate::config::Config) -> Option<Co// ── Direct-mode factory ─────────────────────────────────────────────//-// Mirrors `crates/openhuman-core/src/inference/embeddings/factory.rs` so anyone reading both+// Mirrors `crates/openhuman-core/src/embeddings/factory.rs` so anyone reading both// can pattern-match between domains: string-matched mode, explicit error// on unknown mode, explicit error when `direct` is selected without an// API key.diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rsindex e3b68683b8..afe8b3378e 100644--- a/crates/openhuman-core/src/lib.rs+++ b/crates/openhuman-core/src/lib.rs@@ -58,6 +58,7 @@ pub mod config;pub mod core;pub mod cron;pub mod desktop;+pub mod embeddings;#[cfg(feature = "flows")]pub mod flows;pub mod hooks;diff --git a/crates/openhuman-core/src/memory/host.rs b/crates/openhuman-core/src/memory/host.rsindex c46fe25db2..29537507d7 100644--- a/crates/openhuman-core/src/memory/host.rs+++ b/crates/openhuman-core/src/memory/host.rs@@ -18,7 +18,7 @@//! spans agents, channels, cron and tools as well as memory.//! - The embedding provider trait is not implemented here — it is *defined* in//! `tinymemory_api::host` and re-exported from-//! [`crate::inference::embeddings`], so our existing providers+//! [`crate::embeddings`], so our existing providers//! already implement it.//!//! Call [`install_memory_event_sink`] once during startup, before any memorydiff --git a/crates/openhuman-core/src/memory/tools/search/vector_search.rs b/crates/openhuman-core/src/memory/tools/search/vector_search.rsindex d74b8920f2..1c6f280d20 100644--- a/crates/openhuman-core/src/memory/tools/search/vector_search.rs+++ b/crates/openhuman-core/src/memory/tools/search/vector_search.rs@@ -10,188 +10,16 @@ use serde_json::json;use std::fmt::Write;use crate::config::rpc as config_rpc;-use crate::inference::embeddings::provider_from_config;+use crate::embeddings::provider_from_config;use crate::memory::api::chunks::SourceKind;use crate::memory::api::provider::ChunkQuery;use crate::memory::api::provider::MemoryProvider;use crate::memory::ops::guard::active_memory_guard;use crate::tools::traits::{Tool, ToolExposure, ToolResult};+use tinyinference_embeddings::{cosine_similarity_f64, mmr_select, MmrCandidate};pub struct MemoryVectorSearchTool;-// ── Ranking maths, brought home from the engine crate (#5560) ────────────────-//-// `cosine_similarity` and the MMR selector below were reached at-// `tinycortex::memory::{store::vectors, retrieval::mmr}`. They are ported here-// verbatim rather than routed at the module contract because there is nothing-// on the contract to route them *at*, and nothing that would benefit if there-// were: both are pure arithmetic over `&[f32]` slices this host already holds-// in memory. The chunks and their embeddings come back over the bus-// (`MemoryChunks::list_chunks` + `chunk_embeddings`); what happens to the-// numbers afterwards is this tool's ranking policy, and shipping vectors back-// across a bus boundary to have someone else multiply them would be a round-// trip bought for nothing.-//-// That is also why they are private to this file rather than a shared module:-// this tool is the only caller in the host. `archivist::boundary` keeps its own-// `f32` cosine for its own threshold — see the divergence note on-// [`cosine_similarity`], which is the reason those two are deliberately not-// unified.--/// Cosine similarity between two vectors, in `[-1.0, 1.0]`.-///-/// Returns `0.0` for mismatched lengths, empty vectors, or a zero-magnitude-/// vector on either side. Accumulates in `f64` regardless of the `f32` inputs,-/// so a long vector does not lose precision in the dot product.-///-/// # The `[0.0, 1.0]` clamp this does *not* do-///-/// The engine's `retrieval::mmr` module docs claim this function "clamps its-/// result to `[0.0, 1.0]`", which would make an anti-correlated candidate-/// indistinguishable from an orthogonal one inside [`mmr_select`]. **That-/// comment is stale**: the code clamps to `[-1.0, 1.0]` — the mathematical-/// range — and only to absorb floating-point drift. The port follows the code,-/// so a negatively-correlated candidate keeps its sign and is treated by MMR as-/// *more* diverse than an orthogonal one, which is the behaviour this tool has-/// actually had. Do not "restore" the clamp the stale comment describes.-///-/// Distinct from `archivist::boundary`'s private `cosine_similarity`, which is-/// `f32`-valued and unclamped; that one feeds a segment-boundary threshold, not-/// a ranking, and the two are independent on purpose.-fn cosine_similarity(a: &[f32], b: &[f32]) -> f64 {- if a.len() != b.len() || a.is_empty() {- return 0.0;- }- let mut dot = 0.0_f64;- let mut norm_a = 0.0_f64;- let mut norm_b = 0.0_f64;- for (x, y) in a.iter().zip(b.iter()) {- let x = f64::from(*x);- let y = f64::from(*y);- dot += x * y;- norm_a += x * x;- norm_b += y * y;- }- let denom = norm_a.sqrt() * norm_b.sqrt();- if denom <= f64::EPSILON {- return 0.0;- }- (dot / denom).clamp(-1.0, 1.0)-}--/// A candidate for MMR selection.-struct MmrCandidate<'a> {- /// Caller-side index, echoed back on the result so the candidate can be- /// resolved to its original record.- index: usize,- /// Candidate embedding; must share dimensionality with every other- /// candidate, since cosine similarity is computed pairwise.- embedding: &'a [f32],- /// Precomputed relevance of this candidate to the query (here, its cosine- /// score). Higher is more relevant; weighted by `lambda` in the MMR- /// formula.- relevance: f64,-}--/// Result of MMR selection: the original index and its MMR score.-struct MmrResult {- /// Caller-side index echoed from the chosen [`MmrCandidate::index`], used- /// to resolve the result back to its original record.- index: usize,- /// The MMR score at the step this item was selected:- /// `lambda · relevance − (1 − lambda) · max_similarity(c, selected)`.- /// Not comparable across runs with different `lambda`.- ///- /// Unread by this tool — the output reports each hit's *cosine* score, not- /// its MMR score, because the latter depends on selection order and would- /// read as an unstable percentage. Kept so the port stays a faithful copy- /// of the engine's shape rather than a narrowed re-derivation.- #[allow(- dead_code,- reason = "faithful port; this tool reports the cosine score instead"- )]- score: f64,-}--/// Select up to `limit` items from `candidates` using Maximal Marginal-/// Relevance, balancing relevance against redundancy within the selected set.-///-/// `lambda` controls the relevance-diversity tradeoff:-/// - `1.0` = pure relevance (no diversity)-/// - `0.0` = pure diversity (ignores relevance)-/// - `0.7` = the value this tool passes-///-/// For each selection step:-/// `mmr(c) = lambda · relevance(c) − (1 − lambda) · max_similarity(c, selected)`.-///-/// `lambda` is clamped to `[0.0, 1.0]`; `limit` is clamped to-/// `candidates.len()`. Returns `Vec::new()` immediately if `candidates` is-/// empty or `limit == 0`.-///-/// # Relevance is precomputed, not derived from a query vector here-///-/// The engine's signature took a `query_vec` first argument and never read it —-/// relevance came entirely from [`MmrCandidate::relevance`], which the caller-/// had already derived from the query with the same [`cosine_similarity`] used-/// below. The parameter is dropped in this port because the one call site fills-/// `relevance` exactly that way, so it was provably inert; the selection is-/// bit-for-bit what it was. If a future revision wants query-aware scoring-/// inside the loop, add the parameter back *and wire it*, rather than-/// reinstating a placeholder.-fn mmr_select(candidates: &[MmrCandidate<'_>], limit: usize, lambda: f64) -> Vec<MmrResult> {- if candidates.is_empty() || limit == 0 {- return Vec::new();- }-- let lambda = lambda.clamp(0.0, 1.0);- let limit = limit.min(candidates.len());-- let mut selected_embeddings: Vec<&[f32]> = Vec::with_capacity(limit);- let mut results: Vec<MmrResult> = Vec::with_capacity(limit);- let mut available: Vec<bool> = vec![true; candidates.len()];-- for _ in 0..limit {- let mut best_idx: Option<usize> = None;- let mut best_mmr = f64::NEG_INFINITY;-- for (i, candidate) in candidates.iter().enumerate() {- if !available[i] {- continue;- }- let max_sim_to_selected = if selected_embeddings.is_empty() {- 0.0- } else {- // Seeded with NEG_INFINITY, not 0.0: when every selected- // similarity is negative, a 0.0 seed would win the fold and- // report an anti-correlated candidate as orthogonal — the- // exact collapse the `[0.0, 1.0]` note on- // [`cosine_similarity`] warns against reintroducing. The- // iterator is non-empty on this branch, so the seed never- // escapes.- selected_embeddings- .iter()- .map(|sel| cosine_similarity(candidate.embedding, sel))- .fold(f64::NEG_INFINITY, f64::max)- };- let mmr_score = lambda * candidate.relevance - (1.0 - lambda) * max_sim_to_selected;- if mmr_score > best_mmr {- best_mmr = mmr_score;- best_idx = Some(i);- }- }-- let Some(idx) = best_idx else { break };- available[idx] = false;- selected_embeddings.push(candidates[idx].embedding);- results.push(MmrResult {- index: candidates[idx].index,- score: best_mmr,- });- }-- results-}-#[derive(Debug, Deserialize)]struct Args {query: String,@@ -382,7 +210,7 @@ impl Tool for MemoryVectorSearchTool {if emb.len() != query_vec.len() {continue;}- let score = cosine_similarity(&query_vec, emb);+ let score = cosine_similarity_f64(&query_vec, emb);if score >= min_score {scored.push((idx, score, emb.as_slice()));}@@ -452,7 +280,3 @@ impl Tool for MemoryVectorSearchTool {Ok(ToolResult::success(output))}}--#[cfg(test)]-#[path = "vector_search_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/search/vector_search_tests.rs b/crates/openhuman-core/src/memory/tools/search/vector_search_tests.rsdeleted file mode 100644index 1c8fd9f589..0000000000--- a/crates/openhuman-core/src/memory/tools/search/vector_search_tests.rs+++ /dev/null@@ -1,59 +0,0 @@-//! MMR selection tests.-//!-//! The regression here pins the sign-preserving contract documented on-//! [`cosine_similarity`]: an anti-correlated candidate is *more* diverse than-//! an orthogonal one, and the redundancy fold must not clamp that away.--use super::*;--/// Unit-ish vectors chosen so cosine similarity is exactly their dot product.-fn candidate<'a>(embedding: &'a [f32], relevance: f64, index: usize) -> MmrCandidate<'a> {- MmrCandidate {- index,- embedding,- relevance,- }-}--#[test]-fn mmr_prefers_anti_correlated_over_orthogonal_at_equal_relevance() {- // First pick is the highest-relevance candidate: `a` at [1, 0].- // The two remaining candidates tie on relevance; `anti` at [-1, 0] has- // similarity -1.0 to the selection, `ortho` at [0, 1] has 0.0. With the- // fold seeded at 0.0 both reported 0.0 and the tie broke by index order,- // selecting `ortho`; seeded at NEG_INFINITY the negative survives and the- // MMR penalty term rewards `anti` as the more diverse pick.- let a: [f32; 2] = [1.0, 0.0];- let ortho: [f32; 2] = [0.0, 1.0];- let anti: [f32; 2] = [-1.0, 0.0];- let candidates = vec![- candidate(&a, 1.0, 0),- candidate(&ortho, 0.5, 1),- candidate(&anti, 0.5, 2),- ];-- let picked = mmr_select(&candidates, 2, 0.5);-- assert_eq!(picked.len(), 2);- assert_eq!(picked[0].index, 0, "highest relevance is selected first");- assert_eq!(- picked[1].index, 2,- "with only negative similarity to the selection, the anti-correlated \- candidate must out-score the orthogonal one instead of tying at a \- clamped 0.0"- );-}--#[test]-fn mmr_first_pick_is_pure_relevance() {- // With nothing selected yet there is no redundancy term; the seed change- // must not leak into the first iteration.- let a: [f32; 2] = [1.0, 0.0];- let b: [f32; 2] = [0.0, 1.0];- let candidates = vec![candidate(&a, 0.2, 0), candidate(&b, 0.9, 1)];-- let picked = mmr_select(&candidates, 1, 0.7);-- assert_eq!(picked.len(), 1);- assert_eq!(picked[0].index, 1);-}diff --git a/crates/openhuman-core/src/memory/tree/health/user_error.rs b/crates/openhuman-core/src/memory/tree/health/user_error.rsindex 52cd352815..27ba93e598 100644--- a/crates/openhuman-core/src/memory/tree/health/user_error.rs+++ b/crates/openhuman-core/src/memory/tree/health/user_error.rs@@ -168,14 +168,7 @@ pub(crate) fn notice_local_model_unavailable_once(origin: &str) {/// typed error is no longer available.pub(crate) fn is_local_embedding_error(message: &str) -> bool {let msg = message.to_ascii_lowercase();- // 1. The daemon is not listening.- msg.contains("is ollama running at")- // 2. The embedding model was never pulled: Ollama answers 404.- || msg.contains("ollama embed failed with status 404")- // 3. The chat/summarisation model was never pulled. Matched on- // "ollama" rather than the exact noun phrase so a future reword- // between "Ollama model" and "Ollama embedding model" still lands.- || (msg.contains("is not installed at") && msg.contains("ollama"))+ tinyinference_embeddings::probe::is_local_embedding_unavailable(&msg)}/// host-side fallback for paths that only ever see text.diff --git a/crates/openhuman-core/src/modules/memory_host.rs b/crates/openhuman-core/src/modules/memory_host.rsindex b8c2c31b75..9dc7a07c98 100644--- a/crates/openhuman-core/src/modules/memory_host.rs+++ b/crates/openhuman-core/src/modules/memory_host.rs@@ -63,7 +63,7 @@ impl EmbeddingCallbacks {dimensions: usize,texts: Vec<String>,) -> tinybus::Result<Vec<Vec<f32>>> {- let api_key = crate::inference::embeddings::resolve_api_key(&self.0, &provider);+ let api_key = crate::embeddings::resolve_api_key(&self.0, &provider);let endpoint = self.0.cloud_providers@@ -71,7 +71,7 @@ impl EmbeddingCallbacks {.find(|candidate| candidate.slug == provider).map(|candidate| candidate.endpoint.as_str()).filter(|endpoint| !endpoint.is_empty());- let embedder = crate::inference::embeddings::create_embedding_provider_with_config(+ let embedder = crate::embeddings::create_embedding_provider_with_config(&self.0, &provider, &model, dimensions, &api_key, endpoint,).map_err(method_error)?;diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rsindex 366d6f853c..b97de39254 100644--- a/crates/openhuman-core/src/modules/ops.rs+++ b/crates/openhuman-core/src/modules/ops.rs@@ -505,9 +505,9 @@ fn module_config(config: &Config, id: &str) -> serde_json::Value {// the cloud fallback ask the managed embedder for `nomic-embed-text`// (openhuman#5820)."cloud_embedding_model":- crate::inference::embeddings::DEFAULT_CLOUD_EMBEDDING_MODEL,+ crate::embeddings::DEFAULT_CLOUD_EMBEDDING_MODEL,"cloud_embedding_dimensions":- crate::inference::embeddings::DEFAULT_CLOUD_EMBEDDING_DIMENSIONS,+ crate::embeddings::DEFAULT_CLOUD_EMBEDDING_DIMENSIONS,"models_supporting_dimensions":tinyinference_embeddings::MODELS_SUPPORTING_DIMENSIONS,// The periodic composio and workspace-source sync loops run INSIDE thediff --git a/crates/openhuman-core/src/modules/ops_tests.rs b/crates/openhuman-core/src/modules/ops_tests.rsindex c82218c913..50229f9800 100644--- a/crates/openhuman-core/src/modules/ops_tests.rs+++ b/crates/openhuman-core/src/modules/ops_tests.rs@@ -160,11 +160,11 @@ fn module_config_hands_the_module_the_hosts_cloud_embedding_defaults() {assert_eq!(sent["cloud_embedding_model"],- crate::inference::embeddings::DEFAULT_CLOUD_EMBEDDING_MODEL+ crate::embeddings::DEFAULT_CLOUD_EMBEDDING_MODEL);assert_eq!(sent["cloud_embedding_dimensions"],- crate::inference::embeddings::DEFAULT_CLOUD_EMBEDDING_DIMENSIONS+ crate::embeddings::DEFAULT_CLOUD_EMBEDDING_DIMENSIONS);let supports = sent["models_supporting_dimensions"].as_array()diff --git a/crates/openhuman-core/src/platform/doctor/README.md b/crates/openhuman-core/src/platform/doctor/README.mdindex 9bdc3e51cb..ed7b601024 100644--- a/crates/openhuman-core/src/platform/doctor/README.md+++ b/crates/openhuman-core/src/platform/doctor/README.md@@ -66,7 +66,7 @@ None of its own (no `store.rs`). It only **reads** existing state owned by other- `crate::config::{Config, rpc}` — reads the live config for all probes; `config_rpc::load_config_with_timeout` in the handlers.- `crate::platform::service::daemon` — `state_file_path` for the daemon heartbeat/component snapshot.- `crate::memory::binding` — resolves the workspace's bound memory driver so `ops::memory_chunk_count` can ask `MemoryMaintenance::store_stats` for the chunk count. The engine crate is no longer named here (#5560).-- `crate::inference::embeddings::effective_embedding_settings` — resolves the intended embedding provider/model.+- `crate::embeddings::effective_embedding_settings` — resolves the intended embedding provider/model.- `crate::inference::{provider, local}` — `provider::list_providers` (model targets) and `local::ollama_base_url` (embedding probe).- `crate::api::{config, jwt}` — `effective_api_url` fallback resolution and `get_session_token` for sign-in state.- `crate::core::all::{ControllerFuture, RegisteredController}`, `crate::core::{ControllerSchema, FieldSchema, TypeSchema}` — controller/schema plumbing.diff --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 a57cb7aa80..15c6e2df6a 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@@ -94,7 +94,7 @@ pub(super) fn check_embedding_model_health(config: &Config, items: &mut Vec<Diag// Resolve the effective (intended, non-probed) embedding settings.let local_embedding_model = config.workload_local_model("embeddings");- let (provider, model, _dims) = crate::inference::embeddings::effective_embedding_settings(+ let (provider, model, _dims) = crate::embeddings::effective_embedding_settings(&config.memory,local_embedding_model.as_deref(),);diff --git a/crates/openhuman-core/src/security/credentials/README.md b/crates/openhuman-core/src/security/credentials/README.mdindex 0a3db441a6..b179fade06 100644--- a/crates/openhuman-core/src/security/credentials/README.md+++ b/crates/openhuman-core/src/security/credentials/README.md@@ -99,7 +99,7 @@ Note: `list_provider_credentials_by_prefix` and the Composio-direct/secret helpe## Used by-Many domains consume `AuthService` / session helpers / Composio-direct key, including (paths under `crates/openhuman-core/src/`): `core/{all,auth,jsonrpc}.rs` and `core/runtime/{context,services}.rs` (controller wiring, auth gate, gated services, boot seeding, identity seeding), `api/jwt.rs`, `desktop/app_state/ops/` (snapshot), `channels/controllers/ops/*` and `channels/runtime/startup/credentials.rs` (managed credentials), `integrations/composio/{client/direct,ops/direct_mode}.rs` (BYO key), `config/ops/model.rs`, `config/migrations/unify_ai_provider_settings.rs`, `inference/embeddings/{cloud_adapter,factory,rpc/api_keys}.rs`, `security/encryption/ops.rs`, `http_host/auth.rs`, `inference/{openai_oauth,provider}/*` (provider auth, OpenAI OAuth), `hosted/{announcements,billing,team}/ops.rs`, `flows/*`, `modules/{connectors,memory_host}.rs`, `web3/wallet/ops.rs`, and the prompt-layer identity readers (`agent/tinyagents/host/context_composer.rs`, `agent/harness/session/turn/context.rs`, …).+Many domains consume `AuthService` / session helpers / Composio-direct key, including (paths under `crates/openhuman-core/src/`): `core/{all,auth,jsonrpc}.rs` and `core/runtime/{context,services}.rs` (controller wiring, auth gate, gated services, boot seeding, identity seeding), `api/jwt.rs`, `desktop/app_state/ops/` (snapshot), `channels/controllers/ops/*` and `channels/runtime/startup/credentials.rs` (managed credentials), `integrations/composio/{client/direct,ops/direct_mode}.rs` (BYO key), `config/ops/model.rs`, `config/migrations/unify_ai_provider_settings.rs`, `embeddings/{cloud_adapter,factory,rpc/api_keys}.rs`, `security/encryption/ops.rs`, `http_host/auth.rs`, `inference/{openai_oauth,provider}/*` (provider auth, OpenAI OAuth), `hosted/{announcements,billing,team}/ops.rs`, `flows/*`, `modules/{connectors,memory_host}.rs`, `web3/wallet/ops.rs`, and the prompt-layer identity readers (`agent/tinyagents/host/context_composer.rs`, `agent/harness/session/turn/context.rs`, …).## Notes / gotchasdiff --git a/crates/openhuman-core/src/security/egress/README.md b/crates/openhuman-core/src/security/egress/README.mdindex 0375575fe5..572306861e 100644--- a/crates/openhuman-core/src/security/egress/README.md+++ b/crates/openhuman-core/src/security/egress/README.md@@ -67,7 +67,7 @@ Both `enforce_egress` and `local_only_tool_block` read the live mode via`integrations/composio/execute_dispatch.rs` — backend and Composio calls.- `tools/impl/network/{curl,http_request,web_fetch}.rs` — agent network-fetchtools.-- `search/tools/{tavily/client,exa}.rs`, `inference/embeddings/cloud_adapter.rs`,+- `search/tools/{tavily/client,exa}.rs`, `embeddings/cloud_adapter.rs`,`inference/provider/factory.rs` and its `factory/` submodules — search andcloud inference/embedding providers.- `web_chat/event_bus.rs` — subscribes to `ExternalTransferPending` anddiff --git a/crates/openhuman-core/src/voice/factory/mod.rs b/crates/openhuman-core/src/voice/factory/mod.rsindex 9a8ff23454..117189f891 100644--- a/crates/openhuman-core/src/voice/factory/mod.rs+++ b/crates/openhuman-core/src/voice/factory/mod.rs@@ -1,6 +1,6 @@//! Factory functions for creating voice (STT / TTS) providers.//!-//! Mirrors the shape of [`crate::inference::embeddings::factory`]: a single+//! Mirrors the shape of [`crate::embeddings::factory`]: a single//! entry point that takes a provider name + parameters and returns a boxed//! trait object. Production paths pick the provider based on the user's//! config (`stt_provider`, `tts_provider`); unit tests use the factorydiff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex 946348fedb..25000081fd 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -83,7 +83,7 @@ Canonical mapping of every product feature to its test source(s). Drives gap-fil| 1.3.1 | Token Issuance | WD+RU+RI | `login-flow.spec.ts`, `crates/openhuman-session/src/{client,manager}_tests.rs`, `json_rpc_e2e.rs` | ✅ | || 1.3.2 | Session Persistence | WD+RU | `logout-relogin-onboarding.spec.ts`, `crates/openhuman-core/src/security/credentials/ops_credential_tests.rs` | ✅ | || 1.3.3 | Refresh Token Rotation | VU | _missing_ — tracked #968 | ❌ | Slice-level refresh logic |-| 1.3.4 | Product Identity Header (`x-sdk-name`) | RU | `crates/openhuman-core/src/api/product.rs`, `crates/openhuman-core/src/api/rest_tests.rs`, `crates/openhuman-session/src/client_tests.rs`, `crates/openhuman-core/src/medulla/client/tests/{integration_tests,sse_tests}.rs`, `crates/openhuman-core/src/integrations/client_tests.rs` | ✅ | #5406 — every backend-bound request is attributed to a product, defaulting to `openhuman` and overridable by an embedding product (OpenCompany, Medulla). RU covers the sanitiser (trim / allowlist / truncate / reject), the default, and the override on the wire across all four transports: the SDK path, `raw_client()`, `MedullaClient::authed`, and the SSE handshake (which authenticates by query parameter and so never reaches `authed()`). Managed inference/embeddings go out through `tinyagents`' own clients and Socket.IO sets no HTTP headers, so neither is covered here. |+| 1.3.4 | Product Identity Header (`x-sdk-name`) | RU | `crates/openhuman-core/src/api/product.rs`, `crates/openhuman-core/src/api/rest_tests.rs`, `crates/openhuman-session/src/client_tests.rs`, `crates/openhuman-core/src/medulla/client/tests/{integration_tests,sse_tests}.rs`, `crates/openhuman-core/src/integrations/client_tests.rs` | ✅ | #5406 — every backend-bound request is attributed to a product, defaulting to `openhuman` and overridable by an embedding product (OpenCompany, Medulla). RU covers the sanitiser (trim / allowlist / truncate / reject), the default, and the override on the wire across all four transports: the SDK path, `raw_client()`, `MedullaClient::authed`, and the SSE handshake (which authenticates by query parameter and so never reaches `authed()`). Managed embeddings go out through `tinyagents`' own clients and Socket.IO sets no HTTP headers, so neither is covered here. || 1.3.5 | Credential handoff to core (`auth.set_credential`) | RU+RI | `crates/openhuman-core/src/security/credentials/ops_credential_tests.rs`, `crates/openhuman-session/src/link_tests.rs`, `tests/config_auth_app_state_connectivity_e2e.rs`, `tests/raw_coverage/app_state_credentials_raw_coverage_e2e.rs` | ✅ | The core takes a JWT / API key / local token as given (no `/auth/me`): expired JWTs and sessions without a user id are refused, same-token/same-user is a cheap refresh, a different user is signed out first, the snapshot reports the handed-over user and never calls the backend. |### 1.4 Logout & Revocationdiff --git a/gitbooks/features/model-routing/local-ai.md b/gitbooks/features/model-routing/local-ai.mdindex 626f4d8bf9..d67a41bfcd 100644--- a/gitbooks/features/model-routing/local-ai.md+++ b/gitbooks/features/model-routing/local-ai.md@@ -15,7 +15,7 @@ This is deliberate scoping. The previous design tried to put every modality on-d| Workload | Default model | Implementation || ------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |-| **Memory embeddings** | `bge-m3` | `OllamaEmbeddingModel`, built in `crates/openhuman-core/src/inference/embeddings/factory.rs` - used by the [Memory Tree](../obsidian-wiki/memory-tree.md) for vector search. |+| **Memory embeddings** | `bge-m3` | `OllamaEmbeddingModel`, built in `crates/openhuman-core/src/embeddings/factory.rs` - used by the [Memory Tree](../obsidian-wiki/memory-tree.md) for vector search. || **Summary-tree building** | `gemma3:1b-it-qat` (configurable) | `crates/tinymemory-core/src/tree/summarise.rs` in `vendor/tinymemory` - source / topic / global summary builders for the Memory Tree. || **Learning / reflection** | small chat model | `crates/openhuman-core/src/agent/learning/reflection.rs` - passes that consolidate what was learned. || **Chat** | configured local chat model | `Config::workload_local_model("chat")` reads `chat_provider`; `crates/openhuman-core/src/inference/provider/factory/routing.rs` handles hint routing. |diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 89d64c6090..c18ccd61ba 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 89d64c60905aa65ef96a5f7221f8d5f211a856d2+Subproject commit c18ccd61baede484b7d6d0738650da6f07b8cabc