The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(voice): add speech provider factory
Steven Enamakel320f24fcb3cc
diff --git a/crates/openhuman-core/src/voice/factory/mod.rs b/crates/openhuman-core/src/voice/factory/mod.rsindex e1bc029384..1acfba820c 100644--- a/crates/openhuman-core/src/voice/factory/mod.rs+++ b/crates/openhuman-core/src/voice/factory/mod.rs@@ -13,14 +13,14 @@//!//! | String | Resolves to |//! |-----------------------|------------------------------------------------|-//! | `"cloud"` / `"openhuman"` / `"backend"` | OpenHuman backend proxy |+//! | `"cloud"` / `"openhuman"` / `"backend"` | a registered hosted provider |//! | `"piper"` | Local Piper (TTS) |//! | `"<slug>:<model>"` | Voice provider entry matched by slug |//! | `"<slug>"` | Bare slug — uses provider's default model/voice|//!//! ## STT providers//!-//! - `"cloud"` → backend transcription proxy (POST `/openai/v1/audio/transcriptions`).+//! - `"cloud"` → the hosted transcription provider, when one is registered.//! - `"<slug>:<model>"` → third-party STT API via the voice provider registry//! (e.g. `"deepgram:nova-2"`, `"openai:whisper-1"`, `"elevenlabs:scribe_v1"`).//!@@ -30,8 +30,8 @@//!//! ## TTS providers//!-//! - `"cloud"` → backend ElevenLabs proxy (POST `/openai/v1/audio/speech`)-//! which also returns Oculus-15 visemes for the mascot lip-sync.+//! - `"cloud"` → the hosted speech provider (with Oculus-15 visemes for the+//! mascot lip-sync), when one is registered.//! - `"piper"` → local Piper subprocess via `PIPER_BIN`.//! - `"<slug>:<voice>"` → third-party TTS API via the voice provider registry//! (e.g. `"openai:alloy"`, `"elevenlabs:<voice_id>"`).@@ -55,10 +55,9 @@ mod tests;// Re-export the public API — exact visibility preserved from the original file.pub use entry::{- create_stt_provider, create_tts_provider, default_stt_provider, default_tts_provider,- DEFAULT_PIPER_VOICE, DEFAULT_STT_MODEL,+ create_stt_provider, create_tts_provider, DEFAULT_PIPER_VOICE, DEFAULT_STT_MODEL,};pub use helpers::{effective_stt_provider, effective_tts_provider};-pub use stt_providers::{CloudSttProvider, ExternalSttProvider};+pub use stt_providers::ExternalSttProvider;pub use traits::{SttProvider, SttResult, TtsProvider};-pub use tts_providers::{CloudTtsProvider, ExternalTtsProvider, PiperTtsProvider};+pub use tts_providers::{ExternalTtsProvider, PiperTtsProvider};diff --git a/crates/openhuman-core/src/voice/factory/stt_providers.rs b/crates/openhuman-core/src/voice/factory/stt_providers.rsindex 4b3738c110..e235bfbec0 100644--- a/crates/openhuman-core/src/voice/factory/stt_providers.rs+++ b/crates/openhuman-core/src/voice/factory/stt_providers.rs@@ -1,5 +1,5 @@-//! STT provider implementations: the hosted backend proxy and external-//! (slug-keyed) third-party APIs.+//! STT provider implementation: external (slug-keyed) third-party APIs. The+//! hosted backend proxy is registered by the hosted-backend layer.//!//! There is no local branch any more. The bundled whisper.cpp engine — both the//! in-process `whisper-rs` context and the `whisper-cli` subprocess fallback —@@ -8,70 +8,14 @@use async_trait::async_trait;use log::debug;-use super::super::cloud_transcribe::transcribe_cloud;use super::helpers::base64_decode;use super::traits::{SttProvider, SttResult};use crate::config::Config;use crate::core::Outcome;-use tinyinference_voice::cloud::{CloudTranscribeOptions, CloudTranscribeResult};use tinyinference_voice::external_stt::{ExternalSttClient, SttApiStyle};const LOG_PREFIX: &str = "[voice-factory]";-// ----------------------------------------------------------------------------// Cloud STT-// -----------------------------------------------------------------------------/// Cloud STT — wraps [`transcribe_cloud`]. Stateless; cheap to construct.-pub struct CloudSttProvider {- model: String,-}--impl CloudSttProvider {- pub fn new(model: impl Into<String>) -> Self {- Self {- model: model.into(),- }- }-}--#[async_trait]-impl SttProvider for CloudSttProvider {- fn name(&self) -> &'static str {- "cloud"- }-- async fn transcribe(- &self,- config: &Config,- audio_base64: &str,- mime_type: Option<&str>,- file_name: Option<&str>,- language: Option<&str>,- ) -> Result<Outcome<SttResult>, String> {- debug!(- "{LOG_PREFIX} cloud STT dispatch model={} bytes_b64={}",- self.model,- audio_base64.len()- );- let opts = CloudTranscribeOptions {- model: Some(self.model.clone()),- language: language.map(str::to_string),- mime_type: mime_type.map(str::to_string),- file_name: file_name.map(str::to_string),- };- let outcome = transcribe_cloud(config, audio_base64, &opts).await?;- let CloudTranscribeResult { text } = outcome.value;- Ok(Outcome::single_log(- SttResult {- text,- provider: "cloud".to_string(),- },- "voice-factory: cloud STT completed",- ))- }-}-// ---------------------------------------------------------------------------// External STT provider (slug-keyed, third-party API)// ---------------------------------------------------------------------------diff --git a/crates/openhuman-core/src/voice/factory/tts_providers.rs b/crates/openhuman-core/src/voice/factory/tts_providers.rsindex dcbb961c6c..3a817aaab9 100644--- a/crates/openhuman-core/src/voice/factory/tts_providers.rs+++ b/crates/openhuman-core/src/voice/factory/tts_providers.rs@@ -1,10 +1,10 @@-//! TTS provider implementations: cloud, local Piper, and external (slug-keyed).+//! TTS provider implementations: local Piper and external (slug-keyed). The+//! hosted provider is registered by the hosted-backend layer.use async_trait::async_trait;use log::debug;use super::super::local_speech::{synthesize_piper, PiperOptions};-use super::super::reply_speech::{synthesize_reply, ReplySpeechOptions};use super::traits::TtsProvider;use crate::config::Config;use crate::core::Outcome;@@ -13,57 +13,6 @@ use tinyinference_voice::reply::ReplySpeech as ReplySpeechResult;const LOG_PREFIX: &str = "[voice-factory]";-// ----------------------------------------------------------------------------// Cloud TTS-// -----------------------------------------------------------------------------/// Cloud TTS — wraps [`synthesize_reply`] (backend ElevenLabs proxy).-pub struct CloudTtsProvider {- voice: Option<String>,-}--impl CloudTtsProvider {- pub fn new(voice: Option<String>) -> Self {- Self { voice }- }-}--#[async_trait]-impl TtsProvider for CloudTtsProvider {- fn name(&self) -> &'static str {- "cloud"- }-- async fn synthesize(- &self,- config: &Config,- text: &str,- voice: Option<&str>,- ) -> Result<Outcome<ReplySpeechResult>, String> {- let resolved_voice = voice- .map(str::to_string)- .or_else(|| self.voice.clone())- .filter(|s| !s.trim().is_empty());- debug!(- "{LOG_PREFIX} cloud TTS dispatch voice={} chars={}",- resolved_voice.as_deref().unwrap_or("<default>"),- text.len()- );- let opts = ReplySpeechOptions {- voice_id: resolved_voice,- model_id: None,- output_format: None,- voice_settings: None,- };- synthesize_reply(config, text, &opts).await- }-- #[cfg(test)]- fn configured_voice(&self) -> Option<&str> {- self.voice.as_deref()- }-}-// ---------------------------------------------------------------------------// Local Piper TTS// ---------------------------------------------------------------------------diff --git a/crates/openhuman-core/src/voice/mod.rs b/crates/openhuman-core/src/voice/mod.rsindex 206fa2d998..54303d55be 100644--- a/crates/openhuman-core/src/voice/mod.rs+++ b/crates/openhuman-core/src/voice/mod.rs@@ -15,7 +15,7 @@//! is gated behind the default-ON `voice` Cargo feature. When the feature is//! off, [`stub`] takes its place and exposes the same public surface that//! always-on / other-gated callers depend on (`server`, `dictation_listener`,-//! `streaming`, `reply_speech`, `cloud_transcribe`, `create_stt_provider`,+//! `streaming`, `create_stt_provider`,//! `effective_stt_provider`, `publish_ptt_transcript_committed`) with//! no-op / disabled-error bodies. Keeping the two surfaces in lockstep is//! enforced by the disabled-build check@@ -49,20 +49,14 @@ pub mod live;#[cfg(feature = "voice")]mod ops;#[cfg(feature = "voice")]-pub mod realtime;-#[cfg(feature = "voice")]pub mod realtime_harness;#[cfg(feature = "voice")]-pub mod reply_speech;-#[cfg(feature = "voice")]mod schemas;#[cfg(feature = "voice")]pub mod server;#[cfg(feature = "voice")]mod types;-#[cfg(feature = "voice")]-pub mod cloud_transcribe;#[cfg(feature = "voice")]pub mod local_speech;#[cfg(feature = "voice")]@@ -76,8 +70,7 @@ pub mod streaming;#[cfg(feature = "voice")]pub use factory::{- create_stt_provider, create_tts_provider, default_stt_provider, default_tts_provider,- effective_stt_provider, effective_tts_provider, ExternalSttProvider, ExternalTtsProvider,+ create_stt_provider, create_tts_provider, effective_stt_provider, effective_tts_provider, ExternalSttProvider, ExternalTtsProvider,SttProvider, SttResult, TtsProvider, DEFAULT_PIPER_VOICE, DEFAULT_STT_MODEL,};#[cfg(feature = "voice")]@@ -87,15 +80,6 @@ pub use schemas::{all_voice_controller_schemas, all_voice_registered_controllers#[cfg(feature = "voice")]pub use types::{VoiceSpeechResult, VoiceStatus, VoiceTtsResult};-/// Default model id sent to the backend cloud STT proxy. Kept-/// here (rather than in `cloud_transcribe.rs`) so the factory module can-/// reach it via the public `voice::` surface without re-exporting an-/// internal constant.-#[cfg(feature = "voice")]-pub(crate) fn cloud_transcribe_default_model() -> &'static str {- "whisper-v1"-}-// ---------------------------------------------------------------------------// Disabled facade — compiled only when the `voice` feature is OFF.// ---------------------------------------------------------------------------diff --git a/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs b/crates/openhuman-tinyhumans/src/inference/managed_catalog.rsnew file mode 100644index 0000000000..36bdbc2f16--- /dev/null+++ b/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs@@ -0,0 +1,203 @@+//! The managed model catalog: the `list_configured_models` listing for the+//! managed provider and the model-limits discovery request, both against the+//! hosted backend's `/openai/v1/models?catalog=openrouter`.+//!+//! `?catalog=openrouter` is required: without it the backend returns only the+//! curated legacy list. The catalog listing is gated server-side and returns an+//! empty set when the passthrough is off, so this degrades to "no models"+//! rather than an error on a backend that has not enabled it.++use openhuman_embed::__host::config::Config;+use openhuman_embed::__host::core::Outcome;+use openhuman_embed::__host::inference_registry::{BoxFuture, CatalogEntry, CatalogLimits, CatalogListing};+use openhuman_embed::__host::security::credentials::session_support::{+ classify_session_token, load_app_session_profile, publish_local_session_expiry,+ resolve_backend_credential, BackendCredential, SessionTokenCheck,+};+use openhuman_embed::__host::util::url::join_url;+use std::sync::Arc;+use tinyinference_llm::catalog::{append_query_param, parse_models_response};+use tinyinference_llm::model::discover::DiscoveryRequest;++use crate::backend::headers::attribution_headers;+use crate::backend::url::{effective_api_url, effective_backend_api_url};+use crate::client::endpoint::{is_managed_endpoint_for_api_key, is_safe_endpoint_for_managed_bearer};++const MODELS_PATH: &str = "/openai/v1/models";++/// The registry entry for the managed catalog.+pub(super) fn entry() -> CatalogEntry {+ let list: CatalogListing = Arc::new(|config: Config| -> BoxFuture<Result<Outcome<serde_json::Value>, String>> {+ Box::pin(async move { list_models(&config).await })+ });+ let limits: CatalogLimits = Arc::new(|model: &str, config: &Config| limits_request(model, config));+ CatalogEntry {+ list,+ limits: Some(limits),+ }+}++fn empty_catalog(reason: &str) -> Result<Outcome<serde_json::Value>, String> {+ Ok(Outcome::new(+ serde_json::json!({ "models": Vec::<serde_json::Value>::new() }),+ vec![format!("{reason}; managed catalog is empty")],+ ))+}++fn catalog_url(config: &Config) -> String {+ append_query_param(+ &join_url(&effective_backend_api_url(&config.api_url), MODELS_PATH),+ "catalog",+ "openrouter",+ )+}++/// Whether a non-2xx from the listing reads as "signed out": a 401 on a request+/// that actually carried the app session token. A 401 without one describes the+/// request, not the session.+pub(super) fn managed_401_means_signed_out(status: u16, session_attached: bool) -> bool {+ status == 401 && session_attached+}++fn truncate(text: &str, max_chars: usize) -> String {+ if text.chars().count() <= max_chars {+ return text.to_string();+ }+ let cut: String = text.chars().take(max_chars).collect();+ format!("{cut}...")+}++/// The `list_configured_models` listing for the managed provider.+pub(super) async fn list_models(config: &Config) -> Result<Outcome<serde_json::Value>, String> {+ // Classify the session directly: a store error propagates (a recoverable+ // fault the picker should surface), only an absent or expired session+ // degrades to an empty list.+ let profile = load_app_session_profile(config)?;+ let token = match classify_session_token(profile.as_ref(), chrono::Utc::now()) {+ SessionTokenCheck::Live(token) => token,+ SessionTokenCheck::Expired => {+ // `require_live_session_token` announced this; without it an expired+ // token stays in the store with nothing prompting a re-auth.+ publish_local_session_expiry("list_configured_models");+ log::info!("[tinyhumans][inference] managed catalog unavailable: session expired");+ return empty_catalog("session expired");+ }+ SessionTokenCheck::Absent => {+ log::info!("[tinyhumans][inference] managed catalog unavailable: no session");+ return empty_catalog("no session");+ }+ };++ let url = catalog_url(config);+ log::debug!("[tinyhumans][inference] managed catalog url={url}");+ let client =+ openhuman_embed::__host::config::build_runtime_proxy_client_with_timeouts("providers.list_models", 30, 10);++ let attach = is_safe_endpoint_for_managed_bearer(&url);+ let mut request = client.get(&url);+ if attach {+ request = request.header("Authorization", format!("Bearer {token}"));+ if let Ok(headers) = attribution_headers() {+ request = request.headers(headers);+ }+ } else {+ log::warn!(+ "[tinyhumans][inference] refusing to send a bearer token to a non-https, non-loopback URL"+ );+ }++ let response = request+ .send()+ .await+ .map_err(|e| format!("[providers][list_models] HTTP request failed: {e}"))?;+ let status = response.status();+ if !status.is_success() {+ if managed_401_means_signed_out(status.as_u16(), attach) {+ log::info!(+ "[tinyhumans][inference] managed catalog unavailable: backend rejected the session token (401)"+ );+ return empty_catalog("session not accepted");+ }+ let body = response.text().await.unwrap_or_default();+ let sanitized = tinyinference_core::sanitize::sanitize_api_error(&body);+ return Err(format!(+ "provider returned {}: {}",+ status.as_u16(),+ truncate(&sanitized, 300)+ ));+ }++ let raw_body = response+ .text()+ .await+ .map_err(|e| format!("[providers][list_models] failed to read response body: {e}"))?;+ let body: serde_json::Value = serde_json::from_str(&raw_body).map_err(|e| {+ let snippet = truncate(&tinyinference_core::sanitize::sanitize_api_error(&raw_body), 300);+ format!("[providers][list_models] failed to parse JSON: {e} (body: {snippet})")+ })?;+ if let Some(err_field) = body.get("error") {+ let msg = err_field+ .as_str()+ .map(str::to_string)+ .or_else(|| err_field.get("message").and_then(|m| m.as_str()).map(str::to_string))+ .unwrap_or_else(|| err_field.to_string());+ return Err(format!(+ "provider returned error payload: {}",+ tinyinference_core::sanitize::sanitize_api_error(&msg)+ ));+ }+ let models = parse_models_response(&body).map_err(|error| error.to_string())?;+ log::info!(+ "[tinyhumans][inference] managed catalog fetched {} models",+ models.len()+ );+ Ok(Outcome::new(+ serde_json::json!({ "models": models }),+ vec![format!("fetched {} models", models.len())],+ ))+}++/// Where to ask the managed catalog for `model`'s limits, keyed by the managed+/// inference base so overflow corrections from the chat model land on the same+/// entry. Authenticated with the backend credential when the URL is safe to+/// carry it.+pub(super) fn limits_request(model: &str, config: &Config) -> Option<DiscoveryRequest> {+ let model = model.trim();+ if model.is_empty() {+ return None;+ }+ let inference_base = effective_api_url(&config.api_url);+ let endpoint = format!("{}/openai/v1", inference_base.trim_end_matches('/'));+ let listing_url = catalog_url(config);+ let mut request = DiscoveryRequest::new(endpoint, model)+ .with_listing_url(listing_url.clone())+ .with_single_model_probe(false);+ match resolve_backend_credential(config) {+ Ok(BackendCredential::ApiKey(key)) if is_managed_endpoint_for_api_key(&listing_url) => {+ request = request.with_header("Authorization", format!("Bearer {key}"));+ }+ Ok(BackendCredential::Session(token)) if is_safe_endpoint_for_managed_bearer(&listing_url) => {+ request = request.with_header("Authorization", format!("Bearer {token}"));+ }+ Ok(_) => {+ log::warn!(+ "[tinyhumans][inference] refusing to send the backend credential to an unsafe listing url"+ );+ }+ Err(_) => {+ log::debug!("[tinyhumans][inference] no backend credential; managed listing probed anonymously");+ }+ }+ if let Ok(headers) = attribution_headers() {+ for (name, value) in headers.iter() {+ if let Ok(value) = value.to_str() {+ request = request.with_header(name.as_str(), value);+ }+ }+ }+ Some(request)+}++#[cfg(test)]+#[path = "managed_catalog_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rsnew file mode 100644index 0000000000..fcce501a16--- /dev/null+++ b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs@@ -0,0 +1,124 @@+//! Managed cloud embeddings: `POST /openai/v1/embeddings` on the hosted backend+//! with the session JWT or stored API key, wrapped in the core's egress guard.+//! Registered as the embedding factory for the managed provider id.++use std::sync::Arc;++use openhuman_embed::__host::egress::{+ emit_external_transfer, enforce_egress, EgressDescriptor,+};+use openhuman_embed::__host::inference_registry::EmbeddingRequest;+use openhuman_embed::__host::security::approval::ApprovalChatContext;+use openhuman_embed::__host::security::credentials::{AuthService, APP_SESSION_PROVIDER};+use tinyinference_embeddings::{BearerResolver, CloudEmbeddingModel, EmbeddingModel};++use crate::backend::url::effective_api_url;+use crate::client::endpoint::is_managed_endpoint_for_api_key;++/// Host-owned credential resolution and egress disclosure around the+/// crate-owned cloud transport.+///+/// The egress guard (policy check, then the `ExternalTransferPending`+/// disclosure) runs before the batch reaches the transport, so it can carry the+/// chat of the turn that made the call. One built without a chat (background+/// sync, the embedding RPC) still discloses, unrouted.+pub struct ManagedEmbeddingModel {+ inner: Arc<CloudEmbeddingModel>,+ model: String,+ chat: Option<ApprovalChatContext>,+}++impl ManagedEmbeddingModel {+ /// Builds the embedder for the credential scope `request` carries.+ pub fn from_request(request: &EmbeddingRequest<'_>) -> Self {+ let api_url = request.config.and_then(|config| config.api_url.clone());+ let base_url = format!(+ "{}/openai/v1",+ effective_api_url(&api_url).trim_end_matches('/')+ );+ let key_endpoint = base_url.clone();+ let state_dir = request.state_dir.clone();+ let secrets_encrypt = request.secrets_encrypt;+ let bearer: BearerResolver = Arc::new(move || {+ // A stored TinyHumans API key is the bearer outright, with the+ // plaintext guard: never put the key on a non-HTTPS, non-loopback wire.+ if let Some(key) = openhuman_embed::__host::security::credentials::api_key::get_api_key_in(+ &state_dir,+ secrets_encrypt,+ )+ .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string()))?+ {+ if !is_managed_endpoint_for_api_key(&key_endpoint) {+ return Err(tinyinference_embeddings::Error::Validation(format!(+ "refusing to send the TinyHumans API key over a non-HTTPS, non-loopback \+ endpoint: {key_endpoint}"+ )));+ }+ log::debug!("[tinyhumans][embeddings] authenticating with api-key");+ return Ok(key);+ }+ let auth = AuthService::new(&state_dir, secrets_encrypt);+ auth.get_provider_bearer_token(APP_SESSION_PROVIDER, None)+ .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string()))?+ .filter(|token| !token.trim().is_empty())+ .ok_or_else(|| {+ tinyinference_embeddings::Error::Validation(+ "No backend session for cloud embeddings: log in to OpenHuman or set a \+ TinyHumans API key"+ .into(),+ )+ })+ });+ let model = request.model.to_string();+ Self {+ inner: Arc::new(CloudEmbeddingModel::new(+ base_url,+ model.clone(),+ request.dimensions,+ bearer,+ )),+ model,+ chat: request.chat.clone(),+ }+ }++ fn guard(&self) -> tinyinference_embeddings::Result<()> {+ let egress = EgressDescriptor::embedding("cloud", &self.model);+ enforce_egress(&egress)+ .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string()))?;+ emit_external_transfer(self.chat.as_ref(), egress);+ Ok(())+ }+}++#[async_trait::async_trait]+impl EmbeddingModel for ManagedEmbeddingModel {+ fn name(&self) -> &str {+ self.inner.name()+ }++ fn model_id(&self) -> &str {+ self.inner.model_id()+ }++ fn dimensions(&self) -> usize {+ self.inner.dimensions()+ }++ fn signature(&self) -> String {+ self.inner.signature()+ }++ async fn embed(&self, texts: &[String]) -> tinyinference_embeddings::Result<Vec<Vec<f32>>> {+ // Only a batch that will actually leave is guarded: an empty one answers+ // locally, and a blank input is refused by the transport.+ if !texts.is_empty() && texts.iter().all(|text| !text.trim().is_empty()) {+ self.guard()?;+ }+ self.inner.embed(texts).await+ }+}++#[cfg(test)]+#[path = "managed_embedding_tests.rs"]+mod tests;