Skip to content

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

refactor(inference): split model ops into catalog and managed modules

Steven Enamakel44944a919339
diff --git a/crates/openhuman-core/src/inference/provider/ops/models.rs b/crates/openhuman-core/src/inference/provider/ops/models.rs
index baeeb2b554..0cf68d521c 100644
--- a/crates/openhuman-core/src/inference/provider/ops/models.rs
+++ b/crates/openhuman-core/src/inference/provider/ops/models.rs
@@ -22,7 +22,6 @@ use tinyinference_llm::providers::openai::codex::{
mod catalog_listing;
mod local_runtime;
-mod managed_provider;
mod openrouter;
use tinyinference_llm::catalog::{
append_query_param, endpoint_hosts_models_listing, is_openrouter_provider,
@@ -37,10 +36,6 @@ pub use local_runtime::synthesize_local_runtime_entry;
// Cross-submodule wiring: each submodule reaches these through `use super::*;`
// (mirrors the pre-split `include!`-shared scope).
-use managed_provider::{
- managed_401_means_signed_out, managed_session_attaches, synthesize_managed_entry,
- url_is_credential_safe,
-};
use openrouter::validate_openrouter_api_key;
#[cfg(test)]
diff --git a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs
index b7d2e5d470..bc01c6418c 100644
--- a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs
+++ b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs
@@ -33,6 +33,18 @@ pub(super) fn resolve_local_runtime_key(
looked_up
}
+/// The empty listing the managed provider answers with when no hosted catalog
+/// is registered.
+fn no_managed_catalog() -> crate::core::Outcome<serde_json::Value> {
+ log::info!(
+ "[providers][list_models] managed catalog unavailable: no catalog provider registered; returning an empty list"
+ );
+ crate::core::Outcome::new(
+ serde_json::json!({ "models": Vec::<ModelInfo>::new() }),
+ vec!["no hosted backend; managed catalog is empty".to_string()],
+ )
+}
+
pub async fn list_configured_models(
provider_id: &str,
) -> Result<crate::core::Outcome<serde_json::Value>, String> {
@@ -62,6 +74,9 @@ pub async fn list_configured_models_from_config(
);
return (catalog.list)(config.clone()).await;
}
+ if provider_id == crate::inference::provider::factory::PROVIDER_OPENHUMAN {
+ return Ok(no_managed_catalog());
+ }
// Explicit `cloud_providers` entry wins (e.g. a user-pointed remote
// ollama box at https://ollama.example.com/v1). Falling back to the
@@ -72,9 +87,20 @@ pub async fn list_configured_models_from_config(
.find(|e| e.id == provider_id || e.slug == provider_id)
.cloned()
.or_else(|| synthesize_local_runtime_entry(&provider_id, config))
- .or_else(|| synthesize_managed_entry(&provider_id))
.ok_or_else(|| format!("no cloud provider with id or slug '{}' found", provider_id))?;
+ // An entry that authenticates with the managed session is the managed
+ // catalog: the registered provider lists it, and with none registered
+ // there is nothing to list.
+ if entry.auth_style == crate::config::schema::cloud_providers::AuthStyle::OpenhumanJwt {
+ return match crate::inference::registry::catalog(
+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,
+ ) {
+ Some(catalog) => (catalog.list)(config.clone()).await,
+ None => Ok(no_managed_catalog()),
+ };
+ }
+
// Sentry TAURI-RUST-114C/114D: the app stores Claude Code with the cosmetic
// endpoint `cli://claude-code`. It runs as a local CLI and has no `/models`
// listing, and reqwest cannot build a request for a non-http(s) URL, so the
@@ -135,107 +161,10 @@ pub async fn list_configured_models_from_config(
crate::config::build_runtime_proxy_client_with_timeouts(service_key, 30, 10)
};
- // Managed backend (`openhuman`) needs a different URL *and* a different
- // credential than every BYOK provider above, so neither `entry.endpoint`
- // nor `lookup_key_for_slug` is usable here:
- //
- // * the seeded entry's endpoint is the *chat* base
- // (`https://api.openhuman.ai/v1`), so `{endpoint}/models` would probe
- // the wrong host entirely — the hosted API is resolved by
- // `effective_backend_api_url`, which also ignores an `api_url`
- // override pointing at a local/third-party inference host.
- // * the session JWT lives in the `app-session` auth profile, not
- // `provider:openhuman`, so `lookup_key_for_slug` returns "" and the
- // request would go out unauthenticated (401).
- //
- // `?catalog=openrouter` is required: without it the backend returns only
- // the curated legacy list, which is deliberately
- // byte-identical to the legacy payload. The catalog listing is gated
- // server-side by OPENROUTER_PASSTHROUGH_ENABLED and returns an empty set
- // when the passthrough is off, so this degrades to "no models" rather than
- // an error on a backend that has not enabled it.
- let mut managed_token = String::new();
- if entry.auth_style == AuthStyle::OpenhumanJwt {
- // Do NOT propagate a missing session: a self-hosted entry may carry a
- // provider-scoped key instead, and the auth arm below documents that
- // fallback. Only fail when neither credential exists, so the error the
- // caller sees names the real problem.
- //
- // Classify the session directly rather than going through
- // `require_live_session_token`, which flattens "signed out" and "could
- // not read the credential store" into one opaque Err. A lock timeout or
- // filesystem error is a recoverable fault the picker should surface —
- // swallowing it into a successful empty catalog hides it (review, #6206).
- // A store error still propagates; only a genuinely absent/expired
- // session degrades to an empty list.
- use crate::security::credentials::session_support::{
- classify_session_token, load_app_session_profile, publish_local_session_expiry,
- SessionTokenCheck,
- };
- let profile = load_app_session_profile(config)?;
- match classify_session_token(profile.as_ref(), chrono::Utc::now()) {
- SessionTokenCheck::Live(token) => managed_token = token,
- // Signed out is not a provider failure. The managed catalog has
- // nothing to offer until there is a session, and managed stays
- // selectable on its automatic routing — so return an empty list
- // rather than surfacing "could not load models".
- check if api_key.is_empty() => {
- let reason = match check {
- SessionTokenCheck::Expired => {
- // Still announce the expiry: `require_live_session_token`
- // did this for us before, and without it an expired token
- // stays in the store with nothing prompting a re-auth.
- publish_local_session_expiry("list_configured_models");
- "session expired"
- }
- _ => "no session",
- };
- log::info!(
- "[providers][list_models] managed catalog unavailable — {reason}; returning an empty list"
- );
- return Ok(crate::core::Outcome::new(
- serde_json::json!({ "models": Vec::<ModelInfo>::new() }),
- vec![format!("{reason}; managed catalog is empty")],
- ));
- }
- check => {
- if matches!(check, SessionTokenCheck::Expired) {
- publish_local_session_expiry("list_configured_models");
- }
- log::debug!(
- "[providers][list_models] no live session; falling back to the provider-scoped key"
- );
- }
- }
- let Ok(base) = crate::backend::base_url(&config.api_url) else {
- log::info!(
- "[providers][list_models] managed catalog unavailable — no backend transport; returning an empty list"
- );
- return Ok(crate::core::Outcome::new(
- serde_json::json!({ "models": Vec::<ModelInfo>::new() }),
- vec!["no hosted backend; managed catalog is empty".to_string()],
- ));
- };
- models_url = append_query_param(
- &crate::util::url::join_url(&base, "/openai/v1/models"),
- "catalog",
- "openrouter",
- );
- log::debug!(
- "[providers][list_models] managed catalog url={}",
- models_url
- );
- }
-
if is_openrouter_provider(&entry.slug, &entry.endpoint) {
validate_openrouter_api_key(&client, &routing.endpoint, &api_key).await?;
}
- // Whether the app session token actually made it onto the wire. It is not
- // the same question as "is `managed_token` non-empty": the credential-safety
- // guard below can decline to attach it, and a 401 on an unauthenticated
- // request must not be read as a stale session (review, #6206).
- let mut managed_session_attached = false;
let mut request = client.get(&models_url);
if routing.using_oauth {
request = request
@@ -265,35 +194,8 @@ pub async fn list_configured_models_from_config(
}
r
}
- AuthStyle::OpenhumanJwt => {
- // Prefer the live session JWT resolved above; fall back to a
- // provider-scoped key so a self-hosted entry that stores one still
- // authenticates.
- let token = if !managed_token.is_empty() {
- managed_token.as_str()
- } else {
- api_key.as_str()
- };
- managed_session_attached = managed_session_attaches(&managed_token, &models_url);
- // Never put a bearer credential on the wire in clear text. `https`
- // or a loopback host only — loopback stays allowed so a local
- // backend (BACKEND_URL=http://127.0.0.1:...) still works in dev.
- if !token.is_empty() && url_is_credential_safe(&models_url) {
- // Managed traffic is attributed per embedding product
- // (OpenCompany / desktop); the generic provider client
- // does not carry it, so attach it explicitly.
- request
- .header("Authorization", format!("Bearer {}", token))
- .headers(crate::backend::attribution_headers())
- } else if !token.is_empty() {
- log::warn!(
- "[providers][list_models] refusing to send a bearer token to a non-https, non-loopback URL"
- );
- request
- } else {
- request
- }
- }
+ // Handled above: the managed catalog is served by the registered provider.
+ AuthStyle::OpenhumanJwt => request,
AuthStyle::None => request,
};
@@ -304,29 +206,6 @@ pub async fn list_configured_models_from_config(
let status = response.status();
if !status.is_success() {
- // A 401 from the MANAGED catalog means the caller is not signed in —
- // the stored session was rejected server-side even though its local
- // `exp` was still valid, so `require_live_session_token` handed us a
- // token the backend no longer honours. That is a signed-out state, not
- // a provider failure, and rendering it as "could not load models" put a
- // red error under managed for a user whose only problem is a stale
- // session. Managed stays selectable on its automatic routing, so return
- // an empty catalog and let the app's normal auth surfaces prompt for
- // re-authentication.
- //
- // Scoped to the managed provider on purpose: for a BYOK provider a 401
- // IS the actionable error (a wrong or revoked API key), and hiding it
- // would strand the user with a silently empty dropdown.
- if managed_401_means_signed_out(status.as_u16(), entry.auth_style, managed_session_attached)
- {
- log::info!(
- "[providers][list_models] managed catalog unavailable — backend rejected the session token (401); returning an empty list"
- );
- return Ok(crate::core::Outcome::new(
- serde_json::json!({ "models": Vec::<ModelInfo>::new() }),
- vec!["session not accepted; managed catalog is empty".to_string()],
- ));
- }
let body = response.text().await.unwrap_or_default();
let sanitized = sanitize_api_error(&body);
let truncated = crate::util::truncate_with_ellipsis(&sanitized, 300);
diff --git a/crates/openhuman-core/src/inference/provider/ops/models/managed_provider.rs b/crates/openhuman-core/src/inference/provider/ops/models/managed_provider.rs
deleted file mode 100644
index bf9b662403..0000000000
--- a/crates/openhuman-core/src/inference/provider/ops/models/managed_provider.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-//! Managed-provider (`openhuman`) synthesis and session-safety helpers for
-//! the `/models` listing.
-//!
-//! These exist because the MANAGED backend is not just another entry in
-//! `cloud_providers`: it has its own URL, its own credential, and its own
-//! meaning for a 401.
-
-/// Synthesize the managed (`openhuman`) provider entry when `cloud_providers`
-/// has no row for it.
-///
-/// The row is normally seeded by the `unify_ai_provider_settings` migration,
-/// but it is absent in a freshly created profile — which is exactly what the
-/// app falls back to when a stored session is rejected server-side. Managed is
-/// the product's own backend, not user-supplied configuration, so requiring a
-/// config row to list its models turned "signed out" into
-/// "no cloud provider with id or slug 'openhuman' found".
-///
-/// Endpoint and auth style only have to identify the entry as managed: the
-/// caller replaces the URL with `effective_backend_api_url` and the credential
-/// with the live session token before the request goes out.
-pub(super) fn synthesize_managed_entry(
- slug: &str,
-) -> Option<crate::config::schema::cloud_providers::CloudProviderCreds> {
- use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};
- if slug != "openhuman" {
- return None;
- }
- Some(CloudProviderCreds {
- id: "openhuman".to_string(),
- slug: "openhuman".to_string(),
- label: "OpenHuman".to_string(),
- endpoint: crate::config::schema::cloud_providers::builtin_cloud_provider("openhuman")
- .expect("managed builtin")
- .endpoint
- .to_string(),
- auth_style: AuthStyle::OpenhumanJwt,
- ..Default::default()
- })
-}
-
-/// Whether a bearer credential may be attached to this URL.
-///
-/// `https` always, plus loopback over plain `http` so a locally-hosted backend
-/// (`BACKEND_URL=http://127.0.0.1:5005`) still authenticates in development. Any
-/// other plaintext destination gets the request without the credential rather
-/// than leaking it.
-pub(super) fn url_is_credential_safe(url: &str) -> bool {
- match reqwest::Url::parse(url) {
- Ok(parsed) => {
- if parsed.scheme() == "https" {
- return true;
- }
- matches!(
- parsed.host_str(),
- Some("localhost" | "127.0.0.1" | "::1" | "[::1]")
- )
- }
- // Unparseable: treat as unsafe rather than guessing.
- Err(_) => false,
- }
-}
-
-/// Whether the app session token will actually be attached to the managed
-/// request — the input to [`managed_401_means_signed_out`].
-///
-/// This is deliberately not "is there a session": `url_is_credential_safe`
-/// refuses to put a bearer token on a non-https, non-loopback URL, and in that
-/// case the request goes out unauthenticated even though a live session exists.
-/// A 401 on that request describes the misconfigured URL, not the session.
-///
-/// Note the token-emptiness check in the caller is subsumed here: whenever
-/// `managed_token` is non-empty it *is* the token being sent, so a non-empty
-/// managed token plus a safe URL is exactly the attach condition.
-pub(super) fn managed_session_attaches(managed_token: &str, url: &str) -> bool {
- !managed_token.is_empty() && url_is_credential_safe(url)
-}
-
-/// Whether a non-2xx from a `/models` probe should be read as "signed out"
-/// rather than a provider failure.
-///
-/// Only for the MANAGED provider, and only on 401. A managed 401 means the
-/// stored session was rejected server-side — often while its local `exp` is
-/// still valid, so nothing upstream flagged it — which is a signed-out state,
-/// not a broken provider. For a BYOK provider a 401 IS the actionable error (a
-/// wrong or revoked API key); swallowing it there would strand the user with a
-/// silently empty dropdown and no clue why.
-pub(super) fn managed_401_means_signed_out(
- status: u16,
- auth_style: crate::config::schema::cloud_providers::AuthStyle,
- managed_session_attached: bool,
-) -> bool {
- use crate::config::schema::cloud_providers::AuthStyle;
- // Only a 401 on a request that actually carried the app session token says
- // anything about the session. The two other ways to reach a 401 here are
- // real, actionable faults that must not be hidden behind an empty catalog
- // just because the entry's auth_style is OpenhumanJwt (review, #6206):
- //
- // * no session, so the request went out on the provider-scoped fallback
- // key — a 401 means THAT key is wrong or revoked.
- // * a live session that the credential-safety guard refused to attach
- // (non-https, non-loopback backend URL) — the request was
- // unauthenticated, and the misconfigured URL is the thing to report.
- status == 401 && auth_style == AuthStyle::OpenhumanJwt && managed_session_attached
-}