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
fix(api): handle missing Content-Type header in transport layer
Steven Enamakelde3dee551ab3
diff --git a/crates/openhuman-core/src/api/headers.rs b/crates/openhuman-core/src/api/headers.rsnew file mode 100644index 0000000000..bb49d6d273--- /dev/null+++ b/crates/openhuman-core/src/api/headers.rs@@ -0,0 +1,105 @@+//! Attribution headers and `reqwest` client profiles for TinyHumans backend+//! traffic.+//!+//! Every request that reaches the hosted backend carries the same three+//! attribution headers regardless of which transport sends it: `x-core-version`+//! (this crate), `x-tauri-version` (the desktop shell, when it hosts the core)+//! and `x-sdk-name` (the product identity from [`crate::api::product`]). The+//! header *policy* is OpenHuman's, so it lives here in the core; the+//! [`BackendTransport`](crate::api::transport::BackendTransport)+//! implementation that actually performs the request — the SDK-backed one in+//! `openhuman-tinyhumans`, or the test-only plain client — builds its+//! `reqwest::Client` from these helpers so the wire shape cannot drift between+//! them.++use anyhow::{Context, Result};+use reqwest::header::{HeaderMap, HeaderName, HeaderValue};+use std::time::Duration;++use crate::api::transport::TransportProfile;++/// Upper bound on the `x-core-version` / `x-tauri-version` header values. A+/// version string is short; anything longer is a misconfigured environment and+/// is clamped rather than propagated into every backend request.+pub(crate) const CLIENT_VERSION_HEADER_MAX_LEN: usize = 64;++/// Environment variable the Tauri shell sets to its own package version before+/// spawning the in-process core, so backend analytics can attribute+/// core-originated requests to the desktop build hosting them.+pub const TAURI_VERSION_ENV_VAR: &str = "OPENHUMAN_TAURI_VERSION";++/// Restrict a version string to header-safe characters and clamp its length.+/// Returns `None` when nothing safe remains.+pub(crate) fn sanitize_client_version(raw: &str) -> Option<String> {+ let sanitized: String = raw+ .trim()+ .chars()+ .filter(|c| matches!(c, '0'..='9' | 'A'..='Z' | 'a'..='z' | '.' | '_' | '+' | '-'))+ .take(CLIENT_VERSION_HEADER_MAX_LEN)+ .collect();++ if sanitized.is_empty() {+ None+ } else {+ Some(sanitized)+ }+}++/// The attribution headers every backend-bound request carries:+/// `x-core-version`, `x-tauri-version` (only when the shell exported it) and+/// `x-sdk-name`.+///+/// Set at the transport level rather than per request because some callers+/// drive a raw `reqwest::Client` themselves (multipart STT upload via+/// [`BackendOAuthClient::raw_client`](crate::api::rest::BackendOAuthClient::raw_client))+/// and that traffic needs attributing too.+pub fn attribution_headers() -> Result<HeaderMap> {+ let mut headers = HeaderMap::new();+ if let Some(version) = sanitize_client_version(env!("CARGO_PKG_VERSION")) {+ headers.insert(+ HeaderName::from_static("x-core-version"),+ HeaderValue::from_str(&version).context("invalid x-core-version header value")?,+ );+ }+ if let Ok(raw) = std::env::var(TAURI_VERSION_ENV_VAR) {+ if let Some(version) = sanitize_client_version(&raw) {+ headers.insert(+ HeaderName::from_static("x-tauri-version"),+ HeaderValue::from_str(&version).context("invalid x-tauri-version header value")?,+ );+ }+ }+ let (name, value) = crate::api::product::product_identity_header();+ headers.insert(name, value);+ Ok(headers)+}++/// A `reqwest::ClientBuilder` carrying the platform TLS backend, HTTP/1-only+/// negotiation, the timeouts historically used for `profile`, and the+/// attribution headers as defaults.+///+/// Platform-appropriate TLS: Windows → schannel (honors the OS cert store,+/// required for corporate TLS-inspection proxies); macOS / Linux → rustls.+/// See [`crate::util::tls::tls_client_builder`].+pub fn backend_client_builder(profile: TransportProfile) -> Result<reqwest::ClientBuilder> {+ let timeout = match profile {+ // `BackendOAuthClient` historically allowed 120 s: it fronts slow+ // control-plane calls (billing summaries, integration token handoffs).+ TransportProfile::Api => Duration::from_secs(120),+ // `/agent-integrations/*` tool calls were always capped at 60 s.+ TransportProfile::Integrations => Duration::from_secs(60),+ };+ Ok(crate::util::tls::tls_client_builder()+ .default_headers(attribution_headers()?)+ .http1_only()+ .timeout(timeout)+ .connect_timeout(Duration::from_secs(15)))+}++/// Build the `reqwest::Client` for `profile` with+/// [`backend_client_builder`]'s settings.+pub fn build_backend_client(profile: TransportProfile) -> Result<reqwest::Client> {+ backend_client_builder(profile)?+ .build()+ .map_err(|e| anyhow::anyhow!("failed to build HTTP client: {e}"))+}diff --git a/crates/openhuman-core/src/api/transport/error.rs b/crates/openhuman-core/src/api/transport/error.rsnew file mode 100644index 0000000000..869eea9ca2--- /dev/null+++ b/crates/openhuman-core/src/api/transport/error.rs@@ -0,0 +1,62 @@+//! The error a [`BackendTransport`](super::BackendTransport) returns.+//!+//! This is the core-owned image of the variants the classification code in+//! [`crate::api::rest`] and `integrations/client/errors.rs` matches on. It+//! mirrors the vendored SDK's `Error` one-to-one for those arms so a transport+//! built on the SDK maps mechanically, while the core itself never names the+//! SDK type.++use serde_json::Value;++/// Failure of a single backend round-trip, as seen by the core.+#[derive(Debug, thiserror::Error)]+pub enum BackendTransportError {+ /// No transport is installed in this process, so the core cannot reach the+ /// hosted backend at all. This is the normal state of a core built and+ /// run without `openhuman-tinyhumans`; callers surface it as a typed+ /// "backend unavailable" condition, never as a bug.+ #[error("no backend transport installed")]+ Unavailable,+ /// The base URL and path did not compose into a valid URL.+ #[error("invalid url: {0}")]+ Url(String),+ /// The HTTP client failed before a response arrived (DNS, TLS, connect,+ /// timeout, body read). Kept as the `reqwest` error so the source chain+ /// walk in the classifiers still sees nested causes.+ #[error("http client error: {0}")]+ Http(#[from] reqwest::Error),+ /// The backend answered with a non-2xx status. `body` is the parsed JSON+ /// body when it parsed, otherwise the raw text as a JSON string.+ #[error("http {status}: {body}")]+ Status { status: u16, body: Value },+ /// The response carried a `{success:false, ...}` envelope on a 2xx status.+ #[error("backend reported failure: {error}")]+ Envelope {+ error: String,+ error_code: Option<String>,+ details: Value,+ },+ /// A header value was not representable on the wire.+ #[error("invalid header value: {0}")]+ Header(String),+ /// The response body could not be decoded into the expected shape.+ #[error("response decoding failed: {0}")]+ Decode(String),+ /// The transport refuses this route by policy (the SDK's unexposed-route+ /// registry, for example). `(method, path)`.+ #[error("route is intentionally not exposed by the backend transport: {0} {1}")]+ RouteNotExposed(String, String),+ /// Anything else the transport implementation reports.+ #[error("{0}")]+ Other(String),+}++impl BackendTransportError {+ /// The HTTP status when this error is a [`Self::Status`].+ pub fn status(&self) -> Option<u16> {+ match self {+ Self::Status { status, .. } => Some(*status),+ _ => None,+ }+ }+}diff --git a/crates/openhuman-core/src/api/transport/install.rs b/crates/openhuman-core/src/api/transport/install.rsnew file mode 100644index 0000000000..4549c5394f--- /dev/null+++ b/crates/openhuman-core/src/api/transport/install.rs@@ -0,0 +1,88 @@+//! Where the process finds its [`BackendTransport`].+//!+//! Resolution order, first hit wins:+//!+//! 1. the transport carried by the ambient [`CoreContext`] (installed through+//! `CoreBuilder::backend_transport`; inherited by every derived context);+//! 2. the process-global transport installed with [`install_backend_transport`]+//! — the path the desktop shell and CLI use, because they boot the core+//! through `run_server_embedded_with_ready` / `run_core_from_args` rather+//! than through the builder;+//! 3. under `cfg(test)` only, a plain `reqwest` transport so the crate's+//! wiremock unit tests need no host crate;+//! 4. otherwise [`BackendTransportError::Unavailable`].+//!+//! Production builds have **no** implicit fallback: a core that nobody gave a+//! transport genuinely has no backend, and every caller degrades to a typed+//! "backend unavailable" error.++use std::sync::{Arc, OnceLock, RwLock};++use super::{BackendTransport, BackendTransportError};++static GLOBAL: OnceLock<RwLock<Option<Arc<dyn BackendTransport>>>> = OnceLock::new();++fn slot() -> &'static RwLock<Option<Arc<dyn BackendTransport>>> {+ GLOBAL.get_or_init(|| RwLock::new(None))+}++/// Install `transport` as the process-wide backend transport, replacing any+/// previous one. Idempotent from the caller's point of view: installing the+/// same implementation twice is harmless.+pub fn install_backend_transport(transport: Arc<dyn BackendTransport>) {+ let name = transport.name();+ let previous = slot()+ .write()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .replace(transport)+ .map(|t| t.name());+ match previous {+ Some(prev) if prev != name => {+ log::info!("[backend-transport] replaced global transport {prev} with {name}")+ }+ Some(_) => log::debug!("[backend-transport] re-installed global transport {name}"),+ None => log::info!("[backend-transport] installed global transport {name}"),+ }+}++/// The process-global transport, if one was installed.+pub fn installed_backend_transport() -> Option<Arc<dyn BackendTransport>> {+ slot()+ .read()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .clone()+}++/// Remove the process-global transport. Test hook.+pub fn clear_backend_transport() {+ let cleared = slot()+ .write()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .take()+ .is_some();+ if cleared {+ log::debug!("[backend-transport] cleared global transport");+ }+}++/// Resolve the transport a backend call should use right now (see the module+/// docs for the precedence).+pub fn resolve_backend_transport() -> Result<Arc<dyn BackendTransport>, BackendTransportError> {+ if let Some(transport) =+ crate::core::runtime::context::CoreContext::current().and_then(|ctx| ctx.backend_transport())+ {+ return Ok(transport);+ }+ if let Some(transport) = installed_backend_transport() {+ return Ok(transport);+ }+ #[cfg(test)]+ {+ return Ok(super::plain::PlainHttpTransport::shared());+ }+ #[cfg(not(test))]+ {+ log::debug!("[backend-transport] no transport installed; backend unavailable");+ Err(BackendTransportError::Unavailable)+ }+}