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(memory): add billing tracking for memory operations
Steven Enamakel1a660b30d559
diff --git a/crates/openhuman-core/src/memory/billing.rs b/crates/openhuman-core/src/memory/billing.rsindex 40d64c2617..c2223fe8c7 100644--- a/crates/openhuman-core/src/memory/billing.rs+++ b/crates/openhuman-core/src/memory/billing.rs@@ -5,45 +5,17 @@//! that costs the user nothing; otherwise they wait for the user to start them.//! [`free_period_active`] is the one check every such job asks://!-//! - **Not the hosted engine** (self-hosted CortexDB, or a host's own engine):-//! always free here, because no TinyHumans credit is spent.-//! - **The hosted `tinyhumans` engine**: free only while the backend's memory-//! free period is on (`GET /memory/free-period`, through the backend-//! transport). The answer is cached for [`CACHE_TTL`] per backend.-//! - **Anything unknown** (memory off, signed out, no transport, an error, a-//! backend without the route): not free, so nothing starts on its own.+//! - **An engine with a registered predicate**+//! ([`engine_registry`](super::engine_registry)): the predicate decides. A+//! registration without one is free.+//! - **Any other engine** (self-hosted CortexDB, or a host's own engine):+//! always free here, because no hosted credit is spent.+//! - **Anything unknown** (memory off, signed out, an engine that failed to+//! bind): not free, so nothing starts on its own.-use std::collections::HashMap;-use std::time::{Duration, Instant};--use sha2::Digest;--use crate::backend::BackendClient;use crate::config::Config;-use crate::security::credentials::session_support::BackendCredential;--use super::engine::{self, Binding, TINYHUMANS_ENGINE};-/// How long an answer is reused. A job polls between batches; the period-/// changes on the order of days, so a minute keeps it to one request a minute.-pub const CACHE_TTL: Duration = Duration::from_secs(60);--/// The last answer for each backend. One async lock covers the lookup and the-/// fetch on a miss, so concurrent callers (two jobs polling at once) wait for-/// one request rather than each sending their own.-struct Answer {- inner: tokio::sync::Mutex<Option<HashMap<String, (Instant, bool)>>>,-}--impl Answer {- const fn new() -> Self {- Self {- inner: tokio::sync::Mutex::const_new(None),- }- }-}--static ANSWER: Answer = Answer::new();+use super::engine::{self, Binding};/// Whether memory work is free for the user right now. See the module docs.pub async fn free_period_active(config: &Config) -> bool {@@ -57,95 +29,7 @@ pub async fn free_period_active(config: &Config) -> bool {None => true,};}- if bound.id != TINYHUMANS_ENGINE {- return true;- }- let Ok(credential) =- crate::security::credentials::session_support::resolve_backend_credential(config)- else {- return false;- };- // The answer is the account's on the backend memory is bound to, so the- // cache is keyed by both: one account's answer never serves another.- let key = format!("{}|{}", bound.endpoint, digest(credential.secret()));- active_with_cache(&ANSWER, &key, CACHE_TTL, Instant::now, || {- fetch(&credential, &bound.endpoint)- })- .await-}--/// A one-way digest of a credential for a cache key: the full SHA-256, so-/// two accounts never share a key.-fn digest(secret: &str) -> String {- sha2::Sha256::digest(secret.as_bytes())- .iter()- .map(|byte| format!("{byte:02x}"))- .collect()-}--/// Asks `backend` whether its memory free period is on for `credential`.-async fn fetch(credential: &BackendCredential, backend: &str) -> Result<bool, String> {- let client = BackendClient::new(backend).map_err(|e| format!("{e:#}"))?;- let data = client- .authed_json(- credential.clone(),- reqwest::Method::GET,- "/memory/free-period",- None,- )- .await- .map_err(crate::backend::flatten_authed_error)?;- parse_active(&data)-}--/// `active` from the route's answer; anything else is an error. The-/// transport unwraps the `{success, data}` envelope, but an answer that-/// still carries it is read the same way.-fn parse_active(data: &serde_json::Value) -> Result<bool, String> {- data.get("data")- .unwrap_or(data)- .get("active")- .and_then(serde_json::Value::as_bool)- .ok_or_else(|| "free-period answer has no boolean `active`".to_string())-}--/// The cached answer for `key`, else `fetch`'s, with a failure read as not-/// free. Failures are cached too, so a backend without the route is asked-/// once a minute, not once a batch.-async fn active_with_cache<F, Fut>(- cache: &Answer,- key: &str,- ttl: Duration,- clock: impl Fn() -> Instant,- fetch: F,-) -> bool-where- F: FnOnce() -> Fut,- Fut: std::future::Future<Output = Result<bool, String>>,-{- let mut answers = cache.inner.lock().await;- let answers = answers.get_or_insert_with(HashMap::new);- // Read after the lock: a wait behind another backend's fetch must not- // stretch a cached answer past its TTL.- let now = clock();- if let Some((_, active)) = answers- .get(key)- .filter(|(at, _)| now.duration_since(*at) < ttl)- {- return *active;- }- let active = match fetch().await {- Ok(active) => active,- Err(_) => {- // The error text can carry the backend's response; it is not- // logged.- tracing::debug!("[memory:billing] free period unknown; treating as not free");- false- }- };- // The answer's age starts when it arrives, not when it was asked for.- answers.insert(key.to_string(), (clock(), active));- active+ true}#[cfg(test)]diff --git a/crates/openhuman-core/src/memory/billing_tests.rs b/crates/openhuman-core/src/memory/billing_tests.rsindex 2c9ca0618c..b24c7ef34e 100644--- a/crates/openhuman-core/src/memory/billing_tests.rs+++ b/crates/openhuman-core/src/memory/billing_tests.rs@@ -1,130 +1,4 @@use super::*;-use serde_json::json;-use std::sync::atomic::{AtomicUsize, Ordering};--const KEY: &str = "https://backend.test";--#[test]-fn parse_active_reads_the_flag_and_refuses_anything_else() {- assert_eq!(- parse_active(&json!({"active": true, "until": "x"})),- Ok(true)- );- assert_eq!(- parse_active(&json!({"active": false, "until": null})),- Ok(false)- );- assert!(parse_active(&json!({"active": "yes"})).is_err());- assert!(parse_active(&json!({})).is_err());- assert_eq!(- parse_active(&json!({"success": true, "data": {"active": true}})),- Ok(true),- "an answer still in its envelope reads the same"- );- assert!(parse_active(&json!({"success": true, "data": {}})).is_err());-}--#[tokio::test]-async fn an_answer_is_reused_within_the_ttl_and_asked_again_after() {- let cache = Answer::new();- let base = Instant::now();- let calls = AtomicUsize::new(0);- let ask = |active: bool| {- calls.fetch_add(1, Ordering::SeqCst);- async move { Ok(active) }- };- assert!(active_with_cache(&cache, KEY, CACHE_TTL, || base, || ask(true)).await);- assert!(- active_with_cache(- &cache,- KEY,- CACHE_TTL,- || base + Duration::from_secs(30),- || ask(false)- )- .await,- "still the cached answer"- );- assert_eq!(calls.load(Ordering::SeqCst), 1);- assert!(- !active_with_cache(- &cache,- KEY,- CACHE_TTL,- || base + Duration::from_secs(61),- || ask(false)- )- .await,- "asked again once stale"- );- assert_eq!(calls.load(Ordering::SeqCst), 2);-}--#[tokio::test]-async fn an_error_is_not_free_and_is_not_asked_again_at_once() {- let cache = Answer::new();- let base = Instant::now();- let calls = AtomicUsize::new(0);- let failing = || {- calls.fetch_add(1, Ordering::SeqCst);- async { Err::<bool, _>("GET /memory/free-period failed (404 Not Found)".to_string()) }- };- assert!(!active_with_cache(&cache, KEY, CACHE_TTL, || base, failing).await);- assert!(!active_with_cache(&cache, KEY, CACHE_TTL, || base, failing).await);- assert_eq!(calls.load(Ordering::SeqCst), 1, "a failure is cached too");-}--#[tokio::test]-async fn each_backend_keeps_its_own_answer() {- let cache = Answer::new();- let base = Instant::now();- let calls = AtomicUsize::new(0);- let ask = |active: bool| {- calls.fetch_add(1, Ordering::SeqCst);- async move { Ok(active) }- };- assert!(active_with_cache(&cache, "https://a.test", CACHE_TTL, || base, || ask(true)).await);- assert!(!active_with_cache(&cache, "https://b.test", CACHE_TTL, || base, || ask(false)).await);- assert!(active_with_cache(&cache, "https://a.test", CACHE_TTL, || base, || ask(false)).await);- assert_eq!(calls.load(Ordering::SeqCst), 2, "a's answer survived b's");-}--#[tokio::test]-async fn concurrent_callers_share_one_request() {- let cache = Answer::new();- let base = Instant::now();- let calls = AtomicUsize::new(0);- let ask = || {- calls.fetch_add(1, Ordering::SeqCst);- async {- tokio::time::sleep(Duration::from_millis(20)).await;- Ok(true)- }- };- let (a, b) = tokio::join!(- active_with_cache(&cache, KEY, CACHE_TTL, || base, ask),- active_with_cache(&cache, KEY, CACHE_TTL, || base, ask),- );- assert!(a && b);- assert_eq!(calls.load(Ordering::SeqCst), 1);-}--#[tokio::test]-async fn an_answer_for_one_backend_is_not_reused_for_another() {- let cache = Answer::new();- let base = Instant::now();- assert!(active_with_cache(&cache, KEY, CACHE_TTL, || base, || async { Ok(true) }).await);- assert!(- !active_with_cache(- &cache,- "https://other.test",- CACHE_TTL,- || base,- || async { Ok(false) }- )- .await- );-}#[tokio::test]async fn memory_off_is_not_free() {@@ -135,172 +9,17 @@ async fn memory_off_is_not_free() {}#[tokio::test]-async fn an_engine_other_than_the_hosted_one_is_always_free() {+async fn an_engine_without_a_registration_is_always_free() {let tmp = tempfile::tempdir().unwrap();let config = crate::memory::test_fixtures::config_in(&tmp);crate::memory::test_fixtures::bind_reference(&config);assert!(free_period_active(&config).await);}-fn credential(config: &Config) -> BackendCredential {- crate::security::credentials::session_support::resolve_backend_credential(config).unwrap()-}--fn keyed_config(tmp: &tempfile::TempDir) -> Config {- let mut config = crate::memory::test_fixtures::config_in(tmp);- config.secrets.encrypt = false;- // A key of its own: the answer cache is process-wide and keyed by- // backend and credential, and a mock server may reuse a port another- // test's server held a moment ago.- let key = format!("th_test_{}", tmp.path().display()).replace(['/', '.'], "_");- crate::security::credentials::api_key::store_api_key(&config, &key).unwrap();- config-}--async fn backend_answering(status: u16, body: serde_json::Value) -> wiremock::MockServer {- use wiremock::matchers::{method, path};- let server = wiremock::MockServer::start().await;- wiremock::Mock::given(method("GET"))- .and(path("/memory/free-period"))- .respond_with(wiremock::ResponseTemplate::new(status).set_body_json(body))- .mount(&server)- .await;- server-}--#[tokio::test]-async fn the_backend_says_the_period_is_on() {- let tmp = tempfile::tempdir().unwrap();- let config = keyed_config(&tmp);- let server = backend_answering(- 200,- json!({"success": true, "data": {"active": true, "until": "2026-11-06T00:00:00.000Z"}}),- )- .await;- assert_eq!(fetch(&credential(&config), &server.uri()).await, Ok(true));-}--#[tokio::test]-async fn the_backend_says_the_period_is_off() {- let tmp = tempfile::tempdir().unwrap();- let config = keyed_config(&tmp);- let server = backend_answering(- 200,- json!({"success": true, "data": {"active": false, "until": null}}),- )- .await;- assert_eq!(fetch(&credential(&config), &server.uri()).await, Ok(false));-}--#[tokio::test]-async fn a_backend_without_the_route_is_an_error_read_as_not_free() {- let tmp = tempfile::tempdir().unwrap();- let config = keyed_config(&tmp);- let server = backend_answering(404, json!({"success": false, "error": "Not Found"})).await;- assert!(fetch(&credential(&config), &server.uri()).await.is_err());- let cache = Answer::new();- let uri = server.uri();- let credential = credential(&config);- assert!(- !active_with_cache(&cache, &uri, CACHE_TTL, Instant::now, || fetch(- &credential,- &uri- ))- .await- );-}--#[tokio::test]-async fn the_hosted_engine_asks_the_backend() {- let tmp = tempfile::tempdir().unwrap();- let mut config = keyed_config(&tmp);- let server = backend_answering(- 200,- json!({"success": true, "data": {"active": true, "until": "2026-11-06T00:00:00.000Z"}}),- )- .await;- config.api_url = Some(server.uri());- config.memory.engine = TINYHUMANS_ENGINE.to_string();- assert!(free_period_active(&config).await);- assert_eq!(server.received_requests().await.unwrap().len(), 1);-}-#[tokio::test]-async fn the_engines_own_backend_is_asked_not_the_apps() {+async fn the_hosted_engine_with_nothing_registered_is_not_free() {let tmp = tempfile::tempdir().unwrap();- let mut config = keyed_config(&tmp);- let server = backend_answering(- 200,- json!({"success": true, "data": {"active": true, "until": null}}),- )- .await;- config.api_url = Some("http://127.0.0.1:9".into());- config.memory.engine = TINYHUMANS_ENGINE.to_string();- config.memory.engines.insert(- TINYHUMANS_ENGINE.to_string(),- crate::config::schema::MemoryEngineSettings {- endpoint: Some(server.uri()),- },- );- assert!(free_period_active(&config).await);- assert_eq!(server.received_requests().await.unwrap().len(), 1);-}--#[tokio::test]-async fn each_account_keeps_its_own_answer() {- let server = backend_answering(- 200,- json!({"success": true, "data": {"active": true, "until": null}}),- )- .await;- for key in ["th_account_a", "th_account_b"] {- let tmp = tempfile::tempdir().unwrap();- let mut config = crate::memory::test_fixtures::config_in(&tmp);- config.secrets.encrypt = false;- crate::security::credentials::api_key::store_api_key(&config, key).unwrap();- config.api_url = Some(server.uri());- config.memory.engine = TINYHUMANS_ENGINE.to_string();- assert!(free_period_active(&config).await);- }- assert_eq!(- server.received_requests().await.unwrap().len(),- 2,- "the second account asked for its own answer"- );-}--#[test]-fn the_cache_key_digest_is_the_full_sha256() {- let key = digest("th_account_a");- assert_eq!(key.len(), 64, "{key}");- assert_ne!(key, digest("th_account_b"));-}--#[tokio::test]-async fn an_answer_is_timed_from_when_it_arrives() {- let cache = Answer::new();- let base = Instant::now();- let calls = AtomicUsize::new(0);- let ticks = AtomicUsize::new(0);- // The fetch takes longer than the TTL: asked at `base`, answered at- // `base + 90s`.- let clock = || {- if ticks.fetch_add(1, Ordering::SeqCst) == 0 {- base- } else {- base + Duration::from_secs(90)- }- };- let ask = || {- calls.fetch_add(1, Ordering::SeqCst);- async { Ok(true) }- };- assert!(active_with_cache(&cache, KEY, CACHE_TTL, clock, ask).await);- let later = || base + Duration::from_secs(120);- assert!(active_with_cache(&cache, KEY, CACHE_TTL, later, ask).await);- assert_eq!(- calls.load(Ordering::SeqCst),- 1,- "still fresh 30s after it arrived"- );+ let mut config = crate::memory::test_fixtures::config_in(&tmp);+ config.memory.engine = engine::TINYHUMANS_ENGINE.to_string();+ assert!(!free_period_active(&config).await);}diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rsindex 3b8e342473..2a2a514673 100644--- a/crates/openhuman-core/src/memory/engine.rs+++ b/crates/openhuman-core/src/memory/engine.rs@@ -5,7 +5,7 @@//!//! | Engine | Endpoint | Credential | Off when |//! | --- | --- | --- | --- |-//! | `tinyhumans` | `[memory.engines.tinyhumans] endpoint`, else [`crate::backend::base_url`] | the host's backend credential, resolved per request through [`resolve_backend_credential`] | signed out, or no backend transport |+//! | `tinyhumans` | registered by the host layer that owns it ([`super::engine_registry`]) | the host's backend credential, resolved per request | not registered, or signed out |//! | `cortexdb` | `[memory.engines.cortexdb] endpoint`, else CortexDB's managed API | the API key stored as [`MEMORY_CORTEXDB_KEY_NAME`] | no key stored |//!//! Built engines are cached per config fingerprint (engine id, endpoint,@@ -29,17 +29,16 @@//! TinyHumans credential or a CortexDB key. It is wrapped in the same//! scrubber as a configured engine.//!-//! The core never holds a TinyHumans credential of its own: the bearer comes-//! from the host's credential seam on every request, so a refreshed session is-//! used at once and signing out turns memory off.+//! The core never holds a TinyHumans credential of its own: a registered+//! engine's bearer comes from the host's credential seam on every request, so+//! a refreshed session is used at once and signing out turns memory off.use std::collections::HashMap;use std::sync::{Arc, LazyLock, RwLock};-use async_trait::async_trait;use sha2::{Digest, Sha256};use tinymemory_api::MemoryEngine;-use tinymemory_integrations::{BearerSource, EngineCredential, EngineSettings};+pub use tinymemory_integrations::{BearerSource, EngineCredential, EngineSettings};use crate::config::schema::MEMORY_CORTEXDB_KEY_NAME;use crate::config::Config;@@ -356,7 +355,13 @@ fn resolve_configured(config: &Config, root: Option<&str>) -> Binding {return (entry.build)(&super::engine_registry::EngineRequest { config, root });}match engine_id.as_str() {- TINYHUMANS_ENGINE => resolve_tinyhumans(config, root),+ // The hosted engine is registered by the host layer that owns it+ // (`engine_registry`); without one it is simply unavailable.+ TINYHUMANS_ENGINE => off(+ Some(TINYHUMANS_ENGINE),+ None,+ "no TinyHumans backend is available",+ ),CORTEXDB_ENGINE => resolve_cortexdb(config, root),DISABLED_ENGINE => off(None, None, "memory is disabled"),"" => {@@ -412,7 +417,7 @@ fn off(engine: Option<&str>, endpoint: Option<String>, reason: &str) -> Binding/// on CortexDB's own API it is the root, owned by the actor `user:<id>`./// With `legacy_read`, the earlier `user:<id>` root is still read and/// forgotten (never written).-fn rooted(+pub fn rooted(settings: EngineSettings,root: Option<&str>,tenant: bool,@@ -449,72 +454,6 @@ fn rooted((settings, fingerprint)}-fn resolve_tinyhumans(config: &Config, root: Option<&str>) -> Binding {- let endpoint = match config.memory.endpoint_for(TINYHUMANS_ENGINE) {- Some(endpoint) => endpoint,- None => match crate::backend::base_url(&config.api_url) {- Ok(url) => url,- Err(error) => {- tracing::debug!(error = %error, "[memory:engine] no backend origin for tinyhumans");- return off(- Some(TINYHUMANS_ENGINE),- None,- "no TinyHumans backend is available",- );- }- },- };- if let Err(error) = resolve_backend_credential(config) {- tracing::debug!(error = %error, "[memory:engine] no usable TinyHumans credential");- return off(- Some(TINYHUMANS_ENGINE),- Some(endpoint),- "sign in to use TinyHumans memory",- );- }- // The backend expects the host's attribution (`x-sdk-name`, …) on every- // request, as every other backend caller sends it; the transport owns it.- let headers = attribution_headers();- let fingerprint = format!(- "{TINYHUMANS_ENGINE}|{endpoint}|{}|{headers:?}",- config.config_path.display()- );- let source: Arc<dyn BearerSource> = Arc::new(HostBearer {- config: Arc::new(config.clone()),- });- let (settings, layout) = rooted(- EngineSettings {- endpoint: Some(endpoint),- headers,- ..EngineSettings::default()- },- root,- true,- config.memory.legacy_user_segment_read,- );- build_cached(- TINYHUMANS_ENGINE,- settings,- fingerprint + &layout,- EngineCredential::Dynamic(source),- )-}--/// The installed transport's attribution headers, as engine settings carry-/// them. A value that is not text is left out (and logged by name only).-fn attribution_headers() -> std::collections::BTreeMap<String, String> {- crate::backend::attribution_headers()- .iter()- .filter_map(|(name, value)| match value.to_str() {- Ok(value) => Some((name.as_str().to_string(), value.to_string())),- Err(_) => {- tracing::debug!(header = %name, "[memory:engine] skipping a non-text attribution header");- None- }- })- .collect()-}-fn resolve_cortexdb(config: &Config, root: Option<&str>) -> Binding {let configured = config.memory.endpoint_for(CORTEXDB_ENGINE);let endpoint = configured@@ -562,7 +501,7 @@ fn resolve_cortexdb(config: &Config, root: Option<&str>) -> Binding {)}-fn build_cached(+pub fn build_cached(id: &str,settings: EngineSettings,fingerprint: String,@@ -668,26 +607,6 @@ pub fn has_key(config: &Config, id: &str) -> bool {}}-/// The host's backend credential as a per-request bearer.-struct HostBearer {- config: Arc<Config>,-}--#[async_trait]-impl BearerSource for HostBearer {- async fn bearer(&self) -> tinymemory_api::Result<String> {- match resolve_backend_credential(&self.config) {- Ok(credential) => Ok(credential.into_secret()),- Err(error) => {- tracing::debug!(error = %error, "[memory:engine] backend credential unavailable");- Err(tinymemory_api::Error::Unauthorized(- "the backend credential is unavailable".to_string(),- ))- }- }- }-}-#[cfg(test)]#[path = "engine_tests.rs"]mod tests;diff --git a/crates/openhuman-embed/src/host_internals.rs b/crates/openhuman-embed/src/host_internals.rsindex f5f1743ad6..a130bfbdff 100644--- a/crates/openhuman-embed/src/host_internals.rs+++ b/crates/openhuman-embed/src/host_internals.rs@@ -124,7 +124,7 @@ pub mod backend {pub mod config {pub use openhuman_core::config::{active_workspace_dir, active_workspace_dir_cached, active_workspace_snapshot,- load_config_with_timeout, workspace_handle, Config,+ load_config_with_timeout, workspace_handle, Config, MODEL_MANAGED_DEFAULT,};pub mod app_env {@@ -148,6 +148,13 @@ pub mod config {}}+/// tinyhumans (managed inference): the signed-out gate.+pub mod cron {+ pub mod scheduler_gate {+ pub use openhuman_core::cron::scheduler_gate::is_signed_out;+ }+}+/// tinyhumans: the Jev tool ranker and the jev route.pub mod agent {pub mod tinyagents {@@ -329,7 +336,10 @@ pub mod inference_registry {/// Memory engines by id, and the free-background-work predicate.pub mod memory_engines {- pub use openhuman_core::memory::engine::{Binding, BoundEngine};+ pub use openhuman_core::memory::engine::{+ build_cached, rooted, BearerSource, Binding, BoundEngine, EngineCredential, EngineSettings,+ TINYHUMANS_ENGINE,+ };pub use openhuman_core::memory::engine_registry::{bound_engine, register_memory_engine, register_memory_engine_in, unregister_memory_engine,EngineBuilder, EngineEntry, EngineFuture, EngineRequest, FreeBackground,diff --git a/crates/openhuman-tinyhumans/src/integrations/client/requests.rs b/crates/openhuman-tinyhumans/src/integrations/client/requests.rsindex b8428f4075..9b4a7f9371 100644--- a/crates/openhuman-tinyhumans/src/integrations/client/requests.rs+++ b/crates/openhuman-tinyhumans/src/integrations/client/requests.rs@@ -3,26 +3,13 @@//! (`post`/`get`/`patch`/`delete`/`upload_multipart`).use super::construct::IntegrationClient;+use crate::client::reject_privileged_backend_path;use openhuman_embed::__host::security::approval::ApprovalTurnContext;pub(super) fn managed_budget_applies_to_path(path: &str) -> bool {path != "/agent-integrations/pricing" && path.starts_with("/agent-integrations/")}-fn reject_privileged_backend_path(method: &str, path: &str) -> anyhow::Result<()> {- let route = path.split('?').next().unwrap_or(path);- if route.split('/').any(|segment| {- segment.eq_ignore_ascii_case("webhooks") || segment.eq_ignore_ascii_case("admin")- }) {- anyhow::bail!(- "route is intentionally not exposed by the SDK: {} {}",- method,- route- );- }- Ok(())-}-/// Build the egress descriptor for a managed-backend round-trip. The query/// string is stripped so only the endpoint (the "to where") is described, never/// any data carried in the query.@@ -53,38 +40,20 @@ pub(super) fn enforce_backend_egress(path: &str) -> anyhow::Result<()> {}impl IntegrationClient {- /// The process backend transport, or the typed "backend unavailable"- /// error already classified for this call.- pub(super) fn transport(+ /// Send one JSON round-trip over the shared transport, classifying a+ /// transport failure (including "no transport") for this call.+ pub(super) async fn send_json_request(&self,- method: &str,+ method: reqwest::Method,path: &str,+ body: Option<&serde_json::Value>,+ method_name: &str,url: &str,- ) -> anyhow::Result<std::sync::Arc<dyn crate::backend::transport::BackendTransport>> {- crate::backend::transport::resolve_backend_transport()- .map_err(|error| self.map_transport_error(error, method, path, url))- }-- /// Describe one `/agent-integrations/*` round-trip for the transport: the- /// client's credential (session JWT as bearer, API key as `x-api-key`), no envelope unwrapping (this client parses- /// the `{success,data}` envelope itself so its error classification sees- /// the raw shape).- pub(super) fn backend_request<'a>(- &'a self,- method: reqwest::Method,- path: &'a str,- body: Option<&'a serde_json::Value>,- ) -> crate::backend::transport::BackendRequest<'a> {- crate::backend::transport::BackendRequest {- profile: crate::backend::transport::TransportProfile::Integrations,- base_url: &self.backend_url,- method,- path,- query: &[],- body,- credential: Some(&self.credential),- unwrap_envelope: false,- }+ ) -> anyhow::Result<serde_json::Value> {+ self.http+ .send_json(method, path, body)+ .await+ .map_err(|error| self.map_transport_error(error, method_name, path, url))}pub(super) async fn ensure_budget_available(&self, path: &str) -> anyhow::Result<()> {@@ -138,10 +107,8 @@ impl IntegrationClient {let method_name = method.as_str().to_ascii_lowercase();tracing::debug!("[integrations] {} {}", method.as_str(), url);let value = self- .transport(&method_name, path, &url)?- .send_json(self.backend_request(method, path, body))- .await- .map_err(|error| self.map_transport_error(error, &method_name, path, &url))?;+ .send_json_request(method, path, body, &method_name, &url)+ .await?;Self::parse_envelope(&method_name, path, &url, value)}@@ -189,11 +156,8 @@ impl IntegrationClient {tracing::debug!("[integrations] POST(multipart) {}", url);let value = self- .transport("post_multipart", path, &url)?- .send_multipart(- self.backend_request(reqwest::Method::POST, path, None),- form,- )+ .http+ .send_multipart(path, form).await.map_err(|error| self.map_transport_error(error, "post_multipart", path, &url))?;// The transport unwraps successful `{success,data}` responses. Preservediff --git a/crates/openhuman-tinyhumans/src/voice/speech_providers.rs b/crates/openhuman-tinyhumans/src/voice/speech_providers.rsnew file mode 100644index 0000000000..b502c5d27b--- /dev/null+++ b/crates/openhuman-tinyhumans/src/voice/speech_providers.rs@@ -0,0 +1,145 @@+//! The hosted STT and TTS providers, registered under the historical slugs.+//!+//! [`CloudSttProvider`] wraps [`transcribe_cloud`] and [`CloudTtsProvider`]+//! wraps [`synthesize_reply`]. Both are registered with the core's voice+//! registry (see [`register`]) under the slugs configs already carry+//! (`cloud`, `openhuman`, and for STT also `backend`), so the factory resolves+//! them by configured slug exactly as it resolves any third-party provider.++use async_trait::async_trait;+use log::debug;+use openhuman_embed::__host::config::Config;+use openhuman_embed::__host::core::Outcome;+use openhuman_embed::__host::voice_registry::{+ register_stt_provider, register_tts_provider, SttProvider, SttResult, TtsProvider,+};+use tinyinference_voice::cloud::{CloudTranscribeOptions, CloudTranscribeResult};+use tinyinference_voice::reply::ReplySpeech;++use super::cloud_transcribe::transcribe_cloud;+use super::reply_speech::{synthesize_reply, ReplySpeechOptions};++const LOG_PREFIX: &str = "[voice-factory]";++/// STT slugs the hosted provider answers to.+pub const STT_SLUGS: [&str; 3] = ["cloud", "openhuman", "backend"];+/// TTS slugs the hosted provider answers to.+pub const TTS_SLUGS: [&str; 2] = ["cloud", "openhuman"];+/// Default STT model id for the hosted transcription proxy. The factory's+/// caller-supplied model is ignored: the proxy picks from this one.+pub const DEFAULT_CLOUD_STT_MODEL: &str = "whisper-v1";++/// Cloud STT. 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",+ ))+ }+}++/// Cloud TTS. `voice` is the constructor's voice; `None` lets the backend pick.+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<ReplySpeech>, 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+ }++ fn configured_voice(&self) -> Option<&str> {+ self.voice.as_deref()+ }+}++/// Registers the hosted STT and TTS providers under their slugs.+pub(super) fn register() {+ for slug in STT_SLUGS {+ register_stt_provider(slug, |_model, _config| {+ Ok(Box::new(CloudSttProvider::new(DEFAULT_CLOUD_STT_MODEL)))+ });+ }+ for slug in TTS_SLUGS {+ register_tts_provider(slug, |voice, _config| {+ Ok(Box::new(CloudTtsProvider::new(voice.map(str::to_string))))+ });+ }+ log::debug!("{LOG_PREFIX} registered hosted STT/TTS providers");+}++#[cfg(test)]+#[path = "speech_providers_tests.rs"]+mod tests;