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
Merge remote-tracking branch 'refs/remotes/upstream/main' into pr/6706
Steven Enamakel63e5538998a3
diff --cc crates/openhuman-core/src/backend/client/channel.rsindex 0000000000,f82c98ccf4..528e440bebmode 000000,100644..100644--- a/crates/openhuman-core/src/backend/client/channel.rs+++ b/crates/openhuman-core/src/backend/client/channel.rs@@@ -1,0 -1,200 +1,201 @@@+ //! Channel message and thread routes on the authenticated backend client.++ use anyhow::Result;+ use reqwest::Method;+ use serde_json::{json, Value};++ use super::BackendClient;++use crate::security::credentials::session_support::BackendCredential;++ impl BackendClient {+ /// Sends a message to a communication channel.+ pub async fn send_channel_message(+ &self,+ channel: &str,- bearer_jwt: &str,++ credential: impl Into<BackendCredential>,+ message_body: Value,+ ) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ let encoded = urlencoding::encode(channel);+ self.authed_json(- bearer_jwt,++ credential,+ Method::POST,+ &format!("channels/{encoded}/messages"),+ Some(message_body),+ )+ .await+ }++ /// Signals "the agent is typing…" on a channel that supports it+ /// (Telegram's `sendChatAction`, Slack's typing event, …). The backend+ /// resolves the target chat from the channel integration metadata and+ /// is responsible for hitting the provider-native API.+ ///+ /// Telegram keeps the typing indicator alive for ~5 seconds per call,+ /// so callers should re-invoke every ~4 s for as long as the turn is+ /// in flight. Returns `Err` if the backend doesn't support typing for+ /// this channel — caller should swallow the error silently.- pub async fn send_channel_typing(&self, channel: &str, bearer_jwt: &str) -> Result<Value> {++ pub async fn send_channel_typing(&self, channel: &str, credential: impl Into<BackendCredential>) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ let encoded = urlencoding::encode(channel);+ self.authed_json(- bearer_jwt,++ credential,+ Method::POST,+ &format!("channels/{encoded}/typing"),+ Some(json!({})),+ )+ .await+ }++ /// Edits an existing channel message. Used by the progressive-edit+ /// streaming path (Telegram / Slack) to coalesce live deltas into a+ /// single evolving outbound message rather than spamming the chat+ /// with one bubble per token.+ ///+ /// `message_id` is the backend-returned id of the message that was+ /// first sent via [`Self::send_channel_message`]. Returns the+ /// updated message record, or an `Err` if the backend does not+ /// support editing for this channel (caller should fall back to+ /// atomic-final delivery).+ ///+ /// **The deployed backend does not implement this route yet** (#5230): its+ /// channel router has `POST /:channel/messages` and `DELETE+ /// /:channel/messages/:messageId` only, so every call currently returns the+ /// unmatched-route 404, which [`authed_json`](Self::authed_json) surfaces as+ /// [`BackendApiError::ChannelEditUnsupported`]. Callers must degrade rather+ /// than treat that as the message having been deleted. Keep this method: it+ /// starts working unchanged the moment the backend adds the route.+ pub async fn send_channel_edit(+ &self,+ channel: &str,+ message_id: &str,- bearer_jwt: &str,++ credential: impl Into<BackendCredential>,+ edit_body: Value,+ ) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ anyhow::ensure!(!message_id.is_empty(), "message_id is required");+ let encoded_channel = urlencoding::encode(channel);+ let encoded_id = urlencoding::encode(message_id);+ self.authed_json(- bearer_jwt,++ credential,+ Method::PATCH,+ &format!("channels/{encoded_channel}/messages/{encoded_id}"),+ Some(edit_body),+ )+ .await+ }++ /// Deletes a message from a communication channel. Used to clean up+ /// ephemeral messages (e.g. thinking indicators) after the final+ /// response has been delivered.+ pub async fn send_channel_delete(+ &self,+ channel: &str,+ message_id: &str,- bearer_jwt: &str,++ credential: impl Into<BackendCredential>,+ ) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ anyhow::ensure!(!message_id.is_empty(), "message_id is required");+ let encoded_channel = urlencoding::encode(channel);+ let encoded_id = urlencoding::encode(message_id);+ self.authed_json(- bearer_jwt,++ credential,+ Method::DELETE,+ &format!("channels/{encoded_channel}/messages/{encoded_id}"),+ None,+ )+ .await+ }++ /// Sends a reaction (e.g. emoji) to a message in a channel.+ pub async fn send_channel_reaction(+ &self,+ channel: &str,- bearer_jwt: &str,++ credential: impl Into<BackendCredential>,+ reaction_body: Value,+ ) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ let encoded = urlencoding::encode(channel);+ self.authed_json(- bearer_jwt,++ credential,+ Method::POST,+ &format!("channels/{encoded}/reactions"),+ Some(reaction_body),+ )+ .await+ }++ /// Creates a new thread in a communication channel.+ pub async fn create_channel_thread(+ &self,+ channel: &str,- bearer_jwt: &str,++ credential: impl Into<BackendCredential>,+ title: &str,+ ) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ anyhow::ensure!(!title.trim().is_empty(), "title is required");+ let encoded = urlencoding::encode(channel);+ let body = serde_json::json!({ "title": title.trim() });+ self.authed_json(- bearer_jwt,++ credential,+ Method::POST,+ &format!("channels/{encoded}/threads"),+ Some(body),+ )+ .await+ }++ /// Updates an existing thread (e.g., closing or reopening it).+ pub async fn update_channel_thread(+ &self,+ channel: &str,- bearer_jwt: &str,++ credential: impl Into<BackendCredential>,+ thread_id: &str,+ action: &str,+ ) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ anyhow::ensure!(!thread_id.trim().is_empty(), "threadId is required");+ anyhow::ensure!(+ action == "close" || action == "reopen",+ "action must be 'close' or 'reopen'"+ );+ let encoded_channel = urlencoding::encode(channel);+ let encoded_thread = urlencoding::encode(thread_id.trim());+ let body = serde_json::json!({ "action": action });+ self.authed_json(- bearer_jwt,++ credential,+ Method::PATCH,+ &format!("channels/{encoded_channel}/threads/{encoded_thread}"),+ Some(body),+ )+ .await+ }++ /// Lists threads in a communication channel, optionally filtering by status.+ pub async fn list_channel_threads(+ &self,+ channel: &str,- bearer_jwt: &str,++ credential: impl Into<BackendCredential>,+ active_filter: Option<bool>,+ ) -> Result<Value> {+ let channel = channel.trim().trim_matches('/');+ anyhow::ensure!(!channel.is_empty(), "channel is required");+ let encoded = urlencoding::encode(channel);+ let mut path = format!("channels/{encoded}/threads");+ if let Some(active) = active_filter {+ path.push_str(if active {+ "?active=true"+ } else {+ "?active=false"+ });+ }- self.authed_json(bearer_jwt, Method::GET, &path, None).await++ self.authed_json(credential, Method::GET, &path, None).await+ }+ }diff --cc crates/openhuman-core/src/channels/bus/delivery.rsindex 1de40c9655,37ae447970..75723a1897--- a/crates/openhuman-core/src/channels/bus/delivery.rs+++ b/crates/openhuman-core/src/channels/bus/delivery.rs@@@ -183,13 -183,32 +183,13 @@@ pub(super) async fn finalize_channel_re}}-/// The session JWT the backend channel relay authenticates with, or `None`-/// (logged at debug) when there is none to use: no TinyHumans connection, the-/// user signed out while a relay message was in flight, the offline local-/// session, or an API-key-only runtime (the relay binds a user session). All-/// are user or build state, not faults, so nothing reaches Sentry.-fn relay_session_token(config: &crate::config::Config, op: &str) -> Option<String> {- use crate::security::credentials::session_support::{- direct_backend_credential, BackendCredential,- };- match direct_backend_credential(config, "channel relay") {- Some(BackendCredential::Session(token)) => Some(token),- Some(BackendCredential::ApiKey(_)) => {- tracing::debug!("[channel-inbound] api-key runtime has no relay session — cannot {op}");- None- }- None => {- tracing::debug!("[channel-inbound] no hosted session — cannot {op}");- None- }- }-}--/// Construct the REST client + session JWT shared by every outbound-/// channel call on this turn. Returns `None` and logs if either is+/// Construct the REST client + backend credential (API key or session JWT)+/// shared by every outbound channel call on this turn. Returns `None` and logs if either is/// unavailable so the caller can bail quietly.-pub(super) async fn build_channel_client() -> Option<(crate::backend::BackendClient, String)> {+pub(super) async fn build_channel_client() -> Option<(- crate::api::rest::BackendOAuthClient,++ crate::backend::BackendClient,+ crate::security::credentials::session_support::BackendCredential,+)> {let config = match crate::config::rpc::load_config_with_timeout().await {Ok(c) => c,Err(e) => {@@@ -197,19 -216,8 +197,19 @@@return None;}};- let api_url = crate::api::config::effective_backend_api_url(&config.api_url);- let jwt = relay_session_token(&config, "send")?;- match crate::backend::BackendClient::from_config(&config) {++ let api_url = crate::backend::require_base_url(&config.api_url)?;+ let jwt =+ match crate::security::credentials::session_support::resolve_backend_credential(&config) {+ Ok(credential) => credential,+ Err(e) => {+ tracing::error!(+ "[channel-inbound] no backend credential — cannot send: {}",+ e+ );+ return None;+ }+ };- match crate::api::rest::BackendOAuthClient::new(&api_url) {++ match crate::backend::BackendClient::new(&api_url) {Ok(c) => Some((c, jwt)),Err(e) => {tracing::error!("[channel-inbound] failed to create API client: {}", e);@@@ -228,20 -236,11 +228,20 @@@ pub(super) async fn send_channel_reply(}};- let api_url = crate::api::config::effective_backend_api_url(&config.api_url);- let Some(jwt) = relay_session_token(&config, "reply") else {- return;- };++ let api_url = crate::backend::require_base_url(&config.api_url)?;+ let jwt =+ match crate::security::credentials::session_support::resolve_backend_credential(&config) {+ Ok(credential) => credential,+ Err(e) => {+ tracing::error!(+ "[channel-inbound] no backend credential — cannot reply: {}",+ e+ );+ return;+ }+ };- let client = match crate::api::rest::BackendOAuthClient::new(&api_url) {+ let client = match crate::backend::BackendClient::from_config(&config) {Ok(c) => c,Err(e) => {tracing::error!("[channel-inbound] failed to create API client: {}", e);diff --cc crates/openhuman-core/src/channels/controllers/ops/messaging.rsindex e4c5289c65,cf417d3e38..6fd6d2f3ed--- a/crates/openhuman-core/src/channels/controllers/ops/messaging.rs+++ b/crates/openhuman-core/src/channels/controllers/ops/messaging.rs@@@ -2,11 -2,10 +2,11 @@@use serde_json::Value;- use crate::api::config::effective_backend_api_url;- use crate::api::rest::BackendOAuthClient;+++ use crate::backend::BackendClient;use crate::config::Config;use crate::rpc::RpcOutcome;-use crate::security::credentials::jwt::get_session_token;+use crate::security::credentials::session_support::resolve_backend_credential;/// Send a rich message to a channel via the backend API.pub async fn channel_send_message(@@@ -14,8 -13,9 +14,8 @@@channel: &str,message: Value,) -> Result<RpcOutcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;- let jwt = get_session_token(config)?- .ok_or_else(|| "session JWT required; complete login first".to_string())?;+ let jwt = resolve_backend_credential(config)?;log::debug!("[channels] sending message to channel '{}' via {}",@@@ -40,8 -45,9 +45,8 @@@ pub async fn channel_send_reactionchannel: &str,reaction: Value,) -> Result<RpcOutcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;- let jwt = get_session_token(config)?- .ok_or_else(|| "session JWT required; complete login first".to_string())?;+ let jwt = resolve_backend_credential(config)?;log::debug!("[channels] sending reaction to channel '{}' via {}",@@@ -66,8 -77,9 +76,8 @@@ pub async fn channel_create_threadchannel: &str,title: &str,) -> Result<RpcOutcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;- let jwt = get_session_token(config)?- .ok_or_else(|| "session JWT required; complete login first".to_string())?;+ let jwt = resolve_backend_credential(config)?;log::debug!("[channels] creating thread in channel '{}' title='{}' via {}",@@@ -94,8 -111,9 +109,8 @@@ pub async fn channel_update_threadthread_id: &str,action: &str,) -> Result<RpcOutcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;- let jwt = get_session_token(config)?- .ok_or_else(|| "session JWT required; complete login first".to_string())?;+ let jwt = resolve_backend_credential(config)?;log::debug!("[channels] updating thread '{}' in channel '{}' action='{}' via {}",@@@ -122,8 -145,9 +142,8 @@@ pub async fn channel_list_threadschannel: &str,active: Option<bool>,) -> Result<RpcOutcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;- let jwt = get_session_token(config)?- .ok_or_else(|| "session JWT required; complete login first".to_string())?;+ let jwt = resolve_backend_credential(config)?;log::debug!("[channels] listing threads in channel '{}' active={:?} via {}",diff --cc crates/openhuman-core/src/core/runtime/services.rsindex 98d0651684,a3dfb2ca0a..058d53b5a7--- a/crates/openhuman-core/src/core/runtime/services.rs+++ b/crates/openhuman-core/src/core/runtime/services.rs@@@ -437,23 -437,42 +437,26 @@@ pub fn spawn_socket_auto_connectreturn;}};- let api_url = crate::api::config::effective_backend_api_url(&config.api_url);- // No TinyHumans connection (no backend transport installed): there- // is no backend to hold a socket to, so skip quietly.- if !crate::backend::transport::is_installed() {- log::debug!("[socket] No backend transport installed — skipping auto-connect");- return;- }+ let Ok(api_url) = crate::backend::base_url(&config.api_url) else {- log::debug!("[socket] No backend base URL — skipping auto-connect");++ log::debug!("[socket] No backend transport or base URL — skipping auto-connect");+ return;+ };- let initial_token = match crate::security::credentials::jwt::get_session_token(&config)- {- Ok(Some(t))- if crate::security::credentials::session_support::is_local_session_token(- &t,- ) =>+ // The API key when one is stored, else the session token.+ let initial_token =+ match crate::security::credentials::session_support::backend_bearer_secret(&config){- // The offline local credential has no TinyHumans account,- // so the backend would only reject the handshake.- log::info!(- "[socket] Offline local session — skipping auto-connect (no hosted account)"- );- return;- }- Ok(Some(t)) => t,- Ok(None) => {- log::info!(+ Ok(Some(t)) => t,+ Ok(None) => {+ log::info!("[socket] No session token stored — skipping auto-connect (will connect after login)");- return;- }- Err(e) => {- log::warn!("[socket] Failed to read session token: {e}");- return;- }- };+ return;+ }+ Err(e) => {+ log::warn!("[socket] Failed to read session token: {e}");+ return;+ }+ };log::info!("[socket] Session token found — auto-connecting to {}",api_urldiff --cc crates/openhuman-core/src/inference/embedding_host/cloud_adapter.rsindex e1dd32fac8,4c7e9d9c1c..60bba12b57--- a/crates/openhuman-core/src/inference/embedding_host/cloud_adapter.rs+++ b/crates/openhuman-core/src/inference/embedding_host/cloud_adapter.rs@@@ -28,32 -27,18 +27,40 @@@ impl OpenHumanCloudEmbeddingModeldimensions: usize,) -> Self {let state_dir = openhuman_dir.unwrap_or_else(default_state_dir);- // The managed endpoint comes from the installed backend transport.- // Without one there is nothing to embed against, so the bearer- // resolver (asked before every request) refuses up front.+ let base = crate::backend::inference_base_url(&api_url).ok();+ let backend_available = base.is_some();+ let base_url = format!(+ "{}/openai/v1",- effective_api_url(&api_url).trim_end_matches('/')++ base.unwrap_or_default().trim_end_matches('/')+ );+ let key_endpoint = base_url.clone();let bearer: BearerResolver = Arc::new(move || {+ if !backend_available {+ return Err(tinyinference_embeddings::Error::Validation(format!(+ "{} managed embeddings need a backend transport",+ crate::core::observability::BACKEND_UNAVAILABLE_PREFIX+ )));+ }+ // A stored TinyHumans API key is the bearer outright, exactly as+ // for managed inference (`OpenHumanBackendModel::resolve_bearer`):+ // `/openai/v1/embeddings` accepts it as `Bearer <key>`. Same+ // plaintext guard too — never put the key on a non-HTTPS,+ // non-loopback wire.+ if let Some(key) =+ crate::security::credentials::api_key::get_api_key_in(&state_dir, secrets_encrypt)+ .map_err(|error| tinyinference_embeddings::Error::Embedding(error.to_string()))?+ {+ if !crate::inference::provider::openhuman_backend_model::is_safe_endpoint_for_managed_bearer(+ &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!("[embeddings::cloud] 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()))?diff --cc crates/openhuman-core/src/integrations/client/construct.rsindex 5499d617f1,bc9f0c501a..685a3614aa--- a/crates/openhuman-core/src/integrations/client/construct.rs+++ b/crates/openhuman-core/src/integrations/client/construct.rs@@@ -79,24 -62,10 +79,24 @@@ impl IntegrationClientpub fn new_with_budget_config(backend_url: String,- auth_token: String,+ credential: crate::security::credentials::session_support::BackendCredential,config: Arc<crate::config::Config>,) -> Self {- Self::new_inner(backend_url, auth_token, Some(config))+ Self::new_inner(backend_url, credential, Some(config))+ }++ /// Whether this client authenticates with a TinyHumans API key rather+ /// than a session JWT.+ pub fn uses_api_key(&self) -> bool {+ self.credential.is_api_key()+ }++ /// The auth headers for a request built outside the backend transport+ /// (binary download, raw DELETE): `Authorization: Bearer` for a session,+ /// `x-api-key` for an API key.+ pub(crate) fn auth_headers(&self) -> anyhow::Result<reqwest::header::HeaderMap> {- crate::api::transport::credential_headers(&self.credential)++ crate::backend::transport::credential_headers(&self.credential)+ .map_err(|e| anyhow::anyhow!("invalid backend credential header: {e}"))}fn new_inner(diff --cc crates/openhuman-core/src/integrations/client/pricing.rsindex 937b172dc7,cdcbdb5ad9..f6f471feac--- a/crates/openhuman-core/src/integrations/client/pricing.rs+++ b/crates/openhuman-core/src/integrations/client/pricing.rs@@@ -66,14 -66,14 +66,14 @@@ pub async fn pricing_for_config}/// Helper: build an `Arc<IntegrationClient>` from the root config, or-/// `None` if there is no backend session JWT. A local offline credential keeps+/// `None` if there is no backend credential. A local offline credential keeps/// the core signed in but cannot authenticate hosted integration routes.///-/// Both the backend URL and the auth token come from **core defaults**:+/// Both the backend URL and the credential come from **core defaults**:///- /// - backend URL → [`crate::api::config::effective_backend_api_url`]+ /// - backend URL → [`crate::backend::base_url`]/// applied to `config.api_url`. Unlike the plain- /// [`crate::api::config::effective_api_url`] resolver (which honours a+ /// [`crate::backend::inference_base_url`] resolver (which honours a/// user-set local-AI endpoint so chat completions still work), the/// backend resolver detects local-AI URLs and falls back to the/// `BACKEND_URL` / `VITE_BACKEND_URL` env vars (and finally the hosted@@@ -99,18 -96,26 +99,26 @@@ pub fn build_client(config: &crate::con// which 404 against the local LLM and flooded Sentry// (OPENHUMAN-TAURI-51 / -80 / -7Z). The helper falls through to env /// default backend in that case so integrations actually work.- let backend_url = crate::api::config::effective_backend_api_url(&config.api_url);+ let backend_url = match crate::backend::base_url(&config.api_url) {+ Ok(url) => url,+ Err(_) => {+ tracing::debug!(+ "[integrations] no backend transport — integrations client unavailable"+ );+ return None;+ }+ };- // Primary: app-session JWT from the auth profile store.- let session_token = match crate::security::credentials::jwt::get_session_token(config) {- Ok(token) => token,- Err(e) => {- tracing::warn!("[integrations] failed to read session token: {e}");- None- }- };+ let credential =+ match crate::security::credentials::session_support::resolve_backend_credential(config) {+ Ok(credential) => Some(credential),+ Err(e) => {+ tracing::debug!("[integrations] no backend credential: {e}");+ None+ }+ };- build_client_with_session_token(config, backend_url, session_token)+ build_client_with_credential(config, backend_url, credential)}/// The credential decision is separate from profile-store lookup so callersdiff --cc crates/openhuman-core/src/integrations/client/requests.rsindex f580f997f3,760fdb9117..669121720a--- a/crates/openhuman-core/src/integrations/client/requests.rs+++ b/crates/openhuman-core/src/integrations/client/requests.rs@@@ -56,9 -56,9 +56,9 @@@ impl IntegrationClientmethod: &str,path: &str,url: &str,- ) -> anyhow::Result<std::sync::Arc<dyn crate::api::transport::BackendTransport>> {- crate::api::transport::resolve_backend_transport()+ ) -> 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))+ .map_err(|error| self.map_transport_error(error, method, path, url))}/// Describe one `/agent-integrations/*` round-trip for the transport: thediff --cc crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rsindex 23eb01dc7c,23eb01dc7c..731dabd980--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs@@@ -7,6 -7,6 +7,7 @@@use crate::agent::prompts::ConnectedIntegration;use crate::config::Config;++use sha2::{Digest, Sha256};use std::collections::{HashMap, HashSet};use std::sync::atomic::{AtomicU64, Ordering};@@@ -46,11 -46,11 +47,25 @@@ pub(crate) fn composio_cache_test_lock(.unwrap_or_else(|e| e.into_inner())}--/// Derive a stable cache key from a [`Config`]. We use the stringified--/// `config_path` because it uniquely identifies a user context (it--/// resolves to the per-user openhuman dir).++/// Bind a cached integration list to the effective backend credential and++/// endpoint as well as the local config. The digest keeps secrets out of the++/// cache key and logs while preventing an old identity's cache hit during a++/// credential rotation, even before invalidation completes.pub(crate) fn cache_key(config: &Config) -> String {-- config.config_path.display().to_string()++ let mut digest = Sha256::new();++ digest.update(b"openhuman-integrations-cache-v2\0");++ digest.update(config.config_path.to_string_lossy().as_bytes());++ digest.update(b"\0");++ digest.update(config.api_url.as_deref().unwrap_or_default().as_bytes());++ digest.update(b"\0");++ match crate::security::credentials::session_support::resolve_backend_credential(config) {++ Ok(credential) => {++ digest.update(if credential.is_api_key() { b"api-key\0" } else { b"session\0" });++ digest.update(credential.secret().as_bytes());++ }++ Err(_) => digest.update(b"unavailable"),++ }++ hex::encode(digest.finalize())}/// Clear cached connected integrations so the next call todiff --cc crates/openhuman-core/src/integrations/composio/ops/error_utils.rsindex 5145345577,9010293102..401590ed32--- a/crates/openhuman-core/src/integrations/composio/ops/error_utils.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/error_utils.rs@@@ -111,10 -110,7 +111,10 @@@ pub(crate) fn backend_mode_without_sessif !(mode.is_empty() || mode == crate::config::schema::COMPOSIO_MODE_BACKEND) {return false;}+ if crate::security::credentials::api_key::has_api_key(config) {+ return false;+ }- match crate::api::jwt::get_session_token(config) {+ match crate::security::credentials::jwt::get_session_token(config) {Ok(token) => token.as_deref().map(str::trim).is_none_or(|token| {token.is_empty()|| crate::security::credentials::session_support::is_local_session_token(token)diff --cc crates/openhuman-core/src/memory/host.rsindex c5f2a0a69a,b5e8e3865e..314dc2fd68--- a/crates/openhuman-core/src/memory/host.rs+++ b/crates/openhuman-core/src/memory/host.rs@@@ -98,16 -98,14 +98,16 @@@ impl MemoryHostConfig for Config}fn effective_backend_api_url(&self) -> String {- // Resolution (env override, staging/prod default, trailing-slash- // normalisation) lives in `api::config` and must not be re-derived on- // the other side of the seam.- crate::api::config::effective_backend_api_url(&self.api_url)+ // Resolution (defaults, env overrides, normalisation) belongs to the+ // installed backend transport and must not be re-derived on the other+ // side of the seam. Empty when no transport is installed.+ crate::backend::base_url(&self.api_url).unwrap_or_default()}+ /// The backend bearer: the TinyHumans API key when one is stored, else+ /// the app-session JWT.fn session_token(&self) -> Result<Option<String>, String> {- crate::security::credentials::jwt::get_session_token(self)+ crate::security::credentials::session_support::backend_bearer_secret(self)}fn default_model(&self) -> Option<&str> {diff --cc crates/openhuman-core/src/platform/socket/ops.rsindex 8842dcffee,8f242f27c2..9ac2ad2e02--- a/crates/openhuman-core/src/platform/socket/ops.rs+++ b/crates/openhuman-core/src/platform/socket/ops.rs@@@ -52,11 -52,10 +52,11 @@@ async fn connect_with_session_usingpub async fn connect_with_session(manager: &SocketManager) -> Result<SocketState, String> {log::info!("[socket:rpc] connect_with_session — resolving credentials");let config = std::sync::Arc::new(crate::config::rpc::load_config_with_timeout().await?);- let api_url = crate::api::config::effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;- let token = crate::security::credentials::jwt::get_session_token(&config)+ // The API key when one is stored, else the session token.+ let token = crate::security::credentials::session_support::backend_bearer_secret(&config).map_err(|e| format!("failed to read session token: {e}"))?- .ok_or("no session token stored — user must log in first")?;+ .ok_or("no session token stored — user must log in first or set an API key")?;let provider =super::token_provider::token_provider_from_config(std::sync::Arc::clone(&config));diff --cc crates/openhuman-core/src/security/credentials/README.mdindex e2cb5cf404,63d35582f2..19466162aa--- a/crates/openhuman-core/src/security/credentials/README.md+++ b/crates/openhuman-core/src/security/credentials/README.md@@@ -37,12 -37,12 +37,12 @@@ Credential management for the backend c- **`AuthService`** (`core.rs`) — `from_config`, `new`, `load_profiles`, `store_provider_token`, `set_active_profile`, `remove_profile`, `get_profile`, `get_provider_bearer_token`.- **Constants** — `APP_SESSION_PROVIDER` (`"app-session"`), `DEFAULT_AUTH_PROFILE_NAME` (`"default"`), `COMPOSIO_DIRECT_PROVIDER` (`"composio-direct"`), `api_key::API_KEY_PROVIDER` (`"api-key"`).-- **Credential kinds** — `session_support::CredentialKind {Session, ApiKey, Local}` (wire values `"session"`, `"api-key"`, `"local"`). `session_support::resolve_backend_credential` returns `BackendCredential::ApiKey` when a key is stored (before any session classification) and `BackendCredential::Session` otherwise; `BackendClient::authed_json` sends an API key as `x-api-key` and a session as `Authorization: Bearer`, while `OpenHumanBackendModel::resolve_bearer` sends the key as the bearer for managed inference. `has_backend_credential` is the boot-time "signed in?" question the scheduler gate asks; `SessionExpired` is ignored for an API-key runtime and for a local session.+- **Credential kinds** — `session_support::CredentialKind {Session, ApiKey, Local}` (wire values `"session"`, `"api-key"`, `"local"`). `session_support::resolve_backend_credential` returns `BackendCredential::ApiKey` when a key is stored (before any session classification) and `BackendCredential::Session` otherwise; `BackendOAuthClient::authed_json` sends an API key as `x-api-key` and a session as `Authorization: Bearer`, while `OpenHumanBackendModel::resolve_bearer` sends the key as the bearer for managed inference. Every backend caller goes through it (integrations, voice, channels, webhooks, hosted proxies); bearer-only seams (connector proxy route, memory-host `SessionBearer`, the Socket.IO handshake) use `backend_bearer_secret`, which returns the key first and the stored session otherwise — the backend accepts a key as `Authorization: Bearer` by its `tiny_` prefix. Cloud embeddings mirror `resolve_bearer`. `has_backend_credential` is the boot-time "signed in?" question the scheduler gate asks; `SessionExpired` is ignored for an API-key runtime and for a local session.- **Helpers** — `normalize_provider`, `default_profile_id`, `select_profile_id`, `state_dir_from_config`, `profile_id`.- **Types** (`profiles.rs`) — `AuthProfile`, `AuthProfileKind` (`OAuth`/`Token`), `TokenSet`, `AuthProfilesData`, `AuthProfilesStore`.- - **Ops/RPC** (`ops`, re-exported as `rpc`) — `set_credential`, `clear_credential`, `store_session`, `clear_session`, `SetCredentialRequest`, `seed_api_key_from_env`, `seed_session_from_env`, `auth_get_state`, `auth_get_session_token_json`, `auth_create_channel_link_token`, `store_provider_credentials`, `remove_provider_credentials`, `list_provider_credentials`, `list_provider_credentials_by_prefix`, `oauth_connect`, `oauth_list_integrations`, `oauth_fetch_integration_tokens`, `oauth_fetch_client_key`, `oauth_revoke_integration`, `encrypt_secret`, `decrypt_secret`, `start_credential_gated_services`, `stop_credential_gated_services`.+ - **Ops/RPC** (`ops`, re-exported as `rpc`) — `set_credential`, `clear_credential`, `store_session`, `clear_session`, `SetCredentialRequest`, `seed_api_key_from_env`, `seed_session_from_env`, `auth_get_state`, `auth_get_session_token_json`, `store_provider_credentials`, `remove_provider_credentials`, `list_provider_credentials`, `list_provider_credentials_by_prefix`, `oauth_fetch_client_key`, `encrypt_secret`, `decrypt_secret`, `start_credential_gated_services`, `stop_credential_gated_services`.- **Composio-direct** — `store_composio_api_key`, `get_composio_api_key`, `clear_composio_api_key`, `rpc_store_composio_api_key`.- - **Backend OAuth re-exports** (from `crate::api::rest`) — `BackendOAuthClient`, `ConnectResponse`, `IntegrationSummary`, `IntegrationTokensHandoff`, `decrypt_handoff_blob`, `user_id_from_profile_payload`.+ - **Backend re-exports** — `crate::backend::BackendClient` and `jwt::user_id_from_profile_payload`. The OAuth connect/handoff types (`IntegrationSummary`, `IntegrationTokensHandoff`) and `decrypt_handoff_blob` moved to `crates/openhuman-tinyhumans/src/hosted/oauth/` with the OAuth flows themselves.- **Schema controllers** — `all_credentials_controller_schemas`, `all_credentials_registered_controllers`.## RPC / controllersdiff --cc crates/openhuman-core/src/security/credentials/session_support.rsindex 656e725820,123dd113af..744495dd5f--- a/crates/openhuman-core/src/security/credentials/session_support.rs+++ b/crates/openhuman-core/src/security/credentials/session_support.rs@@@ -383,21 -393,30 +393,37 @@@ pub fn resolve_backend_credential(confi}}-/// The credential for a backend call that talks to the backend host directly-/// rather than through the transport port (Langfuse proxy push, channel reply-/// relay, …), or `None` when the call should be skipped:-///-/// - no backend transport is installed — the core runs without a TinyHumans-/// connection (`backend::transport::is_installed`), or-/// - no usable credential resolves — signed out, the offline local session,-/// or a locally-expired token ([`resolve_backend_credential`]).-///-/// Both are configured states, not faults, so the skip is logged at `debug`-/// with `op` naming the caller; nothing reaches Sentry and no request is made.++/// Resolve a credential for a direct call to the configured backend.++/// A missing transport or unusable credential is an expected offline state.+ pub fn direct_backend_credential(config: &Config, op: &str) -> Option<BackendCredential> {+ if !crate::backend::transport::is_installed() {+ log::debug!("[backend-direct] {op} skipped: no backend transport installed");+ return None;+ }+ match resolve_backend_credential(config) {+ Ok(credential) => Some(credential),+ Err(reason) => {+ log::debug!("[backend-direct] {op} skipped: no usable backend credential ({reason})");+ None+ }+ }+ }+++/// The raw secret a Bearer-only backend caller should send: the stored+/// TinyHumans API key when there is one, else the stored app-session token+/// (unclassified, exactly what [`get_session_token`] returns).+///+/// For module seams that ask "what bearer can I lend right now?" and treat+/// `None` as signed out, where [`resolve_backend_credential`]'s error-for-absent+/// shape does not fit. The backend accepts a key as `Authorization: Bearer`+/// (it recognises it by prefix), so handing the key over as a bearer is+/// correct on every route a key may reach.+pub fn backend_bearer_secret(config: &Config) -> Result<Option<String>, String> {+ if let Some(key) = super::api_key::get_api_key(config).map_err(|e| e.to_string())? {+ return Ok(Some(key));+ }+ get_session_token(config)+}/// Whether *some* backend credential is present — an API key or a non-empty/// app-session token — without classifying expiry. This is the boot-timediff --cc crates/openhuman-core/src/voice/cloud_transcribe.rsindex 6aa716d8be,c517eaeefe..77e774ef86--- a/crates/openhuman-core/src/voice/cloud_transcribe.rs+++ b/crates/openhuman-core/src/voice/cloud_transcribe.rs@@@ -1,10 -1,10 +1,11 @@@//! OpenHuman authentication adapter for hosted speech-to-text.- use crate::api::config::effective_backend_api_url;- use crate::api::BackendOAuthClient;+++ use crate::backend::BackendClient;use crate::config::Config;use crate::rpc::RpcOutcome;-use crate::security::credentials::jwt::get_session_token;++pub use tinyinference_voice::cloud::{CloudTranscribeOptions, CloudTranscribeResult};/// Transcribe renderer-supplied base64 audio through the hosted backend.@@@ -13,22 -13,47 +14,50 @@@ pub async fn transcribe_cloudaudio_base64: &str,options: &CloudTranscribeOptions,) -> Result<RpcOutcome<CloudTranscribeResult>, String> {- let token = get_session_token(config)- .map_err(|error| error.to_string())?- .filter(|token| !token.trim().is_empty())- .ok_or_else(|| "no backend session token; sign in first".to_string())?;- if crate::security::credentials::session_support::is_local_session_token(&token) {- log::debug!("[voice][cloud_stt] offline local session — hosted STT unavailable");- return Err(- crate::security::credentials::session_support::LOCAL_SESSION_BACKEND_UNAVAILABLE- .to_string(),- );- }- let client = BackendClient::new(&crate::backend::require_base_url(&config.api_url)?)+ // The session JWT or the TinyHumans API key. The vendored client sends it+ // as `Authorization: Bearer`, which the backend accepts for either.- let token = crate::security::credentials::session_support::resolve_backend_credential(config)?- .into_secret();- let client = BackendOAuthClient::new(&effective_backend_api_url(&config.api_url))++ let credential = crate::security::credentials::session_support::resolve_backend_credential(config)?;++ let is_api_key = credential.is_api_key();++ let client = BackendClient::from_config(config).map_err(|error| error.to_string())?;let url = client.url_for("/openai/v1/audio/transcriptions").map_err(|error| error.to_string())?;++ if is_api_key++ && !crate::inference::provider::openhuman_backend_model::is_safe_endpoint_for_managed_bearer(url.as_str())++ {++ return Err("refusing to send the TinyHumans API key over a non-HTTPS, non-loopback endpoint".to_string());++ }let http = client.raw_client()- .map_err(crate::api::flatten_authed_error)?;- let result =- tinyinference_voice::cloud::transcribe(&http, url, &token, audio_base64, options).await?;+ .map_err(crate::backend::flatten_authed_error)?;- let result = tinyinference_voice::cloud::transcribe(&http, url, &token, audio_base64, options)++ let result = tinyinference_voice::cloud::transcribe(&http, url, credential.secret(), audio_base64, options)+ .await- .map_err(classify_transcribe_error)?;++ .map_err(|error| classify_transcribe_error(error, is_api_key))?;Ok(RpcOutcome::single_log(result,"cloud STT via POST /openai/v1/audio/transcriptions",))}++ /// Tag a backend 401 with the `SESSION_EXPIRED` sentinel. The request carries+ /// the app-session JWT to the hosted backend, so a 401 here is the session+ /// lapsing — the JSON-RPC layer then re-auths instead of paging Sentry with+ /// the raw `transcription request failed (401 …)` string.-fn classify_transcribe_error(error: String) -> String {++fn classify_transcribe_error(error: String, is_api_key: bool) -> String {+ if error.starts_with("transcription request failed (401") {- log::info!("[voice][cloud_stt] backend rejected the session (401)");- format!("SESSION_EXPIRED: {error}")++ if is_api_key {++ log::info!("[voice][cloud_stt] backend rejected the API key (401)");++ format!("API_KEY_REJECTED: {error}")++ } else {++ log::info!("[voice][cloud_stt] backend rejected the session (401)");++ format!("SESSION_EXPIRED: {error}")++ }+ } else {+ error+ }+ }++ #[cfg(test)]+ #[path = "cloud_transcribe_tests.rs"]+ mod tests;diff --cc crates/openhuman-core/src/voice/cloud_transcribe_tests.rsindex 0000000000,56fb8c9fe6..08e438326dmode 000000,100644..100644--- a/crates/openhuman-core/src/voice/cloud_transcribe_tests.rs+++ b/crates/openhuman-core/src/voice/cloud_transcribe_tests.rs@@@ -1,0 -1,46 +1,57 @@@+ use super::*;++ #[test]+ fn backend_401_is_tagged_as_session_expiry() {+ let tagged = classify_transcribe_error(+ "transcription request failed (401 Unauthorized): {\"error\":\"Invalid token\"}"+ .to_string(),++ false,+ );+ assert!(tagged.starts_with("SESSION_EXPIRED: "));+ assert!(crate::core::observability::is_session_expired_message(+ &tagged+ ));+ }++ #[test]+ fn other_failures_pass_through_unchanged() {+ let error = "transcription request failed (500 Internal Server Error): boom".to_string();- assert_eq!(classify_transcribe_error(error.clone()), error);++ assert_eq!(classify_transcribe_error(error.clone(), false), error);++}++++#[test]++fn backend_401_with_api_key_does_not_expire_session() {++ let tagged = classify_transcribe_error(++ "transcription request failed (401 Unauthorized)".to_string(),++ true,++ );++ assert!(tagged.starts_with("API_KEY_REJECTED: "));++ assert!(!crate::core::observability::is_session_expired_message(&tagged));+ }++ #[tokio::test]+ async fn offline_local_session_refuses_without_a_request() {+ let tmp = tempfile::TempDir::new().unwrap();+ let config = Config {+ workspace_dir: tmp.path().join("workspace"),+ action_dir: tmp.path().join("workspace"),+ config_path: tmp.path().join("config.toml"),+ ..Config::default()+ };+ crate::security::credentials::AuthService::from_config(&config)+ .store_provider_token(+ crate::security::credentials::APP_SESSION_PROVIDER,+ crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,+ "desktop.test.local",+ std::collections::HashMap::new(),+ true,+ )+ .unwrap();+ let err = transcribe_cloud(&config, "AAAA", &CloudTranscribeOptions::default())+ .await+ .unwrap_err();+ assert!(+ crate::core::observability::is_backend_unavailable_message(&err),+ "{err}"+ );+ }diff --cc crates/openhuman-core/src/voice/realtime.rsindex c4b003d734,502a232c16..8a8a1794c3--- a/crates/openhuman-core/src/voice/realtime.rs+++ b/crates/openhuman-core/src/voice/realtime.rs@@@ -13,10 -13,10 +13,11 @@@ use reqwest::Methoduse serde::{Deserialize, Serialize};use serde_json::Value;- use crate::api::config::effective_backend_api_url;- use crate::api::BackendOAuthClient;+++ use crate::backend::BackendClient;use crate::config::Config;use crate::rpc::RpcOutcome;+ use crate::security::credentials::jwt::get_session_token;const LOG_PREFIX: &str = "[voice-realtime]";@@@ -75,30 -75,33 +76,30 @@@ fn authority_host(rest: &str) -> &str/// Mint a realtime voice-agent signed URL by proxying the hosted backend.///-/// Follows the `reply_speech::synthesize_reply` auth pattern: session token →+/// Follows the `reply_speech::synthesize_reply` auth pattern: backend credential →- /// [`BackendOAuthClient`] → `authed_json`, with `flatten_authed_error` so a+ /// [`BackendClient`] → `authed_json`, with `flatten_authed_error` so a/// lapsed-session 401 classifies as `SESSION_EXPIRED` and skips Sentry rather/// than leaking as a raw error string.pub async fn mint_voice_agent_signed_url(config: &Config,) -> Result<RpcOutcome<VoiceAgentSignedUrl>, String> {- let token = get_session_token(config)- .map_err(|e| e.to_string())?- .and_then(|t| {- let s = t.trim().to_string();- if s.is_empty() {- None- } else {- Some(s)- }- })- .ok_or_else(|| "no backend session token; sign in first".to_string())?;+ // API key (sent as `x-api-key`) or live session JWT (sent as Bearer).+ let credential =+ crate::security::credentials::session_support::resolve_backend_credential(config)?;- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;ensure_secure_backend_url(&api_url)?;- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;+ let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;let raw = client- .authed_json(&token, Method::GET, "/voice-agent/get-signed-url", None)+ .authed_json(+ &credential,+ Method::GET,+ "/voice-agent/get-signed-url",+ None,+ ).await- .map_err(crate::api::flatten_authed_error)?;+ .map_err(crate::backend::flatten_authed_error)?;let result = parse_signed_url_response(&raw)?;debug!("{LOG_PREFIX} minted signed url agent={}", result.agent_id);diff --cc crates/openhuman-core/src/voice/reply_speech.rsindex a2c7ca194a,9309c79f1f..697e58bbef--- a/crates/openhuman-core/src/voice/reply_speech.rs+++ b/crates/openhuman-core/src/voice/reply_speech.rs@@@ -20,10 -20,10 +20,11 @@@ use reqwest::Methoduse serde::{Deserialize, Serialize};use serde_json::{json, Value};- use crate::api::config::effective_backend_api_url;- use crate::api::BackendOAuthClient;+++ use crate::backend::BackendClient;use crate::config::Config;use crate::rpc::RpcOutcome;+ use crate::security::credentials::jwt::get_session_token;const LOG_PREFIX: &str = "[voice_reply]";@@@ -156,12 -156,20 +157,12 @@@ pub async fn synthesize_reply));}- let token = get_session_token(config)- .map_err(|e| e.to_string())?- .and_then(|t| {- let s = t.trim().to_string();- if s.is_empty() {- None- } else {- Some(s)- }- })- .ok_or_else(|| "no backend session token; sign in first".to_string())?;+ // API key (sent as `x-api-key`) or live session JWT (sent as Bearer).+ let credential =+ crate::security::credentials::session_support::resolve_backend_credential(config)?;- let api_url = effective_backend_api_url(&config.api_url);- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;+ let api_url = crate::backend::require_base_url(&config.api_url)?;+ let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;let mut body = serde_json::Map::new();body.insert("text".to_string(), json!(trimmed));diff --cc crates/openhuman-embed/README.mdindex bccda2356d,c2a833bcaa..61b5620956--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@@ -139,26 -143,10 +143,26 @@@ managed inference then sends it as `AutTinyHumans OpenAI-compatible endpoint, backend REST calls send it as`x-api-key`, and the scheduler gate treats the runtime as signed in. No`/auth/me` round trip, no session JWT, nothing to expire. An agent that names-its own `Provider` (BYOK) never touches the key. `HarnessBuilder::session`+its own `Provider` (BYOK) never touches the key.++The key covers every hosted feature the core reaches: managed inference, cloud+embeddings, voice (STT, TTS, the realtime voice agent), web search, media+generation, the Jev ranker, Composio and the other `/agent-integrations/*`+tools, channel delivery, webhooks, and the Socket.IO connection. Callers that+can only send a bearer (the vendored STT and embedding clients, the connector+module's proxy route, TinyCortex's Composio sync) send the key as+`Authorization: Bearer`, which the backend accepts because it recognises the+`tiny_live_` / `tiny_test_` prefix. What a key may reach is decided by its+scopes on the backend: `inference`, `voice`, `search`, `media`, `storage`,+`account` and `connections` (Composio). A key minted through the grant flow+omits `connections` unless it is asked for; a missing scope answers `403`.+Only the session-bound `/auth/*` flows (OAuth connect, channel link tokens,+login tokens) still need a signed-in user.++`HarnessBuilder::session`remains for hosts that drive backend features on behalf of a signed-in user;the core stores that session as handed over (`auth.set_credential`) and never- validates it — obtaining and validating a JWT is the host's job (see+ validates it: obtaining and validating a JWT is the host's job (see`openhuman_tinyhumans::session`).### `Harness`: the one-agent shorthand