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
feat(inference): classify provider HTTP errors into typed failures
Steven Enamakel7b2be4b28457
diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error.rs b/crates/openhuman-core/src/inference/provider/ops/http_error.rsindex 1185aa61e4..763f2a58ec 100644--- a/crates/openhuman-core/src/inference/provider/ops/http_error.rs+++ b/crates/openhuman-core/src/inference/provider/ops/http_error.rs@@ -1,60 +1,217 @@-//! HTTP error classification, Sentry-report demotion, and `api_error`.-//!-//! Sub-modules, by responsibility:-//! - [`quota_and_credits`] — budget-exhausted, insufficient-credits, monthly-//! quota exhaustion, and per-request rate-cap classification.-//! - [`local_provider`] — local server "no model loaded" and Ollama Cloud's-//! opaque hosted-inference 500.-//! - [`policy_rejection`] — custom-OpenAI upstream envelopes, provider-//! access-policy denial, backend-owned error codes, moderation rejection,-//! and provider configuration rejection.-//! - [`context_window`] — context-window overflow classification.-//! - [`auth_failure`] — backend session expiry, BYO API-key rejection, and-//! OpenAI OAuth session expiry.-//! - [`dispatch`] — `should_report_provider_http_failure` and the `api_error`-//! entry point that runs a failed response through every classifier above.+//! Host policy over `tinyinference_llm::failure::http`: the body/status+//! classifiers and user messages live upstream; this module owns only the+//! OpenHuman-specific reaction (backend polarity guards, `SessionExpired` /+//! `ProviderApiKeyRejected` publishing, Sentry demotion) behind an+//! [`ErrorReporter`].#[cfg(test)]#[path = "http_error_tests.rs"]mod tests;-mod auth_failure;-mod context_window;-mod dispatch;-mod local_provider;-mod policy_rejection;-mod quota_and_credits;--// Shared imports every classifier submodule reaches through `use super::*;`-// (mirrors the pre-split `include!`-shared scope).use crate::inference::provider::openhuman_backend_model;use tinyinference_core::sanitize::sanitize_api_error;+use tinyinference_llm::failure::http::{+ classify_and_report_http_failure, ErrorReporter, ProviderHttpFailure,+};use tinyinference_llm::failure::{- body_indicates_quota_exhausted, is_context_window_exceeded_message,+ local_provider_no_model_loaded_user_message, ollama_cloud_internal_500_user_message,+ should_report_provider_http_status,};-pub use auth_failure::{- is_backend_auth_failure, is_byo_provider_auth_failure_http,- is_openai_oauth_session_expired_http, log_byo_provider_auth_failure,- log_openai_oauth_session_expired, publish_backend_session_expired,-};-pub use context_window::log_context_window_exceeded;-pub use dispatch::{api_error, should_report_provider_http_failure};-pub use local_provider::{- is_local_provider_no_model_loaded, is_ollama_cloud_internal_500,- is_ollama_cloud_internal_500_message, local_provider_no_model_loaded_user_message,- log_local_provider_no_model_loaded, log_ollama_cloud_internal_500,- ollama_cloud_internal_500_user_message,-};-pub use policy_rejection::{- is_backend_error_code_owned, is_custom_openai_upstream_bad_request_http_400,- is_provider_access_policy_denied_http_403, is_provider_config_rejection_http,- is_provider_moderation_rejection_http_400, log_backend_error_code_owned,- log_custom_openai_upstream_bad_request_http_400, log_provider_access_policy_denied_http_403,- log_provider_config_rejection, log_provider_moderation_rejection,-};-pub use quota_and_credits::{- is_budget_exhausted_http_400, is_provider_insufficient_credits_402,- log_budget_exhausted_http_400, log_provider_insufficient_credits_402,- log_provider_quota_exhausted,-};+/// Whether a non-2xx provider status is worth a per-attempt Sentry report.+pub fn should_report_provider_http_failure(status: reqwest::StatusCode) -> bool {+ should_report_provider_http_status(status.as_u16())+}++/// Whether this is the OpenHuman backend rejecting the app session JWT.+pub fn is_backend_auth_failure(provider: &str, status: reqwest::StatusCode) -> bool {+ matches!(status.as_u16(), 401 | 403) && provider == openhuman_backend_model::PROVIDER_LABEL+}++/// Whether the response carries a managed-backend `errorCode` the backend+/// already owns. Only trustworthy on the managed backend provider.+pub fn is_backend_error_code_owned(provider: &str, body: &str) -> bool {+ provider == openhuman_backend_model::PROVIDER_LABEL+ && crate::inference::provider::backend_error_code_skips_sentry(body)+}++fn log_user_state(+ level_warn: bool,+ kind: &str,+ reason: &str,+ operation: &str,+ provider: &str,+ model: Option<&str>,+ status: u16,+) {+ if level_warn {+ tracing::warn!(+ domain = "llm_provider", operation, provider, model = model.unwrap_or(""),+ status, failure = "non_2xx", kind, reason,+ "[llm_provider] {operation} {reason} ({status}) — not reporting to Sentry"+ );+ } else {+ tracing::info!(+ domain = "llm_provider", operation, provider, model = model.unwrap_or(""),+ status, failure = "non_2xx", kind, reason,+ "[llm_provider] {operation} {reason} ({status}) — not reporting to Sentry"+ );+ }+}++/// Demote a BYO provider auth failure and, on the first record of the episode,+/// surface it to the user (the registry latch keeps retries from re-flooding).+pub fn log_byo_provider_auth_failure(+ operation: &str,+ provider: &str,+ model: Option<&str>,+ status: reqwest::StatusCode,+) {+ log_user_state(+ false,+ "provider_user_state",+ "byo_provider_auth_failure",+ operation,+ provider,+ model,+ status.as_u16(),+ );+ let status_code = status.as_u16();+ if crate::inference::auth_error_registry::record(provider, status_code) {+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ProviderApiKeyRejected {+ provider: provider.to_string(),+ message: crate::inference::auth_error_registry::auth_error_message(+ provider,+ status_code,+ ),+ });+ }+}++/// Publish `SessionExpired` for a backend 401/403 and skip the Sentry report.+/// `message` is re-sanitized before it reaches the subscriber's logs.+pub fn publish_backend_session_expired(+ operation: &str,+ provider: &str,+ status: reqwest::StatusCode,+ message: &str,+) {+ tracing::warn!(+ domain = "llm_provider",+ operation = operation,+ provider = provider,+ status = status.as_u16(),+ "[llm_provider] backend auth failure ({status}) — publishing SessionExpired"+ );+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {+ source: "llm_provider.openhuman_backend".to_string(),+ reason: sanitize_api_error(message),+ });+}++/// The OpenHuman [`ErrorReporter`]: applies backend polarity guards and+/// demotes expected user/provider state; reports the rest to Sentry.+struct HostErrorReporter<'a> {+ message: &'a str,+ backend_error_code_owned: bool,+}++impl ErrorReporter for HostErrorReporter<'_> {+ fn report(&self, failure: ProviderHttpFailure<'_>) {+ let ProviderHttpFailure {+ provider,+ operation,+ model,+ status,+ facts,+ } = failure;+ let is_backend = provider == openhuman_backend_model::PROVIDER_LABEL;+ let status_code =+ reqwest::StatusCode::from_u16(status).unwrap_or(reqwest::StatusCode::BAD_GATEWAY);+ let demote = |kind: &str, reason: &str, warn: bool| {+ log_user_state(warn, kind, reason, operation, provider, model, status);+ };+ // The managed backend's unknown-model body is user-state on every+ // provider; the remaining config-rejection phrases stay third-party+ // scoped so a backend regression still reaches Sentry.+ let config_rejected = facts.configuration_rejected && (facts.unknown_model || !is_backend);++ if matches!(status, 401 | 403) && is_backend {+ publish_backend_session_expired(operation, provider, status_code, self.message);+ } else if facts.budget_exhausted {+ demote("budget", "budget-exhausted 400", false);+ } else if facts.no_model_loaded {+ demote("provider_user_state", "local_provider_no_model_loaded", false);+ } else if facts.custom_upstream_bad_request {+ demote("provider_user_state", "custom_openai_upstream_bad_request", false);+ } else if facts.access_policy_denied {+ demote("provider_access_policy", "provider access-policy 403", false);+ } else if config_rejected {+ demote("provider_config_rejection", "provider config-rejection", false);+ } else if facts.context_window_exceeded {+ demote("context_window_exceeded", "context-window exceeded", true);+ } else if facts.quota_exhausted {+ demote("quota_exhausted", "provider monthly-quota exhausted", false);+ } else if self.backend_error_code_owned {+ demote("backend_error_code", "backend errorCode owned", false);+ } else if facts.api_key_rejected && !is_backend {+ log_byo_provider_auth_failure(operation, provider, model, status_code);+ } else if facts.oauth_session_expired && !is_backend {+ demote("provider_user_state", "openai_oauth_session_expired", false);+ } else if facts.insufficient_credits {+ demote("insufficient_credits", "provider insufficient-credits 402", false);+ } else if facts.ollama_cloud_internal_error {+ demote("ollama_cloud_internal_500", "Ollama Cloud hosted-inference 500", false);+ } else if facts.moderation_rejected {+ demote("external_moderation_rejection", "external content-moderation rejection", false);+ } else if should_report_provider_http_status(status) {+ let status_str = status.to_string();+ crate::core::observability::report_error(+ self.message,+ "llm_provider",+ "api_error",+ &[+ ("provider", provider),+ ("status", status_str.as_str()),+ ("failure", "non_2xx"),+ ],+ );+ }+ }+}++/// Build a sanitized provider error from a failed HTTP response, classifying+/// it upstream and routing the reaction through [`HostErrorReporter`].+pub async fn api_error(provider: &str, response: reqwest::Response) -> anyhow::Error {+ let status = response.status();+ let body = response+ .text()+ .await+ .unwrap_or_else(|_| "<failed to read provider error body>".to_string());+ let message = format!(+ "{provider} API error ({status}): {}",+ sanitize_api_error(&body)+ );+ let reporter = HostErrorReporter {+ message: &message,+ backend_error_code_owned: is_backend_error_code_owned(provider, &body),+ };+ let facts = classify_and_report_http_failure(+ provider,+ "api_error",+ None,+ status.as_u16(),+ &body,+ &reporter,+ );+ if facts.ollama_cloud_internal_error {+ return anyhow::anyhow!(ollama_cloud_internal_500_user_message(+ None,+ status.as_u16()+ ));+ }+ if facts.no_model_loaded {+ return anyhow::anyhow!(local_provider_no_model_loaded_user_message());+ }+ anyhow::anyhow!(message)+}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rsdeleted file mode 100644index b6549584e2..0000000000--- a/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rs+++ /dev/null@@ -1,253 +0,0 @@-//! Auth-failure classification: backend app-session expiry, BYO API-key-//! rejection, and OpenAI OAuth (ChatGPT/Codex) session expiry.--use super::*;--/// Whether a provider non-2xx response is the OpenHuman **backend** rejecting-/// the app session JWT (`401`/`403`). This is expected user-session state-/// (token expired / revoked / rotated server-side), not a product bug — the-/// auth domain owns recovery, so the predicate is provider-scoped to-/// [`openhuman_backend_model::PROVIDER_LABEL`]. A `401`/`403` from **other** providers-/// with an auth-key envelope (missing/invalid BYO key) is demoted separately by-/// [`is_byo_provider_auth_failure_http`]; anything else still reaches Sentry.-pub fn is_backend_auth_failure(provider: &str, status: reqwest::StatusCode) -> bool {- matches!(status.as_u16(), 401 | 403) && provider == openhuman_backend_model::PROVIDER_LABEL-}--/// Whether a non-backend provider's `401`/`403` carries an OpenAI-style-/// authentication-error body — i.e. a missing or invalid BYO API key.-///-/// This is deterministic **user-config** state (the user pasted a bad or empty-/// key into a custom OpenAI-compatible provider), not a product bug. Sentry has-/// no remediation path, yet retry loops (background jobs,-/// cron) hammer the known-bad credential and flood Sentry with thousands of-/// identical events from a single user — TAURI-RUST-DHM (5,636 events from a-/// `kiro` custom provider with no key), the same class as the Cohere-/// "no api key supplied" flood (#3354) and the backend session-expiry flood-/// (#2786 / [`is_backend_auth_failure`]).-///-/// Provider-scoped and body-shape-anchored, mirroring the sibling rules:-/// - The OpenHuman **backend** keeps its [`is_backend_auth_failure`] →-/// [`publish_backend_session_expired`] branch (a backend `401`/`403` is-/// app-session expiry, not a BYO key), so this predicate excludes-/// [`openhuman_backend_model::PROVIDER_LABEL`].-/// - A `401`/`403` whose body does **not** look like an auth-key envelope-/// (e.g. a gateway returning `401` on quota / geo-block) still reaches Sentry-/// — the gate keys on the body, not the bare status.-pub fn is_byo_provider_auth_failure_http(- provider: &str,- status: reqwest::StatusCode,- body: &str,-) -> bool {- if !matches!(status.as_u16(), 401 | 403) {- tracing::debug!(- domain = "llm_provider",- operation = "http_error_classifier",- provider = provider,- status = status.as_u16(),- matched = false,- reason = "byo_provider_auth_failure_probe:non_auth_status",- "[llm_provider] BYO auth-failure classifier skipped — status is not 401/403"- );- return false;- }- if provider == openhuman_backend_model::PROVIDER_LABEL {- tracing::debug!(- domain = "llm_provider",- operation = "http_error_classifier",- provider = provider,- status = status.as_u16(),- matched = false,- reason = "byo_provider_auth_failure_probe:backend_excluded",- "[llm_provider] BYO auth-failure classifier skipped — backend owns session-expiry recovery"- );- return false;- }- let lower = body.to_ascii_lowercase();- // The OpenAI-style auth-envelope marker set lives in `tinyinference-llm`- // (`body_indicates_auth_key_error`).- let matched = tinyinference_llm::failure::body_indicates_auth_key_error(body)- // OpenRouter's wording for a key that resolves to no account- // (revoked / deleted user): `401 {"error":{"message":"User not- // found.","code":401}}`. Same invalid-BYO-key user-state as the- // markers above — OpenHuman has no lever to make the user's- // third-party account exist. Kept OpenRouter-gated (not a global- // marker): `"user not found"` is generic prose another provider- // could emit for an unrelated 401/403, and demoting that would- // suppress a real error and show the wrong remediation. Without this- // anchor the 401 leaks to Sentry once per memory-summarization retry- // (TAURI-RUST-4RC: ~9k events / 6 users). A verbatim-body test- // couples it to this payload so a wording drift fails CI instead of- // silently leaking.- || (provider == "openrouter" && lower.contains("user not found"));- // Body content is intentionally omitted from the log — it can carry the- // raw (sanitized-or-not) provider payload; only the match outcome is logged.- tracing::debug!(- domain = "llm_provider",- operation = "http_error_classifier",- provider = provider,- status = status.as_u16(),- matched,- reason = "byo_provider_auth_failure_probe",- "[llm_provider] evaluated BYO auth-failure classifier"- );- matched-}--pub fn log_byo_provider_auth_failure(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "provider_user_state",- reason = "byo_provider_auth_failure",- "[llm_provider] {operation} BYO provider auth failure ({status}) — \- user API key missing/invalid, not reporting to Sentry"- );-- // Demoting from Sentry hides the failure from us, so it must not also be- // invisible to the user — the failing path is often a silent background- // loop (memory summarization) that just degrades to regex-only. Record the- // rejection into the process registry that backs the AI-settings- // provider-error notice, and on the *first* record of this episode publish- // a one-shot notification. The 401 repeats per retry (~9k events for- // TAURI-RUST-4RC), so the registry latch is what keeps this from- // re-flooding the notification center the way the raw error flooded Sentry.- let status_code = status.as_u16();- if crate::inference::auth_error_registry::record(provider, status_code) {- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ProviderApiKeyRejected {- provider: provider.to_string(),- message: crate::inference::auth_error_registry::auth_error_message(- provider,- status_code,- ),- });- }-}--/// Whether a `401` is the OpenAI **OAuth** (ChatGPT-subscription / Codex)-/// access token having expired — distinct from a misconfigured BYO API key.-///-/// The ChatGPT/Codex OAuth Responses endpoint returns-/// `{"error":{"code":"token_expired","message":"Provided authentication token-/// is expired. Please try signing in again."}}` once the OAuth access token-/// lapses. The valid-`refresh_token` case already self-heals at credential-/// resolution time (`openai_oauth::lookup_openai_oauth_credentials` refreshes-/// proactively within a 2-min skew, and the chat provider is rebuilt per-/// request), so the residual events that reach this 401 are ones where the-/// refresh token is **absent or revoked** — the user must reconnect OpenAI.-/// That is deterministic user-state, not a server bug, and reporting it spams-/// Sentry (TAURI-RUST-8FQ: 97,938 events / 31 users).-///-/// Keyed on the OAuth-expiry body markers, which an API-key rejection never-/// emits (those say "incorrect api key" — caught by-/// [`is_byo_provider_auth_failure_http`] instead). The OpenHuman **backend**-/// provider is excluded — its `401`/`403` is app-session expiry handled by-/// [`publish_backend_session_expired`]. Unlike that path, this does **not**-/// publish [`crate::core::events::DomainEvent::SessionExpired`]: an expired-/// *provider* OAuth token must not tear down the OpenHuman app session.-pub fn is_openai_oauth_session_expired_http(- provider: &str,- status: reqwest::StatusCode,- body: &str,-) -> bool {- if status.as_u16() != 401 {- tracing::debug!(- domain = "llm_provider",- operation = "http_error_classifier",- provider = provider,- status = status.as_u16(),- matched = false,- reason = "openai_oauth_session_expired_probe:non_401",- "[llm_provider] OpenAI OAuth session-expiry classifier skipped — status is not 401"- );- return false;- }- if provider == openhuman_backend_model::PROVIDER_LABEL {- tracing::debug!(- domain = "llm_provider",- operation = "http_error_classifier",- provider = provider,- status = status.as_u16(),- matched = false,- reason = "openai_oauth_session_expired_probe:backend_excluded",- "[llm_provider] OpenAI OAuth session-expiry classifier skipped — backend owns app-session expiry"- );- return false;- }- let matched = tinyinference_providers::is_openai_oauth_session_expired_message(body);- tracing::debug!(- domain = "llm_provider",- operation = "http_error_classifier",- provider = provider,- status = status.as_u16(),- matched,- reason = "openai_oauth_session_expired_probe",- "[llm_provider] evaluated OpenAI OAuth session-expiry classifier"- );- matched-}--/// Demote an OpenAI OAuth session-expiry `401` to an info log (user-state,-/// not a server bug) instead of reporting it to Sentry. The message tells the-/// user to reconnect OpenAI, which is the only recovery once the refresh token-/// is gone. See [`is_openai_oauth_session_expired_http`].-pub fn log_openai_oauth_session_expired(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "provider_user_state",- reason = "openai_oauth_session_expired",- "[llm_provider] {operation} OpenAI OAuth session expired ({status}) — \- ChatGPT/Codex token lapsed without a usable refresh token; user must \- reconnect OpenAI, not reporting to Sentry"- );-}--/// Handle a backend session-expiry auth failure: publish a-/// [`crate::core::events::DomainEvent::SessionExpired`] so the credentials-/// subscriber clears the session and flips the scheduler-gate signed-out-/// override (halting downstream LLM work — see OPENHUMAN-TAURI-1T), and skip-/// the Sentry report. Mirrors the `is_auth_failure && is_backend` arm in-/// [`super::dispatch::api_error`], factored out for adapter error paths that-/// already consumed the response body and cannot delegate to `api_error`.-///-/// `message` is the already-formatted `"{provider} API error ({status}): …"`-/// string; it embeds the sanitized body, but the prefix and caller-controlled-/// provider name aren't scrubbed, so re-run [`sanitize_api_error`] on the final-/// string before it reaches the SessionExpired subscriber's logs.-pub fn publish_backend_session_expired(- operation: &str,- provider: &str,- status: reqwest::StatusCode,- message: &str,-) {- tracing::warn!(- domain = "llm_provider",- operation = operation,- provider = provider,- status = status.as_u16(),- "[llm_provider] backend auth failure ({status}) — publishing SessionExpired"- );- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {- source: "llm_provider.openhuman_backend".to_string(),- reason: sanitize_api_error(message),- });-}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/context_window.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/context_window.rsdeleted file mode 100644index 7de183fe81..0000000000--- a/crates/openhuman-core/src/inference/provider/ops/http_error/context_window.rs+++ /dev/null@@ -1,22 +0,0 @@-//! Context-window overflow demotion log. The pure body matcher-//! (`is_context_window_exceeded_message`) lives in `tinyinference-llm`'s-//! `failure` module.--pub fn log_context_window_exceeded(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::warn!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "context_window_exceeded",- "[llm_provider] {operation} context-window exceeded ({status}) — \- request too long for the model, not reporting to Sentry"- );-}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/dispatch.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/dispatch.rsdeleted file mode 100644index 5de0dc071c..0000000000--- a/crates/openhuman-core/src/inference/provider/ops/http_error/dispatch.rs+++ /dev/null@@ -1,164 +0,0 @@-//! The `api_error` entry point: reads a failed HTTP response, runs it through-//! every classifier in this module in priority order, demotes the ones that-//! are expected user/provider state, and reports the rest to Sentry.--use super::*;--/// Whether a non-2xx provider response is worth reporting to Sentry.-///-/// Transient upstream statuses — 429 Too Many Requests, 408 Request Timeout,-/// and 502/503/504 gateway-layer failures — are caller-side throttling or-/// upstream-capacity signals. The reliable-provider layer already retries-/// with backoff and falls back across providers/models, and the aggregate-/// "all providers exhausted" event still fires if every attempt fails.-/// Reporting each individual transient failure floods Sentry (see-/// OPENHUMAN-TAURI-6Y / 2E / 84 / T: thousands of events/day per user from-/// a single upstream rate-limit / outage window). Callers should still-/// propagate the error so retry and fallback logic runs unchanged; this-/// only gates the per-attempt Sentry report.-pub fn should_report_provider_http_failure(status: reqwest::StatusCode) -> bool {- !crate::core::observability::TRANSIENT_PROVIDER_HTTP_STATUSES.contains(&status.as_u16())-}--/// Build a sanitized provider error from a failed HTTP response.-///-/// Reports the failure to Sentry with `provider` and `status` tags so-/// upstream LLM errors are visible in observability without every call-site-/// having to remember to log — except for:-///-/// - **Transient statuses** (429 — see [`should_report_provider_http_failure`]).-/// These get retried by the reliable-provider layer and don't deserve a-/// per-attempt Sentry event.-/// - **401/403 from the OpenHuman backend provider** — the user's app session-/// expired. That is expected user-state, not a server bug, and reporting it-/// spams Sentry (OPENHUMAN-TAURI-1T: 5,414 events from a single user whose-/// cron loops kept firing post-expiry). Instead we publish a-/// [`crate::core::events::DomainEvent::SessionExpired`] so the credentials-/// subscriber clears the session and flips the scheduler-gate signed-out-/// override, halting downstream LLM work. 401/403 from **other** providers-/// (OpenAI, Anthropic, …) still go to Sentry — those mean a misconfigured-/// API key, which is actionable.-/// - **Provider config-rejection** (4xx unknown-model / abstract-tier /-/// model-specific temperature) from a **non-backend** provider — the-/// user pointed a custom provider at a model/param it doesn't accept.-/// Deterministic user-config state, surfaced in the UI; demoted to an-/// info log (#2079 / #2076 / #2202). See-/// [`is_provider_config_rejection_http`].-pub async fn api_error(provider: &str, response: reqwest::Response) -> anyhow::Error {- let status = response.status();- let status_str = status.as_u16().to_string();- let body = response- .text()- .await- .unwrap_or_else(|_| "<failed to read provider error body>".to_string());- let sanitized = sanitize_api_error(&body);- let message = format!("{provider} API error ({status}): {sanitized}");-- let is_auth_failure = matches!(status.as_u16(), 401 | 403);- let is_backend = provider == openhuman_backend_model::PROVIDER_LABEL;- let is_budget_exhausted_user_state = is_budget_exhausted_http_400(status, &body);- // Local inference server (LM Studio etc.) running with no model loaded —- // pure local user-state, nothing we sent is malformed. Demote and replace- // the body with actionable "load a model" guidance (TAURI-RUST-DMQ, mirrors- // the embeddings #3688 special-case).- let is_local_provider_no_model_loaded = is_local_provider_no_model_loaded(status, &body);- let is_custom_openai_upstream_bad_request =- is_custom_openai_upstream_bad_request_http_400(provider, status, &body);- let is_provider_access_policy_denied = is_provider_access_policy_denied_http_403(status, &body);- let is_provider_config_rejection = is_provider_config_rejection_http(status, provider, &body);- // Context-overflow is status-agnostic: match the body directly (some- // custom gateways mis-report it as 500 — TAURI-RUST-501 — so a status- // gate would let those through to `should_report_provider_http_failure`).- let is_context_window_exceeded = is_context_window_exceeded_message(&body);- // Monthly-quota exhaustion is likewise status-agnostic: the Kiro IDE proxy- // wraps its 402 inside a 500 envelope (TAURI-RUST-C9A), so match the body- // directly rather than gating on a 402 status (which the credits matcher- // below does). The user's third-party plan quota is spent — no local lever.- let is_quota_exhausted = body_indicates_quota_exhausted(&body);- // F4/F2: any managed-backend response carrying a stable `errorCode` is- // backend-owned — it already paged or is expected user-state — so the FE- // must not double-report. The one exception (malformed `BAD_REQUEST`) is- // excluded by `is_backend_error_code_owned` and falls through to the- // status gate below, which reports it (status 400 is non-transient) — F8.- let is_backend_error_code_owned = is_backend_error_code_owned(provider, &body);- // Missing/invalid BYO API key on a non-backend provider — user-config- // state, not a product bug. Demote from Sentry (TAURI-RUST-DHM flood).- let is_byo_auth_failure = is_byo_provider_auth_failure_http(provider, status, &body);- // OpenAI ChatGPT/Codex OAuth access token expired with no usable refresh- // token — user must reconnect OpenAI. Deterministic user-state, demote- // from Sentry (TAURI-RUST-8FQ flood).- let is_openai_oauth_session_expired =- is_openai_oauth_session_expired_http(provider, status, &body);- // Insufficient-credits 402: the user's own BYO provider account is out of- // balance — a flat billing fact, not a reservation-window error, so there is- // NO local max_tokens lever to apply. Demote from Sentry like the per-method- // compatible-provider arms; the complete classification for a genuinely-- // unpreventable BYO-balance condition (TAURI-RUST-4QF DeepSeek "Insufficient- // Balance"). This shared helper backs the two methods that delegate here- // (chat_via_responses fallback and the non-streaming completion path).- let is_insufficient_credits_402 = is_provider_insufficient_credits_402(status, &body);- // Ollama Cloud hosted-inference 500 (`Internal Server Error (ref: <uuid>)`):- // provider-internal, non-deterministic, no client lever. Demote from Sentry- // and replace the opaque ref body with actionable guidance (TAURI-RUST-5MV).- let is_ollama_cloud_internal_500 = is_ollama_cloud_internal_500(provider, status, &body);- // External content-moderation proxy ("Ombudsman") refused the prompt with a- // 400 + verdict — well-formed request, external safety guard, no client- // lever. Demote from Sentry like the native_chat ladder (TAURI-RUST-ECR).- let is_moderation_rejection = is_provider_moderation_rejection_http_400(status, &body);-- if is_auth_failure && is_backend {- // Single source of truth for backend session-expiry handling (warn +- // SessionExpired publish + final-string sanitize) — shared with the- // hand-rolled `chat_completions` chain in `compatible.rs`.- publish_backend_session_expired("api_error", provider, status, &message);- } else if is_budget_exhausted_user_state {- log_budget_exhausted_http_400("api_error", provider, None, status);- } else if is_local_provider_no_model_loaded {- log_local_provider_no_model_loaded("api_error", provider, None, status);- } else if is_custom_openai_upstream_bad_request {- log_custom_openai_upstream_bad_request_http_400("api_error", provider, None, status);- } else if is_provider_access_policy_denied {- log_provider_access_policy_denied_http_403("api_error", provider, None, status);- } else if is_provider_config_rejection {- log_provider_config_rejection("api_error", provider, None, status);- } else if is_context_window_exceeded {- log_context_window_exceeded("api_error", provider, None, status);- } else if is_quota_exhausted {- log_provider_quota_exhausted("api_error", provider, None, status);- } else if is_backend_error_code_owned {- log_backend_error_code_owned("api_error", provider, None, status, &body);- } else if is_byo_auth_failure {- log_byo_provider_auth_failure("api_error", provider, None, status);- } else if is_openai_oauth_session_expired {- log_openai_oauth_session_expired("api_error", provider, None, status);- } else if is_insufficient_credits_402 {- log_provider_insufficient_credits_402("api_error", provider, None, status);- } else if is_ollama_cloud_internal_500 {- log_ollama_cloud_internal_500("api_error", provider, None, status);- } else if is_moderation_rejection {- log_provider_moderation_rejection("api_error", provider, None, status);- } else if should_report_provider_http_failure(status) {- crate::core::observability::report_error(- message.as_str(),- "llm_provider",- "api_error",- &[- ("provider", provider),- ("status", status_str.as_str()),- ("failure", "non_2xx"),- ],- );- }- // Replace the opaque `Internal Server Error (ref: <uuid>)` body with- // actionable guidance; the prefix anchors the higher-layer re-report- // demotion (`is_ollama_cloud_internal_500_message`).- if is_ollama_cloud_internal_500 {- return anyhow::anyhow!(ollama_cloud_internal_500_user_message(None, status));- }- // Replace the raw `No models loaded` body with actionable guidance so the- // surfaced chat error tells the user how to recover (TAURI-RUST-DMQ).- if is_local_provider_no_model_loaded {- return anyhow::anyhow!(local_provider_no_model_loaded_user_message());- }- anyhow::anyhow!(message)-}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/local_provider.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/local_provider.rsdeleted file mode 100644index dd876955a1..0000000000--- a/crates/openhuman-core/src/inference/provider/ops/http_error/local_provider.rs+++ /dev/null@@ -1,138 +0,0 @@-//! Local inference server (LM Studio / Ollama) user-state classification:-//! no model loaded, and Ollama Cloud's opaque hosted-inference 500.--/// Whether a provider non-2xx response is a local inference server that is-/// running but has **no model loaded** (e.g. LM Studio idle): a 400 carrying-/// `No models loaded. Please load a model …`.-///-/// This is pure local user-state — nothing OpenHuman sent is malformed, there-/// is no product bug and no local lever beyond the user loading a model — so it-/// should be demoted from Sentry to an info log rather than paging on every-/// retry (TAURI-RUST-DMQ: 5,469 events from a single idle LM Studio server).-/// The embeddings path already special-cases this exact string-/// (`embeddings/rpc.rs`, PR #3688 / TAURI-RUST-4P4); this is the chat sibling.-pub fn is_local_provider_no_model_loaded(status: reqwest::StatusCode, body: &str) -> bool {- status == reqwest::StatusCode::BAD_REQUEST- && tinyinference_llm::failure::body_indicates_no_model_loaded(body)-}--/// Actionable user-facing guidance for a local inference server with no model-/// loaded, mirroring the embeddings verification message-/// (`embeddings/rpc.rs`). Returned in place of the raw provider body so the-/// surfaced error tells the user how to fix it.-pub fn local_provider_no_model_loaded_user_message() -> String {- "Your local inference server (e.g. LM Studio) is running but has no model loaded. \- Load a model — in LM Studio use the developer page or the `lms load` command — \- then try again."- .to_string()-}--pub fn log_local_provider_no_model_loaded(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "provider_user_state",- reason = "local_provider_no_model_loaded",- "[llm_provider] {operation} local inference server has no model loaded — \- user must load a model, not reporting to Sentry"- );-}--/// Stable anchor phrase for the actionable Ollama-Cloud-500 user message, shared-/// by [`ollama_cloud_internal_500_user_message`] (which builds it) and-/// [`is_ollama_cloud_internal_500_message`] (which matches the re-raised string-/// at the RPC/agent boundary), so the two cannot drift.-const OLLAMA_CLOUD_INTERNAL_500_USER_PREFIX: &str = "Ollama cloud is temporarily unavailable";--/// Whether a provider non-2xx response is an Ollama **Cloud** hosted-inference-/// internal error: `500` + a `{"error":"Internal Server Error (ref: <uuid>)"}`-/// body.-///-/// ollama.com's hosted `*:cloud` models (minimax-m3 / qwen3.5 / gpt-oss …)-/// intermittently `500` with this opaque, server-generated envelope. The `ref:`-/// is a fresh UUID per event, the failure is non-deterministic, and the request-/// that 500s is byte-identical to the one that succeeds when the cloud backend-/// is healthy — so there is **no client lever** (nothing to validate,-/// reshape, or reconfigure). The reliable-provider layer already retries and-/// falls back across providers/models, so each per-attempt 500 is pure noise:-/// TAURI-RUST-5MV, 3,062 events from 5 users in a single window. Demote from-/// Sentry to an info log while the error still propagates so retry/fallback runs-/// unchanged.-///-/// Anchored on the `internal server error (ref:` body shape, which is specific-/// to ollama.com's hosted envelope — a **local** Ollama daemon 500 (a genuine-/// model crash / OOM worth paging) does not carry a `ref:` UUID, so it still-/// reaches Sentry. The phrase is covered by a verbatim-body test so a provider-/// wording drift fails CI instead of silently leaking events.-pub fn is_ollama_cloud_internal_500(- provider: &str,- status: reqwest::StatusCode,- body: &str,-) -> bool {- provider == "ollama"- && status == reqwest::StatusCode::INTERNAL_SERVER_ERROR- && tinyinference_llm::failure::body_indicates_ollama_cloud_internal_error(body)-}--/// Message-level half of [`is_ollama_cloud_internal_500`]: matches the actionable-/// user message re-raised at the RPC/agent boundary-/// (`core::observability::expected_error_kind`), so the higher-layer re-report is-/// demoted too instead of leaking the event the emit-site already suppressed (the-/// `domain=agent` half of TAURI-RUST-5MV). Mirrors the-/// `is_provider_insufficient_credits_402` / `body_indicates_insufficient_credits`-/// split. Keyed on the [`OLLAMA_CLOUD_INTERNAL_500_USER_PREFIX`] anchor, which we-/// own, so it cannot collide with an unrelated provider body.-pub fn is_ollama_cloud_internal_500_message(message: &str) -> bool {- let needle = OLLAMA_CLOUD_INTERNAL_500_USER_PREFIX.to_ascii_lowercase();- message.to_ascii_lowercase().contains(needle.as_str())-}--/// Build the actionable user-facing message for an Ollama-Cloud hosted-inference-/// 500, replacing the opaque `Internal Server Error (ref: <uuid>)` body (which-/// carries no signal the user can act on) with retry/switch guidance. The model-/// is included when known (native/streaming chat); the `api_error` path has no-/// model in scope and omits it.-pub fn ollama_cloud_internal_500_user_message(- model: Option<&str>,- status: reqwest::StatusCode,-) -> String {- let code = status.as_u16();- match model {- Some(model) => format!(- "{OLLAMA_CLOUD_INTERNAL_500_USER_PREFIX} for model `{model}` (Ollama returned HTTP \- {code}); the hosted model failed on Ollama's side — retry shortly or switch models."- ),- None => format!(- "{OLLAMA_CLOUD_INTERNAL_500_USER_PREFIX} (Ollama returned HTTP {code}); the hosted \- model failed on Ollama's side — retry shortly or switch models."- ),- }-}--pub fn log_ollama_cloud_internal_500(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "ollama_cloud_internal_500",- "[llm_provider] {operation} Ollama Cloud hosted-inference 500 — provider-internal \- (no client lever), not reporting to Sentry"- );-}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/policy_rejection.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/policy_rejection.rsdeleted file mode 100644index 720efdda19..0000000000--- a/crates/openhuman-core/src/inference/provider/ops/http_error/policy_rejection.rs+++ /dev/null@@ -1,238 +0,0 @@-//! Deterministic provider/config/policy rejection classification: custom-//! OpenAI-compatible upstream envelopes, provider access-policy denials,-//! backend-owned error codes, external content-moderation rejections, and-//! provider configuration rejections (unknown model, bad temperature, …).--use super::*;--/// Whether a custom OpenAI-compatible proxy returned the known generic-/// upstream 400 envelope:-/// `{"error":{"message":"Bad request to upstream provider","type":"upstream_error","status":400}}`.-///-/// This shape is deterministic provider/user-state (endpoint-model mismatch,-/// unsupported schema, provider-side validation) and does not provide-/// actionable signal for OpenHuman Sentry triage.-pub fn is_custom_openai_upstream_bad_request_http_400(- provider: &str,- status: reqwest::StatusCode,- body: &str,-) -> bool {- if provider != "custom_openai" || status != reqwest::StatusCode::BAD_REQUEST {- return false;- }- tinyinference_llm::failure::body_indicates_custom_openai_upstream_bad_request(body)-}--pub fn log_custom_openai_upstream_bad_request_http_400(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "provider_user_state",- reason = "custom_openai_upstream_bad_request",- "[llm_provider] {operation} custom_openai upstream 400 — not reporting to Sentry"- );-}--/// Whether a provider non-2xx response is a deterministic provider-policy-/// denial (not a product bug) that should be demoted from Sentry.-///-/// Canonical example: Kimi's coding endpoint rejects non-agent clients with-/// HTTP 403 + `access_terminated_error` and a message like:-/// "currently only available for Coding Agents …".-pub fn is_provider_access_policy_denied_http_403(status: reqwest::StatusCode, body: &str) -> bool {- if status != reqwest::StatusCode::FORBIDDEN {- return false;- }- tinyinference_llm::failure::body_indicates_provider_access_policy_denied(body)-}--pub fn log_provider_access_policy_denied_http_403(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "provider_access_policy",- "[llm_provider] {operation} provider access-policy 403 — not reporting to Sentry"- );-}--/// Whether this provider response carries a managed-backend `errorCode` (#870)-/// that the backend already owns — so the FE must not double-report (F2/F4).-///-/// Gated on `provider == `[`openhuman_backend_model::PROVIDER_LABEL`]: an `errorCode`-/// is only trustworthy on the **managed backend**. A BYO / direct-provider body-/// that merely contains an `errorCode`-shaped field must NOT be treated as-/// backend-owned (CodeRabbit) — those keep reaching Sentry via the status gate.-///-/// Returns `false` for a backend-flagged **malformed** `BAD_REQUEST`: that one-/// `errorCode` case is a client-built payload the backend couldn't parse, and-/// the FE *does* page for it (F8). Delegates to the single-source decision in-/// [`crate::inference::provider::backend_error_code_skips_sentry`]-/// so the provider layer, the higher-layer re-report classifier, and the-/// Sentry `before_send` filter can't drift.-pub fn is_backend_error_code_owned(provider: &str, body: &str) -> bool {- provider == openhuman_backend_model::PROVIDER_LABEL- && crate::inference::provider::backend_error_code_skips_sentry(body)-}--pub fn log_backend_error_code_owned(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,- body: &str,-) {- let code =- crate::inference::provider::extract_backend_error_code_token(body).unwrap_or_default();- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "backend_error_code",- error_code = %code,- "[llm_provider] {operation} backend errorCode={code} ({status}) — backend owns \- this error, not reporting to Sentry"- );-}--/// Whether a provider non-2xx response is an **external content-moderation-/// rejection** — the user routes their provider (here: ollama) through a-/// third-party safety/moderation proxy that refuses the prompt with a `400`-/// and a verdict envelope, e.g.-/// `{"error":"Message rejected by Ombudsman","score":80}` (TAURI-RUST-ECR,-/// 4,517 events from a single looping triage-agent machine).-///-/// This is `genuinely-unpreventable` from OpenHuman's side: the request is-/// well-formed, the rejection comes from an external guard we neither own nor-/// configure, and there is no client lever to reshape the request into one the-/// proxy will accept. The triage agent re-issues the same prompt every turn, so-/// the raw 400 floods `report_error` (400 ∉ the transient set in-/// [`super::dispatch::should_report_provider_http_failure`]). Demote to an-/// info log while the error still propagates so retry/fallback runs-/// unchanged — the same classify-and-backpressure answer as the 5MV / A3T /-/// 8S3 precedent.-///-/// Anchored on the moderation-verdict shape — the rejection wording-/// (`message rejected` / `ombudsman`) or the `"score"` verdict field — none of-/// which OpenHuman's own backend or a normal provider 400 (malformed request,-/// schema error) emits, so a genuine bug still reaches Sentry. Covered by a-/// verbatim-body test so a proxy wording drift fails CI instead of silently-/// leaking events.-pub fn is_provider_moderation_rejection_http_400(status: reqwest::StatusCode, body: &str) -> bool {- if status != reqwest::StatusCode::BAD_REQUEST {- return false;- }- tinyinference_llm::failure::body_indicates_moderation_rejection(body)-}--pub fn log_provider_moderation_rejection(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "external_moderation_rejection",- "[llm_provider] {operation} external content-moderation rejection ({status}) — request \- refused by a third-party moderation proxy (no client lever), not reporting to Sentry"- );-}--/// Whether a provider non-2xx response is a deterministic-/// **configuration-rejection** user-state error (unknown model id,-/// abstract tier leaked to a custom provider, model-specific temperature-/// constraint) that should be demoted from Sentry to an info log.-///-/// Provider-aware (inverted polarity vs. the 401/403 backend rule): for-/// most config-rejection phrases the same body from the OpenHuman-/// **backend** stays Sentry-actionable — that would mean we sent our own-/// backend a bad request (a regression, e.g. #2079). Restricted to the-/// observed shapes (400 invalid-param / unknown-model, 404-/// model-does-not-exist, 422 unprocessable); 408/429 are transient and-/// handled separately.-///-/// **Exception: OpenAI-compatible "unknown model"** (`Model 'X' is not-/// available. Use GET /openai/v1/models …`). The OpenHuman backend now-/// emits this exact body for user-configured unknown model ids, so it is-/// user-state regardless of provider — the polarity guard is dropped for-/// this specific shape (TAURI-RUST-2Z1). See-/// [`super::is_openai_compatible_unknown_model_message`].-pub fn is_provider_config_rejection_http(- status: reqwest::StatusCode,- provider: &str,- body: &str,-) -> bool {- // 403 is included for the Ollama Cloud subscription gate:- // `{"error":"this model requires a subscription, upgrade for access: …"}`.- // That is deterministic user-state (paid-tier model, free account) — the- // same class as the 400/404/422 config-rejection shapes above. See- // TAURI-RUST-4XK. The general `is_backend_auth_failure` polarity guard- // still fires first (backend 401/403 → SessionExpired), so this branch- // is only reachable for non-backend providers. The phrase-level polarity- // guard below (`provider != openhuman_backend_model::PROVIDER_LABEL`) provides- // a second layer of defence for the non-OpenAI-compat shapes.- if !matches!(status.as_u16(), 400 | 403 | 404 | 422) {- return false;- }- if !tinyinference_providers::is_provider_config_rejection_message(body) {- return false;- }- // OpenAI-compatible "unknown model" body is user-state regardless of- // provider — both third-party `custom_openai` upstreams and our own- // OpenHuman backend now emit it for user-configured model ids that- // aren't in the registry (TAURI-RUST-2Z1).- if tinyinference_providers::is_openai_compatible_unknown_model_message(body) {- return true;- }- // Remaining config-rejection phrases (DeepSeek `supported api model- // names are`, Moonshot `invalid temperature`, litellm envelopes, …)- // are intrinsically scoped to third-party providers — keep the- // polarity guard so a regression where our own backend emits one of- // those still reaches Sentry.- provider != openhuman_backend_model::PROVIDER_LABEL-}--pub fn log_provider_config_rejection(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "provider_config_rejection",- "[llm_provider] {operation} provider config-rejection ({status}) — \- user model/param configuration, not reporting to Sentry"- );-}diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error/quota_and_credits.rs b/crates/openhuman-core/src/inference/provider/ops/http_error/quota_and_credits.rsdeleted file mode 100644index 33bb323b15..0000000000--- a/crates/openhuman-core/src/inference/provider/ops/http_error/quota_and_credits.rs+++ /dev/null@@ -1,86 +0,0 @@-//! Budget, quota, and per-request rate-cap classification — the deterministic-//! "third-party account/plan is out of runway" family of provider errors.--/// Whether a provider non-2xx response is a deterministic budget-exhausted-/// user-state error that should be demoted from Sentry to an info log.-pub fn is_budget_exhausted_http_400(status: reqwest::StatusCode, body: &str) -> bool {- status == reqwest::StatusCode::BAD_REQUEST- && tinyinference_providers::is_budget_exhausted_message(body)-}--pub fn log_budget_exhausted_http_400(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "budget",- "[llm_provider] {operation} budget-exhausted 400 — not reporting to Sentry"- );-}--/// Whether a provider non-2xx response is a deterministic-/// **insufficient-credits** user-state error — the BYO provider account-/// (e.g. OpenRouter) lacks the balance to satisfy the request.-///-/// This is the *residual* case once the request already caps `max_tokens`-/// (so the provider's pre-flight is priced against a realistic output budget-/// rather than the model's full window — see-/// [`crate::inference::provider::ChatRequest::max_tokens`]): a 402-/// that still arrives means the user's own third-party account is genuinely-/// out of credit, a billing state OpenHuman has no lever over. Demote from-/// Sentry to an info log rather than page once per retry-/// (TAURI-RUST-C62: 12k events from a single low-balance user).-///-/// Gated on the 402 status **and** a credit/payment phrase so an unrelated-/// 402 is not swallowed. The phrase list is covered by a verbatim-body test-/// so a provider wording drift fails CI instead of silently leaking events.-pub fn is_provider_insufficient_credits_402(status: reqwest::StatusCode, body: &str) -> bool {- status == reqwest::StatusCode::PAYMENT_REQUIRED- && tinyinference_llm::failure::body_indicates_insufficient_credits(body)-}--pub fn log_provider_insufficient_credits_402(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "insufficient_credits",- "[llm_provider] {operation} provider insufficient-credits 402 — BYO account out of \- balance (no local lever), not reporting to Sentry"- );-}--pub fn log_provider_quota_exhausted(- operation: &str,- provider: &str,- model: Option<&str>,- status: reqwest::StatusCode,-) {- tracing::info!(- domain = "llm_provider",- operation = operation,- provider = provider,- model = model.unwrap_or(""),- status = status.as_u16(),- failure = "non_2xx",- kind = "quota_exhausted",- "[llm_provider] {operation} provider monthly-quota exhausted — third-party plan limit \- reached (no local lever), not reporting to Sentry"- );-}