Skip to content

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

refactor(http-error): extract HTTP error types into submodules

Steven Enamakel38f19f809f4f
diff --git a/crates/openhuman-core/src/inference/provider/ops/http_error.rs b/crates/openhuman-core/src/inference/provider/ops/http_error.rs
index e540acccab..c457998de8 100644
--- a/crates/openhuman-core/src/inference/provider/ops/http_error.rs
+++ b/crates/openhuman-core/src/inference/provider/ops/http_error.rs
@@ -35,7 +35,11 @@ pub use auth_failure::{
is_openai_oauth_session_expired_http, log_byo_provider_auth_failure,
log_openai_oauth_session_expired, publish_backend_session_expired,
};
-pub use context_window::{is_context_window_exceeded_message, log_context_window_exceeded};
+pub use context_window::log_context_window_exceeded;
+pub use tinyinference_llm::failure::{
+ body_indicates_insufficient_credits, body_indicates_quota_exhausted,
+ is_context_window_exceeded_message, is_provider_rate_cap_exceeded_message,
+};
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,
@@ -51,9 +55,7 @@ pub use policy_rejection::{
log_provider_config_rejection, log_provider_moderation_rejection,
};
pub use quota_and_credits::{
- body_indicates_insufficient_credits, body_indicates_quota_exhausted,
is_budget_exhausted_http_400, is_provider_insufficient_credits_402,
- is_provider_quota_exhausted, is_provider_rate_cap_exceeded_message,
log_budget_exhausted_http_400, log_provider_insufficient_credits_402,
log_provider_quota_exhausted,
};
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.rs
index 6a71e58e7d..f47ebaaa4e 100644
--- 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.rs
@@ -64,23 +64,9 @@ pub fn is_byo_provider_auth_failure_http(
return false;
}
let lower = body.to_ascii_lowercase();
- // OpenAI-style auth envelopes across the BYO providers seen in Sentry:
- // `"type":"authentication_error"` (kiro / Anthropic-style), OpenAI's
- // `"code":"invalid_api_key"` + "Incorrect API key provided", and the
- // bare-message variants Cohere / litellm gateways emit (#3354).
- const AUTH_ERROR_MARKERS: &[&str] = &[
- "authentication_error",
- "invalid_api_key",
- "invalid api key",
- "invalid or missing api key",
- "missing api key",
- "no api key supplied",
- "incorrect api key",
- "invalid authentication",
- ];
- let matched = AUTH_ERROR_MARKERS
- .iter()
- .any(|marker| lower.contains(marker))
+ // 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
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.rs
index 7f1ca87994..7de183fe81 100644
--- 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.rs
@@ -1,96 +1,6 @@
-//! Context-window overflow classification: the request exceeded the
-//! configured model's context length.
-
-/// Whether a provider error body indicates the request exceeded the model's
-/// context window (the conversation/prompt is too long for the configured
-/// model). This is a deterministic user-state / usage condition — the
-/// remediation is "start a new chat, trim the conversation, or pick a
-/// larger-context model" — not a product bug. Sentry has no signal to act
-/// on.
-///
-/// Single source of truth for the context-overflow phrasing, shared by:
-/// - [`super::reliable`]'s non-retryable classifier (retrying the same
-/// oversized request can't help),
-/// - the [`super::dispatch::api_error`] Sentry-suppression cascade, and
-/// - the `core::observability` `ContextWindowExceeded` classifier (which
-/// catches the higher-layer re-report under `domain=agent` /
-/// `web_channel`).
-///
-/// Status-agnostic on purpose: providers disagree on the HTTP code for this
-/// condition — OpenAI / most emit `400 context_length_exceeded`, but some
-/// custom / self-hosted gateways mis-report it as `500` (Sentry
-/// TAURI-RUST-501: `"custom API error (500 …): Context size has been
-/// exceeded."`). Matching on the body keeps all of them in one bucket.
-///
-/// Anchoring is deliberately two-tier because this matcher now also feeds
-/// `core::observability::expected_error_kind` (Sentry suppression) and the
-/// `reliable` non-retryable decision, so an over-broad match would both
-/// hide a real error from Sentry *and* wrongly mark a retryable error as
-/// permanent:
-///
-/// - **Length/context phrases** ([`CONTEXT_HINTS`]) are unambiguous —
-/// "context window", "context length", "prompt is too long" only describe
-/// request-size overflow — so they match alone.
-/// - **Token-count phrases** ([`TOKEN_HINTS`]) collide with per-minute token
-/// *rate* limits ("rate limit reached … too many tokens per min"), which
-/// are transient 429s that MUST stay retryable and keep reaching Sentry.
-/// They only count as context-overflow when no rate-limit marker is
-/// present.
-pub fn is_context_window_exceeded_message(body: &str) -> bool {
- let lower = body.to_ascii_lowercase();
-
- // Unambiguous request-size / context phrases — match on their own.
- const CONTEXT_HINTS: &[&str] = &[
- "exceeds the context window",
- "context window of this model",
- "maximum context length",
- "context length exceeded",
- "context size has been exceeded",
- "prompt is too long",
- "input is too long",
- // LM Studio / llama.cpp un-evictable-prefix overflow (TAURI-RUST-6V0):
- // `"The number of tokens to keep from the initial prompt is greater
- // than the context length (n_keep: 10978 >= n_ctx: 8192). Try to
- // load the model with a larger context length, …"`. The user's local
- // model was loaded with an `n_ctx` smaller than the system/un-evictable
- // prefix; the remediation lives in the user's local server (reload with
- // a larger context), so this is expected user-state, not a product bug.
- "greater than the context length",
- ];
- if CONTEXT_HINTS.iter().any(|hint| lower.contains(hint)) {
- return true;
- }
-
- // LM Studio / llama.cpp emit the overflow as a paired `n_keep … n_ctx`
- // diagnostic. Require BOTH tokens so the arm stays anchored to that exact
- // shape (TAURI-RUST-6V0) and never broadens to unrelated `n_ctx` logging.
- if lower.contains("n_keep") && lower.contains("n_ctx") {
- return true;
- }
-
- // Token-count phrases are ambiguous with token-per-minute RATE limits.
- // Treat them as context-overflow only when the body carries no
- // rate-limit marker — otherwise a transient TPM 429 would be silenced
- // from Sentry and (via `reliable`) wrongly classified as non-retryable.
- const TOKEN_HINTS: &[&str] = &["too many tokens", "token limit exceeded"];
- if TOKEN_HINTS.iter().any(|hint| lower.contains(hint)) {
- const RATE_LIMIT_MARKERS: &[&str] = &[
- "per minute",
- "per min",
- "rate limit",
- "rate_limit",
- "tpm",
- "requests per",
- "retry after",
- "try again in",
- ];
- return !RATE_LIMIT_MARKERS
- .iter()
- .any(|marker| lower.contains(marker));
- }
-
- false
-}
+//! 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,
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.rs
index 89c4f46a35..5de0dc071c 100644
--- a/crates/openhuman-core/src/inference/provider/ops/http_error/dispatch.rs
+++ b/crates/openhuman-core/src/inference/provider/ops/http_error/dispatch.rs
@@ -74,7 +74,7 @@ pub async fn api_error(provider: &str, response: reqwest::Response) -> anyhow::E
// 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 = is_provider_quota_exhausted(&body);
+ 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
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.rs
index a1feb39641..dd876955a1 100644
--- 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.rs
@@ -13,7 +13,7 @@
/// (`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
- && body.to_ascii_lowercase().contains("no models loaded")
+ && tinyinference_llm::failure::body_indicates_no_model_loaded(body)
}
/// Actionable user-facing guidance for a local inference server with no model
@@ -80,9 +80,7 @@ pub fn is_ollama_cloud_internal_500(
) -> bool {
provider == "ollama"
&& status == reqwest::StatusCode::INTERNAL_SERVER_ERROR
- && body
- .to_ascii_lowercase()
- .contains("internal server error (ref:")
+ && tinyinference_llm::failure::body_indicates_ollama_cloud_internal_error(body)
}
/// Message-level half of [`is_ollama_cloud_internal_500`]: matches the actionable
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.rs
index 3e70b0476a..720efdda19 100644
--- 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.rs
@@ -20,8 +20,7 @@ pub fn is_custom_openai_upstream_bad_request_http_400(
if provider != "custom_openai" || status != reqwest::StatusCode::BAD_REQUEST {
return false;
}
- let lower = body.to_ascii_lowercase();
- lower.contains("bad request to upstream provider") && lower.contains("upstream_error")
+ tinyinference_llm::failure::body_indicates_custom_openai_upstream_bad_request(body)
}
pub fn log_custom_openai_upstream_bad_request_http_400(
@@ -53,9 +52,7 @@ pub fn is_provider_access_policy_denied_http_403(status: reqwest::StatusCode, bo
if status != reqwest::StatusCode::FORBIDDEN {
return false;
}
- let lower = body.to_ascii_lowercase();
- lower.contains("access_terminated_error")
- || lower.contains("currently only available for coding agents")
+ tinyinference_llm::failure::body_indicates_provider_access_policy_denied(body)
}
pub fn log_provider_access_policy_denied_http_403(
@@ -145,14 +142,7 @@ pub fn is_provider_moderation_rejection_http_400(status: reqwest::StatusCode, bo
if status != reqwest::StatusCode::BAD_REQUEST {
return false;
}
- let lower = body.to_ascii_lowercase();
- lower.contains("message rejected")
- || lower.contains("ombudsman")
- // The moderation proxy returns its confidence as a `"score"` JSON field
- // alongside the verdict; anchor on the quoted key shape (not a bare
- // `score`) so an unrelated 400 mentioning the word in prose isn't
- // swallowed.
- || lower.contains("\"score\"")
+ tinyinference_llm::failure::body_indicates_moderation_rejection(body)
}
pub fn log_provider_moderation_rejection(
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.rs
index 30c3dc54fe..60eec3affd 100644
--- 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.rs
@@ -43,27 +43,8 @@ pub fn log_budget_exhausted_http_400(
/// 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 && body_indicates_insufficient_credits(body)
-}
-
-/// Phrase-level matcher for an insufficient-credits / out-of-balance provider
-/// error body. Single source of truth for the credit-phrase set, shared by the
-/// emit-site guard [`is_provider_insufficient_credits_402`] (which adds the 402
-/// status gate) and the `before_send` defense-in-depth filter
-/// [`crate::core::observability::is_insufficient_credits_event`] (which matches
-/// the formatted `<provider> API error (402 …): <body>` message so the demotion
-/// reaches every compatible-provider HTTP path — `chat_with_system`,
-/// `chat_with_history`, the streaming gates, and `api_error` — not just
-/// `Provider::chat()`'s `native_chat` cascade). TAURI-RUST-C62.
-pub fn body_indicates_insufficient_credits(body: &str) -> bool {
- let lower = body.to_ascii_lowercase();
- lower.contains("requires more credits")
- || lower.contains("more credits")
- || lower.contains("can only afford")
- || lower.contains("insufficient credit")
- || lower.contains("insufficient balance")
- || lower.contains("insufficient funds")
- || lower.contains("payment required")
+ status == reqwest::StatusCode::PAYMENT_REQUIRED
+ && tinyinference_llm::failure::body_indicates_insufficient_credits(body)
}
pub fn log_provider_insufficient_credits_402(
@@ -85,65 +66,6 @@ pub fn log_provider_insufficient_credits_402(
);
}
-/// Whether a provider non-2xx response is a deterministic **monthly-quota /
-/// usage-limit exhausted** user-state error — the user's third-party plan has
-/// spent its allotment for the period and no request will succeed until it
-/// resets (a billing/plan state OpenHuman has no lever over).
-///
-/// Distinct from [`is_provider_insufficient_credits_402`] in two ways:
-/// 1. The signal is a *usage-quota cap* ("you have reached the limit",
-/// `MONTHLY_REQUEST_COUNT`), not an account balance.
-/// 2. The upstream proxy may wrap its own 402 inside a **500** envelope, e.g.
-/// Kiro IDE: `kiro API error (500 Internal Server Error): {"error":\
-/// {"message":"HTTP 402 from Kiro IDE: {\"reason\":\"MONTHLY_REQUEST_COUNT\"}"…}}`.
-/// So this is **status-agnostic** — matched against the body like
-/// [`super::context_window::is_context_window_exceeded_message`] — because
-/// gating on a 402 transport status (as the credits matcher does) would let
-/// the 500-wrapped flood straight through to
-/// [`super::dispatch::should_report_provider_http_failure`]
-/// (TAURI-RUST-C9A: 9k events from a single quota-capped user, retried per
-/// memory-extraction attempt).
-///
-/// Keyed on quota-specific wording only, so a generic 500 outage (or a 429
-/// rate-limit, which has its own transient handling) is not swallowed. Covered
-/// by a verbatim-body test so a provider wording drift fails CI.
-pub fn is_provider_quota_exhausted(body: &str) -> bool {
- body_indicates_quota_exhausted(body)
-}
-
-/// Phrase-level matcher for a provider monthly-quota / usage-limit exhausted
-/// body. Single source of truth for the quota-phrase set, shared by the
-/// emit-site guard [`is_provider_quota_exhausted`] and the `before_send`
-/// defense-in-depth filter
-/// [`crate::core::observability::is_quota_exhausted_event`] (which matches the
-/// formatted `<provider> API error (…): <body>` message so the demotion reaches
-/// every compatible-provider HTTP path, not just `Provider::chat()`'s
-/// `native_chat` cascade). TAURI-RUST-C9A.
-pub fn body_indicates_quota_exhausted(body: &str) -> bool {
- let lower = body.to_ascii_lowercase();
- lower.contains("monthly_request_count")
- || lower.contains("monthly request")
- || lower.contains("monthly limit")
- || lower.contains("monthly quota")
- || lower.contains("quota exceeded")
- || lower.contains("usage limit exceeded")
- // Codex/ChatGPT OAuth `/responses` plan-cap body (TAURI-RUST-AFE):
- // `usage_limit_reached` / "The usage limit has been reached" — a plan
- // quota with no "monthly"/"quota" co-marker, so the phrases above miss
- // it. Both are quota-specific enough to match on their own (the loop
- // retries until `resets_at`, flooding from a single capped Plus user).
- || lower.contains("usage_limit_reached")
- || lower.contains("usage limit has been reached")
- // "reached the limit" alone is ambiguous (rate-limit, token-limit), so
- // require a quota/plan/request/monthly co-marker to keep the blast
- // radius on plan-quota exhaustion only.
- || (lower.contains("reached the limit")
- && (lower.contains("request")
- || lower.contains("quota")
- || lower.contains("monthly")
- || lower.contains("plan")))
-}
-
pub fn log_provider_quota_exhausted(
operation: &str,
provider: &str,
@@ -163,39 +85,3 @@ pub fn log_provider_quota_exhausted(
);
}
-/// Whether a provider error body is a **permanent per-request rate-cap
-/// rejection**: the provider refused because a *single* request's token count
-/// exceeds the account's tokens-per-minute (TPM) budget, so no amount of
-/// retrying or spacing can ever let it through on the current tier.
-///
-/// Distinct from a *transient* TPM `429` ("rate limit reached … try again in
-/// 2s" — a burst that
-/// [`super::context_window::is_context_window_exceeded_message`] and the
-/// `reliable` retry classifier deliberately keep retryable), from a
-/// monthly-plan quota ([`body_indicates_quota_exhausted`]), and from
-/// context-window overflow
-/// ([`super::context_window::is_context_window_exceeded_message`], a
-/// model-size limit not a rate cap). Here the request is larger than the
-/// per-minute limit outright, so it is permanently non-viable until the user
-/// picks a higher-tier model/provider — OpenHuman has no lever to raise a
-/// third-party account's TPM tier.
-///
-/// Canonical wire shape (groq `on_demand` free tier, Sentry TAURI-RUST-HXF):
-/// `groq API error (413 Payload Too Large): {"error":{"message":"Request too
-/// large for model `openai/gpt-oss-120b` in organization `org_…` service tier
-/// `on_demand` on tokens per minute (TPM): Limit 8000, Requested 42084 …"}}`.
-///
-/// Anchored on BOTH the permanence marker `"request too large"` (a single
-/// request over the cap, not a burst) AND a per-minute-tokens marker
-/// (`"tokens per minute"` / `"(tpm)"`), so a transient "rate limit reached,
-/// retry in Ns" burst — which lacks "request too large" — is NOT swallowed and
-/// stays retryable + Sentry-visible. Status-agnostic (groq uses `413`; a
-/// gateway could wrap it) and covered by a verbatim-body test so a provider
-/// wording drift fails CI. Single source of truth shared by
-/// [`crate::core::observability::is_provider_user_state_message`] (Sentry
-/// demotion of the `domain=agent` re-report).
-pub fn is_provider_rate_cap_exceeded_message(body: &str) -> bool {
- let lower = body.to_ascii_lowercase();
- lower.contains("request too large")
- && (lower.contains("tokens per minute") || lower.contains("(tpm)"))
-}
diff --git a/crates/openhuman-core/src/inference/provider/ops/mod.rs b/crates/openhuman-core/src/inference/provider/ops/mod.rs
index d814e58a4f..fbedc6ec4f 100644
--- a/crates/openhuman-core/src/inference/provider/ops/mod.rs
+++ b/crates/openhuman-core/src/inference/provider/ops/mod.rs
@@ -20,7 +20,7 @@ pub use http_error::{
is_ollama_cloud_internal_500, is_ollama_cloud_internal_500_message,
is_openai_oauth_session_expired_http, is_provider_access_policy_denied_http_403,
is_provider_config_rejection_http, is_provider_insufficient_credits_402,
- is_provider_moderation_rejection_http_400, is_provider_quota_exhausted,
+ is_provider_moderation_rejection_http_400,
is_provider_rate_cap_exceeded_message, local_provider_no_model_loaded_user_message,
log_backend_error_code_owned, log_budget_exhausted_http_400, log_byo_provider_auth_failure,
log_context_window_exceeded, log_custom_openai_upstream_bad_request_http_400,