Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(backend): split transport layer into its own module

Steven Enamakel45827d2b55aa
diff --git a/crates/openhuman-core/src/backend/README.md b/crates/openhuman-core/src/backend/README.md
deleted file mode 100644
index 2c8646b8f2..0000000000
--- a/crates/openhuman-core/src/backend/README.md
+++ /dev/null
@@ -1,259 +0,0 @@
-# backend
-
-This folder is the core's side of talking to a hosted backend it otherwise
-knows nothing about. It defines the transport port every backend call rides,
-the authenticated JSON client (`BackendClient`) that domains use to call
-routes, and the typed errors those calls return. Domains such as channels,
-voice, memory billing, media generation and the integrations budget gate call
-into it; hosts install the actual transport.
-
-The core has no dependency on `tinyhumans-sdk` and holds no hosted URL,
-default, environment variable, header policy or product identity of its own.
-All of that belongs to the installed transport, and the helpers in [`mod.rs`](./mod.rs)
-ask it. The only production transport is `SdkBackendTransport` in
-[`crates/openhuman-tinyhumans`](../../../openhuman-tinyhumans/), built on the vendored SDK.
-
-## How it works
-
-A backend call goes through three layers. The domain names a route and a
-credential, `BackendClient` checks the endpoint, sends the request through the
-resolved transport and classifies the result, and the transport does the HTTP
-round trip with the SDK's route policy.
-
-```text
-domain code (channels, voice, memory billing, ...)
- | BackendClient::from_config(&cfg)?.authed_json(cred, method, path, body)
- v
-BackendClient backend/client.rs
- | endpoint checks (HTTPS or loopback; API key only to managed host)
- | resolve_backend_transport()
- v
-dyn BackendTransport backend/transport/
- | send_json(BackendRequest { profile, base_url, path, credential, .. })
- v
-SdkBackendTransport (crates/openhuman-tinyhumans)
- | TLS, timeouts, attribution headers, route policy, wire classification
- v
-hosted backend
- |
- v Result<Value, BackendTransportError>
-BackendClient::finish_authed_json -> Value or BackendApiError / anyhow
- |
- v (on the JSON-RPC String error channel)
-flatten_authed_error -> SESSION_EXPIRED: / API_KEY_REJECTED: /
- BACKEND_UNAVAILABLE: / full error chain
-```
-
-### Finding a transport
-
-`transport::install::resolve_backend_transport` picks the transport for the
-current call. The first hit wins:
-
-1. The transport bound to the ambient `CoreContext`
- (`CoreBuilder::backend_transport`, inherited by `CoreContext::derive_with`).
-2. The process global set by `install_backend_transport`. The desktop shell,
- TUI and CLI use this path because they boot the core through
- `openhuman_rpc::host` or `run_core_from_args` rather than the
- builder. `openhuman_tinyhumans::install` (or `RuntimeBuilder` for library
- hosts) does the install.
-3. Under `cfg(test)` only, `PlainHttpTransport` from [`transport/plain.rs`](./transport/plain.rs).
-4. Otherwise `BackendTransportError::Unavailable`.
-
-Production has no implicit fallback. A core nobody gave a transport runs
-agents, memory, tools and RPC as normal, and every backend-touching call
-answers with a typed "backend unavailable" error. `is_installed()` lets paths
-that reach the backend host directly (the Langfuse proxy push, the socket,
-channel reply delivery, browser-task module config) skip quietly when there is
-no transport.
-
-### Base URLs and attribution
-
-`mod.rs` has thin helpers that ask the transport for host-specific values:
-
-| Helper | Returns |
-| --- | --- |
-| `base_url(&config.api_url)` | The control-plane origin (account, integrations, channels, voice, sockets, telemetry) for `BaseUrlPurpose::ControlPlane`. `Unavailable` without a transport. |
-| `require_base_url` | The same, on the `String` error channel: a missing transport becomes the `BACKEND_UNAVAILABLE:` sentinel. |
-| `inference_base_url` | The managed OpenAI-compatible inference origin (`BaseUrlPurpose::Inference`), which honours an `api_url` that points at an inference endpoint. Without a transport it still returns an explicitly configured override (normalized by `util::url::normalize_api_base_url`), because managed inference talks to that URL directly. |
-| `product_identity()` | The `x-sdk-name` value the host attributes traffic to, or `None`. |
-| `attribution_headers()` | The host's full attribution header set (`x-sdk-name`, client versions), or an empty map. |
-
-The two purposes differ only in how an operator override is treated: a
-control-plane call must never land on an inference endpoint the user pointed
-`api_url` at, while managed inference uses it as given. The transport owns
-the defaults, the `BACKEND_URL` / `VITE_BACKEND_URL` overrides and that guard
-([`crates/openhuman-tinyhumans/src/backend/url.rs`](../../../openhuman-tinyhumans/src/backend/url.rs)).
-
-### Sending an authenticated request
-
-`BackendClient::new` parses the base URL, requires an absolute `http(s)` URL
-with a host, and strips any path, query and fragment so `Url::join` resolves
-root-relative routes correctly even when a caller passes a full completions
-URL. `BackendClient::from_config` resolves the base through `base_url` and
-fails with `BackendApiError::BackendUnavailable` when no transport is
-installed.
-
-`authed_json(credential, method, path, body)` accepts a `BackendCredential`
-(or a bare session token). Before sending it refuses two unsafe cases: an API
-key may only go to the managed host (`api.tinyhumans.ai`,
-`staging-api.tinyhumans.ai`) or a loopback endpoint, and any credential
-requires HTTPS or loopback HTTP. These checks live in
-`inference::provider::openhuman_backend_model`. It then sends a
-`BackendRequest` with `TransportProfile::Api` and `unwrap_envelope: true`.
-The transport puts a session JWT on `Authorization: Bearer` and an API key on
-`x-api-key` (`transport::credential_headers`).
-
-### Classifying the result
-
-The private `finish_authed_json` is the classification chokepoint for every
-`authed_json` call:
-
-| Transport result | Outcome |
-| --- | --- |
-| `Ok(value)` | Returned as is. |
-| `Unavailable` | `BackendApiError::BackendUnavailable`. |
-| `Http(reqwest::Error)` | Walks the whole `reqwest`/`hyper`/`rustls` source chain. A transient transport phrase (`core::observability::contains_transient_transport_phrase`) is logged as a warning; anything else goes to `report_error`. |
-| `ChannelMessageRouteMissing` | `BackendApiError::ChannelEditUnsupported`. |
-| `ChannelMessageNotFound` | `BackendApiError::MessageNotFound`. |
-| `Status { 401, .. }` | `ApiKeyRejected` for an API-key credential, `Unauthorized` for a session. Not reported to Sentry. |
-| `Status { 400, budget body }` | Logged at info as a budget exhaustion, not reported. |
-| `Status { transient code }` | Logged as a warning (`is_transient_http_status_code`), not reported. |
-| other `Status` | Reported with method, path, host, status and a PII-safe `body_shape`, then returned as an error. |
-| any other error | Returned with `backend request <METHOD> <path>` context. |
-
-`body_shape` (`backend_api_body_shape`) never echoes response values. For a
-JSON object it records the key count and only the keys that look like short
-ASCII identifiers, so an email or UUID used as a key is counted as redacted.
-
-The core never reads a response body to decide what a 404 means. The
-transport classifies the two channel-message 404s (`tinyhumans_sdk::classify`,
-applied by `openhuman-tinyhumans`'s `map_sdk_error`), and the core decides
-the recovery.
-
-### Flattening for JSON-RPC
-
-`flatten_authed_error` turns an `authed_json` error into the string that
-crosses the JSON-RPC boundary, keyed off the typed downcast rather than the
-display text:
-
-- `Unauthorized` becomes `SESSION_EXPIRED: ...`, which the dispatcher treats
- as session expiry: no Sentry report, and `DomainEvent::SessionExpired` is
- published so the host can drive re-sign-in.
-- `ApiKeyRejected` becomes `API_KEY_REJECTED: ...`
- (`core::observability::API_KEY_REJECTED_PREFIX`). It is kept apart from
- session expiry because a library runtime authenticating with an API key has
- no session to clear.
-- `BackendUnavailable` becomes `BACKEND_UNAVAILABLE: ...`
- (`core::observability::BACKEND_UNAVAILABLE_PREFIX`), which observability
- demotes.
-- Everything else keeps its full `{err:#}` chain so real failures still reach
- Sentry.
-
-## Layout
-
-| Path | What it does |
-| --- | --- |
-| `mod.rs` | Re-exports, plus `base_url`, `require_base_url`, `inference_base_url`, `product_identity` and `attribution_headers`. No local URL, header or identity state. |
-| [`client.rs`](./client.rs) | `BackendClient`, `BackendApiError`, `flatten_authed_error`, endpoint checks and `finish_authed_json` classification. |
-| [`client/channel.rs`](./client/channel.rs) | Channel routes on `BackendClient`: `send_channel_message`, `send_channel_typing`, `send_channel_edit`, `send_channel_delete`, `send_channel_reaction`, `create_channel_thread`, `update_channel_thread`, `list_channel_threads`. |
-| [`classify.rs`](./classify.rs) | `is_budget_exhausted_message`, a one-line wrapper over `tinyinference_providers::is_budget_exhausted_message`. |
-| [`transport/`](transport/README.md) | The port: `BackendTransport`, `BackendRequest`, `TransportProfile`, `BaseUrlPurpose`, `BackendTransportError`, the install slot, and shared helpers (`credential_headers`, `parse_body_text`, `unwrap_envelope`, `compose_url`). |
-| `transport/plain.rs` | `PlainHttpTransport`, compiled only under `cfg(test)` so the core's wiremock tests need no host crate. It applies no route policy. |
-
-## Key types and entry points
-
-- `BackendTransport` ([`transport/mod.rs`](./transport/mod.rs)) is the trait a transport
- implements: `send_json`, `send_multipart`, `http_client(profile)`,
- `base_url(configured, purpose)`, `product_identity`,
- `attribution_headers` and `name`. Implementations are process-wide
- `Arc<dyn BackendTransport>` singletons and must be safe to call
- concurrently.
-- `BackendRequest` (`transport/mod.rs`) fully describes one round trip:
- profile (`Api` for control-plane REST, `Integrations` for
- `/agent-integrations/*`), base URL, method, path, query pairs, JSON body,
- optional credential, and whether to unwrap the `{success, data}` envelope.
-- `BackendTransportError` ([`transport/error.rs`](./transport/error.rs)) mirrors the SDK error arms
- the classifiers match on: `Unavailable`, `Url`, `Http`, `Status`,
- `ChannelMessageNotFound`, `ChannelMessageRouteMissing`, `Envelope`,
- `Header`, `Decode`, `RouteNotExposed`, `Other`.
-- `install_backend_transport`, `resolve_backend_transport`, `is_installed`
- ([`transport/install.rs`](./transport/install.rs)) manage the process slot.
-- `BackendClient` (`client.rs`) is the client domains hold. Besides
- `authed_json` it has `url_for(path)` and `raw_client()`, which returns the
- transport's `Api`-profile `reqwest::Client` (attribution headers, no
- credential) for non-JSON shapes such as multipart STT uploads.
-- `BackendApiError` (`client.rs`) is what callers match on for expected
- states: `Unauthorized`, `ApiKeyRejected`, `MessageNotFound`,
- `ChannelEditUnsupported`, `BackendUnavailable`.
-
-## Boundaries
-
-- Route policy, TLS, timeouts, redirects, attribution headers, URL defaults
- and wire classification belong to the transport implementation in
- `crates/openhuman-tinyhumans` (`src/transport/`, `src/backend/url.rs`,
- `src/backend/headers.rs`, `src/backend/product.rs`).
-- Backend routes are defined in [`vendor/tinyhumans-sdk`](../../../../vendor/tinyhumans-sdk/). Add a missing route
- there (its unexposed-route registry is the policy the transport enforces)
- and then name it from the core. Do not recreate route implementations in
- this folder.
-- Account-bound hosted routes (link tokens, OAuth connect and handoff,
- billing, team, webhook tunnels, announcements) are called from
- [`crates/openhuman-tinyhumans/src/hosted/`](../../../openhuman-tinyhumans/src/hosted/) on the SDK's typed clients, not
- through `BackendClient`. The integration token handoff decrypt lives in
- [`crates/openhuman-tinyhumans/src/hosted/oauth/handoff.rs`](../../../openhuman-tinyhumans/src/hosted/oauth/handoff.rs).
-- Session-token lookup, JWT parsing and `Authorization` formatting live in
- `security::credentials::jwt`. The core never obtains, exchanges or validates
- a session.
-- The Socket.IO handshake URL builder is `platform::socket::url::websocket_url`.
-- `IntegrationClient::map_transport_error`
- ([`integrations/client/errors.rs`](../integrations/client/errors.rs)) does the same classification job for
- `/agent-integrations/*` traffic.
-- Hosted memory does not go through this port. The TinyMemory engine uses its
- own HTTP client and only takes `base_url`, `attribution_headers` and a
- credential source from the core.
-
-## Gotchas
-
-- Every TinyHumans backend request must carry a sanitized `x-sdk-name`, which
- the transport stamps. That covers `BackendClient`, `IntegrationClient`
- (except redirected file downloads), the Langfuse and OTLP ingestion push,
- the managed model catalog listing, and the host session owner's
- `POST /auth/login-token/consume` and `GET /auth/me`. Never add it to
- third-party endpoints, MCP servers, BYOK inference endpoints or presigned
- storage redirects.
-- Route new backend calls through `authed_json` (or
- `IntegrationClient::map_transport_error`) instead of matching
- `BackendTransportError` by hand, or 401s and transient failures will page
- Sentry.
-- `ChannelEditUnsupported` and `MessageNotFound` mean different things. A
- missing edit route (every `PATCH` edit today, #5230) says the message still
- exists, so callers must keep its id and only disable editing. Forgetting
- the id there leaves streaming drafts undeleted in the chat.
-- Under `cfg(test)` the "global" transport slot is per thread, so a test that
- installs a fake transport must run on a single thread to see it.
-- When auditing hand-built backend requests, grep for
- `bearer_authorization_value` and `header(AUTHORIZATION`.
-
-## Tests
-
-[`client_tests.rs`](./client_tests.rs) covers base stripping in `BackendClient::new`, 401
-classification, `flatten_authed_error` and `backend_api_body_shape`.
-[`client_channel_tests.rs`](./client_channel_tests.rs) covers channel route shapes and, with a stub
-transport, the mapping of the typed channel-message 404s. [`mod_tests.rs`](./mod_tests.rs) and
-[`transport/transport_tests.rs`](./transport/transport_tests.rs) cover the URL helpers and the port. The 404
-wire classification is tested where it lives
-([`vendor/tinyhumans-sdk/tests/classify.rs`](../../../../vendor/tinyhumans-sdk/tests/classify.rs),
-[`crates/openhuman-tinyhumans/src/transport/channel_404_tests.rs`](../../../openhuman-tinyhumans/src/transport/channel_404_tests.rs)), and the
-attribution header tests are in
-[`crates/openhuman-tinyhumans/src/backend/headers_tests.rs`](../../../openhuman-tinyhumans/src/backend/headers_tests.rs) and
-[`crates/openhuman-tinyhumans/src/transport/transport_tests.rs`](../../../openhuman-tinyhumans/src/transport/transport_tests.rs).
-
-Run with `cargo test -p openhuman backend::` or `pnpm debug rust backend::`.
-
-## Further reading
-
-- [Parent module README](../../README.md)
-- [One TinyHumans API key](../../../../docs/gitbooks/en/developing/tinyhumans-api-key.md)
-- [Deep architecture reference](../../../../docs/gitbooks/en/developing/architecture.md)
-- [openhuman-tinyhumans crate](../../../openhuman-tinyhumans/README.md)
-- [tinyhumans-sdk](../../../../vendor/tinyhumans-sdk/README.md)
diff --git a/crates/openhuman-core/src/backend/classify.rs b/crates/openhuman-core/src/backend/classify.rs
deleted file mode 100644
index d92a758e7c..0000000000
--- a/crates/openhuman-core/src/backend/classify.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-//! Shared provider error classification helpers.
-
-/// Whether a provider error body represents exhausted budget or credits.
-pub fn is_budget_exhausted_message(message: &str) -> bool {
- tinyinference_providers::is_budget_exhausted_message(message)
-}
diff --git a/crates/openhuman-core/src/backend/client.rs b/crates/openhuman-core/src/backend/client.rs
deleted file mode 100644
index d2a216ae50..0000000000
--- a/crates/openhuman-core/src/backend/client.rs
+++ /dev/null
@@ -1,590 +0,0 @@
-//! [`BackendClient`]: authenticated JSON calls to hosted-backend routes over
-//! the [`BackendTransport`] port, and the typed errors they surface.
-
-use anyhow::{Context, Result};
-use reqwest::{Client, Method, Url};
-use serde_json::Value;
-use std::sync::Arc;
-
-use crate::backend::transport::{
- resolve_backend_transport, BackendRequest, BackendTransport, BackendTransportError,
- TransportProfile,
-};
-use crate::security::credentials::session_support::BackendCredential;
-
-/// Typed errors surfaced by `authed_json` for expected backend states that
-/// callers should recover from in-flow rather than funnel into Sentry.
-#[derive(Debug, thiserror::Error)]
-pub enum BackendApiError {
- /// Edit / delete of a channel message returned 404. Happens when the
- /// user deletes the message on the provider side (Telegram, Discord,
- /// Slack, …) but our local `StreamingState` still has the id, or when
- /// the backend GC'd the relay row before we got around to editing it.
- /// Callers should clear stale state and skip the retry. Targets
- /// `OPENHUMAN-TAURI-2Y` (~454 events on `/channels/telegram/messages/<id>`).
- #[error("message not found on {provider}: {message_id}")]
- MessageNotFound {
- /// Channel provider segment (e.g. `"telegram"`, `"discord"`).
- provider: String,
- /// Provider-specific message id from the URL.
- message_id: String,
- },
- /// Backend rejected the bearer JWT with `401 Unauthorized`. This is an
- /// expected user-session state (token expired, revoked, rotated
- /// server-side) — not a code bug. Callers can route to a re-sign-in
- /// flow; the auth domain owns recovery. Targets `OPENHUMAN-TAURI-4K8`
- /// (12 events on `/openai/v1/audio/speech` mascot TTS, but the same
- /// shape fires on every authed endpoint once the session lapses).
- #[error("backend rejected session token on {method} {path}")]
- Unauthorized {
- /// HTTP method as a static string (`"GET"`, `"POST"`, …).
- method: String,
- /// Request path the 401 came back from (no query string).
- path: String,
- },
- /// Backend rejected a TinyHumans API key (`x-api-key`) with
- /// `401 Unauthorized` — a library-mode runtime's credential, not a user
- /// session. Must stay distinct from [`Self::Unauthorized`]:
- /// `flatten_authed_error` maps that variant onto the `SESSION_EXPIRED`
- /// sentinel, which `core/invoke.rs` treats as "clear the app session and
- /// sign out". A rejected API key on a runtime that never had a session
- /// would otherwise trigger that same session-expiry recovery, clearing an
- /// app session that was never the problem and leaving the rejected key
- /// installed. Callers should surface this as a credential error instead.
- #[error("backend rejected api key on {method} {path}")]
- ApiKeyRejected {
- /// HTTP method as a static string (`"GET"`, `"POST"`, …).
- method: String,
- /// Request path the 401 came back from (no query string).
- path: String,
- },
- /// `PATCH /channels/<provider>/messages/<id>` returned 404 because the
- /// backend **implements no such route** — not because the message is gone.
- ///
- /// The backend's channel router serves `POST /:channel/messages` and
- /// `DELETE /:channel/messages/:messageId` only; the `PATCH` edit route was
- /// never added (the deployed OpenAPI contract has no entry for it, and it
- /// is absent from the SDK's generated public-route registry). Every edit
- /// therefore hits the unmatched-route 404, and always has (#5230).
- ///
- /// This must stay distinct from [`Self::MessageNotFound`]: that variant
- /// means "this specific message no longer exists", so its handlers
- /// correctly forget the message id. A missing *route* says nothing about
- /// the message — it is still there and we still own it, so callers must
- /// keep the id (to delete or finally edit it) and only disable the edit
- /// capability. Collapsing the two made the live "💭 Thinking:" bubble and
- /// the streaming draft leak into the chat un-updated and un-deleted.
- ///
- /// Note the backend's `DELETE` handler answers only 400/403/502 and never
- /// 404, so on the deployed contract a 404 on this path can *only* mean
- /// route absence today. `MessageNotFound` is retained for `DELETE` because
- /// the provider-side-deletion semantics are what its callers want and a
- /// future backend revision may start returning it.
- #[error(
- "channel message edit route not implemented by backend ({provider}, message {message_id})"
- )]
- ChannelEditUnsupported {
- /// Channel provider segment (e.g. `"telegram"`, `"discord"`).
- provider: String,
- /// Provider-specific message id from the URL.
- message_id: String,
- },
- /// No [`BackendTransport`] is installed in this process, so the request
- /// could not be sent at all. This is the steady state of a core built
- /// and run without `openhuman-tinyhumans` — an expected build condition,
- /// never a bug. `flatten_authed_error` maps it onto the
- /// `BACKEND_UNAVAILABLE:` sentinel that
- /// `core::observability` demotes.
- #[error("backend transport not available for {method} {path}")]
- BackendUnavailable {
- /// HTTP method as a static string (`"GET"`, `"POST"`, …).
- method: String,
- /// Request path that could not be sent (no query string).
- path: String,
- },
-}
-
-/// Flatten an `authed_json` error onto the JSON-RPC `String` channel.
-///
-/// `BackendApiError::Unauthorized` is an expected backend session-lapse 401
-/// (token expired / revoked / rotated server-side), not a code bug — see the
-/// variant docs above. Callers used to flatten it with `format!("{e:#}")` /
-/// `e.to_string()`, producing `"backend rejected session token on {method}
-/// {path}"`, which matches none of the JSON-RPC session-expiry classifiers
-/// (`is_session_expired_error`, `is_session_expired_message`, the `before_send`
-/// net), so every lapsed-session 401 leaked to Sentry — TAURI-RUST-8WY
-/// (`/teams/me/usage`), TAURI-RUST-8WZ (`/payments/stripe/currentPlan`), and the
-/// rest of the authed-endpoint family (#3297).
-///
-/// Mapping `Unauthorized` onto the existing `SESSION_EXPIRED` sentinel makes the
-/// dispatcher (`openhuman-rpc/src/server/classify.rs`) classify it as session expiry: it skips the
-/// Sentry report AND publishes `DomainEvent::SessionExpired` so the auth domain
-/// drives re-sign-in. This keys off the typed downcast — not the Display
-/// wording — so it stays correct if the `#[error(...)]` text changes, consistent
-/// with #2959's removal of brittle string-based suppression. Every other error
-/// (including `MessageNotFound`) keeps its full `{e:#}` chain so genuine
-/// failures still reach Sentry.
-pub fn flatten_authed_error(err: anyhow::Error) -> String {
- match err.downcast_ref::<BackendApiError>() {
- Some(BackendApiError::Unauthorized { method, path }) => {
- format!("SESSION_EXPIRED: backend rejected session token on {method} {path}")
- }
- // Deliberately NOT the `SESSION_EXPIRED` sentinel: this runtime
- // authenticates with an API key, not a session, so there is no
- // session to expire and `core/invoke.rs`'s `SessionExpired` publish
- // (clear the session, prompt re-sign-in) would be the wrong
- // recovery. See `BackendApiError::ApiKeyRejected`.
- Some(BackendApiError::ApiKeyRejected { method, path }) => {
- format!(
- "{}backend rejected api key on {method} {path}",
- crate::core::observability::API_KEY_REJECTED_PREFIX
- )
- }
- Some(BackendApiError::BackendUnavailable { method, path }) => {
- format!(
- "{}backend transport not available for {method} {path}",
- crate::core::observability::BACKEND_UNAVAILABLE_PREFIX
- )
- }
- _ => format!("{err:#}"),
- }
-}
-
-/// Max bytes of the `body_shape` key-name list echoed into the `authed_json`
-/// report. Bounded so a body with pathologically many keys can't bloat the
-/// event; truncation is UTF-8-safe.
-const BACKEND_API_BODY_SHAPE_MAX_BYTES: usize = 120;
-
-/// PII-safe classification of a non-2xx response body for telemetry.
-///
-/// `report_error`'s message is written to the core/Tauri daily logs BEFORE any
-/// Sentry `before_send` scrubbing, and that scrubber only catches a few
-/// secret-shaped patterns — so the raw body must never be echoed (a non-2xx body
-/// can carry emails / profile JSON / OAuth errors / nonstandard token fields).
-/// We emit only the SHAPE: for a JSON object, the count of top-level keys plus
-/// the sorted subset that look like schema field names; otherwise a coarse
-/// label. Even key NAMES are response-controlled (a foreign backend could return
-/// `{"[email protected]": 1}`), so only keys matching a conservative ASCII-identifier
-/// shape are echoed — everything else is counted as `redacted` and never logged.
-/// The surviving names are enough to identify which backend/gateway produced a
-/// response — the `TAURI-RUST-8C` case (a 91-byte body matching no route this
-/// backend emits), where our canonical envelope is `{success,error,errorCode}`
-/// and a foreign gateway/proxy is not.
-fn backend_api_body_shape(body: &str) -> String {
- let trimmed = body.trim();
- if trimmed.is_empty() {
- return "empty".to_string();
- }
- match serde_json::from_str::<Value>(trimmed) {
- Ok(Value::Object(map)) => {
- let total = map.len();
- let mut safe: Vec<&str> = map
- .keys()
- .map(String::as_str)
- .filter(|k| is_schema_like_key(k))
- .collect();
- safe.sort_unstable();
- let redacted = total - safe.len();
- // `safe` keys are ASCII identifiers, so the join is ASCII and the
- // truncation can only ever land on a byte boundary — but route it
- // through the UTF-8-safe truncator regardless (defence-in-depth).
- let keys = crate::util::truncate_at_byte_boundary(
- &safe.join(","),
- BACKEND_API_BODY_SHAPE_MAX_BYTES,
- );
- format!("object(keys={total},safe=[{keys}],redacted={redacted})")
- }
- Ok(Value::Array(_)) => "array".to_string(),
- Ok(_) => "scalar".to_string(),
- Err(_) => "non_json".to_string(),
- }
-}
-
-/// A JSON key safe to echo into telemetry: a short ASCII identifier (the shape
-/// of a schema field name). Anything else — non-ASCII, punctuation like `@`,
-/// whitespace, or overlong — is treated as response-controlled data and excluded
-/// so `body_shape` can never leak an email/UUID/free-text used as a key.
-fn is_schema_like_key(key: &str) -> bool {
- const MAX_KEY_LEN: usize = 40;
- !key.is_empty()
- && key.len() <= MAX_KEY_LEN
- && key
- .bytes()
- .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
-}
-
-/// A client for authenticated hosted-backend routes.
-///
-/// Owns the *routes* and the error classification; the HTTP round-trip itself
-/// rides the process [`BackendTransport`] (see [`crate::backend::transport`]),
-/// which is what carries TLS, timeouts, attribution headers and the
-/// credential header shape. A core with no transport installed answers every
-/// call with [`BackendApiError::BackendUnavailable`].
-#[derive(Clone)]
-pub struct BackendClient {
- base: Url,
-}
-
-impl BackendClient {
- /// Creates a new `BackendClient` with the given API base URL.
- ///
- /// Any path, query, or fragment in `api_base` is stripped so that
- /// `Url::join` always resolves root-relative REST paths correctly.
- /// This guards against callers who pass a full LLM completions URL
- /// (e.g. `https://host/v1/chat/completions`) instead of just the origin:
- /// without stripping, `join("teams/me/usage")` would produce the wrong
- /// path `/v1/chat/teams/me/usage` via RFC 3986 relative resolution.
- pub fn new(api_base: &str) -> Result<Self> {
- let mut base = Url::parse(api_base.trim()).context("Invalid API base URL")?;
- anyhow::ensure!(
- matches!(base.scheme(), "http" | "https") && base.host_str().is_some(),
- "API base URL must be an absolute http(s) URL with host"
- );
- base.set_path("");
- base.set_query(None);
- base.set_fragment(None);
- Ok(Self { base })
- }
-
- /// A client for the backend origin the installed transport resolves from
- /// `config.api_url` (see [`crate::backend::base_url`]).
- ///
- /// Without a transport this fails with
- /// [`BackendApiError::BackendUnavailable`], which
- /// [`flatten_authed_error`] turns into the `BACKEND_UNAVAILABLE:` sentinel.
- pub fn from_config(config: &crate::config::Config) -> Result<Self> {
- match crate::backend::base_url(&config.api_url) {
- Ok(base) => Self::new(&base),
- Err(BackendTransportError::Unavailable) => {
- log::debug!("[backend-api] no backend transport installed; client unavailable");
- Err(anyhow::Error::new(BackendApiError::BackendUnavailable {
- method: "ANY".to_string(),
- path: String::new(),
- }))
- }
- Err(other) => Err(anyhow::Error::new(other)),
- }
- }
-
- /// The backend origin this client resolves routes against.
- pub fn base_url(&self) -> &str {
- self.base.as_str()
- }
-
- /// The process backend transport, or [`BackendApiError::BackendUnavailable`]
- /// for `method path` when none is installed.
- fn transport(&self, method: &Method, path: &str) -> Result<Arc<dyn BackendTransport>> {
- resolve_backend_transport().map_err(|error| match error {
- BackendTransportError::Unavailable => {
- let route = self.url_for(path).map(|u| u.path().to_string());
- log::debug!(
- "[backend-api] no backend transport installed; {} {} unavailable",
- method.as_str(),
- route.as_deref().unwrap_or(path)
- );
- anyhow::Error::new(BackendApiError::BackendUnavailable {
- method: method.as_str().to_string(),
- path: route.unwrap_or_else(|_| path.to_string()),
- })
- }
- other => anyhow::Error::new(other),
- })
- }
-
- /// The transport's `reqwest::Client` for callers that need to drive a
- /// non-JSON request shape (e.g. `multipart/form-data` uploads for cloud
- /// STT) without re-implementing TLS/proxy plumbing. Carries the
- /// attribution headers; the caller adds the credential.
- pub fn raw_client(&self) -> Result<Client> {
- Ok(resolve_backend_transport()
- .map_err(|error| match error {
- BackendTransportError::Unavailable => {
- anyhow::Error::new(BackendApiError::BackendUnavailable {
- method: "RAW".to_string(),
- path: String::new(),
- })
- }
- other => anyhow::Error::new(other),
- })?
- .http_client(TransportProfile::Api))
- }
-
- /// Resolve a backend-relative path against the configured base URL.
- /// Mirrors what `authed_json` does internally so callers using
- /// `raw_client()` don't have to assemble URLs by hand.
- pub fn url_for(&self, path: &str) -> Result<Url> {
- self.base
- .join(path.trim_start_matches('/'))
- .with_context(|| format!("build URL for {path}"))
- }
-
- /// Generic authenticated JSON request helper for backend API routes.
- ///
- /// `credential` accepts a [`BackendCredential`] or a bare session token.
- /// The transport sends API keys as `x-api-key` and sessions as Bearer JWTs.
- pub async fn authed_json(
- &self,
- credential: impl Into<BackendCredential>,
- method: Method,
- path: &str,
- body: Option<Value>,
- ) -> Result<Value> {
- let credential = credential.into();
- let is_api_key = credential.is_api_key();
- if is_api_key
- && !crate::inference::provider::openhuman_backend_model::is_managed_endpoint_for_api_key(
- self.base.as_str(),
- )
- {
- anyhow::bail!("TinyHumans API key requires the managed backend or a loopback endpoint");
- }
- if !crate::inference::provider::openhuman_backend_model::is_safe_endpoint_for_managed_bearer(
- self.base.as_str(),
- ) {
- anyhow::bail!("backend credential requires HTTPS or a loopback HTTP endpoint");
- }
- let transport = self.transport(&method, path)?;
- let response = transport
- .send_json(BackendRequest {
- profile: TransportProfile::Api,
- base_url: self.base.as_str(),
- method: method.clone(),
- path,
- query: &[],
- body: body.as_ref(),
- credential: Some(&credential),
- unwrap_envelope: true,
- })
- .await;
- self.finish_authed_json(method, path, response, is_api_key)
- }
-
- fn finish_authed_json(
- &self,
- method: Method,
- path: &str,
- response: Result<Value, BackendTransportError>,
- is_api_key: bool,
- ) -> Result<Value> {
- let url = self.url_for(path)?;
- let value = match response {
- Ok(value) => return Ok(value),
- Err(BackendTransportError::Unavailable) => {
- return Err(anyhow::Error::new(BackendApiError::BackendUnavailable {
- method: method.as_str().to_string(),
- path: url.path().to_string(),
- }));
- }
- Err(BackendTransportError::Http(e)) => {
- // Walk the error source chain so transient markers hidden in nested
- // causes (reqwest -> hyper -> rustls TLS EOF, etc.) still classify
- // correctly. The top-level `e.to_string()` often only carries the
- // outermost wrapper, e.g. "error sending request for url (...)".
- let mut error_message = e.to_string();
- let mut src: Option<&(dyn std::error::Error + 'static)> =
- std::error::Error::source(&e);
- while let Some(s) = src {
- error_message.push_str(" → ");
- error_message.push_str(&s.to_string());
- src = s.source();
- }
- if crate::core::observability::contains_transient_transport_phrase(&error_message) {
- tracing::warn!(
- domain = "backend_api",
- operation = "authed_json",
- method = method.as_str(),
- path = url.path(),
- failure = "transport",
- error = %error_message,
- "[backend_api] transient transport failure on {} {}: {}",
- method.as_str(),
- url.path(),
- error_message,
- );
- } else {
- crate::core::observability::report_error(
- error_message.as_str(),
- "backend_api",
- "authed_json",
- &[
- ("method", method.as_str()),
- ("path", url.path()),
- ("failure", "transport"),
- ],
- );
- }
- return Err(anyhow::Error::new(e).context(format!(
- "backend request {} {}",
- method.as_str(),
- url.path()
- )));
- }
- // The transport classifies channel-message 404s (it owns the
- // backend's wire behaviour); the recovery each one implies is ours.
- Err(BackendTransportError::ChannelMessageRouteMissing {
- provider,
- message_id,
- }) => {
- tracing::warn!(
- domain = "backend_api",
- operation = "authed_json",
- provider = provider,
- message_id = message_id,
- "[backend_api] channel-message 404 on {} {} — backend implements no such \
- route; surfacing ChannelEditUnsupported so callers degrade instead of \
- forgetting the message id (#5230)",
- method.as_str(),
- url.path(),
- );
- return Err(anyhow::Error::new(
- BackendApiError::ChannelEditUnsupported {
- provider,
- message_id,
- },
- ));
- }
- Err(BackendTransportError::ChannelMessageNotFound {
- provider,
- message_id,
- }) => {
- tracing::info!(
- domain = "backend_api",
- operation = "authed_json",
- provider = provider,
- message_id = message_id,
- "[backend_api] message-not-found 404 on {} {} — surfacing typed error",
- method.as_str(),
- url.path(),
- );
- return Err(anyhow::Error::new(BackendApiError::MessageNotFound {
- provider,
- message_id,
- }));
- }
- Err(BackendTransportError::Status { status, body }) => (status, body),
- Err(error) => {
- return Err(anyhow::Error::new(error).context(format!(
- "backend request {} {}",
- method.as_str(),
- url.path()
- )));
- }
- };
- {
- let (status_code, response_body) = value;
- let status = reqwest::StatusCode::from_u16(status_code)
- .context("backend transport returned an invalid HTTP status")?;
- let text = match response_body {
- Value::String(text) => text,
- other => serde_json::to_string(&other).unwrap_or_default(),
- };
- let status_str = status_code.to_string();
-
- // 401 on any authed backend endpoint is an expected user-session
- // state (token expired / revoked / rotated server-side), not a
- // code bug — every authed endpoint will see this once the session
- // lapses. Surface a typed `BackendApiError::Unauthorized` so the
- // auth domain can drive recovery, and skip `report_error` to
- // avoid Sentry noise. Targets `OPENHUMAN-TAURI-4K8` (mascot TTS
- // surfaced it first on `/openai/v1/audio/speech`, but the same
- // shape applies to every `authed_json` path).
- if status_code == 401 {
- tracing::info!(
- domain = "backend_api",
- operation = "authed_json",
- method = method.as_str(),
- path = url.path(),
- status = status_code,
- failure = "non_2xx",
- "[backend_api] 401 on {} {} — session token rejected, surfacing typed error",
- method.as_str(),
- url.path(),
- );
- // The credential kind decides the *recovery*, not just the
- // wording: `flatten_authed_error` maps `Unauthorized` onto
- // the `SESSION_EXPIRED` sentinel that triggers session
- // sign-out, which is the wrong recovery for a rejected API
- // key (there is no session to expire) — see
- // `BackendApiError::ApiKeyRejected`.
- return Err(anyhow::Error::new(if is_api_key {
- BackendApiError::ApiKeyRejected {
- method: method.as_str().to_string(),
- path: url.path().to_string(),
- }
- } else {
- BackendApiError::Unauthorized {
- method: method.as_str().to_string(),
- path: url.path().to_string(),
- }
- }));
- }
-
- // These are transient infrastructure errors (proxy/CDN/backend
- // temporarily unavailable). They are not code bugs and callers already
- // implement retry/disable logic, so skip Sentry to avoid noise.
- let is_transient_infra =
- crate::core::observability::is_transient_http_status_code(status_code);
- let is_budget_exhausted =
- status_code == 400 && tinyinference_providers::is_budget_exhausted_message(&text);
- if is_budget_exhausted {
- tracing::info!(
- method = method.as_str(),
- path = url.path(),
- status = status_code,
- failure = "non_2xx",
- kind = "budget",
- "[backend_api] budget-exhausted 400 on {} {} — not reporting to Sentry",
- method.as_str(),
- url.path(),
- );
- } else if is_transient_infra {
- tracing::warn!(
- domain = "backend_api",
- operation = "authed_json",
- method = method.as_str(),
- path = url.path(),
- status = status_code,
- failure = "non_2xx",
- "[backend_api] transient {status} on {} {} — not reporting to Sentry",
- method.as_str(),
- url.path(),
- );
- } else {
- // Record the host and JSON key names to locate misrouted
- // backend errors without sending response values (TAURI-RUST-8C).
- let host = url.host_str().unwrap_or("");
- let body_shape = backend_api_body_shape(&text);
- crate::core::observability::report_error(
- format!(
- "{} {} failed ({status}); response_body_len={}; body_shape={}",
- method.as_str(),
- url.path(),
- text.len(),
- body_shape,
- )
- .as_str(),
- "backend_api",
- "authed_json",
- &[
- ("method", method.as_str()),
- ("path", url.path()),
- ("host", host),
- ("status", status_str.as_str()),
- ("failure", "non_2xx"),
- ],
- );
- }
- anyhow::bail!(
- "{} {} failed ({status}): {text}",
- method.as_str(),
- url.path()
- );
- }
- }
-}
-
-#[cfg(test)]
-#[path = "client_tests.rs"]
-mod tests;
-
-mod channel;
diff --git a/crates/openhuman-core/src/backend/client/channel.rs b/crates/openhuman-core/src/backend/client/channel.rs
deleted file mode 100644
index 4d02015bb3..0000000000
--- a/crates/openhuman-core/src/backend/client/channel.rs
+++ /dev/null
@@ -1,205 +0,0 @@
-//! 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,
- 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(
- 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,
- 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(
- 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,
- 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(
- 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,
- 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(
- 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,
- 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(
- 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,
- 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(
- 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,
- 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(
- 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,
- 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(credential, Method::GET, &path, None).await
- }
-}
diff --git a/crates/openhuman-core/src/backend/client_channel_tests.rs b/crates/openhuman-core/src/backend/client_channel_tests.rs
deleted file mode 100644
index 6b3bdec06e..0000000000
--- a/crates/openhuman-core/src/backend/client_channel_tests.rs
+++ /dev/null
@@ -1,427 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn channel_routes_build_expected_requests_and_validate_inputs() {
- type Requests = Arc<Mutex<Vec<(String, String, Value)>>>;
- async fn capture(
- State(seen): State<Requests>,
- request: axum::http::Request<axum::body::Body>,
- ) -> Json<Value> {
- let method = request.method().to_string();
- let path = request.uri().to_string();
- let bytes = axum::body::to_bytes(request.into_body(), usize::MAX)
- .await
- .unwrap();
- let body = if bytes.is_empty() {
- Value::Null
- } else {
- serde_json::from_slice(&bytes).unwrap()
- };
- seen.lock().unwrap().push((method, path, body));
- Json(json!({ "success": true, "data": { "ok": true } }))
- }
-
- let seen = Requests::default();
- let app = Router::new().fallback(capture).with_state(seen.clone());
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- let client = BackendClient::new(&format!("http://{addr}")).unwrap();
-
- client
- .send_channel_message(" /telegram/ ", "jwt", json!({ "text": "hello" }))
- .await
- .unwrap();
- client
- .send_channel_reaction("telegram", "jwt", json!({ "emoji": "👍" }))
- .await
- .unwrap();
- client
- .create_channel_thread("telegram", "jwt", " topic ")
- .await
- .unwrap();
- client
- .update_channel_thread("telegram", "jwt", "thread-1", "close")
- .await
- .unwrap();
- client
- .list_channel_threads("telegram", "jwt", Some(true))
- .await
- .unwrap();
- client
- .list_channel_threads("telegram", "jwt", Some(false))
- .await
- .unwrap();
- client
- .list_channel_threads("telegram", "jwt", None)
- .await
- .unwrap();
-
- let requests = seen.lock().unwrap().clone();
- assert_eq!(
- requests[0],
- (
- "POST".into(),
- "/channels/telegram/messages".into(),
- json!({ "text": "hello" })
- )
- );
- assert_eq!(
- requests[1],
- (
- "POST".into(),
- "/channels/telegram/reactions".into(),
- json!({ "emoji": "👍" })
- )
- );
- assert_eq!(
- requests[2],
- (
- "POST".into(),
- "/channels/telegram/threads".into(),
- json!({ "title": "topic" })
- )
- );
- assert_eq!(
- requests[3],
- (
- "PATCH".into(),
- "/channels/telegram/threads/thread-1".into(),
- json!({ "action": "close" })
- )
- );
- assert_eq!(requests[4].1, "/channels/telegram/threads?active=true");
- assert_eq!(requests[5].1, "/channels/telegram/threads?active=false");
- assert_eq!(requests[6].1, "/channels/telegram/threads");
- drop(requests);
-
- assert!(client
- .send_channel_message(" / ", "jwt", json!({}))
- .await
- .is_err());
- assert!(client
- .send_channel_reaction(" ", "jwt", json!({}))
- .await
- .is_err());
- assert!(client
- .create_channel_thread("telegram", "jwt", " ")
- .await
- .is_err());
- assert!(client
- .update_channel_thread("telegram", "jwt", " ", "close")
- .await
- .is_err());
- assert!(client
- .update_channel_thread("telegram", "jwt", "thread-1", "delete")
- .await
- .is_err());
- assert!(client.list_channel_threads("", "jwt", None).await.is_err());
-}
-
-#[tokio::test]
-async fn authed_json_reports_non_channel_404_still_propagates() {
- // TAURI-RUST-8C: a GET 404 on a non-channel path (e.g. `/teams/me/usage`)
- // falls through to `report_error` (not a typed/suppressed state) — it must
- // still return an Err (no suppression) and not a typed `BackendApiError`.
- let app = Router::new().route(
- "/teams/me/usage",
- get(|| async {
- (
- axum::http::StatusCode::NOT_FOUND,
- r#"{"message":"Not Found"}"#,
- )
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- let base_url = format!("http://{addr}");
- let client = BackendClient::new(&base_url).unwrap();
-
- let err = client
- .authed_json("mock-jwt", Method::GET, "/teams/me/usage", None)
- .await
- .unwrap_err();
- assert!(err.downcast_ref::<BackendApiError>().is_none());
- let msg = format!("{err:#}");
- assert!(msg.contains("404"), "error should carry the status: {msg}");
- assert!(
- msg.contains("/teams/me/usage"),
- "error should carry the path: {msg}"
- );
-}
-
-#[test]
-fn flatten_authed_error_maps_unauthorized_to_session_expired_sentinel() {
- // #3297: the typed `Unauthorized` (expected session-lapse 401) must flatten
- // onto a string that the JSON-RPC session-expiry classifiers recognise, so
- // it is suppressed from Sentry (TAURI-RUST-8WY / 8WZ) instead of leaking.
- let err = anyhow::Error::new(BackendApiError::Unauthorized {
- method: "GET".to_string(),
- path: "/teams/me/usage".to_string(),
- });
- let flat = flatten_authed_error(err);
-
- // Carries the SESSION_EXPIRED sentinel + preserves method/path for logs.
- assert!(
- flat.contains("SESSION_EXPIRED"),
- "expected sentinel, got: {flat}"
- );
- assert!(flat.contains("GET"), "method preserved: {flat}");
- assert!(flat.contains("/teams/me/usage"), "path preserved: {flat}");
-
- // Contract cross-check: the flattened string MUST classify as session
- // expiry. This couples the mapping to the actual classifier — if either the
- // sentinel or the classifier drifts, this fails instead of silently leaking.
- assert!(
- crate::core::observability::is_session_expired_message(&flat),
- "flattened Unauthorized must classify as session expiry: {flat}"
- );
-}
-
-#[test]
-fn flatten_authed_error_preserves_non_unauthorized_chain() {
- // A non-Unauthorized failure (e.g. a transient network/timeout error) keeps
- // its full `{e:#}` anyhow chain and must NOT be demoted to session expiry —
- // genuine failures still reach Sentry.
- let err = anyhow::anyhow!("connect timeout").context("backend request GET /teams/me/usage");
- let flat = flatten_authed_error(err);
-
- assert!(!flat.contains("SESSION_EXPIRED"), "must not map: {flat}");
- assert!(flat.contains("connect timeout"), "cause preserved: {flat}");
- assert!(
- !crate::core::observability::is_session_expired_message(&flat),
- "non-auth error must NOT classify as session expiry: {flat}"
- );
-}
-
-#[test]
-fn flatten_authed_error_does_not_swallow_message_not_found() {
- // `MessageNotFound` is a different expected state handled by its own callers
- // (channel streaming/delete paths downcast it); it must not be collapsed
- // into the session-expiry sentinel here.
- let err = anyhow::Error::new(BackendApiError::MessageNotFound {
- provider: "telegram".to_string(),
- message_id: "1103".to_string(),
- });
- let flat = flatten_authed_error(err);
-
- assert!(!flat.contains("SESSION_EXPIRED"), "must not map: {flat}");
- assert!(
- flat.contains("message not found"),
- "display preserved: {flat}"
- );
-}
-
-#[tokio::test]
-async fn authed_json_403_is_not_demoted_to_unauthorized() {
- // 403 (Forbidden) is a genuine authorization/permission problem — the
- // token authenticated but lacked scope. That IS a code/config bug we
- // want to keep in Sentry; only 401 (token rejected as a whole) maps
- // to the expected-state `Unauthorized` variant.
- let app = Router::new().route(
- "/openai/v1/audio/speech",
- post(|| async { (axum::http::StatusCode::FORBIDDEN, "Forbidden") }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- let base_url = format!("http://{addr}");
- let client = BackendClient::new(&base_url).unwrap();
-
- let err = client
- .authed_json("mock-jwt", Method::POST, "/openai/v1/audio/speech", None)
- .await
- .unwrap_err();
- assert!(
- err.downcast_ref::<BackendApiError>().is_none(),
- "403 must not be classified as Unauthorized"
- );
-}
-
-#[tokio::test]
-async fn authed_json_404_outside_messages_path_still_reports() {
- // 404 on a non-`/channels/<provider>/messages/<id>` path should NOT be
- // demoted to MessageNotFound — it's a real backend bug or routing
- // mistake and must keep its Sentry signal.
- let app = Router::new().route(
- "/auth/profile",
- get(|| async { (axum::http::StatusCode::NOT_FOUND, "Not Found") }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- let base_url = format!("http://{addr}");
- let client = BackendClient::new(&base_url).unwrap();
-
- let err = client
- .authed_json("mock-jwt", Method::GET, "/auth/profile", None)
- .await
- .unwrap_err();
- assert!(
- err.downcast_ref::<BackendApiError>().is_none(),
- "non-channel-message 404 must not be classified as MessageNotFound"
- );
-}
-
-#[tokio::test]
-async fn sdk_backed_channel_typing_surfaces_unauthorized_on_401() {
- let app = Router::new().route(
- "/channels/telegram/typing",
- post(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- let client = BackendClient::new(&format!("http://{addr}")).unwrap();
- let err = client
- .send_channel_typing("telegram", "mock-jwt")
- .await
- .unwrap_err();
-
- let typed = err.downcast_ref::<BackendApiError>().unwrap();
- let BackendApiError::Unauthorized { method, path } = typed else {
- panic!("expected Unauthorized, got {typed:?}");
- };
- assert_eq!(method, "POST");
- assert_eq!(path, "/channels/telegram/typing");
- // The session-expiry sentinel must still be derivable, so the dispatcher
- // keeps routing this to re-sign-in rather than to Sentry.
- assert!(flatten_authed_error(err).starts_with("SESSION_EXPIRED:"));
-}
-
-// ── typed channel-message 404s from the transport ───────────────────────────
-//
-// The transport (openhuman-tinyhumans) owns what a channel-message 404 means on
-// the backend; these pin the recovery the core attaches to each variant.
-
-/// A transport that answers every request with the error `make` builds.
-struct FailingTransport(fn() -> crate::backend::BackendTransportError);
-
-#[async_trait::async_trait]
-impl crate::backend::BackendTransport for FailingTransport {
- async fn send_json(
- &self,
- _req: crate::backend::BackendRequest<'_>,
- ) -> Result<serde_json::Value, crate::backend::BackendTransportError> {
- Err((self.0)())
- }
-
- async fn send_multipart(
- &self,
- _req: crate::backend::BackendRequest<'_>,
- _form: reqwest::multipart::Form,
- ) -> Result<serde_json::Value, crate::backend::BackendTransportError> {
- Err((self.0)())
- }
-
- fn http_client(&self, _profile: crate::backend::TransportProfile) -> reqwest::Client {
- reqwest::Client::new()
- }
-
- fn base_url(
- &self,
- configured: Option<&str>,
- purpose: crate::backend::BaseUrlPurpose,
- ) -> String {
- crate::backend::transport::plain::PlainHttpTransport::new().base_url(configured, purpose)
- }
-
- fn product_identity(&self) -> String {
- crate::backend::transport::plain::TEST_PRODUCT_IDENTITY.to_string()
- }
-
- fn attribution_headers(&self) -> reqwest::header::HeaderMap {
- reqwest::header::HeaderMap::new()
- }
-
- fn name(&self) -> &'static str {
- "failing-test-transport"
- }
-}
-
-/// Run `f` with a [`FailingTransport`] installed. The `cfg(test)` global slot
-/// is per thread and `#[tokio::test]` runs on one, so this cannot leak.
-async fn with_failing_transport<F, Fut>(make: fn() -> crate::backend::BackendTransportError, f: F)
-where
- F: FnOnce() -> Fut,
- Fut: std::future::Future<Output = ()>,
-{
- crate::backend::install_backend_transport(std::sync::Arc::new(FailingTransport(make)));
- f().await;
- crate::backend::transport::install::clear_backend_transport();
-}
-
-#[tokio::test]
-async fn route_missing_becomes_channel_edit_unsupported() {
- with_failing_transport(
- || crate::backend::BackendTransportError::ChannelMessageRouteMissing {
- provider: "telegram".into(),
- message_id: "1103".into(),
- },
- || async {
- let client = BackendClient::new("http://127.0.0.1:9").unwrap();
- let err = client
- .send_channel_edit("telegram", "1103", "mock-jwt", serde_json::json!({}))
- .await
- .unwrap_err();
- let typed = err.downcast_ref::<BackendApiError>().unwrap();
- let BackendApiError::ChannelEditUnsupported {
- provider,
- message_id,
- } = typed
- else {
- panic!("expected ChannelEditUnsupported, got {typed:?}");
- };
- assert_eq!(
- (provider.as_str(), message_id.as_str()),
- ("telegram", "1103")
- );
- },
- )
- .await;
-}
-
-#[tokio::test]
-async fn message_not_found_becomes_message_not_found() {
- with_failing_transport(
- || crate::backend::BackendTransportError::ChannelMessageNotFound {
- provider: "discord".into(),
- message_id: "abc".into(),
- },
- || async {
- let client = BackendClient::new("http://127.0.0.1:9").unwrap();
- let err = client
- .send_channel_delete("discord", "abc", "mock-jwt")
- .await
- .unwrap_err();
- let typed = err.downcast_ref::<BackendApiError>().unwrap();
- let BackendApiError::MessageNotFound {
- provider,
- message_id,
- } = typed
- else {
- panic!("expected MessageNotFound, got {typed:?}");
- };
- assert_eq!((provider.as_str(), message_id.as_str()), ("discord", "abc"));
- // A missing message is an expected state: it keeps its own chain
- // rather than turning into a session-expiry sentinel.
- assert!(!flatten_authed_error(err).starts_with("SESSION_EXPIRED:"));
- },
- )
- .await;
-}
diff --git a/crates/openhuman-core/src/backend/client_tests.rs b/crates/openhuman-core/src/backend/client_tests.rs
deleted file mode 100644
index 7410065707..0000000000
--- a/crates/openhuman-core/src/backend/client_tests.rs
+++ /dev/null
@@ -1,362 +0,0 @@
-use super::{
- backend_api_body_shape, flatten_authed_error, BackendApiError, BackendClient,
- BACKEND_API_BODY_SHAPE_MAX_BYTES,
-};
-use crate::backend::transport::plain::TEST_PRODUCT_HEADER as PRODUCT_IDENTITY_HEADER;
-use axum::extract::State;
-use axum::http::HeaderMap;
-use axum::routing::{get, post};
-use axum::{Json, Router};
-use reqwest::Method;
-use serde_json::{json, Value};
-use std::sync::{Arc, Mutex};
-use tokio::net::TcpListener;
-
-#[tokio::test]
-async fn authed_json_rejects_api_key_for_foreign_or_plaintext_endpoint() {
- use crate::security::credentials::session_support::BackendCredential;
-
- for endpoint in ["https://example.com", "http://example.com"] {
- let client = BackendClient::new(endpoint).unwrap();
- let error = client
- .authed_json(
- BackendCredential::ApiKey("th_test_key".to_string()),
- Method::GET,
- "/probe",
- None,
- )
- .await
- .unwrap_err();
- assert!(error.to_string().contains("TinyHumans API key requires"));
- }
-}
-
-#[derive(Clone, Default)]
-struct CapturedHeaders {
- entries: Arc<Mutex<Vec<HeaderMap>>>,
-}
-
-impl CapturedHeaders {
- fn push(&self, headers: &HeaderMap) {
- self.entries.lock().unwrap().push(headers.clone());
- }
-
- fn take(&self) -> Vec<HeaderMap> {
- self.entries.lock().unwrap().clone()
- }
-}
-
-async fn spawn_header_capture_server() -> (String, CapturedHeaders) {
- async fn capture_me(
- State(captured): State<CapturedHeaders>,
- headers: HeaderMap,
- ) -> Json<Value> {
- captured.push(&headers);
- Json(json!({
- "success": true,
- "data": { "_id": "user-123" }
- }))
- }
-
- async fn capture_probe(
- State(captured): State<CapturedHeaders>,
- headers: HeaderMap,
- ) -> Json<Value> {
- captured.push(&headers);
- Json(json!({ "ok": true }))
- }
-
- let captured = CapturedHeaders::default();
- let app = Router::new()
- .route("/auth/me", get(capture_me))
- .route("/probe", get(capture_probe))
- .with_state(captured.clone());
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- (format!("http://{addr}"), captured)
-}
-
-#[tokio::test]
-async fn authed_json_sends_an_api_key_as_x_api_key_and_no_bearer() {
- // Library mode: the TinyHumans API key rides the SDK REST routes as
- // `x-api-key`, never as `Authorization: Bearer` (that header is the
- // managed-inference shape, handled by `OpenHumanBackendModel`).
- use crate::security::credentials::session_support::BackendCredential;
-
- let (base_url, captured) = spawn_header_capture_server().await;
- let client = BackendClient::new(&base_url).unwrap();
-
- let response = client
- .authed_json(
- &BackendCredential::ApiKey("th_test_key".to_string()),
- Method::GET,
- "/probe",
- None,
- )
- .await
- .unwrap();
- assert_eq!(response, json!({ "ok": true }));
-
- let headers = captured.take();
- let request_headers = headers.last().unwrap();
- assert_eq!(
- request_headers
- .get("x-api-key")
- .and_then(|value| value.to_str().ok()),
- Some("th_test_key")
- );
- assert!(
- request_headers.get("authorization").is_none(),
- "an API key must not also be sent as a bearer"
- );
- assert!(request_headers.get(PRODUCT_IDENTITY_HEADER).is_some());
-}
-
-#[tokio::test]
-async fn authed_json_sends_a_session_credential_as_a_bearer_only() {
- use crate::security::credentials::session_support::BackendCredential;
-
- let (base_url, captured) = spawn_header_capture_server().await;
- let client = BackendClient::new(&base_url).unwrap();
-
- client
- .authed_json(
- &BackendCredential::Session("jwt-token".to_string()),
- Method::GET,
- "/probe",
- None,
- )
- .await
- .unwrap();
-
- let headers = captured.take();
- let request_headers = headers.last().unwrap();
- assert_eq!(
- request_headers
- .get("authorization")
- .and_then(|value| value.to_str().ok()),
- Some("Bearer jwt-token")
- );
- assert!(request_headers.get("x-api-key").is_none());
-}
-
-// Regression: OPENHUMAN-TAURI-8K / Sentry issue 7473650958.
-// When config.api_url is a full LLM completions URL (e.g. /v1/chat/completions),
-// Url::join used to produce wrong paths like /v1/chat/teams/me/usage instead of
-// /teams/me/usage — BackendClient::new must strip the path to prevent this.
-#[test]
-fn new_strips_path_from_completions_url() {
- for base in [
- "https://api.tinyhumans.ai/v1/chat/completions",
- "https://api.openai.com/v1/chat/completions",
- "https://api.tinyhumans.ai",
- "https://api.tinyhumans.ai/",
- ] {
- let client = BackendClient::new(base).unwrap();
- let url = client.url_for("/teams/me/usage").unwrap();
- assert_eq!(url.path(), "/teams/me/usage", "{base}");
- }
-}
-
-#[tokio::test]
-async fn authed_json_surfaces_unauthorized_on_401() {
- // OPENHUMAN-TAURI-4K8: 401 on any authed backend endpoint must surface a
- // typed `BackendApiError::Unauthorized` and NOT funnel into `report_error`.
- // The mascot TTS path (`/openai/v1/audio/speech`) was the loudest reporter,
- // but the same shape fires on every authed endpoint once a session lapses,
- // so we cover two different paths/methods to prove the suppression is
- // status-driven, not path-keyed.
- let app = Router::new()
- .route(
- "/openai/v1/audio/speech",
- post(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
- )
- .route(
- "/referral/stats",
- get(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- let base_url = format!("http://{addr}");
- let client = BackendClient::new(&base_url).unwrap();
-
- // Mascot TTS path — the original reporter.
- let err = client
- .authed_json(
- "mock-jwt",
- Method::POST,
- "/openai/v1/audio/speech",
- Some(json!({ "text": "hello" })),
- )
- .await
- .unwrap_err();
- let typed = err.downcast_ref::<BackendApiError>().unwrap();
- let BackendApiError::Unauthorized { method, path } = typed else {
- panic!("expected Unauthorized, got {typed:?}");
- };
- assert_eq!(method, "POST");
- assert_eq!(path, "/openai/v1/audio/speech");
-
- // Generic GET on a non-TTS path — proves the suppression is per-status,
- // not per-path. (Same root cause: expired/revoked backend session.)
- let err = client
- .authed_json("mock-jwt", Method::GET, "/referral/stats", None)
- .await
- .unwrap_err();
- let typed = err.downcast_ref::<BackendApiError>().unwrap();
- let BackendApiError::Unauthorized { method, path } = typed else {
- panic!("expected Unauthorized, got {typed:?}");
- };
- assert_eq!(method, "GET");
- assert_eq!(path, "/referral/stats");
-}
-
-/// Regression: a 401 for an API-key-authenticated request must classify as
-/// `BackendApiError::ApiKeyRejected`, not `Unauthorized`. `Unauthorized` is
-/// what `flatten_authed_error` maps onto the `SESSION_EXPIRED` sentinel, and
-/// `core/jsonrpc.rs`'s `is_session_expired_error` treats that sentinel as
-/// "clear the app session and sign out" — the wrong recovery for a
-/// library-mode runtime that authenticates with an API key and has no
-/// session at all.
-#[tokio::test]
-async fn authed_json_surfaces_api_key_rejected_not_unauthorized_on_401() {
- use crate::security::credentials::session_support::BackendCredential;
-
- let app = Router::new().route(
- "/teams/me/usage",
- get(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- let base_url = format!("http://{addr}");
- let client = BackendClient::new(&base_url).unwrap();
-
- let err = client
- .authed_json(
- BackendCredential::ApiKey("th_test_key".to_string()),
- Method::GET,
- "/teams/me/usage",
- None,
- )
- .await
- .unwrap_err();
- let typed = err.downcast_ref::<BackendApiError>().unwrap();
- let BackendApiError::ApiKeyRejected { method, path } = typed else {
- panic!("expected ApiKeyRejected for an api-key credential, got {typed:?}");
- };
- assert_eq!(method, "GET");
- assert_eq!(path, "/teams/me/usage");
-
- // The flattened message must NOT carry the `SESSION_EXPIRED` sentinel —
- // that would make `core/jsonrpc.rs::is_session_expired_error` clear an
- // app session that was never the problem.
- let flattened = flatten_authed_error(err);
- assert!(
- !flattened.contains("SESSION_EXPIRED"),
- "an api-key 401 must not trigger session-expiry recovery: {flattened}"
- );
- assert!(flattened.contains("API_KEY_REJECTED"), "{flattened}");
-
- // A session credential on the same endpoint still classifies as the
- // original `Unauthorized` / `SESSION_EXPIRED` path — this fix must not
- // regress the existing session-expiry recovery.
- let err = client
- .authed_json(
- BackendCredential::Session("mock-jwt".to_string()),
- Method::GET,
- "/teams/me/usage",
- None,
- )
- .await
- .unwrap_err();
- let typed = err.downcast_ref::<BackendApiError>().unwrap();
- assert!(
- matches!(typed, BackendApiError::Unauthorized { .. }),
- "expected Unauthorized for a session credential, got {typed:?}"
- );
- assert!(flatten_authed_error(err).contains("SESSION_EXPIRED"));
-}
-
-#[test]
-fn backend_api_body_shape_emits_safe_keys_not_values() {
- // PII guard (Codex P1 on #4058): the body SHAPE must expose only schema-like
- // top-level key NAMES and NEVER the values — a non-2xx body can carry emails /
- // tokens / profile JSON that would otherwise leak to unscrubbed daily logs.
- let body = r#"{"error":"not found","email":"[email protected]","token":"sk-secret"}"#;
- let shape = backend_api_body_shape(body);
- assert_eq!(shape, "object(keys=3,safe=[email,error,token],redacted=0)");
- assert!(!shape.contains("[email protected]"), "value leaked: {shape}");
- assert!(!shape.contains("sk-secret"), "value leaked: {shape}");
- assert!(!shape.contains("not found"), "value leaked: {shape}");
-}
-
-#[test]
-fn backend_api_body_shape_redacts_pii_and_nonidentifier_keys() {
- // CodeRabbit Major on #4058: key NAMES are response-controlled too. A foreign
- // backend can put an email / free text / unicode in the KEY position; those
- // must be counted as `redacted`, never echoed.
- let body = r#"{"[email protected]":1,"a b":2,"naïve":3,"error":4}"#;
- let shape = backend_api_body_shape(body);
- // Only the schema-like `error` survives; the other three are redacted.
- assert_eq!(shape, "object(keys=4,safe=[error],redacted=3)");
- assert!(!shape.contains("[email protected]"), "PII key leaked: {shape}");
- assert!(!shape.contains("naïve"), "non-ascii key leaked: {shape}");
- assert!(!shape.contains("a b"), "free-text key leaked: {shape}");
-}
-
-#[test]
-fn backend_api_body_shape_classifies_non_object_bodies() {
- assert_eq!(backend_api_body_shape(""), "empty");
- assert_eq!(backend_api_body_shape(" "), "empty");
- assert_eq!(
- backend_api_body_shape("Cannot GET /teams/me/usage"),
- "non_json"
- );
- assert_eq!(backend_api_body_shape("<html>404</html>"), "non_json");
- assert_eq!(backend_api_body_shape("[1,2,3]"), "array");
- assert_eq!(backend_api_body_shape("42"), "scalar");
-}
-
-#[test]
-fn backend_api_body_shape_bounds_long_safe_key_list() {
- // The `safe=[…]` list is truncated at BACKEND_API_BODY_SHAPE_MAX_BYTES = 120.
- // Surviving keys are ASCII identifiers (non-ASCII keys are redacted upstream),
- // so build many ASCII keys to overflow the cap and assert the truncation
- // CONTRACT: bounded, ellipsis-terminated, and not carrying the last key.
- let mut obj = serde_json::Map::new();
- for i in 0..30 {
- obj.insert(format!("field{i:02}"), json!(1)); // 30 × "fieldNN" (7 bytes) ≫ 120
- }
- let body = serde_json::to_string(&Value::Object(obj)).unwrap();
- let shape = backend_api_body_shape(&body);
-
- let keys = shape
- .strip_prefix("object(keys=30,safe=[")
- .and_then(|s| s.strip_suffix("],redacted=0)"))
- .unwrap_or_else(|| panic!("unexpected shape: {shape}"));
- assert!(
- keys.len() <= BACKEND_API_BODY_SHAPE_MAX_BYTES,
- "safe list exceeds cap ({} > {BACKEND_API_BODY_SHAPE_MAX_BYTES}): {keys}",
- keys.len()
- );
- assert!(keys.ends_with('…'), "expected ellipsis-terminated: {keys}");
- assert!(
- !keys.contains("field29"),
- "last key should be truncated away: {keys}"
- );
-}
-
-#[path = "client_channel_tests.rs"]
-mod channel_tests;
diff --git a/crates/openhuman-core/src/backend/mod.rs b/crates/openhuman-core/src/backend/mod.rs
deleted file mode 100644
index 1aed951924..0000000000
--- a/crates/openhuman-core/src/backend/mod.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-//! The backend port: how the core reaches a hosted backend it knows nothing
-//! about.
-//!
-//! The core holds no hosted-backend URL, header policy, product identity or
-//! SDK. A host installs a [`BackendTransport`] (`openhuman-tinyhumans` installs
-//! the TinyHumans one) and the core asks it for everything host-specific:
-//!
-//! - [`transport`] — the port itself: [`BackendTransport`], [`BackendRequest`],
-//! [`BackendTransportError`] and the process-wide install slot. The transport
-//! sends requests *and* answers [`base_url`] / [`inference_base_url`]
-//! (defaults, environment overrides, the inference-endpoint guard) and
-//! [`product_identity`].
-//! - [`client`] — [`BackendClient`]: authenticated JSON calls over the port,
-//! the typed [`BackendApiError`] results domains recover from, and
-//! [`flatten_authed_error`], the chokepoint that turns them into the
-//! `SESSION_EXPIRED:` / `API_KEY_REJECTED:` / `BACKEND_UNAVAILABLE:`
-//! sentinels `core::observability` classifies.
-//!
-//! A core with no transport installed runs agents, memory, tools and RPC as
-//! normal; every backend-touching call answers
-//! [`BackendApiError::BackendUnavailable`] / `BACKEND_UNAVAILABLE:`, and the
-//! URL helpers here return [`BackendTransportError::Unavailable`].
-
-pub mod classify;
-pub mod client;
-pub mod transport;
-
-pub use client::{flatten_authed_error, BackendApiError, BackendClient};
-pub use transport::{
- install_backend_transport, installed_backend_transport, is_installed,
- resolve_backend_transport, BackendRequest, BackendTransport, BackendTransportError,
- BaseUrlPurpose, TransportProfile,
-};
-
-/// The operator's override, trimmed; `None` when unset or blank.
-fn configured(api_url: &Option<String>) -> Option<&str> {
- api_url.as_deref().map(str::trim).filter(|s| !s.is_empty())
-}
-
-/// The backend origin for control-plane calls (account, integrations,
-/// channels, voice, sockets, telemetry), resolved by the installed transport
-/// from the configured `api_url` override.
-pub fn base_url(api_url: &Option<String>) -> Result<String, BackendTransportError> {
- let transport = resolve_backend_transport()?;
- Ok(transport.base_url(configured(api_url), BaseUrlPurpose::ControlPlane))
-}
-
-/// [`base_url`] for callers on the JSON-RPC `String` error channel: a missing
-/// transport becomes the `BACKEND_UNAVAILABLE:` sentinel `core::observability`
-/// demotes, so a core without a hosted backend never pages Sentry for it.
-pub fn require_base_url(api_url: &Option<String>) -> Result<String, String> {
- base_url(api_url).map_err(|error| match error {
- BackendTransportError::Unavailable => format!(
- "{} no backend transport installed",
- crate::core::observability::BACKEND_UNAVAILABLE_PREFIX
- ),
- other => other.to_string(),
- })
-}
-
-/// The backend origin for the managed OpenAI-compatible inference proxy
-/// (chat, embeddings). Unlike [`base_url`] this honours an `api_url` override
-/// that points at an inference endpoint.
-///
-/// Managed inference talks to that URL directly rather than through the
-/// transport, so a library host with no transport installed still reaches an
-/// origin it configured explicitly (`openhuman_embed::Runtime::backend_url`).
-/// Only the *default* origin is the host's to supply: with neither a
-/// transport nor an override this is [`BackendTransportError::Unavailable`].
-pub fn inference_base_url(api_url: &Option<String>) -> Result<String, BackendTransportError> {
- match resolve_backend_transport() {
- Ok(transport) => Ok(transport.base_url(configured(api_url), BaseUrlPurpose::Inference)),
- Err(BackendTransportError::Unavailable) => configured(api_url)
- .map(crate::util::url::normalize_api_base_url)
- .ok_or(BackendTransportError::Unavailable),
- Err(other) => Err(other),
- }
-}
-
-/// The product identity the installed host attributes backend traffic to
-/// (the `x-sdk-name` value), or `None` when no transport is installed.
-pub fn product_identity() -> Option<String> {
- resolve_backend_transport()
- .ok()
- .map(|transport| transport.product_identity())
-}
-
-/// The installed host's attribution headers (see
-/// [`BackendTransport::attribution_headers`]); empty without a transport.
-pub fn attribution_headers() -> reqwest::header::HeaderMap {
- resolve_backend_transport()
- .map(|transport| transport.attribution_headers())
- .unwrap_or_default()
-}
-
-#[cfg(test)]
-#[path = "mod_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/backend/mod_tests.rs b/crates/openhuman-core/src/backend/mod_tests.rs
deleted file mode 100644
index 3b967ac288..0000000000
--- a/crates/openhuman-core/src/backend/mod_tests.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use super::*;
-
-#[test]
-fn base_urls_come_from_the_transport_and_honour_the_override() {
- // Under `cfg(test)` the plain transport answers: the configured origin,
- // or a loopback discard port when nothing is configured.
- let configured = Some(" http://127.0.0.1:4010/openai/v1/chat/completions ".to_string());
- assert_eq!(base_url(&configured).unwrap(), "http://127.0.0.1:4010");
- assert_eq!(
- inference_base_url(&configured).unwrap(),
- "http://127.0.0.1:4010"
- );
- assert_eq!(
- base_url(&Some(" ".to_string())).unwrap(),
- transport::plain::TEST_FALLBACK_BASE_URL
- );
- assert_eq!(
- base_url(&None).unwrap(),
- transport::plain::TEST_FALLBACK_BASE_URL
- );
-}
-
-#[test]
-fn product_identity_comes_from_the_transport() {
- assert_eq!(
- product_identity().as_deref(),
- Some(transport::plain::TEST_PRODUCT_IDENTITY)
- );
-}
-
-#[test]
-fn require_base_url_resolves_through_the_transport() {
- let configured = Some("http://127.0.0.1:4010".to_string());
- assert_eq!(
- require_base_url(&configured).unwrap(),
- "http://127.0.0.1:4010"
- );
-}
-
-#[test]
-fn attribution_headers_come_from_the_transport() {
- let headers = attribution_headers();
- assert_eq!(
- headers
- .get(transport::plain::TEST_PRODUCT_HEADER)
- .and_then(|v| v.to_str().ok()),
- Some(transport::plain::TEST_PRODUCT_IDENTITY)
- );
-}
diff --git a/crates/openhuman-core/src/backend/transport/README.md b/crates/openhuman-core/src/backend/transport/README.md
deleted file mode 100644
index ab35561be9..0000000000
--- a/crates/openhuman-core/src/backend/transport/README.md
+++ /dev/null
@@ -1,81 +0,0 @@
-# Transport
-
-The port the core uses to reach the hosted TinyHumans backend. It defines the
-one HTTP primitive every backend-bound call rides, but carries no
-implementation of its own. The core owns routes and error classification; an
-implementation of this trait owns TLS, timeouts, redirects, and the SDK's
-route policy.
-
-This split is what keeps `tinyhumans-sdk` out of the core. A core built
-without a transport still runs agents, memory, tools, and RPC. Every call
-that would touch the backend degrades to `BackendTransportError::Unavailable`
-(`BACKEND_UNAVAILABLE:` at the RPC boundary) instead of failing to compile or
-panicking.
-
-## Layout
-
-| File | Purpose |
-| --- | --- |
-| [`mod.rs`](./mod.rs) | `BackendTransport` trait, `BackendRequest`, `TransportProfile`, `credential_headers`, `parse_body_text`, `unwrap_envelope`, `compose_url` |
-| [`error.rs`](./error.rs) | `BackendTransportError`, the core-owned mirror of the variants classifiers match on |
-| [`install.rs`](./install.rs) | Process-global install/resolve for the transport, plus the `CoreContext`-scoped lookup |
-| [`plain.rs`](./plain.rs) | `cfg(test)`-only reqwest transport, so this crate's tests do not need a host crate |
-| [`transport_tests.rs`](./transport_tests.rs) | Tests for `mod.rs` (included via `#[path]`) |
-
-## Key types
-
-`BackendTransport` is the trait a transport implements:
-
-```rust
-async fn send_json(&self, req: BackendRequest<'_>) -> Result<Value, BackendTransportError>;
-async fn send_multipart(&self, req: BackendRequest<'_>, form: Form) -> Result<Value, BackendTransportError>;
-fn http_client(&self, profile: TransportProfile) -> reqwest::Client;
-fn name(&self) -> &'static str;
-```
-
-`BackendRequest` fully describes one round trip: the `TransportProfile`
-(`Api` for control-plane REST, `Integrations` for `/agent-integrations/*`),
-base URL, method, path, query, JSON body, an optional `BackendCredential`
-(session JWT rides as `Authorization: Bearer`, an API key as `x-api-key`),
-and whether the `{success, data}` envelope should be unwrapped.
-`BackendTransportError` covers `Unavailable`, `Url`, `Http` (wraps the
-`reqwest::Error` so classifiers can still walk its source chain), `Status`,
-`Envelope`, `Header`, `Decode`, `RouteNotExposed`, and `Other`.
-
-Implementations are process-wide singletons (`Arc<dyn BackendTransport>`)
-and must be safe to call concurrently.
-
-## Resolution
-
-`resolve_backend_transport` tries, in order: the transport bound to the
-ambient `CoreContext` (set via `CoreBuilder::backend_transport`, inherited by
-`derive_with`), then the process global set by `install_backend_transport`
-(what the desktop shell, TUI, and CLI use, since they boot the core through
-`openhuman_rpc::host` / `run_core_from_args` rather than the
-builder), then, under `cfg(test)` only, the `plain.rs` fallback. Outside
-tests, a miss returns `Err(BackendTransportError::Unavailable)`. There is no
-implicit production fallback.
-
-## How it fits
-
-Everything else under `crates/openhuman-core/src/api/` (routes in `rest.rs`,
-attribution headers in `headers.rs`, URL resolution in `config.rs`) calls
-through this trait rather than building `reqwest` requests directly. The
-only production implementation is `SdkBackendTransport` in
-[`crates/openhuman-tinyhumans`](../../../../openhuman-tinyhumans/), built on top of the vendored `tinyhumans-sdk`,
-and installed once per process by `openhuman_tinyhumans::install` (or
-`RuntimeBuilder` for library hosts, or `CoreBuilder::backend_transport`).
-
-## Where next
-
-Read `crates/openhuman-core/src/api/README.md` for the routes and error
-classification that sit above this port, and `crates/openhuman-tinyhumans/`
-for the real transport and how it maps SDK errors onto
-`BackendTransportError`.
-
-## Further reading
-
-- [Parent module README](../README.md)
-- [One TinyHumans API key](../../../../../docs/gitbooks/en/developing/tinyhumans-api-key.md)
-- [openhuman-tinyhumans crate](../../../../openhuman-tinyhumans/README.md)
-- [tinyhumans-sdk](../../../../../vendor/tinyhumans-sdk/README.md)
diff --git a/crates/openhuman-core/src/backend/transport/error.rs b/crates/openhuman-core/src/backend/transport/error.rs
deleted file mode 100644
index a2975cb205..0000000000
--- a/crates/openhuman-core/src/backend/transport/error.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-//! The error a [`BackendTransport`](super::BackendTransport) returns.
-//!
-//! This is the core-owned image of the variants the classification code in
-//! [`crate::backend::client`] 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 },
- /// `404` on a channel-message route answered by a backend handler: that
- /// message no longer exists (deleted provider-side or garbage-collected).
- #[error("http 404: channel message {provider}/{message_id} not found")]
- ChannelMessageNotFound {
- /// Channel provider path segment (`telegram`, `discord`, …).
- provider: String,
- /// Provider message id from the path.
- message_id: String,
- },
- /// `404` on a channel-message route because the backend has **no such
- /// route** (no handler matched), not because the message is gone. Today
- /// this is every `PATCH` edit (#5230): the message still exists and the
- /// caller must keep its id.
- #[error("http 404: backend implements no route for channel message {provider}/{message_id}")]
- ChannelMessageRouteMissing {
- /// Channel provider path segment.
- provider: String,
- /// Provider message id from the path.
- message_id: String,
- },
- /// 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),
- Self::ChannelMessageNotFound { .. } | Self::ChannelMessageRouteMissing { .. } => {
- Some(404)
- }
- _ => None,
- }
- }
-}
diff --git a/crates/openhuman-core/src/backend/transport/install.rs b/crates/openhuman-core/src/backend/transport/install.rs
deleted file mode 100644
index 784275c2b1..0000000000
--- a/crates/openhuman-core/src/backend/transport/install.rs
+++ /dev/null
@@ -1,113 +0,0 @@
-//! 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`]
-//! (per thread under `cfg(test)`, so installs cannot leak between tests)
-//! — the path the desktop shell and CLI use, because they boot the core
-//! through `openhuman_rpc::host` / `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, RwLock};
-
-use super::{BackendTransport, BackendTransportError};
-
-#[cfg(not(test))]
-fn slot() -> &'static RwLock<Option<Arc<dyn BackendTransport>>> {
- use std::sync::OnceLock;
- static GLOBAL: OnceLock<RwLock<Option<Arc<dyn BackendTransport>>>> = OnceLock::new();
- GLOBAL.get_or_init(|| RwLock::new(None))
-}
-
-/// Under `cfg(test)` the "global" slot is per thread: a test that installs a
-/// fake transport (always-unavailable, canned responses) must not leak it into
-/// the wiremock tests running in parallel, which resolve the plain fallback.
-/// Every test that installs one runs on a single thread.
-#[cfg(test)]
-fn slot() -> &'static RwLock<Option<Arc<dyn BackendTransport>>> {
- thread_local! {
- static SLOT: &'static RwLock<Option<Arc<dyn BackendTransport>>> =
- Box::leak(Box::new(RwLock::new(None)));
- }
- SLOT.with(|slot| *slot)
-}
-
-/// 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)]
- {
- Ok(super::plain::PlainHttpTransport::fresh())
- }
- #[cfg(not(test))]
- {
- log::debug!("[backend-transport] no transport installed; backend unavailable");
- Err(BackendTransportError::Unavailable)
- }
-}
-
-/// Whether a backend call made right now would find a transport (see
-/// [`resolve_backend_transport`]). Paths that talk to the backend host
-/// directly instead of through the port (the Langfuse proxy push, the socket,
-/// channel reply delivery, browser-task module config) check this first, so a
-/// core running without a TinyHumans connection skips them quietly instead of
-/// reaching a backend it was never connected to.
-pub fn is_installed() -> bool {
- resolve_backend_transport().is_ok()
-}
diff --git a/crates/openhuman-core/src/backend/transport/mod.rs b/crates/openhuman-core/src/backend/transport/mod.rs
deleted file mode 100644
index 53c19220a8..0000000000
--- a/crates/openhuman-core/src/backend/transport/mod.rs
+++ /dev/null
@@ -1,259 +0,0 @@
-//! The backend port: how the core reaches the hosted TinyHumans backend
-//! without depending on the SDK that speaks to it.
-//!
-//! The core owns the *routes* (`/payments/summary`,
-//! `/agent-integrations/...`, `channels/{c}/messages`, ...) and the error
-//! *classification* ([`crate::backend::client`], `integrations/client/errors.rs`).
-//! What it does not own is the HTTP primitive that carries a request with the
-//! right credential header shape and route policy. That is a
-//! [`BackendTransport`], and the only production implementation lives in the
-//! `openhuman-tinyhumans` crate on top of the vendored `tinyhumans-sdk`. A core
-//! built without that crate has no transport and every backend-touching call
-//! degrades to [`BackendTransportError::Unavailable`] — the core keeps running
-//! agents, memory, tools and RPC without any TinyHumans connection.
-//!
-//! See [`install`] for how a transport reaches the core at runtime.
-
-use async_trait::async_trait;
-use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
-use reqwest::Method;
-use serde_json::Value;
-
-use crate::security::credentials::session_support::BackendCredential;
-
-pub mod error;
-pub mod install;
-#[cfg(test)]
-pub mod plain;
-
-pub use error::BackendTransportError;
-pub use install::{
- clear_backend_transport, install_backend_transport, installed_backend_transport, is_installed,
- resolve_backend_transport,
-};
-
-/// One `(name, value)` query pair; a `None` value omits the pair.
-pub type QueryParam = (&'static str, Option<String>);
-
-/// Which pre-built HTTP client profile a request rides. The two profiles
-/// preserve the historically distinct `reqwest` configurations of
-/// [`crate::backend::BackendClient`] and
-/// `integrations::client::IntegrationClient`; the transport builds one
-/// `reqwest::Client` per profile.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub enum TransportProfile {
- /// Control-plane REST (`/auth/*`, `/payments/*`, `/channels/*`, ...).
- Api,
- /// Agent tool traffic (`/agent-integrations/*`).
- Integrations,
-}
-
-/// A single backend round-trip, fully described by the caller.
-#[derive(Debug)]
-pub struct BackendRequest<'a> {
- /// Client profile to send with.
- pub profile: TransportProfile,
- /// Origin of the backend. Already sanitised by the caller
- /// (`BackendClient::new`, `IntegrationClient::new`): absolute
- /// `http(s)` URL, no path, no query.
- pub base_url: &'a str,
- /// HTTP verb.
- pub method: Method,
- /// Root-relative route, with or without a leading `/`.
- pub path: &'a str,
- /// Query pairs; `None` values are omitted.
- pub query: &'a [QueryParam],
- /// JSON body, if any.
- pub body: Option<&'a Value>,
- /// The credential to present. A session JWT rides as `Authorization:
- /// Bearer`, an API key as `x-api-key`; `None` sends an anonymous request.
- pub credential: Option<&'a BackendCredential>,
- /// Whether a `{success, data}` envelope is unwrapped before the value is
- /// returned (`success: false` then becomes
- /// [`BackendTransportError::Envelope`]).
- pub unwrap_envelope: bool,
-}
-
-impl<'a> BackendRequest<'a> {
- /// A request with no query, no body and no credential.
- pub fn new(
- profile: TransportProfile,
- base_url: &'a str,
- method: Method,
- path: &'a str,
- ) -> Self {
- Self {
- profile,
- base_url,
- method,
- path,
- query: &[],
- body: None,
- credential: None,
- unwrap_envelope: true,
- }
- }
-}
-
-/// The HTTP primitive every backend-bound call in the core goes through.
-///
-/// Implementations are process-wide singletons (`Arc<dyn BackendTransport>`)
-/// and must be cheap to call concurrently. They own TLS, timeouts, redirect
-/// and route policy; the core supplies routes, credentials and classification.
-#[async_trait]
-pub trait BackendTransport: Send + Sync + 'static {
- /// Send `req` and return the (optionally envelope-unwrapped) JSON body.
- async fn send_json(&self, req: BackendRequest<'_>) -> Result<Value, BackendTransportError>;
-
- /// `POST` a `multipart/form-data` body to `req.path` and return the
- /// envelope-unwrapped JSON body. `req.body` is ignored.
- async fn send_multipart(
- &self,
- req: BackendRequest<'_>,
- form: reqwest::multipart::Form,
- ) -> Result<Value, BackendTransportError>;
-
- /// The configured `reqwest::Client` for `profile`, for callers that drive a
- /// non-JSON request shape themselves (multipart STT upload). Carries the
- /// profile's TLS settings and attribution headers, but **no** credential.
- fn http_client(&self, profile: TransportProfile) -> reqwest::Client;
-
- /// The backend origin for `purpose`, given the operator's configured
- /// override (`config.api_url`, already trimmed; `None` when unset).
- ///
- /// The transport owns defaults, environment overrides and any guard
- /// against an override that is really an inference endpoint — the core
- /// knows none of the hosted backend's URLs.
- fn base_url(&self, configured: Option<&str>, purpose: BaseUrlPurpose) -> String;
-
- /// The product identity this host attributes backend traffic to (the
- /// `x-sdk-name` value), for callers that hand it to a module or header
- /// the transport does not build itself.
- fn product_identity(&self) -> String;
-
- /// The attribution headers this host stamps on backend traffic
- /// (product identity, client versions), for a caller that must reach the
- /// backend with a client the transport did not build (the managed model
- /// catalog rides the generic provider client).
- fn attribution_headers(&self) -> HeaderMap;
-
- /// Short stable name for logs (`"tinyhumans-sdk"`, `"plain-test"`).
- fn name(&self) -> &'static str;
-}
-
-/// What a backend base URL is for. The two differ only in how an operator
-/// override is treated: control-plane calls must never land on an inference
-/// endpoint the user pointed `api_url` at, while managed inference honours it
-/// as-is.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub enum BaseUrlPurpose {
- /// Account, integrations, channels, voice, sockets, telemetry.
- ControlPlane,
- /// The OpenAI-compatible inference proxy (chat, embeddings, models).
- Inference,
-}
-
-/// Header the backend expects a TinyHumans API key on.
-pub const API_KEY_HEADER: &str = "x-api-key";
-
-/// The header a [`BackendCredential`] rides on: session JWT as
-/// `Authorization: Bearer`, API key as `x-api-key`. Shared by transport
-/// implementations that shape headers themselves.
-pub fn credential_headers(
- credential: &BackendCredential,
-) -> Result<HeaderMap, BackendTransportError> {
- let secret = credential.secret().trim();
- let mut headers = HeaderMap::new();
- match credential {
- BackendCredential::Session(_) => {
- headers.insert(
- AUTHORIZATION,
- HeaderValue::from_str(&format!("Bearer {secret}"))
- .map_err(|e| BackendTransportError::Header(e.to_string()))?,
- );
- }
- BackendCredential::ApiKey(_) => {
- log::trace!("[backend-transport] authenticating request with x-api-key");
- headers.insert(
- API_KEY_HEADER,
- HeaderValue::from_str(secret)
- .map_err(|e| BackendTransportError::Header(e.to_string()))?,
- );
- }
- }
- Ok(headers)
-}
-
-/// Parse a response body the way the backend transports do: empty → `Null`,
-/// JSON → the value, anything else → the raw text as a JSON string.
-pub fn parse_body_text(text: String) -> Value {
- if text.is_empty() {
- Value::Null
- } else {
- serde_json::from_str(&text).unwrap_or(Value::String(text))
- }
-}
-
-/// Unwrap the hosted-backend `{success, data}` envelope.
-///
-/// `success: false` becomes [`BackendTransportError::Envelope`]: the backend
-/// pairs a failed operation with an unsuccessful envelope that is not always
-/// accompanied by a non-2xx status. A successful envelope with no `data` key
-/// yields the remaining fields with `success` removed, so envelopes that
-/// inline their payload (`{success, jwt}`) do not leak the flag.
-pub fn unwrap_envelope(body: Value) -> Result<Value, BackendTransportError> {
- let Value::Object(mut map) = body else {
- return Ok(body);
- };
- match map.get("success").and_then(Value::as_bool) {
- Some(true) => {
- if let Some(data) = map.remove("data") {
- return Ok(data);
- }
- map.remove("success");
- Ok(Value::Object(map))
- }
- Some(false) => Err(BackendTransportError::Envelope {
- error: map
- .get("error")
- .or_else(|| map.get("message"))
- .and_then(Value::as_str)
- .unwrap_or("request unsuccessful")
- .to_owned(),
- error_code: map
- .get("errorCode")
- .and_then(Value::as_str)
- .map(str::to_owned),
- details: map.get("details").cloned().unwrap_or(Value::Null),
- }),
- None => Ok(Value::Object(map)),
- }
-}
-
-/// Compose `base_url` + `path` + `query` into the request URL.
-pub fn compose_url(
- base_url: &str,
- path: &str,
- query: &[QueryParam],
-) -> Result<reqwest::Url, BackendTransportError> {
- let base = base_url.trim().trim_end_matches('/');
- let normalized = if path.starts_with('/') {
- path.to_owned()
- } else {
- format!("/{path}")
- };
- let mut url = reqwest::Url::parse(&format!("{base}{normalized}"))
- .map_err(|e| BackendTransportError::Url(e.to_string()))?;
- let pairs: Vec<(&str, String)> = query
- .iter()
- .filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.clone())))
- .collect();
- if !pairs.is_empty() {
- url.query_pairs_mut().extend_pairs(pairs);
- }
- Ok(url)
-}
-
-#[cfg(test)]
-#[path = "transport_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/backend/transport/plain.rs b/crates/openhuman-core/src/backend/transport/plain.rs
deleted file mode 100644
index 60e61d3f0b..0000000000
--- a/crates/openhuman-core/src/backend/transport/plain.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-//! Test-only `reqwest` transport so the core's wiremock unit tests exercise
-//! [`BackendClient`](crate::backend::BackendClient) and
-//! `IntegrationClient` without any host crate. Never compiled into a
-//! production build: [`resolve_backend_transport`](super::resolve_backend_transport)
-//! only reaches it under `cfg(test)`.
-//!
-//! Deliberately *not* a copy of the SDK transport: it applies no route policy
-//! and sends no `x-sdk-client`. The `openhuman-tinyhumans` crate carries a
-//! parity test pinning the headers and envelope behaviour both share.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use reqwest::header::CONTENT_TYPE;
-use reqwest::Method;
-use serde_json::Value;
-
-use super::{
- compose_url, credential_headers, parse_body_text, unwrap_envelope, BackendRequest,
- BackendTransport, BackendTransportError, BaseUrlPurpose, TransportProfile,
-};
-
-/// Attribution header the test transport stamps, mirroring the host's.
-pub const TEST_PRODUCT_HEADER: &str = "x-sdk-name";
-/// Product identity the test transport reports and stamps.
-pub const TEST_PRODUCT_IDENTITY: &str = "openhuman";
-/// Base URL for a test that configured none: the discard port on loopback.
-pub const TEST_FALLBACK_BASE_URL: &str = "http://127.0.0.1:9";
-
-fn plain_client() -> reqwest::Client {
- reqwest::Client::builder()
- .timeout(std::time::Duration::from_secs(30))
- .build()
- .expect("plain test client")
-}
-
-pub struct PlainHttpTransport {
- api: reqwest::Client,
- integrations: reqwest::Client,
-}
-
-impl PlainHttpTransport {
- pub fn new() -> Self {
- Self {
- api: plain_client(),
- integrations: plain_client(),
- }
- }
-
- /// A fresh instance (building two `reqwest::Client`s is cheap).
- pub fn fresh() -> Arc<dyn BackendTransport> {
- Arc::new(Self::new())
- }
-
- fn client(&self, profile: TransportProfile) -> &reqwest::Client {
- match profile {
- TransportProfile::Api => &self.api,
- TransportProfile::Integrations => &self.integrations,
- }
- }
-
- async fn finish(
- response: reqwest::Response,
- unwrap: bool,
- ) -> Result<Value, BackendTransportError> {
- let status = response.status();
- let value = parse_body_text(response.text().await?);
- if !status.is_success() {
- return Err(BackendTransportError::Status {
- status: status.as_u16(),
- body: value,
- });
- }
- if unwrap {
- unwrap_envelope(value)
- } else {
- Ok(value)
- }
- }
-}
-
-impl Default for PlainHttpTransport {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl BackendTransport for PlainHttpTransport {
- async fn send_json(&self, req: BackendRequest<'_>) -> Result<Value, BackendTransportError> {
- let url = compose_url(req.base_url, req.path, req.query)?;
- let mut request = self
- .client(req.profile)
- .request(req.method, url)
- .header(TEST_PRODUCT_HEADER, TEST_PRODUCT_IDENTITY)
- .header(reqwest::header::ACCEPT, "application/json")
- .header(CONTENT_TYPE, "application/json");
- if let Some(credential) = req.credential {
- request = request.headers(credential_headers(credential)?);
- }
- if let Some(body) = req.body {
- request = request.json(body);
- }
- Self::finish(request.send().await?, req.unwrap_envelope).await
- }
-
- async fn send_multipart(
- &self,
- req: BackendRequest<'_>,
- form: reqwest::multipart::Form,
- ) -> Result<Value, BackendTransportError> {
- let url = compose_url(req.base_url, req.path, &[])?;
- let mut request = self
- .client(req.profile)
- .request(Method::POST, url)
- .header(TEST_PRODUCT_HEADER, TEST_PRODUCT_IDENTITY)
- .header(reqwest::header::ACCEPT, "application/json");
- if let Some(credential) = req.credential {
- request = request.headers(credential_headers(credential)?);
- }
- Self::finish(request.multipart(form).send().await?, true).await
- }
-
- fn http_client(&self, profile: TransportProfile) -> reqwest::Client {
- self.client(profile).clone()
- }
-
- fn base_url(&self, configured: Option<&str>, _purpose: BaseUrlPurpose) -> String {
- // No defaults here: a test that reaches the backend points
- // `api_url` at its mock server. The fallback is a discard port so an
- // unconfigured test can never reach a real host.
- configured
- .map(crate::util::url::normalize_backend_api_base_url)
- .filter(|url| !url.is_empty())
- .unwrap_or_else(|| TEST_FALLBACK_BASE_URL.to_string())
- }
-
- fn product_identity(&self) -> String {
- TEST_PRODUCT_IDENTITY.to_string()
- }
-
- fn attribution_headers(&self) -> reqwest::header::HeaderMap {
- let mut headers = reqwest::header::HeaderMap::new();
- headers.insert(
- TEST_PRODUCT_HEADER,
- reqwest::header::HeaderValue::from_static(TEST_PRODUCT_IDENTITY),
- );
- headers
- }
-
- fn name(&self) -> &'static str {
- "plain-test"
- }
-}
diff --git a/crates/openhuman-core/src/backend/transport/transport_tests.rs b/crates/openhuman-core/src/backend/transport/transport_tests.rs
deleted file mode 100644
index 15c6f962c9..0000000000
--- a/crates/openhuman-core/src/backend/transport/transport_tests.rs
+++ /dev/null
@@ -1,318 +0,0 @@
-use super::*;
-use crate::security::credentials::session_support::BackendCredential;
-use serde_json::json;
-use std::sync::Arc;
-use wiremock::matchers::{header, method, path};
-use wiremock::{Mock, MockServer, ResponseTemplate};
-
-struct NamedTransport(&'static str);
-
-#[async_trait]
-impl BackendTransport for NamedTransport {
- async fn send_json(&self, _req: BackendRequest<'_>) -> Result<Value, BackendTransportError> {
- Ok(json!({"from": self.0}))
- }
-
- async fn send_multipart(
- &self,
- _req: BackendRequest<'_>,
- _form: reqwest::multipart::Form,
- ) -> Result<Value, BackendTransportError> {
- Ok(Value::Null)
- }
-
- fn http_client(&self, _profile: TransportProfile) -> reqwest::Client {
- reqwest::Client::new()
- }
-
- // URL and attribution answers delegate to the plain transport: this
- // double is installed process-wide while other tests resolve base URLs.
- fn base_url(&self, configured: Option<&str>, purpose: BaseUrlPurpose) -> String {
- plain::PlainHttpTransport::new().base_url(configured, purpose)
- }
-
- fn product_identity(&self) -> String {
- plain::TEST_PRODUCT_IDENTITY.to_string()
- }
-
- fn attribution_headers(&self) -> reqwest::header::HeaderMap {
- plain::PlainHttpTransport::new().attribution_headers()
- }
-
- fn name(&self) -> &'static str {
- self.0
- }
-}
-
-/// The global slot is process state; serialise the tests that touch it.
-fn global_lock() -> &'static tokio::sync::Mutex<()> {
- static LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
- LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
-}
-
-#[test]
-fn unwrap_envelope_returns_data_and_strips_success_flag() {
- assert_eq!(
- unwrap_envelope(json!({"success": true, "data": {"a": 1}})).unwrap(),
- json!({"a": 1})
- );
- assert_eq!(
- unwrap_envelope(json!({"success": true, "jwt": "t"})).unwrap(),
- json!({"jwt": "t"})
- );
- assert_eq!(
- unwrap_envelope(json!({"plain": true})).unwrap(),
- json!({"plain": true})
- );
- assert_eq!(unwrap_envelope(json!([1, 2])).unwrap(), json!([1, 2]));
-}
-
-#[test]
-fn unwrap_envelope_turns_failure_into_typed_error() {
- let err = unwrap_envelope(json!({
- "success": false,
- "error": "Insufficient balance",
- "errorCode": "E_BAL",
- "details": {"needed": 3}
- }))
- .unwrap_err();
- match err {
- BackendTransportError::Envelope {
- error,
- error_code,
- details,
- } => {
- assert_eq!(error, "Insufficient balance");
- assert_eq!(error_code.as_deref(), Some("E_BAL"));
- assert_eq!(details, json!({"needed": 3}));
- }
- other => panic!("expected Envelope, got {other:?}"),
- }
- // `message` is accepted as the failure text, and a bare `success:false`
- // still fails with a generic reason rather than being handed back as data.
- assert!(matches!(
- unwrap_envelope(json!({"success": false, "message": "nope"})),
- Err(BackendTransportError::Envelope { error, .. }) if error == "nope"
- ));
- assert!(matches!(
- unwrap_envelope(json!({"success": false})),
- Err(BackendTransportError::Envelope { error, .. }) if error == "request unsuccessful"
- ));
-}
-
-#[test]
-fn credential_headers_put_session_on_bearer_and_api_key_on_x_api_key() {
- let session =
- credential_headers(&BackendCredential::Session(" jwt.token.sig \n".into())).unwrap();
- assert_eq!(
- session.get(reqwest::header::AUTHORIZATION).unwrap(),
- "Bearer jwt.token.sig"
- );
- assert!(session.get(API_KEY_HEADER).is_none());
-
- let key = credential_headers(&BackendCredential::ApiKey("th_key".into())).unwrap();
- assert_eq!(key.get(API_KEY_HEADER).unwrap(), "th_key");
- assert!(key.get(reqwest::header::AUTHORIZATION).is_none());
-}
-
-#[test]
-fn compose_url_joins_base_path_and_omits_none_query_values() {
- let url = compose_url(
- "https://api.example.test/",
- "teams/me/usage",
- &[("a", Some("1".into())), ("b", None)],
- )
- .unwrap();
- assert_eq!(url.as_str(), "https://api.example.test/teams/me/usage?a=1");
- let url = compose_url("https://api.example.test", "/x", &[]).unwrap();
- assert_eq!(url.as_str(), "https://api.example.test/x");
- assert!(matches!(
- compose_url("not a url", "/x", &[]),
- Err(BackendTransportError::Url(_))
- ));
-}
-
-#[test]
-fn parse_body_text_handles_empty_json_and_plain_text() {
- assert_eq!(parse_body_text(String::new()), Value::Null);
- assert_eq!(parse_body_text("{\"a\":1}".into()), json!({"a": 1}));
- assert_eq!(parse_body_text("nope".into()), json!("nope"));
-}
-
-#[test]
-fn global_install_replaces_and_clears() {
- let _guard = global_lock().blocking_lock();
- clear_backend_transport();
- assert!(installed_backend_transport().is_none());
-
- install_backend_transport(Arc::new(NamedTransport("first")));
- assert_eq!(installed_backend_transport().unwrap().name(), "first");
-
- install_backend_transport(Arc::new(NamedTransport("second")));
- assert_eq!(installed_backend_transport().unwrap().name(), "second");
-
- clear_backend_transport();
- assert!(installed_backend_transport().is_none());
-}
-
-#[test]
-fn resolve_prefers_global_over_test_fallback() {
- let _guard = global_lock().blocking_lock();
- clear_backend_transport();
- // Under cfg(test) the plain transport is the floor, never `Unavailable`.
- assert_eq!(resolve_backend_transport().unwrap().name(), "plain-test");
-
- install_backend_transport(Arc::new(NamedTransport("host")));
- assert_eq!(resolve_backend_transport().unwrap().name(), "host");
- clear_backend_transport();
-}
-
-#[test]
-fn error_status_accessor_only_reports_status_variant() {
- assert_eq!(
- BackendTransportError::Status {
- status: 404,
- body: Value::Null
- }
- .status(),
- Some(404)
- );
- assert_eq!(BackendTransportError::Unavailable.status(), None);
-}
-
-#[tokio::test]
-async fn plain_transport_sends_attribution_and_credential_headers() {
- let server = MockServer::start().await;
- Mock::given(method("GET"))
- .and(path("/teams/me/usage"))
- .and(header("authorization", "Bearer jwt.a.b"))
- .and(header(
- plain::TEST_PRODUCT_HEADER,
- plain::TEST_PRODUCT_IDENTITY,
- ))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "success": true,
- "data": {"remainingUsd": 4.5}
- })))
- .mount(&server)
- .await;
-
- let transport = plain::PlainHttpTransport::new();
- let credential = BackendCredential::Session("jwt.a.b".into());
- let value = transport
- .send_json(BackendRequest {
- profile: TransportProfile::Api,
- base_url: &server.uri(),
- method: reqwest::Method::GET,
- path: "/teams/me/usage",
- query: &[],
- body: None,
- credential: Some(&credential),
- unwrap_envelope: true,
- })
- .await
- .unwrap();
- assert_eq!(value, json!({"remainingUsd": 4.5}));
-}
-
-#[tokio::test]
-async fn plain_transport_maps_non_2xx_to_status_and_keeps_raw_when_not_unwrapping() {
- let server = MockServer::start().await;
- Mock::given(method("POST"))
- .and(path("/agent-integrations/x"))
- .and(header(API_KEY_HEADER, "k1"))
- .respond_with(ResponseTemplate::new(402).set_body_string("Insufficient balance"))
- .mount(&server)
- .await;
- Mock::given(method("GET"))
- .and(path("/raw"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({"success": true, "data": 1})))
- .mount(&server)
- .await;
-
- let transport = plain::PlainHttpTransport::new();
- let credential = BackendCredential::ApiKey("k1".into());
- let body = json!({"q": 1});
- let err = transport
- .send_json(BackendRequest {
- profile: TransportProfile::Integrations,
- base_url: &server.uri(),
- method: reqwest::Method::POST,
- path: "agent-integrations/x",
- query: &[],
- body: Some(&body),
- credential: Some(&credential),
- unwrap_envelope: false,
- })
- .await
- .unwrap_err();
- assert!(matches!(
- err,
- BackendTransportError::Status { status: 402, ref body } if body == "Insufficient balance"
- ));
-
- let base = server.uri();
- let mut req = BackendRequest::new(TransportProfile::Api, &base, reqwest::Method::GET, "/raw");
- req.unwrap_envelope = false;
- assert_eq!(
- transport.send_json(req).await.unwrap(),
- json!({"success": true, "data": 1})
- );
-}
-
-#[tokio::test]
-async fn backend_client_reports_unavailable_when_transport_returns_unavailable() {
- struct Absent;
- #[async_trait]
- impl BackendTransport for Absent {
- async fn send_json(
- &self,
- _req: BackendRequest<'_>,
- ) -> Result<Value, BackendTransportError> {
- Err(BackendTransportError::Unavailable)
- }
- async fn send_multipart(
- &self,
- _req: BackendRequest<'_>,
- _form: reqwest::multipart::Form,
- ) -> Result<Value, BackendTransportError> {
- Err(BackendTransportError::Unavailable)
- }
- fn http_client(&self, _profile: TransportProfile) -> reqwest::Client {
- reqwest::Client::new()
- }
- fn base_url(&self, configured: Option<&str>, purpose: BaseUrlPurpose) -> String {
- plain::PlainHttpTransport::new().base_url(configured, purpose)
- }
- fn product_identity(&self) -> String {
- plain::TEST_PRODUCT_IDENTITY.to_string()
- }
- fn attribution_headers(&self) -> reqwest::header::HeaderMap {
- plain::PlainHttpTransport::new().attribution_headers()
- }
- fn name(&self) -> &'static str {
- "absent"
- }
- }
-
- let _guard = global_lock().lock().await;
- install_backend_transport(Arc::new(Absent));
- let client = crate::backend::BackendClient::new("https://api.example.test").unwrap();
- let err = client
- .authed_json("jwt", reqwest::Method::GET, "/payments/summary", None)
- .await
- .unwrap_err();
- clear_backend_transport();
-
- assert!(matches!(
- err.downcast_ref::<crate::backend::BackendApiError>(),
- Some(crate::backend::BackendApiError::BackendUnavailable { method, path })
- if method == "GET" && path == "/payments/summary"
- ));
- let flat = crate::backend::flatten_authed_error(err);
- assert!(flat.starts_with(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX));
- assert_eq!(
- crate::core::observability::expected_error_kind(&flat),
- Some(crate::core::observability::ExpectedErrorKind::BackendUnavailable)
- );
-}
diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rs
index 682d2b6a38..db5be2908d 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -53,7 +53,6 @@
#![allow(dead_code)]
pub mod agent;
-pub mod backend;
pub mod channels;
pub mod commands;
pub mod config;
diff --git a/crates/openhuman-core/src/security/credentials/mod.rs b/crates/openhuman-core/src/security/credentials/mod.rs
index aac767dcc5..30fe16ae91 100644
--- a/crates/openhuman-core/src/security/credentials/mod.rs
+++ b/crates/openhuman-core/src/security/credentials/mod.rs
@@ -16,7 +16,6 @@ pub mod sentry_scope;
pub mod session_support;
pub mod tools;
-pub use crate::backend::BackendClient;
pub use core::*;
pub use credential_ref::{CredentialRef, CredentialRefError, CredentialRefScheme, ResolvedSecret};
pub use http_creds::{