Skip to content

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

feat(web_chat): add structured error handling with retry and classification

Steven Enamakel304654fad13b
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index c683b4444a..0d85abf472 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -47,9 +47,8 @@ pub(crate) use web_errors::classify_inference_error;
#[cfg(any(test, debug_assertions))]
#[allow(unused_imports)]
pub(crate) use web_errors::{
- extract_provider_error_detail, extract_provider_name, generic_inference_error_user_message,
- is_action_budget_exhausted, is_fallback_chain_exhausted, is_non_retryable_rate_limit_text,
- parse_retry_after_secs_from_str, retry_after_hint, with_provider_detail, ClassifiedError,
+ generic_inference_error_user_message, is_action_budget_exhausted,
+ is_non_retryable_rate_limit_text, retry_after_hint, ClassifiedError,
};
// Public API — event bus
diff --git a/crates/openhuman-core/src/web_chat/mod_test_support_tests.rs b/crates/openhuman-core/src/web_chat/mod_test_support_tests.rs
index 81aec09ef6..e2f51525ef 100644
--- a/crates/openhuman-core/src/web_chat/mod_test_support_tests.rs
+++ b/crates/openhuman-core/src/web_chat/mod_test_support_tests.rs
@@ -22,14 +22,6 @@ pub fn classify_error_for_test(err: &str) -> ClassifiedErrorSnapshot {
}
}
-pub fn extracted_provider_detail_for_test(err: &str) -> Option<String> {
- super::extract_provider_error_detail(err)
-}
-
-pub fn retry_after_secs_for_test(err: &str) -> Option<u64> {
- super::parse_retry_after_secs_from_str(err)
-}
-
pub fn is_non_retryable_rate_limit_for_test(lower: &str) -> bool {
super::is_non_retryable_rate_limit_text(lower)
}
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 140e1dc27c..1cf713a9f1 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -19,9 +19,9 @@ use super::session::{
};
use super::types::{ChatRequestMetadata, WebChatTaskResult};
use super::web_errors::{
- inference_budget_exceeded_user_message, is_empty_provider_response_text,
- is_inference_budget_exceeded_error,
+ inference_budget_exceeded_user_message, is_inference_budget_exceeded_error,
};
+use tinyinference_llm::failure::is_empty_provider_response_text;
#[cfg(any(test, debug_assertions))]
use super::ops::TEST_FORCED_RUN_CHAT_TASK_ERROR;
diff --git a/crates/openhuman-core/src/web_chat/web_errors.rs b/crates/openhuman-core/src/web_chat/web_errors.rs
index 4e5c1c8c8b..b08d86adf0 100644
--- a/crates/openhuman-core/src/web_chat/web_errors.rs
+++ b/crates/openhuman-core/src/web_chat/web_errors.rs
@@ -1,12 +1,11 @@
//! Turning a flattened inference/agent-loop error string into a stable,
//! user-facing chat error: budget/quota copy, timeout markers, provider
-//! detail extraction, retry-after parsing, and the classification ladder
+//! detail formatting and the classification ladder
//! that ties them together.
mod backend_error_code;
mod budget;
mod classify;
-mod provider_detail;
mod response_predicates;
mod retry;
mod timeout;
@@ -16,14 +15,7 @@ pub(crate) use budget::{
is_action_budget_exhausted, is_inference_budget_exceeded_error,
};
pub(crate) use classify::{classify_inference_error, ClassifiedError};
-pub(crate) use provider_detail::{
- extract_provider_error_detail, extract_provider_name, is_fallback_chain_exhausted,
- with_provider_detail,
-};
-pub(crate) use response_predicates::is_empty_provider_response_text;
-pub(crate) use retry::{
- is_non_retryable_rate_limit_text, parse_retry_after_secs_from_str, retry_after_hint,
-};
+pub(crate) use retry::{is_non_retryable_rate_limit_text, retry_after_hint};
pub(crate) use timeout::{
is_outer_backstop_timeout, is_turn_timeout_error, turn_timeout_error_message,
};
diff --git a/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rs b/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rs
index 47595034c1..447819d0c5 100644
--- a/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rs
+++ b/crates/openhuman-core/src/web_chat/web_errors/backend_error_code.rs
@@ -3,8 +3,9 @@
//! [`classify_inference_error`](super::classify::classify_inference_error).
use super::classify::ClassifiedError;
-use super::response_predicates::{is_malformed_tool_history_text, malformed_history_user_message};
-use super::retry::{parse_retry_after_secs_from_str, retry_after_hint};
+use super::response_predicates::malformed_history_user_message;
+use super::retry::retry_after_hint;
+use tinyinference_llm::failure::{is_malformed_tool_history_text, parse_retry_after_secs};
/// Classify a managed-backend error by its stable `errorCode` (#870).
///
@@ -50,7 +51,7 @@ pub(super) fn classify_by_backend_error_code(
let classified = match code {
BackendErrorCode::RateLimited => {
- let retry_secs = parse_retry_after_secs_from_str(err);
+ let retry_secs = parse_retry_after_secs(err);
ClassifiedError {
error_type: "rate_limited",
message: format!(
diff --git a/crates/openhuman-core/src/web_chat/web_errors/classify.rs b/crates/openhuman-core/src/web_chat/web_errors/classify.rs
index e546053598..071090d130 100644
--- a/crates/openhuman-core/src/web_chat/web_errors/classify.rs
+++ b/crates/openhuman-core/src/web_chat/web_errors/classify.rs
@@ -7,16 +7,12 @@ use super::budget::{
generic_inference_error_user_message, inference_budget_exceeded_user_message,
is_action_budget_exhausted, is_inference_budget_exceeded_error,
};
-use super::provider_detail::{
- extract_provider_name, is_fallback_chain_exhausted, with_provider_detail,
-};
-use super::response_predicates::{
- is_connection_dropped_text, is_empty_provider_response_text, is_malformed_tool_history_text,
- is_provider_request_rejected_text, is_transient_unavailability_text,
- malformed_history_user_message,
-};
-use super::retry::{
- is_non_retryable_rate_limit_text, parse_retry_after_secs_from_str, retry_after_hint,
+use super::response_predicates::malformed_history_user_message;
+use super::retry::{is_non_retryable_rate_limit_text, retry_after_hint};
+use tinyinference_llm::failure::{
+ extract_provider_name, is_connection_dropped_text, is_empty_provider_response_text,
+ is_fallback_chain_exhausted, is_malformed_tool_history_text, is_provider_request_rejected_text,
+ is_transient_unavailability_text, parse_retry_after_secs, with_provider_detail,
};
use super::timeout::is_turn_timeout_error;
@@ -292,7 +288,7 @@ pub(crate) fn classify_inference_error(err: &str) -> ClassifiedError {
fallback_available,
}
} else if lower.contains("rate limit") || lower.contains("429") {
- let retry_secs = parse_retry_after_secs_from_str(err);
+ let retry_secs = parse_retry_after_secs(err);
// Non-retryable business 429s ("plan does not include", balance
// exhausted, known provider business codes like Z.AI 1311/1113)
// also surface here — mark them non-retryable so the FE can hide
diff --git a/crates/openhuman-core/src/web_chat/web_errors/provider_detail.rs b/crates/openhuman-core/src/web_chat/web_errors/provider_detail.rs
deleted file mode 100644
index 8f8c298ea2..0000000000
--- a/crates/openhuman-core/src/web_chat/web_errors/provider_detail.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-//! Extracting and quoting the upstream provider's own error detail, and
-//! naming the provider an error chain came from.
-
-/// Pull the structured provider error message out of a raw error string.
-///
-/// Provider error chains from OpenAI/Anthropic/OpenRouter/etc. arrive looking
-/// like `custom_openai API error (404 Not Found): {"error":{"message":"...","type":"..."}}`.
-/// We extract the `error.message` value so the UI can show the *real* reason
-/// — e.g. "Project ... does not have access to model `gpt-5.5`" — instead of
-/// a generic apology.
-///
-/// Returns `None` for transport-level failures (DNS, TLS, connect refused)
-/// where there is no provider body to quote — those have no actionable
-/// detail and the raw error text can leak internal infrastructure URLs,
-/// which the chat surface deliberately does not expose to end users.
-pub(crate) fn extract_provider_error_detail(err: &str) -> Option<String> {
- const MAX_DETAIL_CHARS: usize = 300;
-
- // Find the first `"message"` JSON field anywhere in the error chain.
- let key = "\"message\"";
- let idx = err.find(key)?;
- let after_key = &err[idx + key.len()..];
- // Skip whitespace and the colon to the opening quote of the value.
- let after_colon = after_key.trim_start_matches(|c: char| c != '"');
- let stripped = after_colon.strip_prefix('"')?;
-
- // Manual unescape over the standard JSON escape set. `\uXXXX` is
- // deliberately left alone rather than decoded: this is an error-display
- // path, and an unhandled sequence should stay visible as the literal
- // `\uXXXX` instead of silently losing a character.
- let mut out = String::new();
- let mut chars = stripped.chars();
- while let Some(c) = chars.next() {
- match c {
- '"' => {
- let trimmed = out.trim();
- if trimmed.is_empty() {
- return None;
- }
- let sanitized = tinyinference_core::sanitize::sanitize_api_error(trimmed);
- return Some(crate::util::truncate_with_ellipsis(
- &sanitized,
- MAX_DETAIL_CHARS,
- ));
- }
- '\\' => {
- if let Some(esc) = chars.next() {
- match esc {
- '"' => out.push('"'),
- '\\' => out.push('\\'),
- '/' => out.push('/'),
- 'n' => out.push('\n'),
- 't' => out.push('\t'),
- 'r' => out.push('\r'),
- 'b' => out.push('\u{8}'),
- 'f' => out.push('\u{c}'),
- other => {
- out.push('\\');
- out.push(other);
- }
- }
- }
- }
- other => out.push(other),
- }
- }
-
- None
-}
-
-/// Append the upstream provider detail to a user-facing message, if a useful
-/// one can be extracted. Keeps the friendly summary first and the verbatim
-/// provider reason below as a quotable block.
-pub(crate) fn with_provider_detail(summary: &str, err: &str) -> String {
- match extract_provider_error_detail(err) {
- Some(detail) => format!("{summary}\n\n> {detail}"),
- None => summary.to_string(),
- }
-}
-
-/// Best-effort extraction of the provider name from an error string.
-///
-/// `inference::provider::ops::api_error` formats upstream failures as
-/// `"<provider> API error (<status>): <body>"`, e.g.
-/// `"openrouter API error (429 Too Many Requests): ..."`. We pull the
-/// leading word and lowercase it so the wire value is stable across
-/// providers' own capitalisation.
-///
-/// Returns `None` when:
-/// - The error string doesn't carry the `" API error"` infix.
-/// - The candidate word contains characters that wouldn't appear in a
-/// provider name (slashes, colons, etc. — guards against transport
-/// error prefixes that happen to be followed by " API error").
-pub(crate) fn extract_provider_name(err: &str) -> Option<String> {
- const INFIX: &str = " API error";
- let idx = err.find(INFIX)?;
- let prefix = err[..idx].trim_end();
- let candidate = prefix
- .rsplit_once(char::is_whitespace)
- .map_or(prefix, |(_, last)| last);
- if candidate.is_empty()
- || !candidate
- .chars()
- .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
- {
- return None;
- }
- Some(candidate.to_ascii_lowercase())
-}
-
-/// Detect the reliable-provider aggregate that fires once every
-/// configured `model_fallbacks` entry has been tried.
-///
-/// `reliable.rs::format_failure_aggregate` always opens with
-/// `"All providers/models failed. Attempts:"`. When that marker is
-/// present the FE should NOT offer a fallback retry — there is none
-/// left to try.
-pub(crate) fn is_fallback_chain_exhausted(err: &str) -> bool {
- err.contains("All providers/models failed")
-}
diff --git a/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs b/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs
index f8df65933c..77131be581 100644
--- a/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs
+++ b/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs
@@ -1,24 +1,5 @@
-//! String-flat predicates over a lowercased error message: recognising the
-//! shapes of a poisoned tool-call history, an empty provider response, a
-//! dropped connection, a rejected 4xx, or a transient outage.
-
-/// String-flat mirror of
-/// `crate::core::observability::is_empty_provider_response_message`.
-///
-/// The typed `AgentError::EmptyProviderResponse` is collapsed to a `String`
-/// at the native-bus boundary before reaching this layer, so we re-detect
-/// the same canonical phrase the agent harness emits. Anchored on
-/// `"model returned an empty response"` (the verbatim user-facing string from
-/// `AgentError::EmptyProviderResponse`) — NOT the looser `"empty response"`,
-/// so internal fall-through phrases (`"summarizer returned empty response"`,
-/// `"provider returned an empty response; returning empty extraction"`) are
-/// not misclassified. Keep the anchor in lockstep with the observability
-/// mirror.
-///
-/// Caller passes the already-lowercased error string.
-pub(crate) fn is_empty_provider_response_text(lower: &str) -> bool {
- lower.contains("model returned an empty response")
-}
+//! User-facing copy tied to a recognised response shape. The string-level
+//! predicates themselves live in `tinyinference_llm::failure`.
/// User-facing copy for a poisoned-history 400 (orphaned tool message). The
/// de-poison guard (`run_task.rs`) has already evicted the offending warm
@@ -27,110 +8,3 @@ pub(crate) fn malformed_history_user_message() -> &'static str {
"We hit a temporary glitch in this conversation — we've cleared it. \
Please send your message again."
}
-
-/// Detect a malformed tool-history rejection (orphaned / mismatched
-/// `role:'tool'` message). This is the *poisoned history* shape the de-poison
-/// guard recovers from — NOT a model/parameter mismatch — so it earns the
-/// "we cleared it, resend" copy instead of "try a different model".
-///
-/// Anchored on the managed backend's `validateToolMessageOrdering` strings
-/// (verified against tinyhumansai/backend `chatCompletions.ts` — "role 'tool' …
-/// matching tool_call", "does not match any tool_call from the preceding
-/// assistant message"), the raw upstream jinja variant ("tool role … no
-/// previous assistant message with a tool call"), and the equivalent BYO
-/// provider phrasings. Caller passes the already-lowercased error string.
-pub(crate) fn is_malformed_tool_history_text(lower: &str) -> bool {
- let tool_role = lower.contains("role 'tool'") || lower.contains("tool role");
- let about_tool_call = lower.contains("tool call") || lower.contains("tool_call");
- (tool_role && about_tool_call)
- || lower.contains("does not match any tool_call from the preceding assistant message")
-}
-
-/// Detect a transport-level connection drop with no provider status / managed
-/// `errorCode` — the residue that otherwise falls to the generic `inference`
-/// catch-all (issue #3714 bucket #1).
-///
-/// Anchored on the canonical reqwest/hyper shapes for a severed or never-opened
-/// connection (stale keep-alive reused after sleep/wake, network change, raw
-/// mid-stream SSE drop). Intentionally does NOT match `"timed out"` (the
-/// dedicated `timeout` arm owns that) nor any `4xx/5xx` status (those arms claim
-/// their shapes earlier). Caller passes the already-lowercased error string.
-pub(crate) fn is_connection_dropped_text(lower: &str) -> bool {
- const DROP_MARKERS: &[&str] = &[
- "connection closed before message completed", // hyper IncompleteMessage
- "error reading a body from connection",
- "connection reset",
- "connection refused",
- "connection aborted",
- "broken pipe",
- "unexpected end of file",
- "unexpected eof",
- "error sending request",
- "tcp connect error",
- "dns error",
- "failed to lookup address",
- ];
- DROP_MARKERS.iter().any(|marker| lower.contains(marker))
-}
-
-/// Detect an un-claimed provider 4xx (generic client-side request rejection).
-///
-/// Mirrors the status tokens emitted by `inference::provider::ops::api_error`
-/// (`"<provider> API error (400 Bad Request): …"`). Ordered AFTER the
-/// provider-config-rejection and model-unavailable arms in
-/// [`classify_inference_error`](super::classify::classify_inference_error), so
-/// only 4xx shapes those arms did not claim reach this predicate.
-///
-/// Caller passes the already-lowercased error string.
-pub(crate) fn is_provider_request_rejected_text(lower: &str) -> bool {
- // Match only when the 4xx status appears inside a provider error envelope
- // (`<provider> API error (4xx …)`, emitted by
- // `inference::provider::ops::api_error`). Matching a bare "400"/"404"
- // anywhere would misclassify unrelated errors that merely contain those
- // digits (token counts, byte offsets, timestamps). Per CodeRabbit review
- // on PR #3199. The `returned http 4xx` forms are tinyinference's
- // `ProviderError` Display (`<provider> returned HTTP 400: …`), which is
- // how a failure reported inside a stream reaches classification (#6724).
- const PROVIDER_4XX_MARKERS: &[&str] = &[
- "api error (400",
- "api error (404",
- "api error (409",
- "api error (422",
- "returned http 400",
- "returned http 404",
- "returned http 409",
- "returned http 422",
- ];
- PROVIDER_4XX_MARKERS
- .iter()
- .any(|marker| lower.contains(marker))
-}
-
-/// Whether a model-availability error body describes a **transient** upstream
-/// outage rather than a user misconfiguration (#5503).
-///
-/// The `model_unavailable` arm matches on the bare word `unavailable`, which a
-/// provider emits for BOTH "you picked a model I don't host" (config, terminal)
-/// and "this model is temporarily down / overloaded right now" (transient,
-/// retryable). Only the second class carries one of these temporary-outage
-/// markers, so it's the safe discriminator: a terminal endpoint rejection like
-/// `"model unavailable on this endpoint"` (a 404 for a model that endpoint
-/// doesn't host) carries none of them and stays on the config verdict.
-///
-/// Deliberately does NOT key on the bare word `unavailable` — that's the very
-/// ambiguity being disambiguated. Caller passes the already-lowercased string.
-pub(crate) fn is_transient_unavailability_text(lower: &str) -> bool {
- const TRANSIENT_MARKERS: &[&str] = &[
- "temporarily",
- "temporary",
- "currently unavailable",
- "currently overloaded",
- "overloaded",
- "try again later",
- "try again in a",
- "please retry",
- ];
- TRANSIENT_MARKERS
- .iter()
- .any(|marker| lower.contains(marker))
-}
diff --git a/crates/openhuman-core/src/web_chat/web_errors/retry.rs b/crates/openhuman-core/src/web_chat/web_errors/retry.rs
index 1f40685925..4b405a75af 100644
--- a/crates/openhuman-core/src/web_chat/web_errors/retry.rs
+++ b/crates/openhuman-core/src/web_chat/web_errors/retry.rs
@@ -1,52 +1,6 @@
-//! Parsing and formatting the "retry after" hint upstream providers supply,
-//! and telling a retryable 429 apart from a non-retryable business one.
-
-/// Extract a Retry-After / retry_after seconds hint from a free-form
-/// error string. Mirrors the typed [`crate::inference::
-/// provider::error_classify::parse_retry_after_ms`] helper but operates on
-/// the already-flattened `String` that reaches the channel-classifier
-/// layer.
-///
-/// Returns `Some(n)` when a non-negative integer or fractional value
-/// follows one of the canonical headers; fractional values are
-/// rounded up so the user is never told to retry sooner than the
-/// upstream actually allows.
-pub(crate) fn parse_retry_after_secs_from_str(err: &str) -> Option<u64> {
- // Normalise quoted JSON-key wrappers ("retry_after": 30) by
- // stripping double quotes before scanning for prefixes
- // (CodeRabbit review on #2371). A serialised provider body like
- // `{"retry_after": 30}` would otherwise miss every prefix and
- // the user would lose the retry hint the provider supplied.
- let normalized = err.to_ascii_lowercase().replace('"', "");
- for prefix in &[
- "retry-after:",
- "retry_after:",
- "retry-after ",
- "retry_after ",
- // Managed backend (#870) emits the structured `retryAfter` field
- // (camelCase). After lower-casing + quote-stripping above it
- // collapses to `retryafter: 30` / `retryafter 30`, so the
- // separator-bearing prefixes here let the same parser surface the
- // structured field the spec asks us to prefer (F5).
- "retryafter:",
- "retryafter ",
- ] {
- if let Some(pos) = normalized.find(prefix) {
- let after = &normalized[pos + prefix.len()..];
- let num_str: String = after
- .trim()
- .chars()
- .take_while(|c| c.is_ascii_digit() || *c == '.')
- .collect();
- if let Ok(secs) = num_str.parse::<f64>() {
- if secs.is_finite() && secs >= 0.0 {
- return Some(secs.ceil() as u64);
- }
- }
- }
- }
- None
-}
+//! Formatting the "retry after" hint for users, and telling a retryable 429
+//! apart from a non-retryable business one. Parsing the hint out of an error
+//! string is `tinyinference_llm::failure::parse_retry_after_secs`.
/// Format the retry-after hint as a short user-friendly suffix
/// (`" Try again in 30 seconds."`). Returns an empty string when no
diff --git a/crates/openhuman-core/src/web_chat/web_tests.rs b/crates/openhuman-core/src/web_chat/web_tests.rs
index cd59e0269f..6ccc63d700 100644
--- a/crates/openhuman-core/src/web_chat/web_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests.rs
@@ -2,7 +2,7 @@ use super::{
all_web_channel_controller_schemas, all_web_channel_registered_controllers, cancel_chat,
channel_web_cancel, channel_web_queue_clear, channel_web_queue_remove,
channel_web_queue_status, classify_inference_error, drain_queued_turns_for_test,
- event_session_id_for, extract_provider_error_detail, generic_inference_error_user_message,
+ event_session_id_for, generic_inference_error_user_message,
in_flight_entries_for_test, inference_budget_exceeded_user_message,
is_inference_budget_exceeded_error, json_output, key_for, locale_reply_directive,
normalize_model_override, optional_f64, optional_string, parallel_in_flight_entries_for_test,