Skip to content

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

chore: Based on the diff provided, the change appears to be a **refactor** (restructuring with no be

Steven Enamakel935fb0e92246
diff --git a/crates/openhuman-core/src/inference/provider/ops/models/parsing.rs b/crates/openhuman-core/src/inference/provider/ops/models/parsing.rs
new file mode 100644
index 0000000000..c18a92545e
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/ops/models/parsing.rs
@@ -0,0 +1,199 @@
+//! Parsing the OpenAI-compatible (and ChatGPT Codex) `/models` response
+//! envelope into typed [`ModelInfo`] entries.
+
+use super::*;
+
+/// Parse the OpenAI-compatible `/models` response envelope, or the ChatGPT
+/// Codex backend's sibling `models` envelope, into typed [`ModelInfo`] entries.
+///
+/// Returns distinct errors for the three failure modes the wild has
+/// produced in `inference_list_models` Sentry events:
+///
+/// 1. **Missing `data`/`models` field** — endpoint isn't `/models`-compatible
+/// (user typo'd the base URL, pointed at a vector-DB host, etc.).
+/// 2. **`data`/`models` field present but wrong type** — provider returned
+/// `{"object":"error","data":{…}}` or similar non-array. The error names
+/// the actual JSON type so triage knows what the provider sent.
+/// 3. **Non-object top-level body** — provider returned a bare array,
+/// string, etc. Caught explicitly so the parser doesn't silently
+/// drop into the missing-data arm with a `<non-object>` keys list.
+///
+/// A **null** `data`/`models` field on a **success envelope** is NOT an
+/// error — Ollama's OpenAI-compatible `/v1/models` null-encodes the catalog
+/// (`{"object":"list","data":null}`) when no models are pulled, so it is
+/// treated as an empty model list (TAURI-RUST-874 / TAURI-RUST-875). The
+/// null-as-empty short-circuit is gated on `object` being absent or `"list"`:
+/// a null `data` on an error envelope (`{"object":"error","data":null}`)
+/// instead falls through to failure mode 2 so the provider error still
+/// surfaces in the UI and Sentry.
+///
+/// Per-entry parsing ignores entries that don't have a usable string id/slug
+/// (lax on purpose — many OpenAI-compatible servers include malformed rows for
+/// capabilities they don't fully implement).
+pub fn parse_models_response(body: &serde_json::Value) -> Result<Vec<ModelInfo>, String> {
+ let obj = body.as_object().ok_or_else(|| {
+ format!(
+ "provider response is not a JSON object — endpoint is not OpenAI-compatible (got {} at top level)",
+ json_value_kind(body)
+ )
+ })?;
+
+ let (field_name, data_value) = obj
+ .get("data")
+ .map(|value| ("data", value))
+ .or_else(|| obj.get("models").map(|value| ("models", value)))
+ .ok_or_else(|| {
+ let keys = obj.keys().cloned().collect::<Vec<_>>().join(", ");
+ format!(
+ "provider response missing `data` or `models` field — endpoint is not OpenAI-compatible (got keys: {})",
+ keys
+ )
+ })?;
+
+ // A null `data`/`models` field is a valid empty catalog ONLY on a success
+ // envelope: Ollama's OpenAI-compatible `/v1/models` returns
+ // `{"object":"list","data":null}` (object="list", the success marker) when
+ // no models are pulled. Treat that as an empty model list so a healthy-but-
+ // empty local runtime doesn't manufacture a hard error (TAURI-RUST-874 /
+ // TAURI-RUST-875).
+ //
+ // An error body such as `{"object":"error","data":null}` ALSO null-encodes
+ // `data`; swallowing it as an empty catalog would hide provider/endpoint
+ // failures from the UI and Sentry. So gate on a success envelope: short-
+ // circuit only when `object` is absent or "list". Any other `object` value
+ // (e.g. "error") with null `data` falls through to the descriptive error
+ // below, which surfaces the `object` value for triage. Non-array kinds
+ // (object/string/number/bool) likewise fall through.
+ let is_success_envelope = obj
+ .get("object")
+ .and_then(|value| value.as_str())
+ .is_none_or(|object| object.eq_ignore_ascii_case("list"));
+
+ if data_value.is_null() && is_success_envelope {
+ log::info!(
+ "[providers][list_models] `{field_name}` is null on a success envelope — provider returned an empty catalog (no models)"
+ );
+ return Ok(Vec::new());
+ }
+
+ let data = data_value.as_array().ok_or_else(|| {
+ // Include the sibling `object` field if present — OpenAI-shaped
+ // servers set it to `"list"` on success and `"error"` (or omit)
+ // on failure, so its value is the fastest triage signal for
+ // future Sentry events on the wrong-type arm.
+ let object_field = obj
+ .get("object")
+ .map(|v| v.to_string())
+ .unwrap_or_else(|| "<absent>".to_string());
+ format!(
+ "provider response has `{}` field but it is {}, expected array — endpoint may be returning an error envelope (\"object\" = {})",
+ field_name,
+ json_value_kind(data_value),
+ object_field,
+ )
+ })?;
+
+ Ok(data
+ .iter()
+ .filter_map(model_info_from_catalog_item)
+ .collect())
+}
+
+/// Name the JSON value kind for use in `parse_models_response` error
+/// messages. Mirrors `serde_json::Value::*` variants exactly so test
+/// assertions on the rendered token (`object`/`string`/`null`/…) stay
+/// in lock-step with the matcher.
+fn json_value_kind(v: &serde_json::Value) -> &'static str {
+ match v {
+ serde_json::Value::Null => "null",
+ serde_json::Value::Bool(_) => "bool",
+ serde_json::Value::Number(_) => "number",
+ serde_json::Value::String(_) => "string",
+ serde_json::Value::Array(_) => "array",
+ serde_json::Value::Object(_) => "object",
+ }
+}
+
+pub fn merge_openai_codex_model_hints(models: &mut Vec<ModelInfo>) {
+ let mut seen = models
+ .iter()
+ .map(|model| model.id.to_ascii_lowercase())
+ .collect::<std::collections::HashSet<_>>();
+
+ for id in OPENAI_CODEX_MODEL_HINTS {
+ if seen.insert(id.to_ascii_lowercase()) {
+ models.push(ModelInfo {
+ id: (*id).to_string(),
+ owned_by: Some("openai-codex".to_string()),
+ context_window: None,
+ display_name: None,
+ input_per_1m: None,
+ output_per_1m: None,
+ });
+ }
+ }
+}
+
+#[allow(dead_code)]
+pub fn model_items_from_body(body: &serde_json::Value) -> Option<Vec<serde_json::Value>> {
+ body.get("data")
+ .and_then(|d| d.as_array())
+ .or_else(|| body.get("models").and_then(|d| d.as_array()))
+ .cloned()
+}
+
+fn model_info_from_catalog_item(item: &serde_json::Value) -> Option<ModelInfo> {
+ if let Some(id) = item.as_str().map(str::trim).filter(|id| !id.is_empty()) {
+ return Some(ModelInfo {
+ id: id.to_string(),
+ owned_by: None,
+ context_window: None,
+ display_name: None,
+ input_per_1m: None,
+ output_per_1m: None,
+ });
+ }
+
+ let id = item
+ .get("id")
+ .or_else(|| item.get("slug"))
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|id| !id.is_empty())?
+ .to_string();
+ let owned_by = item
+ .get("owned_by")
+ .or_else(|| item.get("owned_by_organization"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+ let context_window = item
+ .get("context_length")
+ .or_else(|| item.get("context_window"))
+ .or_else(|| item.get("max_context_window"))
+ .and_then(|v| v.as_u64());
+ let display_name = item
+ .get("display_name")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(|s| s.to_string());
+ // `pricing` is already the CHARGED price per 1M tokens on the managed
+ // catalog listing, so it can be surfaced verbatim — no margin math here.
+ let pricing = item.get("pricing");
+ let price = |key: &str| -> Option<f64> {
+ pricing
+ .and_then(|p| p.get(key))
+ .and_then(|v| v.as_f64())
+ .filter(|n| n.is_finite() && *n >= 0.0)
+ };
+ Some(ModelInfo {
+ id,
+ owned_by,
+ context_window,
+ display_name,
+ input_per_1m: price("inputPer1M"),
+ output_per_1m: price("outputPer1M"),
+ })
+}
diff --git a/crates/openhuman-core/src/integrations/client/errors.rs b/crates/openhuman-core/src/integrations/client/errors.rs
new file mode 100644
index 0000000000..e47746469b
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/client/errors.rs
@@ -0,0 +1,271 @@
+//! Backend error classification for [`IntegrationClient`]: extracting a
+//! readable detail from an error body, mapping SDK errors to `anyhow`, and
+//! handling the session-JWT 401 → session-expiry recovery path.
+
+use std::error::Error as _;
+use tinyhumans_sdk::Error as SdkError;
+
+use crate::integrations::types::BackendResponse;
+
+use super::construct::IntegrationClient;
+
+/// Maximum length (in bytes) of backend error body included in propagated
+/// errors. Keep this bounded — error messages flow through tracing/Sentry and
+/// are surfaced in user-facing toasts, neither of which want a 100KB blob.
+pub(super) const MAX_ERROR_BODY_LEN: usize = 500;
+
+/// Extract a human-readable failure detail from a backend error response body.
+///
+/// The backend wraps every error response in
+/// `{ "success": false, "error": "<msg>" }` (see
+/// `backend-openhuman/src/middlewares/errorHandler.ts`). When the body parses
+/// as that envelope, return the inner `error` string verbatim — it is the
+/// authoritative failure message (e.g. `"Insufficient balance"`,
+/// `"Toolkit \"X\" is not enabled"`).
+///
+/// Otherwise (non-JSON body, missing `error` field) fall back to the raw
+/// text truncated to `max_bytes` at a UTF-8 char boundary so callers always
+/// get *something* to grep for, without unbounded memory in error paths.
+pub(super) fn extract_error_detail(body: &str, max_bytes: usize) -> String {
+ if body.is_empty() {
+ return "<empty body>".to_string();
+ }
+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {
+ if let Some(msg) = v.get("error").and_then(|e| e.as_str()) {
+ let trimmed = msg.trim();
+ if !trimmed.is_empty() {
+ return crate::util::truncate_at_byte_boundary(trimmed, max_bytes);
+ }
+ }
+ }
+ crate::util::truncate_at_byte_boundary(body, max_bytes)
+}
+
+/// Handle a `401 Unauthorized` from the OpenHuman backend's
+/// `/agent-integrations/*` routes.
+///
+/// **Why this 401 is unambiguously a session-JWT rejection.** Every request
+/// from [`IntegrationClient`] attaches the *app-session JWT* as its
+/// `Authorization: Bearer` — [`super::construct::IntegrationClient::new`] resolves the
+/// token via [`crate::api::jwt::get_session_token`], the same token billing / team /
+/// webhooks / memory all use. The backend's auth middleware
+/// (`backend-openhuman`) is what answers `401 {"error":"Invalid token"}` when
+/// that JWT is expired / revoked / rotated server-side — see the identical
+/// envelope pinned in `inference/provider/config_rejection.rs` and the socket
+/// reconnect loop's `"Invalid token"` handling in
+/// `openhuman::platform::socket::ws_loop`. A *third-party* integration's auth failure
+/// never reaches this arm:
+///
+/// - **Composio backend mode** (the default that routes through this client):
+/// provider-side failures come back as `2xx` envelope `success:false`
+/// (`"Toolkit X is not enabled"`, `"Missing required fields: …"`) or a
+/// descriptive non-401 4xx/5xx — handled by
+/// [`crate::core::observability::is_provider_user_state_message`] /
+/// [`crate::core::observability::is_backend_user_error_message`], NOT a bare
+/// 401. The backend's auth wall is the only thing that returns 401 here.
+/// - **Composio direct mode**: bypasses this client entirely (it talks to
+/// `backend.composio.dev` with `x-api-key` via `ComposioTool`), so a
+/// direct-mode key 401 carries the distinct `"[composio-direct] … HTTP 401:
+/// Invalid API key"` shape and never lands here.
+///
+/// So narrowing to `status == 401` (and *only* 401 — 403 stays generic, it can
+/// be an authz/scope rejection on a backend-mediated resource rather than a
+/// dead session) targets exactly the session-JWT rejection with zero risk of
+/// logging the user out for an unrelated integration problem.
+///
+/// What this does, mirroring `api/rest.rs::flatten_authed_error` (typed-401 →
+/// `SESSION_EXPIRED:` sentinel) and
+/// `inference/provider/ops/http_error.rs::publish_backend_session_expired`
+/// (direct publish for paths whose error is consumed inline / swallowed):
+///
+/// 1. Build a `SESSION_EXPIRED:`-prefixed message so it (a) classifies as
+/// [`crate::core::observability::ExpectedErrorKind::SessionExpired`] and
+/// stays demoted from Sentry, and (b) is recognised by
+/// `core::jsonrpc::is_session_expired_error` *if* it ever propagates up to
+/// the RPC boundary.
+/// 2. **Publish `DomainEvent::SessionExpired` directly.** The autonomous agent
+/// tool path converts tool errors into a `role:tool` result string fed back
+/// to the model — the `Err` never
+/// reaches `jsonrpc::invoke_method`, so relying on propagation alone would
+/// leave re-login un-triggered (this is the root-cause gap behind
+/// TAURI-RUST-84E: the prior fix demoted the noise but never drove
+/// recovery). Publishing here makes the credentials subscriber clear the
+/// session and the UI prompt re-sign-in regardless of which call site
+/// surfaced the 401.
+fn handle_session_jwt_unauthorized(method: &str, path: &str, url: &str, detail: &str) -> String {
+ let message = format!(
+ "SESSION_EXPIRED: backend rejected session token on {method} {path} \
+ (401 for {url}: {detail}) — sign in again to resume"
+ );
+
+ let soft = is_composio_soft_auth_path(method, path);
+
+ tracing::warn!(
+ path = %path,
+ method = %method,
+ soft_auth = soft,
+ "[integrations] backend rejected session JWT (401)"
+ );
+
+ // Demote from Sentry (SESSION_EXPIRED classifies as expected) — keeps the
+ // noise suppression the prior fix established. Applies to both paths.
+ crate::core::observability::report_error_or_expected(
+ message.as_str(),
+ "integrations",
+ "session_expired",
+ &[
+ ("path", path),
+ ("status", "401"),
+ ("failure", "session_jwt"),
+ ],
+ );
+
+ // Soft path: surface the sentinel to the caller (→ in-place CTA) WITHOUT
+ // the global sign-out. See `is_composio_soft_auth_path`.
+ if soft {
+ tracing::debug!(
+ path = %path,
+ "[integrations] soft composio auth path — returning SESSION_EXPIRED to the panel without publishing global SessionExpired (#4281)"
+ );
+ return message;
+ }
+
+ // Drive recovery: publish SessionExpired so the credentials subscriber
+ // clears the stale token and the UI prompts re-sign-in. The reason string
+ // is already free of secrets (it names the path + sanitized backend
+ // `error` detail), but re-scrub for defense-in-depth before it reaches the
+ // subscriber's logs.
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
+ source: format!("integrations.{method}:{path}"),
+ reason: crate::inference::provider::ops::sanitize_api_error(&message),
+ });
+
+ message
+}
+
+/// Composio **trigger-catalog reads** (`GET /agent-integrations/composio/triggers…`)
+/// where a 401 is a single recoverable read failure rather than whole-session
+/// death. The connection itself is still active — `list_connections` uses the
+/// *same* session JWT and succeeds, so signing the user out on a triggers-only
+/// 401 over-reacts and (per #2286) must not happen.
+///
+/// For these reads [`handle_session_jwt_unauthorized`] still builds the
+/// `SESSION_EXPIRED:` sentinel (so the trigger panel can classify the error and
+/// render an in-place "Sign in again" CTA) and still demotes from Sentry, but
+/// it does **not** publish [`DomainEvent::SessionExpired`] — that global
+/// teardown would unmount the panel before the CTA is usable (#4281). A
+/// genuinely dead session is still caught by the authoritative paths
+/// (app-state snapshot, connections poll), which keep driving re-login.
+///
+/// Scoped to `GET` deliberately: trigger **writes** (`POST` enable / disable /
+/// create) keep the standard global-sign-out on a 401 — they are not the
+/// "catalog won't load" surface this issue addresses, and a write that 401s on
+/// a dead session has no in-place CTA to fall back to (its error renders as a
+/// per-row toggle failure, not the panel banner).
+pub(super) fn is_composio_soft_auth_path(method: &str, path: &str) -> bool {
+ // Match on a real path boundary, not a bare prefix: `…/triggers` exact,
+ // `…/triggers/…` (the `available` catalog), or `…/triggers?…` (the active
+ // list with a `toolkit` query). A bare `starts_with` would also match an
+ // unrelated `…/triggersXYZ` route and wrongly suppress the global sign-out.
+ const BASE: &str = "/agent-integrations/composio/triggers";
+ method.eq_ignore_ascii_case("GET")
+ && path
+ .strip_prefix(BASE)
+ .is_some_and(|rest| rest.is_empty() || rest.starts_with('/') || rest.starts_with('?'))
+}
+
+impl IntegrationClient {
+ /// Render a reqwest transport error with its full source chain (mirrors
+ /// the inline closures in [`Self::post`] / [`Self::get`]) and route it
+ /// through the observability classifier so network-environment failures
+ /// skip Sentry.
+ pub(super) fn report_transport_error(
+ e: reqwest::Error,
+ method: &str,
+ path: &str,
+ url: &str,
+ ) -> anyhow::Error {
+ let mut chain = format!("{e}");
+ let mut src: Option<&(dyn std::error::Error + 'static)> = e.source();
+ while let Some(s) = src {
+ chain.push_str(" → ");
+ chain.push_str(&s.to_string());
+ src = s.source();
+ }
+ crate::core::observability::report_error_or_expected(
+ chain.as_str(),
+ "integrations",
+ method,
+ &[("path", path), ("failure", "transport")],
+ );
+ anyhow::anyhow!("{} {} failed: {}", method.to_uppercase(), url, chain)
+ }
+
+ pub(super) fn map_sdk_error(error: SdkError, method: &str, path: &str, url: &str) -> anyhow::Error {
+ let method_upper = method.to_uppercase();
+ match error {
+ SdkError::Http(error) => Self::report_transport_error(error, method, path, url),
+ SdkError::Status { status, body } => {
+ let body_text = match body {
+ serde_json::Value::String(text) => text,
+ value => value.to_string(),
+ };
+ let detail = extract_error_detail(&body_text, MAX_ERROR_BODY_LEN);
+ if status == reqwest::StatusCode::UNAUTHORIZED.as_u16() {
+ return anyhow::anyhow!(handle_session_jwt_unauthorized(
+ &method_upper,
+ path,
+ url,
+ &detail
+ ));
+ }
+ let status_text = reqwest::StatusCode::from_u16(status)
+ .map(|status| status.to_string())
+ .unwrap_or_else(|_| status.to_string());
+ let status_code = status.to_string();
+ crate::core::observability::report_error_or_expected(
+ format!("Backend returned {status_text} for {method_upper} {url}: {detail}")
+ .as_str(),
+ "integrations",
+ method,
+ &[
+ ("path", path),
+ ("status", status_code.as_str()),
+ ("failure", "non_2xx"),
+ ],
+ );
+ anyhow::anyhow!("Backend returned {status_text} for {method_upper} {url}: {detail}")
+ }
+ other => anyhow::anyhow!("{method_upper} {url} failed: {other}"),
+ }
+ }
+
+ pub(super) fn parse_envelope<T: serde::de::DeserializeOwned>(
+ method: &str,
+ path: &str,
+ url: &str,
+ value: serde_json::Value,
+ ) -> anyhow::Result<T> {
+ let method_upper = method.to_uppercase();
+ let envelope: BackendResponse<T> = serde_json::from_value(value)?;
+ if !envelope.success {
+ let msg = envelope
+ .error
+ .unwrap_or_else(|| "unknown backend error".into());
+ crate::core::observability::report_error_or_expected(
+ msg.as_str(),
+ "integrations",
+ method,
+ &[("path", path), ("failure", "envelope_error")],
+ );
+ anyhow::bail!("Backend error for {} {}: {}", method_upper, url, msg);
+ }
+ envelope.data.ok_or_else(|| {
+ anyhow::anyhow!(
+ "Backend returned success but no data for {} {}",
+ method_upper,
+ url
+ )
+ })
+ }
+}