Skip to content

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

feat(inference): add managed session and usage tracking

Steven Enamakel7cc8e10cc06d
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_calls.rs b/crates/openhuman-tinyhumans/src/inference/managed_calls.rs
new file mode 100644
index 0000000000..3e0f30e7ea
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/inference/managed_calls.rs
@@ -0,0 +1,159 @@
+//! The [`ChatModel`] implementation of the managed model: per-call wire model,
+//! reasoning and thread extensions, usage projection and failure observation.
+
+use async_trait::async_trait;
+use tinyinference_llm::model::{
+ ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
+ ProviderError,
+};
+use tinyinference_llm::Error as TiError;
+
+use super::managed_model::OpenHumanBackendModel;
+use super::managed_reasoning::{apply_reasoning_hint, with_thread_id};
+use super::managed_session::{maybe_publish_provider_session_expired, maybe_publish_session_expired};
+use super::managed_usage::project_managed_usage;
+
+/// 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.
+pub(super) 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.
+pub(super) 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.
+pub(super) 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");
+ }
+}
+
+
+#[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-tinyhumans/src/inference/managed_reasoning.rs b/crates/openhuman-tinyhumans/src/inference/managed_reasoning.rs
new file mode 100644
index 0000000000..608d637d6f
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/inference/managed_reasoning.rs
@@ -0,0 +1,87 @@
+//! Managed-backend wire extensions: the `reasoning` object and the `thread_id`
+//! field, derived from the provider-neutral request.
+
+use serde_json::Value;
+use tinyinference_llm::model::ModelRequest;
+
+use openhuman_embed::__host::inference_registry::REASONING_OFF_METADATA_KEY;
+
+
+/// 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 (core, `REASONING_OFF_METADATA_KEY`), 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.
+pub(super) 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.
+pub(super) 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)
+}
+
+#[cfg(test)]
+#[path = "managed_reasoning_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_session.rs b/crates/openhuman-tinyhumans/src/inference/managed_session.rs
new file mode 100644
index 0000000000..29bd08d33c
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/inference/managed_session.rs
@@ -0,0 +1,94 @@
+//! Session handling for managed inference: the bearer a stored session token
+//! yields, and the `SessionExpired` publications that follow an expired or
+//! rejected session.
+
+use tinyinference_llm::model::ProviderError;
+use tinyinference_llm::Error as TiError;
+
+/// 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.
+pub(super) fn managed_bearer(
+ check: openhuman_embed::__host::security::credentials::session_support::SessionTokenCheck,
+) -> anyhow::Result<String> {
+ use openhuman_embed::__host::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
+/// `OpenHumanBackendModel::resolve_bearer` rejects an expired
+/// managed session token before a request is ever sent — mirroring
+/// `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 openhuman_embed::__host::cron::scheduler_gate::is_signed_out() {
+ return;
+ }
+ log::warn!(
+ "[providers][openhuman-backend] managed session token expired locally — \
+ publishing SessionExpired before any inference request"
+ );
+ openhuman_embed::__host::core::bus::BUS.publish(openhuman_embed::__host::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
+/// the core `CrateBackedProvider::invoke` which the
+/// crate-native path bypasses.
+pub(super) fn maybe_publish_session_expired(err: &TiError, operation: &str) {
+ if let TiError::Provider(pe) = err {
+ maybe_publish_provider_session_expired(pe, operation);
+ }
+}
+
+pub(super) 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);
+ openhuman_embed::__host::core::bus::BUS.publish(openhuman_embed::__host::core::events::DomainEvent::SessionExpired {
+ source: format!(
+ "openhuman_backend_model.{}({})",
+ operation,
+ pe.status.unwrap_or(0)
+ ),
+ reason,
+ });
+ }
+}
+
+#[cfg(test)]
+#[path = "managed_session_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_usage.rs b/crates/openhuman-tinyhumans/src/inference/managed_usage.rs
new file mode 100644
index 0000000000..333e1a4945
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/inference/managed_usage.rs
@@ -0,0 +1,78 @@
+//! 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
+}
+
+#[cfg(test)]
+#[path = "managed_usage_tests.rs"]
+mod tests;