The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(inference): move managed backend model into the provider crate
Steven Enamakelc407e4626ecc
diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rsindex d7b2caeefa..66192712dd 100644--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs@@ -1,44 +1,16 @@-//! Crate-native managed OpenHuman backend as a host [`ChatModel`] (issue #4727,-//! Motion B).+//! Provider-neutral pieces of the managed provider that stay in the core: the+//! label wire errors are stamped with, and the `without_reasoning` request hint.//!-//! The managed backend can't be a plain crate `OpenAiModel` preset: it uses a-//! **dynamic** session JWT (fetched per call), emits the `thread_id` extension so-//! the backend groups InferenceLog entries + aligns KV-cache keys, and relies on-//! the `openhuman.usage/billing` response envelope for charged-USD / cached-token-//! accounting. This host `ChatModel` bridges all three onto the crate wire client:+//! The managed model itself is built by the chat-model provider registered under+//! [`PROVIDER_OPENHUMAN`](super::factory::PROVIDER_OPENHUMAN)+//! ([`crate::inference::registry`]); it lives with that provider.//!-//! * **Dynamic JWT** — [`invoke`](ChatModel::invoke)/[`stream`](ChatModel::stream)-//! resolve the current bearer and build a fresh crate `OpenAiModel` (Bearer)-//! per call.-//! * **`thread_id`** — injected into `ModelRequest.provider_options` so the crate-//! flattens it into the request body as the top-level `thread_id` field (parity-//! with the host `with_openhuman_thread_id`).-//! * **Billing envelope** — the crate `parse_response` preserves the full response-//! JSON on `ModelResponse.raw` but has no field for the managed backend's-//! charged USD, so [`project_managed_usage`] re-projects the-//! `openhuman.{billing,usage}` envelope into the `openhuman_usage_meta` shape +-//! crate `Usage` cache tokens the seam's `usage_info_from_response` reads —-//! without it the crate-native managed path would report `$0` charged.-//!-//! This is the bespoke-provider rewrite that gates deleting `compatible*.rs` (the-//! managed backend was its last non-BYOK consumer).+//! The two `is_*_managed_*` endpoint guards below are transitional: they remain+//! only until the last core callers (integrations, voice, socket URL, backend+//! client) move onto the provider crate's own copies.-use async_trait::async_trait;use serde_json::Value;-use std::path::PathBuf;-use std::time::Duration;--use tinyinference_llm::message::Message;-use tinyinference_llm::model::{- ChatModel, Modalities, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,- ProviderError,-};-use tinyinference_llm::providers::openai::OpenAiModel;-use tinyinference_llm::providers::ProviderRequestOptions;-use tinyinference_llm::Error as TiError;--use super::ProviderRuntimeOptions;-use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER};+use tinyinference_llm::model::ModelRequest;pub const PROVIDER_LABEL: &str = "OpenHuman";@@ -92,316 +64,11 @@ pub(crate) fn is_managed_endpoint_for_api_key(endpoint: &str) -> bool {/// The managed OpenHuman backend as a crate [`ChatModel`]. Holds the backend/// connection settings (for JWT + base-URL resolution) and the default model id-/// sent when a request doesn't override it.-pub struct OpenHumanBackendModel {- options: ProviderRuntimeOptions,- api_url: Option<String>,- default_model: String,- native_tool_calling: bool,- profile: ModelProfile,- /// Normalized OpenHuman conversation thread. This is deliberately owned by- /// the managed backend model: BYOK and third-party models must never see- /// this backend-only extension.- thread_id: Option<String>,-}--impl OpenHumanBackendModel {- pub fn new(- api_url: Option<&str>,- options: &ProviderRuntimeOptions,- default_model: impl Into<String>,- ) -> Self {- Self {- options: options.clone(),- api_url: api_url- .map(str::trim)- .filter(|url| !url.is_empty())- .map(ToOwned::to_owned),- default_model: resolve_model(&default_model.into()),- native_tool_calling: true,- profile: ModelProfile {- provider: Some("managed".to_string()),- modalities: Modalities {- image_in: true,- ..Modalities::default()- },- tool_calling: true,- parallel_tool_calls: true,- streaming: true,- streaming_tool_chunks: true,- ..ModelProfile::default()- },- thread_id: None,- }- }-- /// Attach the explicit run thread used by OpenHuman's managed inference- /// endpoint. Blank values mean no backend thread rather than an empty wire- /// field.- pub fn with_thread_id(mut self, thread_id: Option<impl AsRef<str>>) -> Self {- self.thread_id = thread_id.and_then(|thread_id| {- let thread_id = thread_id.as_ref().trim();- (!thread_id.is_empty()).then(|| thread_id.to_owned())- });- self- }-- pub fn with_default_model(mut self, model: impl Into<String>) -> Self {- self.default_model = resolve_model(&model.into());- self- }-- /// Force prompt-guided tool calling for toolsets that exceed the managed- /// backend's native grammar ceiling.- pub fn with_native_tool_calling(mut self, enabled: bool) -> Self {- self.native_tool_calling = enabled;- self.profile.tool_calling = enabled;- self.profile.parallel_tool_calls = enabled;- self.profile.streaming_tool_chunks = enabled;- self- }-- fn state_dir(&self) -> PathBuf {- self.options.openhuman_dir.clone().unwrap_or_else(|| {- directories::UserDirs::new()- .map(|dirs| dirs.home_dir().join(".openhuman"))- .unwrap_or_else(|| PathBuf::from(".openhuman"))- })- }-- fn resolve_bearer(&self) -> anyhow::Result<String> {- use crate::security::credentials::session_support::classify_session_token;-- // A stored API key (library runtime) is the bearer outright: the- // OpenAI-compatible managed endpoint accepts it as `Bearer <key>`,- // and there is no session — so no `exp` and no signed-out state — to- // consult.- if let Some(key) = crate::security::credentials::api_key::get_api_key_in(- &self.state_dir(),- self.options.secrets_encrypt,- )? {- // Refuse to send the key over a plaintext channel it could leak- // from. Scoped to this managed-key path only — `base_url()`- // comes from the backend transport, which a library host can point- // at anything (a BYOK/local endpoint legitimately runs over- // plain HTTP on loopback), so this cannot tighten- // `normalize_api_base_url` itself without breaking those.- let endpoint = self.base_url()?;- if !is_managed_endpoint_for_api_key(&endpoint) {- anyhow::bail!(- "refusing to send the TinyHumans API key to an unmanaged or insecure \- endpoint: {endpoint} — use the managed backend or loopback for local testing"- );- }- log::debug!(- "[providers][openhuman-backend] authenticating managed inference with api-key"- );- return Ok(key);- }- if crate::cron::scheduler_gate::is_signed_out() {- anyhow::bail!(- "SESSION_EXPIRED: backend session not active — sign in to resume LLM work"- );- }- let auth = AuthService::new(&self.state_dir(), self.options.secrets_encrypt);- let profile = auth.get_profile(- APP_SESSION_PROVIDER,- self.options.auth_profile_override.as_deref(),- )?;-- // #5503: precheck the recorded JWT `exp` BEFORE building a request, the- // same way `require_live_session_token` guards the backend REST callers.- // Managed inference used to fire a doomed request on an expired-but-- // stored token and let the 401 come back — but an expired session can- // also surface upstream as a misleading "model unavailable", which is a- // core symptom of #5503 (all tiers "die" over a long session). Failing- // fast as `session_expired` routes the user to re-auth instead.- managed_bearer(classify_session_token(profile.as_ref(), chrono::Utc::now()))- }-- /// The managed OpenAI-compatible endpoint, from the installed backend- /// transport. Without one there is no managed backend to reach.- fn base_url(&self) -> anyhow::Result<String> {- let base = crate::backend::inference_base_url(&self.api_url).map_err(|_| {- anyhow::anyhow!(- "{} managed inference needs a backend transport",- crate::core::observability::BACKEND_UNAVAILABLE_PREFIX- )- })?;- Ok(format!("{}/openai/v1", base.trim_end_matches('/')))- }-- /// Resolve the current JWT + base URL and build a fresh crate `OpenAiModel`- /// (Bearer). Rebuilt per call because the session JWT rotates, but every- /// build shares one pooled HTTP client ([`managed_inference_http_client`]),- /// so consecutive calls reuse a warm TLS connection to the backend.- fn build_wire_model(&self) -> tinyinference_llm::Result<OpenAiModel> {- let token = self- .resolve_bearer()- .map_err(|e| TiError::Model(e.to_string()))?;- let base_url = self.base_url().map_err(|e| TiError::Model(e.to_string()))?;- // The hosted API is chat-completions only (no `/v1/responses`); auth is a- // plain bearer JWT. The tier/model rides `request.model`, which the backend- // resolves — the baked default only applies when a request omits it.- Ok(- OpenAiModel::compatible_provider(PROVIDER_LABEL, token, base_url, &self.default_model)- .with_native_tool_calling(self.native_tool_calling)- .with_request_options(ProviderRequestOptions {- http: Some(managed_inference_http_client()),- ..ProviderRequestOptions::default()- }),- )- }-- /// Probe whether the managed backend account actually has a working- /// inference provider configured, cheaply and without inflating usage- /// (issue B45 — flows provider-connectivity author gate).- ///- /// [`build_wire_model`](Self::build_wire_model) only resolves the session- /// JWT and builds the request client — it says nothing about whether the- /// account has a provider API key configured server-side. That only- /// surfaces on a real completion attempt, as an HTTP 400- /// `{"success":false,"error":"API key not configured for provider","errorCode":"BAD_REQUEST"}`.- /// Previously the first time a flows author found this out was mid-run,- /// deep inside a tinyflows `agent` node. This probe moves that discovery- /// to author time by issuing one minimal completion (`"ping"`,- /// `max_tokens: 1`) and classifying the result.- ///- /// Fails OPEN on everything except a definitive client-configuration- /// error: a 5-second timeout, a transport failure, a 5xx, or any other- /// non-matching provider error all return `Ok(())` so a flaky backend or- /// slow network never blocks authoring. Only a backend-confirmed "no- /// provider configured for this account" response returns `Err` —- /// carrying the backend's own error string so the author sees exactly- /// what run time would have shown them.- pub async fn probe_readiness(&self) -> Result<(), String> {- log::debug!(- "[flows][inference-probe] entering probe_readiness model={}",- self.default_model- );-- let model = match self.build_wire_model() {- Ok(model) => model,- Err(e) => {- // The flows readiness gate's Layer 1 (sign-in / session- // checks) is responsible for catching a genuinely- // absent/expired session before this ever runs — a- // construction failure reaching here is a race, not a- // provider-configuration problem, so fail open rather than- // duplicate or contradict that gate's message.- log::debug!(- "[flows][inference-probe] wire model construction failed, failing open: {e}"- );- return Ok(());- }- };-- let request = ModelRequest::new(vec![Message::user("ping")]).with_max_tokens(1);-- let outcome =- match tokio::time::timeout(Duration::from_secs(5), model.invoke(&(), request)).await {- Ok(result) => result,- Err(_) => {- log::debug!(- "[flows][inference-probe] model={} timed out after 5s, failing open",- self.default_model- );- return Ok(());- }- };-- match outcome {- Ok(_) => {- log::debug!(- "[flows][inference-probe] model={} probe completion succeeded — provider ready",- self.default_model- );- Ok(())- }- Err(TiError::Provider(err)) => {- if is_provider_not_configured_error(&err) {- log::warn!(- "[flows][inference-probe] model={} backend reports no provider configured: {}",- self.default_model,- err.message- );- Err(err.message.clone())- } else if err.status.is_some_and(|status| status >= 500) {- log::debug!(- "[flows][inference-probe] model={} backend {:?}, failing open: {}",- self.default_model,- err.status,- err.message- );- Ok(())- } else {- // Any other structured provider failure (401, 429, a- // malformed request, …) is not the definitive "provider- // not configured" signal this probe exists to catch —- // fail open rather than risk a false-positive- // author-time block.- log::debug!(- "[flows][inference-probe] model={} non-definitive provider error {:?}, \- failing open: {}",- self.default_model,- err.status,- err.message- );- Ok(())- }- }- Err(e) => {- log::debug!(- "[flows][inference-probe] model={} transport/model error, failing open: {e}",- self.default_model- );- Ok(())- }- }- }-}--/// Whether `err` is the definitive "no inference provider configured for this-/// account" signal the managed backend returns as an HTTP 400 with body-/// `{"success":false,"error":"API key not configured for provider","errorCode":"BAD_REQUEST"}`.-///-/// Deliberately narrow: matches ONLY a 400 whose message contains the specific-/// `"api key not configured for provider"` phrasing, or (as a `BAD_REQUEST`--/// coded tolerance for message wording drift) the narrower `"not configured-/// for provider"` substring — never a bare `"not configured"`, which an-/// unrelated 400 (a malformed request naming some other unconfigured field,-/// a validation error, …) could also contain. Every other 4xx/5xx/transport-/// failure fails open (see [`OpenHumanBackendModel::probe_readiness`]'s doc).-fn is_provider_not_configured_error(err: &ProviderError) -> bool {- if err.status != Some(400) {- return false;- }- let message = err.message.to_ascii_lowercase();- let code_is_bad_request = err- .code- .as_deref()- .is_some_and(|c| c.eq_ignore_ascii_case("BAD_REQUEST"));- message.contains("api key not configured for provider")- || (code_is_bad_request && message.contains("not configured for provider"))-}--fn resolve_model(model: &str) -> String {- let trimmed = model.trim();- if trimmed.is_empty() {- log::debug!(- "[providers][openhuman-backend] empty model passed to OpenHuman backend; \- substituting default `{}` (TAURI-RUST-RS)",- crate::config::MODEL_MANAGED_DEFAULT- );- crate::config::MODEL_MANAGED_DEFAULT.to_string()- } else {- trimmed.to_string()- }}/// Request-metadata key a caller sets (to `true`) to ask for no reasoning on/// a call — see [`without_reasoning`].-const REASONING_OFF_METADATA_KEY: &str = "openhuman_reasoning_off";+pub const REASONING_OFF_METADATA_KEY: &str = "openhuman_reasoning_off";/// Mark `request` as not needing the model to reason first. Provider-neutral:/// `ModelRequest.metadata` never reaches the wire, so a BYOK or local provider@@ -413,266 +80,3 @@ pub(crate) fn without_reasoning(mut request: ModelRequest) -> ModelRequest {if !request.metadata.is_object() {request.metadata = Value::Object(serde_json::Map::new());}- if let Some(map) = request.metadata.as_object_mut() {- map.insert(REASONING_OFF_METADATA_KEY.to_string(), Value::Bool(true));- }- request-}--/// Translate the request's reasoning choice into the managed backend's wire-/// field: the OpenRouter-style `reasoning` object, which the backend forwards-/// upstream.-///-/// Sources, highest first: a `reasoning` object the caller already put in-/// provider options (left alone); the [`without_reasoning`] hint, which marks-/// one helper call specifically; the request's provider-neutral-/// `ModelRequest::reasoning` (the user's thinking level, from the harness-/// `RunPolicy::default_reasoning`). The-/// neutral field is consumed here, so the OpenAI-compatible transport does not-/// also emit a top-level `reasoning_effort` for the same choice.-fn apply_reasoning_hint(mut request: ModelRequest) -> ModelRequest {- if request.provider_options.get("reasoning").is_some() {- return request;- }- let wants_off = request- .metadata- .get(REASONING_OFF_METADATA_KEY)- .and_then(Value::as_bool)- .unwrap_or(false);- let neutral = request.reasoning.take();- let wire = if wants_off {- Some(serde_json::json!({ "enabled": false }))- } else {- neutral.as_ref().and_then(managed_reasoning_wire)- };- let Some(wire) = wire else {- return request;- };- let mut options = request.provider_options.clone();- if !options.is_object() {- options = Value::Object(serde_json::Map::new());- }- if let Some(map) = options.as_object_mut() {- map.insert("reasoning".to_string(), wire.clone());- }- log::debug!("[inference][managed] reasoning for this call: {wire}");- request.with_provider_options(options)-}--/// The OpenRouter `reasoning` object for a provider-neutral config: `none`-/// disables reasoning, an explicit budget becomes `max_tokens`, and any other-/// effort is sent by name. An empty config sends nothing.-fn managed_reasoning_wire(reasoning: &tinyinference_llm::model::ReasoningConfig) -> Option<Value> {- use tinyinference_llm::model::ReasoningEffort;- if reasoning.effort == Some(ReasoningEffort::None) {- return Some(serde_json::json!({ "enabled": false }));- }- if let Some(budget) = reasoning.budget_tokens {- return Some(serde_json::json!({ "max_tokens": budget }));- }- reasoning- .effort- .map(|effort| serde_json::json!({ "effort": effort.as_str() }))-}--/// Inject this managed model's explicitly owned thread into provider options.-/// This backend-only wire extension is never inferred from ambient state.-fn with_thread_id(request: ModelRequest, thread_id: Option<&str>) -> ModelRequest {- let Some(thread_id) = thread_id else {- return request;- };- let mut options = request.provider_options.clone();- if !options.is_object() {- options = Value::Object(serde_json::Map::new());- }- if let Some(map) = options.as_object_mut() {- map.insert(- "thread_id".to_string(),- Value::String(thread_id.to_string()),- );- }- request.with_provider_options(options)-}--/// The bearer a classified app-session token yields for managed inference.-///-/// Separate from [`OpenHumanBackendModel::resolve_bearer`] so the decision is-/// testable without an on-disk auth profile.-///-/// `exp`-less tokens carry no recorded expiry, so `classify_session_token`-/// reports them `Live`; the offline local session is one of those, and it-/// authenticates no TinyHumans account. Sending it anyway earned a backend-/// `401 "Invalid token"`, which published `SessionExpired` and told a user who-/// was signed in locally that their session had expired (#6932). Refusing here-/// mirrors the arm `resolve_backend_credential` already applies to every-/// backend REST caller, and keeps the local credential intact.-fn managed_bearer(- check: crate::security::credentials::session_support::SessionTokenCheck,-) -> anyhow::Result<String> {- use crate::security::credentials::session_support::{- is_local_session_token, SessionTokenCheck, LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE,- };-- match check {- SessionTokenCheck::Live(token) if is_local_session_token(&token) => {- log::debug!(- "[providers][openhuman-backend] refusing managed inference for the offline local session"- );- anyhow::bail!(LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE)- }- SessionTokenCheck::Live(token) => Ok(token),- SessionTokenCheck::Expired => {- maybe_publish_local_session_expiry();- anyhow::bail!(- "SESSION_EXPIRED: backend session token expired locally — re-authentication required"- )- }- SessionTokenCheck::Absent => {- anyhow::bail!("No backend session: store a JWT via auth (app-session)")- }- }-}--/// Publish a `SessionExpired` event when the local `exp` precheck in-/// [`resolve_bearer`](OpenHumanBackendModel::resolve_bearer) rejects an expired-/// managed session token before a request is ever sent — mirroring-/// [`require_live_session_token`](crate::security::credentials::session_support::require_live_session_token)'s-/// pre-flight publish so the credentials subscriber clears state and the UI-/// re-auths exactly as it would on a real backend 401. Deduped via the-/// scheduler gate so N parallel managed turns in one tick don't emit N events.-fn maybe_publish_local_session_expiry() {- if crate::cron::scheduler_gate::is_signed_out() {- return;- }- log::warn!(- "[providers][openhuman-backend] managed session token expired locally — \- publishing SessionExpired before any inference request"- );- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {- source: "openhuman_backend_model.resolve_bearer".to_string(),- reason: "backend session token expired locally — re-authentication required".to_string(),- });-}--/// Publish a `SessionExpired` event when the backend rejects a crate-native-/// model call with `401`/`403` Unauthorized — mirroring the check in-/// [`CrateBackedProvider::invoke`](super::CrateBackedProvider) which the-/// crate-native path bypasses.-fn maybe_publish_session_expired(err: &TiError, operation: &str) {- if let TiError::Provider(pe) = err {- maybe_publish_provider_session_expired(pe, operation);- }-}--fn maybe_publish_provider_session_expired(pe: &ProviderError, operation: &str) {- if pe.provider.as_str() == "OpenHuman" && matches!(pe.status, Some(401 | 403)) {- let reason = tinyinference_core::sanitize::sanitize_api_error(&pe.message);- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {- source: format!(- "openhuman_backend_model.{}({})",- operation,- pe.status.unwrap_or(0)- ),- reason,- });- }-}--/// Log the raw upstream failure at the managed inference dispatch boundary-/// (#5503, part d). The managed unavailability path used to surface the true-/// backend cause only after the web-chat error classifier had already collapsed-/// it to a user-facing bucket, so an operator investigating "all tiers died-/// over hours" had no record of what the backend actually returned. This is the-/// one place every managed `invoke`/`stream` failure passes through, so it's-/// where the diagnostic belongs. Structured fields (`status`/`code`/`provider`/-/// `retryable`) are low-cardinality; the message is secret-scrubbed and capped-/// by [`sanitize_api_error`] before it's logged — no tokens, no full PII.-fn log_managed_dispatch_error(err: &TiError, operation: &str) {- match err {- TiError::Provider(pe) => log_managed_provider_error(pe, operation),- other => {- log::warn!(- "[providers][openhuman-backend] managed {operation} failed (non-provider error): {}",- tinyinference_core::sanitize::sanitize_api_error(&other.to_string()),- );- }- }-}--/// Logs a structured provider failure; the detail is secret-scrubbed and-/// truncated because a provider error can echo request content.-fn log_managed_provider_error(pe: &ProviderError, operation: &str) {- log::warn!(- "[providers][openhuman-backend] managed {operation} failed: status={:?} code={:?} provider={} retryable={} detail={}",- pe.status,- pe.code,- pe.provider,- pe.retryable,- tinyinference_core::sanitize::sanitize_api_error(&pe.message),- );-}--/// Gives a failure reported inside a stream the same handling as a failed-/// `stream()` call: logged, and an expired session starts re-authentication.-fn observe_in_band_failure(item: &ModelStreamItem) {- if let ModelStreamItem::ProviderFailed(pe) = item {- log_managed_provider_error(pe, "stream (in-band)");- maybe_publish_provider_session_expired(pe, "stream");- }-}--#[path = "openhuman_backend_model_calls.rs"]-mod calls;--/// Connect timeout for the shared managed-inference client; matches the-/// adapter's own default.-const MANAGED_INFERENCE_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);--/// How long an idle pooled connection is kept. Below the AWS ALB's default 60s-/// idle timeout in front of the backend, so the pool never hands out a-/// connection the load balancer has already closed.-const MANAGED_INFERENCE_POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(50);--/// The one HTTP client every managed-inference call in the process shares.-///-/// `OpenAiModel` otherwise builds its own `reqwest::Client` per instance, and-/// [`OpenHumanBackendModel::build_wire_model`] builds an instance per model-/// call, so each call paid a fresh TCP + TLS handshake to the backend (about-/// 150-300 ms measured to `api.tinyhumans.ai`) before its first token. A-/// `reqwest::Client` is a cheap handle over a shared connection pool, so-/// cloning it keeps connections warm across calls, turns and threads.-fn managed_inference_http_client() -> reqwest::Client {- static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();- CLIENT- .get_or_init(|| {- tracing::debug!(- idle_timeout_secs = MANAGED_INFERENCE_POOL_IDLE_TIMEOUT.as_secs(),- "[inference][managed] building shared pooled HTTP client"- );- reqwest::Client::builder()- .connect_timeout(MANAGED_INFERENCE_CONNECT_TIMEOUT)- .pool_idle_timeout(MANAGED_INFERENCE_POOL_IDLE_TIMEOUT)- .tcp_keepalive(Duration::from_secs(30))- .build()- .unwrap_or_else(|error| {- tracing::warn!(- error = %error,- "[inference][managed] pooled client build failed; using reqwest defaults"- );- reqwest::Client::new()- })- })- .clone()-}--#[path = "openhuman_backend_model_usage.rs"]-mod usage;-use usage::project_managed_usage;--#[cfg(test)]-#[path = "openhuman_backend_model_tests.rs"]-mod tests;--#[cfg(test)]-#[path = "openhuman_backend_model_usage_tests.rs"]-mod usage_tests;diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_auth_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_auth_tests.rsdeleted file mode 100644index e3d4332286..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_auth_tests.rs+++ /dev/null@@ -1,46 +0,0 @@-use super::*;--// #6932: the offline local profile is a valid sign-in with no TinyHumans-// account behind it. `classify_session_token` reports its `exp`-less token-// `Live`, so managed inference used to send it, collect a backend-// `401 "Invalid token"` and surface that as an expired session.-#[test]-fn the_offline_local_session_cannot_authenticate_managed_inference() {- use crate::security::credentials::session_support::{- SessionTokenCheck, LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE,- };-- let error = managed_bearer(SessionTokenCheck::Live("header.payload.local".to_string()))- .expect_err("a local session has no managed bearer");-- assert_eq!(- error.to_string(),- LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE- );-}--#[test]-fn the_refusal_does_not_read_as_an_expired_session() {- use crate::security::credentials::session_support::SessionTokenCheck;-- let error = managed_bearer(SessionTokenCheck::Live("header.payload.local".to_string()))- .expect_err("a local session has no managed bearer");-- // The whole point of the fix: this must not reach the sign-out path that- // the backend's 401 envelope used to trigger.- assert!(!crate::core::observability::is_session_expired_message(- &error.to_string()- ));-}--#[test]-fn a_signed_in_session_still_authenticates_managed_inference() {- use crate::security::credentials::session_support::SessionTokenCheck;-- let bearer = managed_bearer(SessionTokenCheck::Live(- "header.payload.signature".to_string(),- ))- .expect("a hosted session is the bearer");-- assert_eq!(bearer, "header.payload.signature");-}diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_calls.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_calls.rsdeleted file mode 100644index 701d9c8372..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_calls.rs+++ /dev/null@@ -1,102 +0,0 @@-use super::*;--#[async_trait]-impl ChatModel<()> for OpenHumanBackendModel {- fn profile(&self) -> Option<&ModelProfile> {- Some(&self.profile)- }-- fn supports_input(- &self,- modality: tinyinference_llm::model::InputModality,- mime: &str,- source: tinyinference_llm::model::InputSource,- ) -> bool {- use tinyinference_llm::model::{InputModality, InputSource};- matches!(- (modality, source),- (InputModality::Image, InputSource::Base64 | InputSource::Url)- ) && matches!(- mime,- "image/png" | "image/jpeg" | "image/webp" | "image/gif"- ) || matches!(- (modality, source),- (InputModality::Audio, InputSource::Base64)- ) && matches!(- mime,- "audio/wav" | "audio/x-wav" | "audio/mpeg" | "audio/mp3"- )- }-- /// Identity for harness response-cache scoping: the backend base URL and- /// the default tier/model. The session JWT is deliberately absent — it- /// rotates, and a key derived from it would never hit twice — and the- /// backend resolves the tier per account anyway, so two accounts sharing- /// a cache would need their own namespace, not a credential in the key.- fn cache_identity(&self) -> Option<String> {- self.base_url()- .ok()- .map(|base| format!("openhuman:{base}:{}", self.default_model))- }-- async fn invoke(- &self,- state: &(),- request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- let model = self.build_wire_model()?;- let response = match model- .invoke(- state,- with_thread_id(apply_reasoning_hint(request), self.thread_id.as_deref()),- )- .await- {- Ok(response) => response,- Err(e) => {- log_managed_dispatch_error(&e, "invoke");- maybe_publish_session_expired(&e, "invoke");- return Err(e);- }- };- Ok(project_managed_usage(response))- }-- async fn stream(- &self,- state: &(),- request: ModelRequest,- ) -> tinyinference_llm::Result<ModelStream> {- let model = self.build_wire_model()?;- // The backend sends its charge on an `openhuman-metadata` frame before- // `[DONE]`; the crate's SSE parser keeps that envelope on the terminal- // response's `raw`, so the streamed `Completed` is projected exactly like- // the `invoke` path above and carries the charged USD.- match model- .stream(- state,- with_thread_id(apply_reasoning_hint(request), self.thread_id.as_deref()),- )- .await- {- // A failure can also arrive *inside* an HTTP 200 stream as an SSE- // `{"error":…}` payload; it never reaches the `Err` arm (#6724).- Ok(stream) => Ok(stream.map_items(|item| {- observe_in_band_failure(&item);- match item {- tinyinference_llm::model::ModelStreamItem::Completed(response) => {- tinyinference_llm::model::ModelStreamItem::Completed(project_managed_usage(- response,- ))- }- other => other,- }- })),- Err(e) => {- log_managed_dispatch_error(&e, "stream");- maybe_publish_session_expired(&e, "stream");- Err(e)- }- }- }-}diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_endpoint_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_endpoint_tests.rsdeleted file mode 100644index c2e7efa5c9..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_endpoint_tests.rs+++ /dev/null@@ -1,61 +0,0 @@-use super::*;--#[test]-fn api_key_endpoint_is_bound_to_tinyhumans_or_loopback() {- use super::is_managed_endpoint_for_api_key;-- assert!(is_managed_endpoint_for_api_key(- "https://api.tinyhumans.ai/openai/v1"- ));- assert!(is_managed_endpoint_for_api_key(- "http://127.0.0.1:18765/openai/v1"- ));- assert!(is_managed_endpoint_for_api_key(- "http://[::1]:18765/openai/v1"- ));- assert!(!is_managed_endpoint_for_api_key(- "https://example.com/openai/v1"- ));- assert!(!is_managed_endpoint_for_api_key(- "http://api.tinyhumans.ai/openai/v1"- ));-}--/// #6724 (review): a 401 reported *inside* a stream must start re-auth just-/// like a failed `stream()` call does.-#[tokio::test]-async fn an_in_band_401_publishes_session_expired() {- use crate::core::events::DomainEvent;-- crate::core::bus::init().await.expect("bus init");- let mut rx = crate::core::bus::BUS- .get()- .expect("event bus initialized")- .receiver();-- observe_in_band_failure(&ModelStreamItem::ProviderFailed(ProviderError {- provider: PROVIDER_LABEL.to_string(),- status: Some(401),- message: "TEST_MARKER_IN_BAND token expired".to_string(),- ..ProviderError::default()- }));-- let mut source_seen = None;- loop {- match rx.try_recv() {- Ok(DomainEvent::SessionExpired { source, reason })- if reason.contains("TEST_MARKER_IN_BAND") =>- {- source_seen = Some(source);- break;- }- Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,- Err(_) => break,- }- }- assert_eq!(- source_seen.as_deref(),- Some("openhuman_backend_model.stream(401)"),- "an in-band 401 must publish SessionExpired"- );-}diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_offline_session_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_offline_session_tests.rsdeleted file mode 100644index 2aa9f0bf26..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_offline_session_tests.rs+++ /dev/null@@ -1,42 +0,0 @@-use super::*;--// #6932: an offline local profile is a valid sign-in, but it cannot-// authenticate managed inference.-#[test]-fn the_offline_local_session_cannot_authenticate_managed_inference() {- use crate::security::credentials::session_support::{- SessionTokenCheck, LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE,- };-- let error = managed_bearer(SessionTokenCheck::Live("header.payload.local".to_string()))- .expect_err("a local session has no managed bearer");-- assert_eq!(- error.to_string(),- LOCAL_SESSION_MANAGED_INFERENCE_UNAVAILABLE- );-}--#[test]-fn the_refusal_does_not_read_as_an_expired_session() {- use crate::security::credentials::session_support::SessionTokenCheck;-- let error = managed_bearer(SessionTokenCheck::Live("header.payload.local".to_string()))- .expect_err("a local session has no managed bearer");-- assert!(!crate::core::observability::is_session_expired_message(- &error.to_string()- ));-}--#[test]-fn a_signed_in_session_still_authenticates_managed_inference() {- use crate::security::credentials::session_support::SessionTokenCheck;-- let bearer = managed_bearer(SessionTokenCheck::Live(- "header.payload.signature".to_string(),- ))- .expect("a hosted session is the bearer");-- assert_eq!(bearer, "header.payload.signature");-}diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_reasoning_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_reasoning_tests.rsdeleted file mode 100644index 67de5318fc..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_reasoning_tests.rs+++ /dev/null@@ -1,159 +0,0 @@-//! The reasoning-off hint and request reasoning on the managed wire.--use super::*;--#[test]-fn reasoning_hint_becomes_disabled_reasoning_on_the_managed_wire() {- let request = apply_reasoning_hint(without_reasoning(ModelRequest::new(vec![Message::user(- "hi",- )])));- assert_eq!(- request.provider_options["reasoning"],- serde_json::json!({ "enabled": false })- );-}--#[test]-fn no_hint_leaves_provider_options_untouched() {- let request = apply_reasoning_hint(ModelRequest::new(vec![Message::user("hi")]));- assert!(request.provider_options.get("reasoning").is_none());-}--#[test]-fn request_reasoning_effort_becomes_the_managed_reasoning_object() {- use tinyinference_llm::model::{ReasoningConfig, ReasoningEffort};- let request = apply_reasoning_hint(- ModelRequest::new(vec![Message::user("hi")])- .with_reasoning(ReasoningConfig::effort(ReasoningEffort::High)),- );- assert_eq!(- request.provider_options["reasoning"],- serde_json::json!({ "effort": "high" })- );- assert!(- request.reasoning.is_none(),- "the neutral field is consumed so the transport sends no second `reasoning_effort`"- );-}--#[test]-fn request_reasoning_none_disables_reasoning_on_the_managed_wire() {- use tinyinference_llm::model::{ReasoningConfig, ReasoningEffort};- let request = apply_reasoning_hint(- ModelRequest::new(vec![Message::user("hi")])- .with_reasoning(ReasoningConfig::effort(ReasoningEffort::None)),- );- assert_eq!(- request.provider_options["reasoning"],- serde_json::json!({ "enabled": false })- );-}--#[test]-fn request_reasoning_budget_becomes_max_tokens() {- use tinyinference_llm::model::{ReasoningConfig, ReasoningEffort};- let request = apply_reasoning_hint(- ModelRequest::new(vec![Message::user("hi")]).with_reasoning(ReasoningConfig {- effort: Some(ReasoningEffort::High),- budget_tokens: Some(8_000),- summary: None,- }),- );- assert_eq!(- request.provider_options["reasoning"],- serde_json::json!({ "max_tokens": 8000 })- );-}--#[test]-fn suggestion_off_hint_wins_over_request_reasoning() {- use tinyinference_llm::model::{ReasoningConfig, ReasoningEffort};- let request = apply_reasoning_hint(- without_reasoning(ModelRequest::new(vec![Message::user("hi")]))- .with_reasoning(ReasoningConfig::effort(ReasoningEffort::Low)),- );- assert_eq!(- request.provider_options["reasoning"],- serde_json::json!({ "enabled": false })- );-}--#[test]-fn explicit_reasoning_option_wins_over_the_hint() {- let request = without_reasoning(ModelRequest::new(vec![Message::user("hi")]))- .with_provider_options(serde_json::json!({ "reasoning": { "effort": "high" } }));- let request = apply_reasoning_hint(request);- assert_eq!(- request.provider_options["reasoning"],- serde_json::json!({ "effort": "high" })- );-}--/// Captures the JSON body of every chat-completions request it receives.-async fn spawn_capturing_chat_server() -> (String, std::sync::Arc<std::sync::Mutex<Vec<Value>>>) {- let bodies = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let seen = bodies.clone();- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind");- let addr = listener.local_addr().expect("local_addr").to_string();- let app = axum::Router::new().route(- "/openai/v1/chat/completions",- axum::routing::post(move |axum::Json(body): axum::Json<Value>| {- let seen = seen.clone();- async move {- seen.lock().unwrap().push(body);- axum::Json(serde_json::json!({- "id": "chatcmpl-capture",- "object": "chat.completion",- "created": 1,- "model": "reasoning-v1",- "choices": [{- "index": 0,- "message": { "role": "assistant", "content": "[]" },- "finish_reason": "stop"- }],- "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }- }))- }- }),- );- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve");- });- (addr, bodies)-}--#[tokio::test]-async fn managed_call_sends_reasoning_disabled_only_when_hinted() {- let tmp = tempfile::TempDir::new().unwrap();- seed_app_session(tmp.path());- let (addr, bodies) = spawn_capturing_chat_server().await;- let backend = backend_pointed_at(&addr, tmp.path());-- backend- .invoke(- &(),- without_reasoning(ModelRequest::new(vec![Message::user("suggest")])),- )- .await- .expect("hinted call");- backend- .invoke(&(), ModelRequest::new(vec![Message::user("chat")]))- .await- .expect("plain call");-- let bodies = bodies.lock().unwrap();- assert_eq!(bodies.len(), 2);- assert_eq!(- bodies[0]["reasoning"],- serde_json::json!({ "enabled": false })- );- assert!(- bodies[1].get("reasoning").is_none(),- "an unhinted call must not change reasoning: {}",- bodies[1]- );- // The hint itself never reaches the wire.- assert!(!bodies[0].to_string().contains("openhuman_reasoning_off"));-}diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_stream_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_stream_tests.rsdeleted file mode 100644index e25340ea1a..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_stream_tests.rs+++ /dev/null@@ -1,309 +0,0 @@-//! Managed-model SSE proxy replay and empty-response recovery.--use super::*;--async fn spawn_sse_chat_server(chunks: Vec<Value>) -> String {- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind SSE proxy");- let addr = listener.local_addr().expect("SSE proxy address");- let body = chunks- .into_iter()- .map(|chunk| format!("data: {chunk}\n\n"))- .collect::<String>()- + "data: [DONE]\n\n";- let app = axum::Router::new()- .route(- "/openai/v1/chat/completions",- axum::routing::post(- |axum::extract::State(body): axum::extract::State<String>| async move {- (- [(axum::http::header::CONTENT_TYPE, "text/event-stream")],- body,- )- },- ),- )- .with_state(body);- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve SSE proxy");- });- addr.to_string()-}--async fn spawn_recovering_sse_proxy(- first_delta: Value,-) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {- use std::sync::atomic::{AtomicUsize, Ordering};-- #[derive(Clone)]- struct ProxyState {- first_delta: Value,- calls: std::sync::Arc<AtomicUsize>,- }-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind recovering SSE proxy");- let addr = listener.local_addr().expect("recovering proxy address");- let calls = std::sync::Arc::new(AtomicUsize::new(0));- let app = axum::Router::new()- .route(- "/openai/v1/chat/completions",- axum::routing::post(- |axum::extract::State(state): axum::extract::State<ProxyState>| async move {- let attempt = state.calls.fetch_add(1, Ordering::SeqCst);- let delta = if attempt == 0 {- state.first_delta- } else {- serde_json::json!({ "content": "Hello there" })- };- let body = format!(- "data: {}\n\ndata: {}\n\ndata: [DONE]\n\n",- serde_json::json!({ "choices": [{ "index": 0, "delta": delta }] }),- serde_json::json!({ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }] }),- );- ([(axum::http::header::CONTENT_TYPE, "text/event-stream")], body)- },- ),- )- .with_state(ProxyState {- first_delta,- calls: calls.clone(),- });- tokio::spawn(async move {- axum::serve(listener, app)- .await- .expect("serve recovering SSE proxy");- });- (addr.to_string(), calls)-}--#[tokio::test]-async fn managed_stream_proxy_distinguishes_visible_and_reasoning_only_content() {- use futures::StreamExt;- use tinyinference_llm::model::StreamAccumulator;-- for (delta, expected_text) in [- (- serde_json::json!({ "content": "Hello there" }),- "Hello there",- ),- (serde_json::json!({ "reasoning": "Hello there" }), ""),- (serde_json::json!({ "content": "<think>Hello there" }), ""),- ] {- let tmp = tempfile::TempDir::new().expect("scratch credentials");- seed_app_session(tmp.path());- let addr = spawn_sse_chat_server(vec![- serde_json::json!({ "choices": [{ "index": 0, "delta": delta }] }),- serde_json::json!({ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }] }),- ])- .await;- let backend = backend_pointed_at(&addr, tmp.path());- let stream = backend- .stream(&(), ModelRequest::new(vec![Message::user("hi")]))- .await- .expect("mock SSE response");- let mut accumulated = StreamAccumulator::new();- for item in stream.collect::<Vec<_>>().await {- accumulated.push(&item);- }- let response = accumulated.finish().expect("completed SSE stream");- assert_eq!(response.text(), expected_text);- assert_eq!(response.finish_reason.as_deref(), Some("stop"));- }-}--#[tokio::test]-async fn managed_stream_retries_a_proxy_completion_without_visible_text() {- use std::sync::atomic::Ordering;- use tinyagents_harness::context::RunConfig;- use tinyagents_harness::runtime::{AgentHarness, RunPolicy};-- for first_delta in [- serde_json::json!({ "reasoning": "Hello there" }),- serde_json::json!({ "content": "<think>Hello there" }),- ] {- let tmp = tempfile::TempDir::new().expect("scratch credentials");- seed_app_session(tmp.path());- let (addr, calls) = spawn_recovering_sse_proxy(first_delta).await;- let mut harness: AgentHarness<()> = AgentHarness::new();- harness.register_model(- "managed",- std::sync::Arc::new(backend_pointed_at(&addr, tmp.path())),- );- harness.with_policy(RunPolicy {- empty_response_retries: 1,- ..RunPolicy::default()- });-- let run = harness- .invoke_streaming(- &(),- (),- RunConfig::new("proxy-retry"),- vec![Message::user("hi")],- )- .await- .expect("second proxy completion should produce a visible answer");- assert_eq!(run.text(), Some("Hello there".to_string()));- assert_eq!(run.model_calls, 2);- assert_eq!(calls.load(Ordering::SeqCst), 2);- }-}--/// Serves one SSE completion and records the JSON body it was sent.-async fn spawn_capturing_sse_server() -> (String, std::sync::Arc<std::sync::Mutex<Option<Value>>>) {- let seen = std::sync::Arc::new(std::sync::Mutex::new(None));- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind capturing server");- let addr = listener.local_addr().expect("capturing server address");- let app = axum::Router::new()- .route(- "/openai/v1/chat/completions",- axum::routing::post(- |axum::extract::State(seen): axum::extract::State<- std::sync::Arc<std::sync::Mutex<Option<Value>>>,- >,- axum::Json(body): axum::Json<Value>| async move {- *seen.lock().unwrap() = Some(body);- let chunk = serde_json::json!({- "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }]- });- (- [(axum::http::header::CONTENT_TYPE, "text/event-stream")],- format!("data: {chunk}\n\ndata: [DONE]\n\n"),- )- },- ),- )- .with_state(seen.clone());- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve capturing");- });- (addr.to_string(), seen)-}--/// Anthropic's prompt cache is opt-in: the managed model must send-/// `cache_control` breakpoints for a Claude upstream and nothing extra for any-/// other, otherwise every call re-bills the whole stable prefix.-#[tokio::test]-async fn managed_stream_marks_the_cacheable_prefix_for_anthropic_models_only() {- use futures::StreamExt;- use tinyinference_llm::model::{PromptSegment, SegmentRole};-- for (model, expect_markers) in [- ("anthropic/claude-sonnet-4-6", true),- ("openrouter/anthropic/claude-haiku-4.5", true),- ("deepseek/deepseek-v4-flash", false),- ] {- let tmp = tempfile::TempDir::new().expect("scratch credentials");- seed_app_session(tmp.path());- let (addr, seen) = spawn_capturing_sse_server().await;- let backend = backend_pointed_at(&addr, tmp.path());- let request = ModelRequest::new(vec![Message::system("stable rules"), Message::user("hi")])- .with_model(model)- .with_cache_segments(vec![PromptSegment {- id: "system".into(),- role: SegmentRole::System,- cacheable: true,- }]);- let stream = backend- .stream(&(), request)- .await- .expect("mock SSE response");- let _ = stream.collect::<Vec<_>>().await;- let body = seen.lock().unwrap().clone().expect("request body captured");- let markers = body.to_string().matches("cache_control").count();- assert_eq!(markers > 0, expect_markers, "model={model} body={body}");- }-}--/// Streams `chunks` from a mock backend and returns the terminal response.-async fn streamed_response(chunks: Vec<Value>) -> tinyinference_llm::model::ModelResponse {- use futures::StreamExt;- use tinyinference_llm::model::ModelStreamItem;-- let tmp = tempfile::TempDir::new().expect("scratch credentials");- seed_app_session(tmp.path());- let addr = spawn_sse_chat_server(chunks).await;- let backend = backend_pointed_at(&addr, tmp.path());- backend- .stream(&(), ModelRequest::new(vec![Message::user("hi")]))- .await- .expect("mock SSE response")- .collect::<Vec<_>>()- .await- .into_iter()- .find_map(|item| match item {- ModelStreamItem::Completed(response) => Some(response),- _ => None,- })- .expect("stream completes")-}--/// The backend bills a streamed call and reports the charge on its own frame-/// before `[DONE]`. The streamed response must carry that charge to the cost-/// accounting, as the non-streaming path always has; it used to be dropped,-/// so every streamed managed turn fell back to a guessed rate.-#[tokio::test]-async fn managed_stream_carries_the_backend_charge_to_the_cost_accounting() {- let response = streamed_response(vec![- serde_json::json!({ "choices": [{ "index": 0, "delta": { "content": "hi" }, "finish_reason": "stop" }] }),- serde_json::json!({ "choices": [], "usage": { "prompt_tokens": 1000, "completion_tokens": 20, "total_tokens": 1020 } }),- serde_json::json!({ "openhuman": {- "usage": { "input_tokens": 1000, "output_tokens": 20, "total_tokens": 1020, "cached_input_tokens": 800 },- "billing": { "charged_amount_usd": 0.0000634 }- } }),- ])- .await;-- let billed = crate::agent::tinyagents::model::usage_info_from_response(&response)- .expect("usage reported");- assert!(- billed.charge_reported,- "the backend's charge reached the core"- );- assert!((billed.charged_amount_usd - 0.0000634).abs() < 1e-12);- assert_eq!(billed.cached_input_tokens(), 800);- assert_eq!(- crate::agent::cost::call_cost("openrouter/z-ai/glm-5.3-flash", &billed),- tinyagents_harness::cost::CallCost::Charged(0.0000634)- );-}--/// A free route bills $0, and that is a known cost, not a missing one.-#[tokio::test]-async fn managed_stream_keeps_a_zero_charge_as_known() {- let response = streamed_response(vec![- serde_json::json!({ "choices": [{ "index": 0, "delta": { "content": "hi" }, "finish_reason": "stop" }] }),- serde_json::json!({ "choices": [], "usage": { "prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12 } }),- serde_json::json!({ "openhuman": { "billing": { "charged_amount_usd": 0.0 } } }),- ])- .await;- let billed = crate::agent::tinyagents::model::usage_info_from_response(&response)- .expect("usage reported");- assert_eq!(- crate::agent::cost::call_cost("openrouter/z-ai/glm-5.3-flash", &billed),- tinyagents_harness::cost::CallCost::Charged(0.0)- );-}--/// A stream with no billing frame carries no charge: the cost stays unknown-/// for an uncatalogued model instead of being priced at a default rate.-#[tokio::test]-async fn managed_stream_without_a_billing_frame_has_no_charge() {- let response = streamed_response(vec![- serde_json::json!({ "choices": [{ "index": 0, "delta": { "content": "hi" }, "finish_reason": "stop" }] }),- serde_json::json!({ "choices": [], "usage": { "prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12 } }),- ])- .await;- let billed = crate::agent::tinyagents::model::usage_info_from_response(&response)- .expect("usage reported");- assert!(!billed.charge_reported);- assert_eq!(- crate::agent::cost::call_cost("openrouter/z-ai/glm-5.3-flash", &billed),- tinyagents_harness::cost::CallCost::Unknown- );-}diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rsdeleted file mode 100644index 6049879da9..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs+++ /dev/null@@ -1,547 +0,0 @@-use super::*;-use crate::inference::provider::ProviderRuntimeOptions;-use tinyinference_llm::message::Message;--fn backend() -> OpenHumanBackendModel {- OpenHumanBackendModel::new(- Some("https://api.example.test"),- &ProviderRuntimeOptions::default(),- "reasoning-v1",- )-}--#[test]-fn with_thread_id_injects_explicit_thread() {- let request = ModelRequest::new(vec![Message::user("hi")]);- let updated = with_thread_id(request, Some("thread-42"));- assert_eq!(- updated.provider_options["thread_id"],- serde_json::json!("thread-42")- );-}--#[test]-fn with_thread_id_is_noop_without_explicit_thread() {- let request = ModelRequest::new(vec![Message::user("hi")]);- let updated = with_thread_id(request, None);- assert!(updated.provider_options.get("thread_id").is_none());-}--#[test]-fn managed_model_keeps_its_explicit_thread_without_an_ambient_scope() {- let model = backend().with_thread_id(Some(" delegate-thread "));- assert_eq!(model.thread_id.as_deref(), Some("delegate-thread"));-}--#[test]-fn managed_model_advertises_tool_and_vision_capabilities() {- let model = backend();- let profile = model.profile().expect("managed profile");- assert!(profile.tool_calling);- assert!(profile.modalities.image_in);-}--#[test]-fn managed_model_supports_only_serializable_native_media_inputs() {- use tinyinference_llm::model::{InputModality, InputSource};-- let model = backend();- for mime in ["image/png", "image/jpeg", "image/webp", "image/gif"] {- for source in [InputSource::Base64, InputSource::Url] {- assert!(- model.supports_input(InputModality::Image, mime, source),- "managed transport should serialize {mime} from {source:?}"- );- }- }-- for mime in ["audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3"] {- assert!(- model.supports_input(InputModality::Audio, mime, InputSource::Base64),- "managed transport should serialize inline {mime}"- );- assert!(- !model.supports_input(InputModality::Audio, mime, InputSource::Url),- "managed transport must not advertise URL serialization for {mime}"- );- }-- for modality in [InputModality::Image, InputModality::Audio] {- for source in [InputSource::Base64, InputSource::Url, InputSource::Path] {- assert!(- !model.supports_input(modality, "application/pdf", source),- "managed transport must reject PDF as {modality:?}/{source:?}"- );- }- }- for modality in [InputModality::Video, InputModality::Document] {- for source in [InputSource::Base64, InputSource::Url, InputSource::Path] {- assert!(- !model.supports_input(modality, "application/octet-stream", source),- "managed transport must reject {modality:?}/{source:?}"- );- }- }- assert!(!model.supports_input(InputModality::Image, "image/tiff", InputSource::Base64));- assert!(!model.supports_input(InputModality::Audio, "audio/ogg", InputSource::Base64));- assert!(!model.supports_input(InputModality::Image, "image/png", InputSource::Path));-}--#[test]-fn resolve_model_normalizes_blank_and_trims_non_empty_values() {- assert_eq!(resolve_model(""), crate::config::MODEL_MANAGED_DEFAULT);- assert_eq!(resolve_model(" \t\n"), crate::config::MODEL_MANAGED_DEFAULT);- assert_eq!(resolve_model(" reasoning-v1 "), "reasoning-v1");- assert_eq!(resolve_model("hint:reasoning"), "hint:reasoning");-}--// ── probe_readiness (B45 — flows provider-connectivity author gate) ────--#[test]-fn is_provider_not_configured_error_matches_exact_backend_shape() {- let err = ProviderError {- provider: "OpenHuman".to_string(),- model: None,- status: Some(400),- code: Some("BAD_REQUEST".to_string()),- message: "API key not configured for provider".to_string(),- retryable: false,- retry_after_ms: None,- raw: None,- ..ProviderError::default()- };- assert!(is_provider_not_configured_error(&err));-}--#[test]-fn is_provider_not_configured_error_rejects_other_400s() {- // A 400 that isn't the "no provider configured" class (e.g. a bad- // request shape) must NOT be classified as provider-not-configured —- // only the exact backend-confirmed signal should ever reject.- let err = ProviderError {- provider: "OpenHuman".to_string(),- model: None,- status: Some(400),- code: Some("BAD_REQUEST".to_string()),- message: "invalid request: messages must not be empty".to_string(),- retryable: false,- retry_after_ms: None,- raw: None,- ..ProviderError::default()- };- assert!(!is_provider_not_configured_error(&err));-}--#[test]-fn is_provider_not_configured_error_tolerates_not_configured_for_provider_wording_drift() {- // The `code_is_bad_request` branch still matches the narrower- // "not configured for provider" substring even when it isn't- // introduced by the exact "api key" prefix — tolerance for backend- // message wording drift, not a broadening to any "not configured".- let err = ProviderError {- provider: "OpenHuman".to_string(),- model: None,- status: Some(400),- code: Some("BAD_REQUEST".to_string()),- message: "credentials not configured for provider 'anthropic'".to_string(),- retryable: false,- retry_after_ms: None,- raw: None,- ..ProviderError::default()- };- assert!(is_provider_not_configured_error(&err));-}--#[test]-fn is_provider_not_configured_error_rejects_generic_not_configured_400() {- // Tightened contract (finding D): a 400 `BAD_REQUEST` whose message- // contains only the generic word "not configured" — but not the- // specific "not configured for provider" phrasing — must fail OPEN,- // not be misclassified as the provider-key signal. Otherwise an- // unrelated backend validation error ("model X not configured", "this- // feature is not configured for your account", …) would falsely- // reject a run/proposal as a provider problem.- let err = ProviderError {- provider: "OpenHuman".to_string(),- model: None,- status: Some(400),- code: Some("BAD_REQUEST".to_string()),- message: "webhook target not configured".to_string(),- retryable: false,- retry_after_ms: None,- raw: None,- ..ProviderError::default()- };- assert!(!is_provider_not_configured_error(&err));-}--#[test]-fn is_provider_not_configured_error_rejects_non_400_status() {- let err = ProviderError {- provider: "OpenHuman".to_string(),- model: None,- status: Some(401),- code: None,- message: "API key not configured for provider".to_string(),- retryable: false,- retry_after_ms: None,- raw: None,- ..ProviderError::default()- };- assert!(!is_provider_not_configured_error(&err));-}--fn seed_app_session(dir: &std::path::Path) {- use crate::security::credentials::{- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,- };- AuthService::new(dir, false)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "test.session.jwt",- std::collections::HashMap::new(),- true,- )- .expect("seed app-session token");-}--/// Seed an app-session profile whose recorded `exp` metadata is `expires_at`-/// (RFC3339) so the `resolve_bearer` local-expiry precheck (#5503, part e)-/// can be exercised without a live backend.-fn seed_app_session_with_expiry(dir: &std::path::Path, expires_at: &str) {- use crate::security::credentials::{- session_support::SESSION_EXPIRES_AT_META, AuthService, APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- };- let mut metadata = std::collections::HashMap::new();- metadata.insert(SESSION_EXPIRES_AT_META.to_string(), expires_at.to_string());- AuthService::new(dir, false)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "test.session.jwt",- metadata,- true,- )- .expect("seed app-session token with expiry");-}--fn backend_pointed_at(addr: &str, dir: &std::path::Path) -> OpenHumanBackendModel {- OpenHumanBackendModel::new(- Some(&format!("http://{addr}")),- &ProviderRuntimeOptions {- openhuman_dir: Some(dir.to_path_buf()),- secrets_encrypt: false,- ..ProviderRuntimeOptions::default()- },- "reasoning-v1",- )-}--#[derive(Clone)]-struct StaticChatResponse {- status: axum::http::StatusCode,- body: Value,-}--async fn static_chat_handler(- axum::extract::State(s): axum::extract::State<StaticChatResponse>,-) -> axum::response::Response {- use axum::response::IntoResponse;- (s.status, axum::Json(s.body)).into_response()-}--async fn spawn_static_chat_server(status: axum::http::StatusCode, body: Value) -> String {- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind");- let addr = listener.local_addr().expect("local_addr");- let app = axum::Router::new()- .route(- "/openai/v1/chat/completions",- axum::routing::post(static_chat_handler),- )- .with_state(StaticChatResponse { status, body });- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve");- });- addr.to_string()-}--#[path = "openhuman_backend_model_stream_tests.rs"]-mod stream_tests;--async fn slow_chat_handler() -> axum::response::Response {- use axum::response::IntoResponse;- // Longer than the probe's 5s timeout — the probe must return before- // this ever resolves.- tokio::time::sleep(Duration::from_secs(8)).await;- (- axum::http::StatusCode::OK,- axum::Json(serde_json::json!({- "choices": [{ "message": { "role": "assistant", "content": "pong" } }]- })),- )- .into_response()-}--async fn spawn_slow_chat_server() -> String {- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind");- let addr = listener.local_addr().expect("local_addr");- let app = axum::Router::new().route(- "/openai/v1/chat/completions",- axum::routing::post(slow_chat_handler),- );- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve");- });- addr.to_string()-}--#[tokio::test]-async fn probe_readiness_surfaces_api_key_not_configured() {- let tmp = tempfile::TempDir::new().unwrap();- seed_app_session(tmp.path());- let addr = spawn_static_chat_server(- axum::http::StatusCode::BAD_REQUEST,- serde_json::json!({- "success": false,- "error": "API key not configured for provider",- "errorCode": "BAD_REQUEST"- }),- )- .await;- let backend = backend_pointed_at(&addr, tmp.path());-- let err = backend- .probe_readiness()- .await- .expect_err("a confirmed provider-not-configured 400 must reject");- assert!(- err.to_ascii_lowercase()- .contains("api key not configured for provider"),- "error must surface the backend's own message: {err}"- );-}--#[tokio::test]-async fn probe_readiness_fails_open_on_timeout_or_5xx() {- // 5xx sub-case: a transient backend failure must never block authoring.- let tmp = tempfile::TempDir::new().unwrap();- seed_app_session(tmp.path());- let addr = spawn_static_chat_server(- axum::http::StatusCode::SERVICE_UNAVAILABLE,- serde_json::json!({ "error": "temporarily unavailable" }),- )- .await;- let backend = backend_pointed_at(&addr, tmp.path());- backend- .probe_readiness()- .await- .expect("a transient 5xx must fail open (Ok)");-- // Timeout sub-case: a hung backend must fail open once the 5s probe- // timeout fires, without waiting for the slow handler to respond.- let tmp2 = tempfile::TempDir::new().unwrap();- seed_app_session(tmp2.path());- let addr2 = spawn_slow_chat_server().await;- let backend2 = backend_pointed_at(&addr2, tmp2.path());- let started = std::time::Instant::now();- backend2- .probe_readiness()- .await- .expect("a hung backend must fail open (Ok) once the 5s timeout fires");- assert!(- started.elapsed() < Duration::from_secs(7),- "probe must return around the 5s timeout, not wait for the slow handler"- );-}--#[path = "openhuman_backend_model_reasoning_tests.rs"]-mod reasoning_tests;--// ── shared pooled client (time to first token) ──────────────────────────--/// A TCP relay in front of `upstream` that counts the connections it accepts.-async fn spawn_counting_relay(- upstream: String,-) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {- let accepted = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind relay");- let addr = listener.local_addr().expect("relay addr").to_string();- let counter = accepted.clone();- tokio::spawn(async move {- while let Ok((mut inbound, _)) = listener.accept().await {- counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);- let upstream = upstream.clone();- tokio::spawn(async move {- if let Ok(mut outbound) = tokio::net::TcpStream::connect(&upstream).await {- let _ = tokio::io::copy_bidirectional(&mut inbound, &mut outbound).await;- }- });- }- });- (addr, accepted)-}--/// Every managed call used to build its own `reqwest::Client`, so each call-/// opened a new connection (a fresh TCP + TLS handshake against the real-/// backend) before its first token. Consecutive calls must now reuse one.-#[tokio::test]-async fn consecutive_managed_calls_reuse_one_connection() {- let tmp = tempfile::TempDir::new().unwrap();- seed_app_session(tmp.path());- let upstream = spawn_static_chat_server(- axum::http::StatusCode::OK,- serde_json::json!({- "id": "chatcmpl-pool",- "object": "chat.completion",- "created": 1,- "model": "reasoning-v1",- "choices": [{- "index": 0,- "message": { "role": "assistant", "content": "ok" },- "finish_reason": "stop"- }],- "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }- }),- )- .await;- let (relay, accepted) = spawn_counting_relay(upstream).await;- let backend = backend_pointed_at(&relay, tmp.path());-- for call in 0..3 {- backend- .probe_readiness()- .await- .unwrap_or_else(|error| panic!("managed call {call} failed: {error}"));- }-- assert_eq!(- accepted.load(std::sync::atomic::Ordering::SeqCst),- 1,- "three consecutive managed calls must share one pooled connection"- );-}--#[test]-fn resolve_bearer_fast_fails_session_expired_on_expired_token() {- let tmp = tempfile::TempDir::new().unwrap();- let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();- seed_app_session_with_expiry(tmp.path(), &past);- let backend = backend_pointed_at("127.0.0.1:9", tmp.path());-- let err = backend- .resolve_bearer()- .expect_err("an expired managed JWT must fast-fail the precheck");- let msg = err.to_string();- assert!(- msg.contains("SESSION_EXPIRED"),- "must carry the SESSION_EXPIRED sentinel the classifier keys on: {msg}"- );- assert!(- crate::core::observability::is_session_expired_message(&msg),- "must classify as session-expiry, not model-unavailable: {msg}"- );-}--#[test]-fn resolve_bearer_returns_token_when_expiry_in_future() {- let tmp = tempfile::TempDir::new().unwrap();- let future = (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339();- seed_app_session_with_expiry(tmp.path(), &future);- let backend = backend_pointed_at("127.0.0.1:9", tmp.path());-- let token = backend- .resolve_bearer()- .expect("a live (future-exp) managed JWT must resolve");- assert_eq!(token, "test.session.jwt");-}--fn backend_with_api_key(api_url: &str, dir: &std::path::Path) -> OpenHumanBackendModel {- crate::security::credentials::api_key::store_api_key_in(dir, false, "th_test_key")- .expect("seed api key");- OpenHumanBackendModel::new(- Some(api_url),- &ProviderRuntimeOptions {- openhuman_dir: Some(dir.to_path_buf()),- secrets_encrypt: false,- ..ProviderRuntimeOptions::default()- },- "reasoning-v1",- )-}--#[test]-fn resolve_bearer_refuses_a_stored_api_key_over_plaintext_non_loopback() {- // A non-HTTPS, non-loopback managed endpoint must never carry the- // TinyHumans API key as a bearer — that puts a durable credential (not a- // short-lived session JWT) on the wire in the clear.- let tmp = tempfile::TempDir::new().unwrap();- let backend = backend_with_api_key("http://api.example.test", tmp.path());-- let err = backend- .resolve_bearer()- .expect_err("a plaintext non-loopback endpoint must refuse the api-key bearer");- let msg = err.to_string();- assert!(- msg.contains("refusing to send")- && msg.contains("unmanaged or insecure")- && msg.contains("api.example.test"),- "error must name the refusal and the offending endpoint: {msg}"- );-}--#[test]-fn resolve_bearer_sends_a_stored_api_key_to_managed_https() {- let tmp = tempfile::TempDir::new().unwrap();- let backend = backend_with_api_key("https://api.tinyhumans.ai", tmp.path());-- let token = backend- .resolve_bearer()- .expect("managed HTTPS must be allowed to carry the api-key bearer");- assert_eq!(token, "th_test_key");-}--#[test]-fn resolve_bearer_rejects_foreign_https_for_api_key() {- let tmp = tempfile::TempDir::new().unwrap();- let backend = backend_with_api_key("https://api.example.test", tmp.path());- let error = backend.resolve_bearer().unwrap_err();- assert!(error.to_string().contains("unmanaged or insecure"));-}--#[test]-fn resolve_bearer_sends_a_stored_api_key_over_plain_loopback() {- let tmp = tempfile::TempDir::new().unwrap();- let backend = backend_with_api_key("http://127.0.0.1:9999", tmp.path());-- let token = backend- .resolve_bearer()- .expect("loopback http must still be allowed for local testing");- assert_eq!(token, "th_test_key");-}--#[test]-fn resolve_bearer_returns_token_for_exp_less_offline_session() {- let tmp = tempfile::TempDir::new().unwrap();- seed_app_session(tmp.path());- let backend = backend_pointed_at("127.0.0.1:9", tmp.path());-- let token = backend- .resolve_bearer()- .expect("an exp-less offline session must resolve (presence-only)");- assert_eq!(token, "test.session.jwt");-}-#[path = "openhuman_backend_model_auth_tests.rs"]-mod auth_tests;-#[path = "openhuman_backend_model_endpoint_tests.rs"]-mod endpoint_tests;--#[path = "openhuman_backend_model_offline_session_tests.rs"]-mod offline_session_tests;diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_usage.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_usage.rsdeleted file mode 100644index eda6f339b7..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_usage.rs+++ /dev/null@@ -1,74 +0,0 @@-//! Re-projection of the managed backend's `openhuman` response envelope into-//! the metadata the host cost bridge reads. Split out of-//! `openhuman_backend_model.rs` to keep it under the line cap.--use tinyinference_llm::model::ModelResponse;--/// The subset of the managed backend's `openhuman` response envelope the crate-/// `Usage`/`ModelResponse` can't carry — billing + cache tokens — so it can be-/// re-projected for the host cost bridge.-#[derive(Debug, Default, serde::Deserialize)]-pub(super) struct ManagedEnvelope {- #[serde(default)]- usage: Option<ManagedEnvelopeUsage>,- #[serde(default)]- billing: Option<ManagedEnvelopeBilling>,-}--#[derive(Debug, Default, serde::Deserialize)]-pub(super) struct ManagedEnvelopeUsage {- #[serde(default)]- cached_input_tokens: Option<u64>,- #[serde(default)]- context_window: Option<u64>,-}--#[derive(Debug, Default, serde::Deserialize)]-pub(super) struct ManagedEnvelopeBilling {- #[serde(default)]- charged_amount_usd: f64,-}--/// Re-project the managed `openhuman.{billing,usage}` envelope — which the crate-/// `OpenAiModel` leaves only on `ModelResponse.raw` — into the metadata the host-/// cost bridge reads: `openhuman_usage_meta` (charged USD + context window) plus a-/// crate `Usage.cache_read_tokens` reconciliation when the crate missed the-/// envelope's cached count. Parity with the legacy model-adapter path's-/// `usage_info_from_response`; without it the crate-native managed turn reports-/// `$0` charged and drops backend-reported cached tokens.-pub(super) fn project_managed_usage(mut response: ModelResponse) -> ModelResponse {- let envelope: ManagedEnvelope = response- .raw- .as_ref()- .and_then(|raw| raw.get("openhuman"))- .and_then(|oh| serde_json::from_value(oh.clone()).ok())- .unwrap_or_default();-- // A `billing` block is the backend's statement of what it debited, so it- // is a known charge even at zero; no block means no charge was reported.- let charged_amount_usd = envelope.billing.map(|b| b.charged_amount_usd);- let context_window = envelope- .usage- .as_ref()- .and_then(|u| u.context_window)- .unwrap_or(0);-- // The `openhuman.usage` cached count is authoritative (the legacy `extract_usage`- // preferred it over the standard block); backfill it when the crate's standard- // parse produced none.- if let (Some(usage), Some(cached)) = (- response.usage.as_mut(),- envelope.usage.as_ref().and_then(|u| u.cached_input_tokens),- ) {- if usage.cache_read_tokens == 0 {- usage.cache_read_tokens = cached;- }- }-- response.raw = tinyinference_llm::usage::merge_usage_meta(- response.raw,- charged_amount_usd,- context_window,- );- response-}diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_usage_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_usage_tests.rsdeleted file mode 100644index 38dda30be1..0000000000--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_usage_tests.rs+++ /dev/null@@ -1,95 +0,0 @@-use super::*;--/// The managed `openhuman.{billing,usage}` envelope on `raw` must re-project-/// into the host `BilledUsage` the cost bridge reads — charged USD, cached-/// tokens, and context window — exactly as the legacy legacy model-adapter path did.-#[test]-fn project_managed_usage_recovers_charged_and_cached() {- use crate::agent::tinyagents::model::usage_info_from_response;- use tinyinference_llm::message::AssistantMessage;- use tinyinference_llm::usage::Usage;-- let raw = serde_json::json!({- "openhuman": {- "usage": { "cached_input_tokens": 128, "context_window": 200000 },- "billing": { "charged_amount_usd": 0.0042 }- }- });- let response = ModelResponse {- message: AssistantMessage {- id: None,- content: vec![],- tool_calls: vec![],- usage: None,- origin: None,- },- usage: Some(Usage {- input_tokens: 1000,- output_tokens: 50,- ..Usage::default()- }),- finish_reason: None,- raw: Some(raw),- resolved_model: None,- continue_turn: None,- served_from_cache: false,- correlation: None,- resolved_route: None,- };-- let projected = project_managed_usage(response);- let usage = usage_info_from_response(&projected).expect("usage recovered");- assert!(- (usage.charged_amount_usd - 0.0042).abs() < 1e-9,- "charged={}",- usage.charged_amount_usd- );- assert_eq!(usage.cached_input_tokens(), 128, "cached tokens backfilled");- assert_eq!(usage.context_window(), 200_000);- assert_eq!(usage.input_tokens, 1000);- assert_eq!(usage.output_tokens, 50);-}--/// A response with no `openhuman` envelope stays untouched — no meta key, no-/// charged USD — so non-managed/billing-free responses aren't fabricated.-#[test]-fn project_managed_usage_is_noop_without_envelope() {- use crate::agent::tinyagents::model::usage_info_from_response;- use tinyinference_llm::message::AssistantMessage;- use tinyinference_llm::usage::Usage;-- let response = ModelResponse {- message: AssistantMessage {- id: None,- content: vec![],- tool_calls: vec![],- usage: None,- origin: None,- },- usage: Some(Usage {- input_tokens: 10,- output_tokens: 5,- cache_read_tokens: 3,- ..Usage::default()- }),- finish_reason: None,- raw: Some(serde_json::json!({ "id": "resp_1" })),- resolved_model: None,- continue_turn: None,- served_from_cache: false,- correlation: None,- resolved_route: None,- };-- let projected = project_managed_usage(response);- // raw keeps only the wire fields — no meta key injected.- assert!(projected- .raw- .as_ref()- .unwrap()- .get("openhuman_usage_meta")- .is_none());- let usage = usage_info_from_response(&projected).expect("usage present");- assert_eq!(usage.charged_amount_usd, 0.0);- assert_eq!(usage.cache_read_tokens, 3, "crate cached preserved");-}