Skip to content

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

fix: keep product inference policy in OpenHuman

Steven Enamakel2363766c00bd
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs
index 2b1e5b2c23..6c46892437 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs
@@ -113,9 +113,8 @@ fn has_inference_failure_envelope(result: &str) -> bool {
/// the two tight provider classifiers. Budget takes precedence if both match.
/// Ported from legacy `tool_loop::terminal_inference_failure_kind` (#3104).
pub(crate) fn terminal_inference_failure_kind(result: &str) -> Option<TerminalInferenceFailure> {
- use tinyinference::classification::{
- is_budget_exhausted_message, is_provider_config_rejection_message,
- };
+ use crate::inference::provider::is_provider_config_rejection_message;
+ use tinyinference::classification::is_budget_exhausted_message;
if !has_inference_failure_envelope(result) {
return None;
}
diff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rs
index b886c2127b..3216dac8b9 100644
--- a/crates/openhuman-core/src/config/ops/model.rs
+++ b/crates/openhuman-core/src/config/ops/model.rs
@@ -318,8 +318,7 @@ pub async fn apply_memory_settings(
// would otherwise be stored unchecked and 400 "does not exist" on every
// memory re-embed (2205 events from one user). Conservative check — see
// `tinyinference::embeddings::catalog::non_embedding_model_reason`.
- if let Some(reason) =
- tinyinference::embeddings::catalog::non_embedding_model_reason(&model)
+ if let Some(reason) = tinyinference::embeddings::catalog::non_embedding_model_reason(&model)
{
return Err(format!("invalid embeddings model `{model}`: {reason}"));
}
diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rs
index 4097ae234d..09fb6755e2 100644
--- a/crates/openhuman-core/src/core/observability.rs
+++ b/crates/openhuman-core/src/core/observability.rs
@@ -103,7 +103,7 @@ pub enum ExpectedErrorKind {
/// Deterministic user-config state surfaced in the UI — Sentry has no
/// remediation path (OPENHUMAN-TAURI-WJ / -QW / -HB / -NH, ~273
/// events). See
- /// [`tinyinference::classification::is_provider_config_rejection_message`]
+ /// [`crate::inference::provider::is_provider_config_rejection_message`]
/// for the polarity contract and exact body shapes.
ProviderConfigRejection,
LocalAiCapabilityUnavailable,
@@ -299,7 +299,7 @@ pub enum ExpectedErrorKind {
/// The single exception — a backend-flagged **malformed** `BAD_REQUEST` —
/// is NOT classified here (it is a client-built payload the backend
/// couldn't parse, and the FE *does* page for it, F8). See
- /// [`tinyinference::classification::backend_error_code_skips_sentry`].
+ /// [`crate::inference::provider::backend_error_code_skips_sentry`].
BackendErrorCodeOwned,
/// A provider embedding call (Cohere `/v2/embed`, OpenAI/Voyage embed,
/// custom OpenAI-compatible embed) returned a **403/Forbidden gateway
@@ -423,7 +423,7 @@ pub fn expected_error_kind(message: &str) -> Option<ExpectedErrorKind> {
// decision is gated on the managed-backend envelope so a BYO payload
// carrying an `errorCode`-shaped field is not wrongly suppressed
// (CodeRabbit).
- if tinyinference::classification::managed_error_skips_sentry(message) {
+ if crate::inference::provider::managed_error_skips_sentry(message) {
return Some(ExpectedErrorKind::BackendErrorCodeOwned);
}
// A managed-backend client-guard-leak code (`PAYLOAD_TOO_LARGE` /
@@ -436,8 +436,8 @@ pub fn expected_error_kind(message: &str) -> Option<ExpectedErrorKind> {
// `ContextWindowExceeded` bucket (CodeRabbit). Gated on the managed envelope
// so a BYO provider's own context-overflow — genuine user-state, not our
// guard — still flows to that matcher and stays demoted.
- if tinyinference::classification::is_managed_backend_envelope(message)
- && tinyinference::classification::is_backend_client_guard_leak(message)
+ if crate::inference::provider::is_managed_backend_envelope(message)
+ && crate::inference::provider::is_backend_client_guard_leak(message)
{
return None;
}
@@ -642,7 +642,7 @@ pub fn expected_error_kind(message: &str) -> Option<ExpectedErrorKind> {
// backend never emits these phrases. See the predicate's polarity
// contract. Drops OPENHUMAN-TAURI-WJ / -QW / -HB / -NH re-reports
// (#2079 / #2076 / #2202).
- if tinyinference::classification::is_provider_config_rejection_message(message) {
+ if crate::inference::provider::is_provider_config_rejection_message(message) {
return Some(ExpectedErrorKind::ProviderConfigRejection);
}
if is_local_ai_capability_unavailable_message(&lower) {
@@ -2474,7 +2474,7 @@ fn report_expected_message(kind: ExpectedErrorKind, message: &str, domain: &str,
// The FE surfaces actionable copy via `classify_inference_error`;
// Sentry must not double-report (F2/F4). Demote at `warn!` so the
// breadcrumb retains the code for triage without spawning an event.
- let code = tinyinference::classification::extract_backend_error_code_token(message)
+ let code = crate::inference::provider::extract_backend_error_code_token(message)
.unwrap_or_default();
tracing::warn!(
domain = domain,
@@ -2757,7 +2757,7 @@ pub fn is_transient_provider_http_failure(event: &sentry::protocol::Event<'_>) -
/// classifier (`expected_error_kind` → [`ExpectedErrorKind::BackendErrorCodeOwned`]).
/// This catches any future call site that re-emits the same flattened error
/// without routing through those funnels. Delegates the decision to the
-/// single-source [`tinyinference::classification::managed_error_skips_sentry`]
+/// single-source [`crate::inference::provider::managed_error_skips_sentry`]
/// (managed-envelope gated, so a BYO payload carrying an `errorCode`-shaped
/// field is not wrongly dropped) so the layers can't drift.
#[cfg(feature = "crash-reporting")]
@@ -2768,7 +2768,7 @@ pub fn is_backend_error_code_event(event: &sentry::protocol::Event<'_>) -> bool
[direct, from_logentry, from_exception]
.into_iter()
.flatten()
- .any(tinyinference::classification::managed_error_skips_sentry)
+ .any(crate::inference::provider::managed_error_skips_sentry)
}
/// Defense-in-depth `before_send` filter for transient streaming **transport**
diff --git a/crates/openhuman-core/src/inference/README.md b/crates/openhuman-core/src/inference/README.md
index cc7b2bc8df..4146bc1c3f 100644
--- a/crates/openhuman-core/src/inference/README.md
+++ b/crates/openhuman-core/src/inference/README.md
@@ -29,7 +29,7 @@ compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.
| `mod.rs` | Domain root; module decls + re-exports; wires `inference.*` controller schemas/controllers. |
| `ops.rs` | Canonical handler file — `inference_*` business logic returning `RpcOutcome<T>`; delegates to `local`, `provider`, `sentiment`, `device`, `presets`, `openai_oauth`. Includes Sentry-noise suppression for expected provider/user-config failures. |
| `schemas.rs` + `schemas/` (`catalog.rs`, `prompt_handlers.rs`, `oauth_handlers.rs`, `claude_code_handlers.rs`, `settings_handlers.rs`) | `inference.*` controller schemas + `handle_*` fns + param DTOs. |
-| `tinyinference::{auth_errors,classification,completion,device,sanitize,sentiment}` | Reusable inference state, parsing, hardware detection, diagnostics, and error sanitization called directly by the host. |
+| `tinyinference::{classification,completion,device,sanitize,sentiment}` | Reusable parsing, hardware detection, diagnostics, and error sanitization called directly by the host. |
| `tinyinference::model::model_id_supports_vision` | Upstream capability hint used directly for local model ids when the runtime cannot return an authoritative profile. |
| `tinyinference::model::effective_temperature` | Applies unsupported-model glob patterns and overrides before provider serialization. |
| `types.rs` | Serde DTOs: `LocalAiStatus`, `LocalAiAssetsStatus`, `LocalAiDownloadsProgress`, `LocalAiEmbeddingResult`, `LocalAiSpeechResult`, `LocalAiTtsResult`, etc. |
@@ -87,7 +87,7 @@ Also exposes a non-RPC HTTP router (`http::router()`) nested at `/v1` by `crates
## Events
- Publishes `DomainEvent::SessionExpired` from `provider/ops/http_error/auth_failure.rs` (`publish_backend_session_expired`) and `provider/openhuman_backend_model.rs` when the managed backend rejects a session, so the credentials layer can clear/refresh it.
-- Publishes `DomainEvent::ProviderApiKeyRejected` once per provider from `provider/ops/http_error/auth_failure.rs` the first time a BYO key is rejected (401/403), gated by `tinyinference::auth_errors::record`.
+- Publishes `DomainEvent::ProviderApiKeyRejected` once per provider from `provider/ops/http_error/auth_failure.rs` the first time a BYO key is rejected (401/403), gated by the OpenHuman-owned `auth_error_registry`.
- No `bus.rs` / `EventHandler` subscribers in this domain.
## Persistence
diff --git a/crates/openhuman-core/src/inference/auth_error_registry.rs b/crates/openhuman-core/src/inference/auth_error_registry.rs
new file mode 100644
index 0000000000..8456674112
--- /dev/null
+++ b/crates/openhuman-core/src/inference/auth_error_registry.rs
@@ -0,0 +1,117 @@
+//! Process-lived registry of BYO provider auth failures (invalid / revoked
+//! API key, HTTP 401 / 403).
+//!
+//! Single source of truth feeding both user-facing surfaces for a rejected
+//! BYO key, so the two can never drift:
+//! - the **notification center** — a one-shot [`crate::core::bus::
+//! DomainEvent::ProviderApiKeyRejected`] published the first time a
+//! provider starts failing, and
+//! - the **AI-settings provider-error notice** — read live via the
+//! `openhuman.inference_provider_auth_errors` RPC ([`snapshot`]).
+//!
+//! Entries are recorded at the demote site
+//! ([`provider::ops::http_error::log_byo_provider_auth_failure`](super::provider::ops::http_error::log_byo_provider_auth_failure)) and cleared
+//! when the user updates or removes that provider's key
+//! (`credentials::ops`). The [`record`] latch is what makes the notification
+//! fire **once per failure episode** rather than once per retry: the
+//! triggering 401 repeats thousands of times (the memory-summarization loop
+//! re-attempts on every scoring pass — TAURI-RUST-4RC: ~9k events / 6 users),
+//! and an unguarded publish would re-flood the notification center the same
+//! way the raw error flooded Sentry.
+
+use std::collections::HashMap;
+use std::sync::{OnceLock, RwLock};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+/// A recorded BYO provider auth failure. Serialized verbatim onto the
+/// `inference_provider_auth_errors` RPC snapshot the AI settings panel reads.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub struct ProviderAuthError {
+ /// Provider slug as used by the chat factory / classifier, e.g.
+ /// `"openrouter"`.
+ pub provider: String,
+ /// The rejecting HTTP status — always `401` or `403` (the classifier
+ /// gate), kept for fidelity in the surfaced copy.
+ pub status: u16,
+ /// Pre-formatted, user-facing, actionable message — safe to show in a
+ /// notification or settings notice as-is. See [`auth_error_message`].
+ pub message: String,
+ /// Wall-clock milliseconds since the unix epoch when last recorded.
+ pub timestamp_ms: u64,
+}
+
+fn registry() -> &'static RwLock<HashMap<String, ProviderAuthError>> {
+ static REG: OnceLock<RwLock<HashMap<String, ProviderAuthError>>> = OnceLock::new();
+ REG.get_or_init(|| RwLock::new(HashMap::new()))
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+/// Build the actionable, user-facing message for a BYO key the provider
+/// rejected. Phrased so it reads the same in the notification center and the
+/// AI-settings notice, and points the user at the one fix that resolves it
+/// (the third-party key is invalid / revoked — OpenHuman has no other lever).
+pub fn auth_error_message(provider: &str, status: u16) -> String {
+ format!(
+ "{provider} rejected the API key (HTTP {status}). Update your {provider} \
+ API key in Connections → API keys → LLM to restore it."
+ )
+}
+
+/// Record a BYO provider auth failure.
+///
+/// Returns `true` when this is a **new** failure episode for `provider` (no
+/// prior entry) — callers publish the one-shot notification only on `true` so
+/// a 401 that repeats per-retry doesn't re-notify. An existing entry is
+/// refreshed (status / timestamp) and returns `false`.
+pub fn record(provider: &str, status: u16) -> bool {
+ let entry = ProviderAuthError {
+ provider: provider.to_string(),
+ status,
+ message: auth_error_message(provider, status),
+ timestamp_ms: now_ms(),
+ };
+ let mut map = registry().write().unwrap_or_else(|e| e.into_inner());
+ let is_new = !map.contains_key(provider);
+ map.insert(provider.to_string(), entry);
+ is_new
+}
+
+/// Clear any recorded auth error for `provider` (the user updated / removed
+/// the key, or a call newly succeeded). Returns `true` if an entry was
+/// removed. Re-arms the [`record`] latch so a fresh failure re-notifies.
+pub fn clear(provider: &str) -> bool {
+ registry()
+ .write()
+ .unwrap_or_else(|e| e.into_inner())
+ .remove(provider)
+ .is_some()
+}
+
+/// Snapshot all currently-recorded provider auth errors, sorted by provider
+/// slug for a stable RPC payload.
+pub fn snapshot() -> Vec<ProviderAuthError> {
+ let map = registry().read().unwrap_or_else(|e| e.into_inner());
+ let mut out: Vec<ProviderAuthError> = map.values().cloned().collect();
+ out.sort_by(|a, b| a.provider.cmp(&b.provider));
+ out
+}
+
+/// Test-only: wipe the registry so a test can't be flaked by an entry an
+/// earlier test left behind (the map is process-global).
+#[cfg(any(test, debug_assertions))]
+pub fn reset_for_tests() {
+ registry()
+ .write()
+ .unwrap_or_else(|e| e.into_inner())
+ .clear();
+}
+
+#[cfg(test)]
+#[path = "auth_error_registry_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/inference/auth_error_registry_tests.rs b/crates/openhuman-core/src/inference/auth_error_registry_tests.rs
new file mode 100644
index 0000000000..b267b88460
--- /dev/null
+++ b/crates/openhuman-core/src/inference/auth_error_registry_tests.rs
@@ -0,0 +1,49 @@
+use super::*;
+use std::sync::Mutex;
+
+// The registry is process-global, so these tests would otherwise race:
+// one test's `reset_for_tests` can wipe another's entries mid-run. Serialize
+// them on a shared lock (poison-tolerant) so each runs against a clean,
+// exclusive registry.
+static TEST_LOCK: Mutex<()> = Mutex::new(());
+
+#[test]
+fn record_returns_true_only_on_first_episode() {
+ let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ reset_for_tests();
+ assert!(record("openrouter", 401), "first record is a new episode");
+ assert!(
+ !record("openrouter", 401),
+ "repeat record of same provider does not re-notify"
+ );
+ // A different provider is its own episode.
+ assert!(record("openai", 403));
+ reset_for_tests();
+}
+
+#[test]
+fn clear_removes_entry_and_rearms_latch() {
+ let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ reset_for_tests();
+ assert!(record("openrouter", 401));
+ assert!(clear("openrouter"), "entry was present");
+ assert!(!clear("openrouter"), "second clear is a no-op");
+ // After clear, the next failure is a new episode again.
+ assert!(record("openrouter", 401), "latch re-armed after clear");
+ reset_for_tests();
+}
+
+#[test]
+fn snapshot_is_sorted_and_carries_actionable_message() {
+ let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ reset_for_tests();
+ record("openrouter", 401);
+ record("anthropic", 401);
+ let snap = snapshot();
+ assert_eq!(snap.len(), 2);
+ assert_eq!(snap[0].provider, "anthropic");
+ assert_eq!(snap[1].provider, "openrouter");
+ assert!(snap[1].message.contains("openrouter"));
+ assert!(snap[1].message.contains("Connections → API keys → LLM"));
+ reset_for_tests();
+}
diff --git a/crates/openhuman-core/src/inference/mod.rs b/crates/openhuman-core/src/inference/mod.rs
index 84fc4745e4..53634f5f42 100644
--- a/crates/openhuman-core/src/inference/mod.rs
+++ b/crates/openhuman-core/src/inference/mod.rs
@@ -24,6 +24,7 @@
/// reports `Unknown`.
pub const INFERENCE_COMPILED_IN: bool = cfg!(feature = "inference");
+pub mod auth_error_registry;
pub mod embeddings;
pub mod http;
pub mod local;
diff --git a/crates/openhuman-core/src/inference/ops.rs b/crates/openhuman-core/src/inference/ops.rs
index fadc462765..273cdb6e98 100644
--- a/crates/openhuman-core/src/inference/ops.rs
+++ b/crates/openhuman-core/src/inference/ops.rs
@@ -397,7 +397,7 @@ pub async fn inference_device_profile() -> Result<RpcOutcome<Value>, String> {
/// editor, not only in the notification center. Cleared when the user updates
/// or removes the offending key.
pub async fn inference_provider_auth_errors() -> Result<RpcOutcome<Value>, String> {
- let errors = tinyinference::auth_errors::snapshot();
+ let errors = crate::inference::auth_error_registry::snapshot();
debug!(count = errors.len(), "{LOG_PREFIX} provider_auth_errors:ok");
Ok(RpcOutcome::single_log(
json!({ "errors": errors }),
diff --git a/crates/openhuman-core/src/inference/provider/README.md b/crates/openhuman-core/src/inference/provider/README.md
index 1688d1f8e0..2ae9d295fc 100644
--- a/crates/openhuman-core/src/inference/provider/README.md
+++ b/crates/openhuman-core/src/inference/provider/README.md
@@ -24,7 +24,7 @@ domain.
- **DTOs** (`types.rs`) — `ChatRequest`, `ChatResponse`, `ProviderDelta`,
`ToolCall`, `UsageInfo`, `AGENT_TURN_MAX_OUTPUT_TOKENS`.
- **Error classifiers** — reusable classifiers live in
- `tinyinference::classification`; this directory retains only OpenHuman policy.
+ `tinyinference::classification`; this directory retains OpenHuman managed-backend and telemetry policy.
## Transports
@@ -52,7 +52,7 @@ domain.
(`factory/access_gates.rs`).
- `crate::inference::local` — `profile::is_local_provider_string`, Ollama /
LM Studio base-url resolution for local provider strings.
-- `tinyinference::auth_errors` — surfaces per-provider auth errors
+- `crate::inference::auth_error_registry` — surfaces OpenHuman per-provider auth errors
back to the UI.
- `crate::core::bus` (`BUS.publish`) / `crate::core::events::DomainEvent` —
`ops/http_error/auth_failure.rs::publish_backend_session_expired` and
diff --git a/crates/openhuman-core/src/inference/provider/config_rejection.rs b/crates/openhuman-core/src/inference/provider/config_rejection.rs
new file mode 100644
index 0000000000..96a5ce1da4
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/config_rejection.rs
@@ -0,0 +1,315 @@
+//! Classifier for **provider configuration-rejection** errors.
+//!
+//! When OpenHuman talks to a user-configured custom cloud endpoint
+//! (`custom_openai` → DeepSeek / OpenRouter / Moonshot / …) the upstream
+//! API rejects requests whose model id or sampling params it doesn't
+//! understand:
+//!
+//! - `"The supported API model names are deepseek-v4-pro or
+//! deepseek-v4-flash, but you passed reasoning-v1."` (#2079 — an
+//! OpenHuman abstract tier alias leaked to a provider that only speaks
+//! its own native ids)
+//! - `"Model 'deepseek-v4-pro' is not available. Use GET
+//! /openai/v1/models to list available models."` (#2202)
+//! - `"invalid temperature: only 1 is allowed for this model"` (#2076 —
+//! Moonshot Kimi K2)
+//! - `"The model \`gpt-5.5\` does not exist or you do not have access to
+//! it."` / `"model_not_found"` (stale model pin)
+//! - `"This model is not available in your region."` (R1 — region-blocked
+//! model on a custom cloud provider)
+//! - `"ModelNotAllowed"` (R4 — Doubao/ChatGLM model-allowlist enforcement)
+//! - `"invalid_authentication_error"` (YC — user pasted a malformed /
+//! revoked API key into the provider config)
+//! - `"This request requires more credits"` (S5 — OpenRouter `402` when
+//! the user's account is out of credits)
+//! - `"Insufficient Balance"` (4ZF — DeepSeek custom BYO-key `402` when
+//! the user's DeepSeek account balance is exhausted)
+//! - `"Invalid model name passed in model="` (Y0 — litellm-style proxy
+//! rejecting a model id pre-routing)
+//! - `"No active credentials for provider:"` (JN / KB — user hasn't
+//! plugged in their API key for the selected provider yet)
+//! - `"litellm.BadRequestError"` (JK — litellm github_copilot proxy 400
+//! from a user OAuth/scope gap)
+//! - `"not_found_error"` (J2 / J5 / J4 — litellm-compatible envelope
+//! `type` field carrying "model 'X' not found")
+//!
+//! These are **deterministic user-configuration state**, not bugs the
+//! maintainers can act on: the user pointed OpenHuman at a custom
+//! provider with a model / temperature / region / credential that
+//! provider does not accept. The remediation is "fix the model, key, or
+//! routing in Settings", which the UI surfaces. Yet every agent turn
+//! produces a fresh Sentry event (OPENHUMAN-TAURI-WJ / -QW / -HB / -NH /
+//! -R1 / -R4 / -YC / -S5 / -Y0 / -JN / -KB / -JK / -J2 / -J5 / -J4 —
+//! ~250 additional events on top of the Wave 1-3 IDs). This is the
+//! same class as budget-exhaustion ([`super::billing_error`]) and must
+//! be demoted from Sentry to an info log the same way.
+//!
+//! ## Provider-aware polarity (important)
+//!
+//! Most of the phrases below are emitted by **third-party upstream APIs**
+//! (DeepSeek / OpenRouter / Moonshot). The OpenHuman hosted backend
+//! resolves tier aliases natively and never emits "supported API model
+//! names are deepseek-…" or "invalid temperature: only 1 is allowed" — so
+//! that phrase set is intrinsically scoped to custom providers. The
+//! HTTP-layer wrapper [`super::ops::is_provider_config_rejection_http`]
+//! polarity-guards those phrases on `provider !=
+//! openhuman_backend_model::PROVIDER_LABEL` so a model-rejection from our
+//! **own** backend that we did not expect (which would be a real
+//! regression we sent it a bad request) still reaches Sentry. The
+//! message-only predicate is consumed by
+//! [`crate::core::observability::expected_error_kind`] for the
+//! re-reported error that escapes the provider layer and is raised again
+//! by `agent.run_single` / `web_channel.run_chat_task`.
+//!
+//! **Exception: the OpenAI-compatible "unknown model" shape** (`Model 'X'
+//! is not available. Use GET /openai/v1/models …`) is now emitted by the
+//! OpenHuman hosted backend too, in response to user-configured model ids
+//! that aren't in the backend's registry. Pinned by
+//! [`is_openai_compatible_unknown_model_message`]. The HTTP-layer wrapper
+//! drops the polarity guard for that specific shape so the same body is
+//! treated as user-state regardless of provider — see TAURI-RUST-2Z1
+//! where a user-typed `MiniMax-M2.7-highspeed` model id (plus two
+//! `custom:` fallback variants from their own `model_fallbacks` config)
+//! was rejected with this wire shape and otherwise reached Sentry.
+//!
+//! Keep the list deliberately tight: a false positive demotes a real
+//! provider/backend bug to an info log.
+
+/// Stable fragment emitted when provider resolution has no configured model id.
+pub const NO_MODEL_CONFIGURED_ANCHOR: &str = "resolved to an empty model id";
+
+/// Returns true if a provider error body indicates the request was
+/// rejected because of the user's model / parameter **configuration**
+/// (unknown model id, abstract tier leaked to a custom provider,
+/// model-specific temperature constraint), as opposed to a transient
+/// failure or a server bug.
+///
+/// Case-insensitive substring match. See the module docs for the polarity
+/// contract and the OPENHUMAN-TAURI Sentry issues each phrase drops.
+pub fn is_provider_config_rejection_message(body: &str) -> bool {
+ const PHRASES: &[&str] = &[
+ // #2079 — an OpenHuman abstract tier alias (`reasoning-v1`,
+ // `chat-v1`, …) reached a custom provider that lists its own
+ // native ids back at us.
+ "supported api model names are",
+ // #2202 — OpenAI-compatible "unknown model" body. The
+ // `/openai/v1/models` remediation hint is the stable, unique
+ // anchor (the quoted model id varies per user).
+ "/openai/v1/models",
+ // OpenAI / OpenRouter stale-pin shape (`claude-opus-4-7`,
+ // `gpt-5.5`, …) — model removed or no access.
+ "does not exist or you do not have access",
+ "model_not_found",
+ // #2076 — Moonshot Kimi K2 only accepts `temperature: 1`.
+ "invalid temperature",
+ "only 1 is allowed for this model",
+ // Our own actionable error once a proper tier→model resolution
+ // is in place (keeps this classifier stable across that fix).
+ "is an abstract tier",
+ // OPENHUMAN-TAURI-R1 — custom_openai upstream 403 with body
+ // `{"error":{"message":"This model is not available in your region.","code":403}}`.
+ // User picked a model the provider blocks for their account's
+ // region. Sentry has no remediation; user must switch model.
+ "not available in your region",
+ // OPENHUMAN-TAURI-R4 — Doubao / ChatGLM-style model allowlist
+ // enforcement. Body: `{"reason":"ModelNotAllowed",...}`. Match
+ // lowercased — the provider sends the camelCase token as a
+ // sentinel `reason` value.
+ "modelnotallowed",
+ // OPENHUMAN-TAURI-YC — user-supplied custom_openai API key was
+ // rejected by upstream with the OpenAI-compatible
+ // `{"error":{"type":"invalid_authentication_error",...}}`
+ // envelope. Anchored on the type token (stable across providers
+ // that emit this OpenAI-compatible body).
+ "invalid_authentication_error",
+ // OPENHUMAN-TAURI-S5 — OpenRouter 402 when the user is out of
+ // credits. Body always carries "requires more credits, or fewer
+ // max_tokens"; pin to the unique-enough credits phrase. (The
+ // separate `billing_error` classifier handles our own
+ // OpenHuman-backend balance gate; this catches the third-party
+ // OpenRouter shape that re-emits via `agent.run_single`.)
+ "requires more credits",
+ // TAURI-RUST-4ZF — DeepSeek (custom BYO-key) 402 when the user's
+ // DeepSeek account balance is exhausted. Body carries the upstream
+ // `{"error":{"message":"Insufficient Balance",...}}` envelope.
+ // Same user-billing class as the OpenRouter S5 shape above.
+ // NOTE: `is_budget_exhausted_message` (billing_error.rs) also
+ // contains this phrase. In `expected_error_kind` (observability.rs)
+ // this classifier is checked first (line 199 vs 205), so a re-
+ // reported "Insufficient Balance" error routes to
+ // `ProviderConfigRejection` rather than `BudgetExhausted`. Both
+ // suppress Sentry at info-level — no event-volume regression — but
+ // the telemetry `kind` tag becomes "provider_config_rejection".
+ "insufficient balance",
+ // OPENHUMAN-TAURI-Y0 — litellm-style proxy rejected the model
+ // id pre-routing with `Invalid model name passed in model=…`.
+ // Anchored on the `passed in model=` suffix so a stray "invalid
+ // model name" log line elsewhere does not classify.
+ "invalid model name passed in model=",
+ // OPENHUMAN-TAURI-JN / -KB — custom provider proxy that fronts
+ // multiple upstream APIs surfaces a "you haven't configured the
+ // upstream provider yet" 401/404 as `{"error":{"message":"No
+ // active credentials for provider: openai",...}}`. The
+ // remediation is "add the upstream API key in Settings".
+ "no active credentials for provider",
+ // OPENHUMAN-TAURI-JK — litellm github_copilot proxy 400 driven
+ // by the user's missing / expired Copilot OAuth scope. The body
+ // always starts with the `litellm.BadRequestError:` envelope.
+ // Anchor to that prefix-shaped substring so we don't catch
+ // unrelated 400s that merely mention litellm in passing.
+ "litellm.badrequesterror",
+ // OPENHUMAN-TAURI-J2 / -J5 / -J4 — litellm-compatible
+ // envelope with `"type":"not_found_error"` carrying "model 'X'
+ // not found". Distinct from the existing `model_not_found`
+ // phrase: that's the `code` field used by OpenAI-native bodies;
+ // this is the `type` field used by litellm/Anthropic-style
+ // envelopes for the same class of user-state error.
+ "not_found_error",
+ // TAURI-RUST-4NM — nvidia-nim (and compatible providers) return
+ // `{"error":{"message":"model field is required","code":"missing_required_field"}}`
+ // when the request body contains an empty `"model":""` field.
+ "model field is required",
+ // TAURI-RUST-GKV (~2.3k events / 1 user) — the LOCAL form of the
+ // 4NM empty-model state, caught one layer earlier. The #2784 cloud-slug
+ // resolution guard bails BEFORE any
+ // provider HTTP call when a `<slug>` provider string carries no
+ // model and the `cloud_providers` entry has no `default_model`:
+ // "[chat-factory] no model configured: role '<r>' resolved to an
+ // empty model id for slug '<s>'. Include a model in the provider
+ // string (e.g. '<s>:<model-id>') or set default_model …".
+ // User-state — the remediation is "add/pick a model in Settings →
+ // LLM", which the user-facing copy surfaces; Sentry has no
+ // remediation. Anchored on the role/slug-interpolation-free
+ // substring, which IS `factory::NO_MODEL_CONFIGURED_ANCHOR` —
+ // referenced directly so the two can never drift (the round-trip
+ // test in `factory_tests.rs` remains as a belt-and-braces guard).
+ NO_MODEL_CONFIGURED_ANCHOR,
+ // TAURI-RUST-4XK (~649 events) — Ollama Cloud subscription gate.
+ // Body: `{"error":"this model requires a subscription, upgrade for
+ // access: https://ollama.com/upgrade (ref: <uuid>)"}` on a 403
+ // Forbidden from the OpenAI-compatible client with
+ // `name = "ollama"`. User-state: the model picked in Settings is
+ // a paid-tier Ollama Cloud model the user's account doesn't
+ // cover. The UI surfaces an actionable upgrade link in the
+ // remediation message itself.
+ "requires a subscription, upgrade for access",
+ // TAURI-RUST-1V / OPENHUMAN-TAURI-4JS —
+ // `reliable.rs::format_failure_aggregate` (no-configured-fallbacks
+ // branch) wraps every exhausted `reliable_chat_with_system` turn
+ // with:
+ //
+ // "The model `<name>` may not be available on your provider.
+ // Configure a fallback chain via `reliability.model_fallbacks`
+ // in your OpenHuman config, or change your default model in
+ // Connections → API keys → LLM.\n\nAll providers/models failed. Attempts:\n…"
+ //
+ // The aggregate fires once per turn regardless of the underlying
+ // per-attempt cause (auth wall, unknown model, region block,
+ // rate-limit cliff). All of those are user-actionable: pick a
+ // different model, fix the credential, or configure fallbacks —
+ // the message body literally tells the user how. Sentry has no
+ // remediation path the per-attempt classifiers haven't already
+ // covered at the lower layer (provider/ops.rs:486 publishes
+ // SessionExpired, billing_error covers credit walls, etc.).
+ //
+ // Two anchors, both unique to this single emit site (verified via
+ // grep across `src/`) and both present only in the no-configured-
+ // fallbacks branch — the configured-fallbacks branch emits only
+ // the bare "All providers/models failed. Attempts:\n…" dump, so
+ // neither phrase fires on it (see the
+ // `does_not_classify_reliable_aggregate_with_configured_fallbacks`
+ // test). `may not be available on your provider` is the canonical
+ // remediation-sentence phrase (TAURI-RUST-1V); the
+ // `reliability.model_fallbacks` config path (OPENHUMAN-TAURI-4JS)
+ // is kept as a redundant belt-and-braces anchor for the same line.
+ // TAURI-RUST-35 family — user picked a model that doesn't
+ // implement tool calling, agent harness sent a tool spec
+ // anyway, upstream rejected with `{"error":{"message":
+ // "<model id> does not support tools",
+ // "type":"invalid_request_error",...}}`. Same body across the
+ // `cloud` / `ollama` / `custom_openai` provider prefixes — one
+ // phrase drops all 10+ sibling Sentry issues currently
+ // fragmented by model id (TAURI-RUST-35, -DF, -123, -4K7,
+ // -4FS, -4F6, -2YA, -4KR, -4KH, -4KY — ~458 events). The user
+ // must pick a tool-capable model; Sentry has no remediation.
+ // NOTE: also pinned in the TAURI-RUST-4K7 capability-discovery
+ // block above; both match the same phrase — the duplicate is
+ // harmless (`.any()` short-circuits) and kept so each Sentry
+ // family stays self-documenting.
+ "does not support tools",
+ // TAURI-RUST-ADC (~5.9k events / 10 users) — OpenRouter's
+ // *router-level* phrasing of the same tool-capability user-state.
+ // When the picked model has no provider endpoint that supports tool
+ // calling, OpenRouter returns a 404 with `{"error":{"message":"No
+ // endpoints found that support tool use. Try disabling \"<tool>\".
+ // ..."}}`. The wording differs from the direct-provider `does not
+ // support tools` body above ("tool use" vs "tools", prefixed with
+ // "No endpoints found"), so it needs its own anchor. Same user-state
+ // class: pick a tool-capable model. Surfaced most often by the
+ // autonomous Subconscious loop, which additionally halts on this via
+ // its own capability breaker (`subconscious/engine.rs`).
+ "no endpoints found that support tool use",
+ // TAURI-RUST-4P6 (~36.6k events / 2 users) — user picked an
+ // *embedding* model (Ollama `bge-m3:latest`, OpenHuman's default
+ // memory-tree embed model) as their chat model. Ollama rejects every
+ // chat turn with `{"error":{"message":"\"bge-m3:latest\" does not
+ // support chat","type":"invalid_request_error",...}}` on a 400. Same
+ // user-state class as `does not support tools`: the model lacks the
+ // chat capability and the user must pick a chat-capable model — Sentry
+ // has no remediation. The 400 status bypasses the
+ // `completion_only_404_guard` (404-only), so without this phrase the
+ // raw body re-reports every turn. The companion `not_chat_capable_guard`
+ // in `compatible.rs` rewrites the opaque upstream JSON into an
+ // actionable "assign a chat-capable model" message that still carries
+ // this substring, so it stays demoted.
+ "does not support chat",
+ ];
+
+ let lower = body.to_ascii_lowercase();
+ if lower.contains("reliability.model_fallbacks")
+ || lower.contains("may not be available on your provider")
+ {
+ let transient_attempt = [
+ "timed out",
+ "timeout",
+ "503 service unavailable",
+ "502 bad gateway",
+ "504 gateway timeout",
+ "internal server error",
+ "upstream unavailable",
+ ]
+ .iter()
+ .any(|marker| lower.contains(marker));
+ if !transient_attempt {
+ return true;
+ }
+ }
+ PHRASES.iter().any(|phrase| lower.contains(phrase))
+}
+
+/// Returns true if a provider error body matches the OpenAI-compatible
+/// "unknown model" shape — anchored on the `/openai/v1/models`
+/// remediation hint the upstream returns alongside `Model 'X' is not
+/// available.`.
+///
+/// This is a strict subset of [`is_provider_config_rejection_message`]:
+/// the same phrase already lives in that predicate's list. The narrower
+/// helper exists so the HTTP-layer wrapper
+/// ([`super::ops::is_provider_config_rejection_http`]) can drop its
+/// `provider != openhuman_backend_model::PROVIDER_LABEL` polarity guard for
+/// this specific body shape — the OpenHuman hosted backend now emits the
+/// same OpenAI-compatible "Model 'X' is not available" wire body in
+/// response to user-configured unknown model ids, so the original
+/// polarity assumption ("only third-party providers speak this dialect")
+/// no longer holds.
+///
+/// Drops TAURI-RUST-2Z1 (per-attempt) — the aggregate sibling
+/// TAURI-RUST-2Z2 is already covered by the message-only classifier in
+/// [`crate::core::observability::expected_error_kind`].
+pub fn is_openai_compatible_unknown_model_message(body: &str) -> bool {
+ body.to_ascii_lowercase().contains("/openai/v1/models")
+}
+
+#[cfg(test)]
+#[path = "config_rejection_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/config_rejection_tests.rs b/crates/openhuman-core/src/inference/provider/config_rejection_tests.rs
new file mode 100644
index 0000000000..9d4b2093f7
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/config_rejection_tests.rs
@@ -0,0 +1,392 @@
+use super::*;
+
+#[test]
+fn detects_real_sentry_bodies() {
+ // The exact upstream bodies from OPENHUMAN-TAURI-WJ / -QW / -HB
+ // / -NH and the stale-pin family.
+ for body in [
+ "The supported API model names are deepseek-v4-pro or deepseek-v4-flash, but you passed reasoning-v1.",
+ "Model 'deepseek-v4-pro' is not available. Use GET /openai/v1/models to list available models.",
+ "Model 'claude-opus-4-7' is not available. Use GET /openai/v1/models to list available models.",
+ "invalid temperature: only 1 is allowed for this model",
+ "The model `gpt-5.5` does not exist or you do not have access to it.",
+ r#"{"error":{"message":"model not found","code":"model_not_found"}}"#,
+ "Model 'reasoning-v1' is an abstract tier — configure a concrete model for your custom provider",
+ ] {
+ assert!(
+ is_provider_config_rejection_message(body),
+ "{body:?} must classify as a provider config-rejection user-state"
+ );
+ }
+}
+
+#[test]
+fn detects_wave4_sentry_bodies() {
+ // Real wire bodies pulled from the OPENHUMAN-TAURI-* Sentry
+ // events the Wave 4 phrases drop.
+ for (sentry_id, body) in [
+ (
+ "R1",
+ r#"custom_openai API error (403 Forbidden): {"error":{"message":"This model is not available in your region.","code":403}}"#,
+ ),
+ (
+ "R4",
+ r#"custom_openai API error (403 Forbidden): {"code":403,"reason":"ModelNotAllowed","message":"模型不允许访问","metadata":{"request_id":"2026051706431574423265420620337"}}"#,
+ ),
+ (
+ "YC",
+ r#"custom_openai API error (401 Unauthorized): {"error":{"message":"Invalid Authentication","type":"invalid_authentication_error"}}"#,
+ ),
+ (
+ "S5",
+ r#"custom_openai API error (402 Payment Required): {"error":{"message":"This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, but can only afford 597.","type":"insufficient_credits"}}"#,
+ ),
+ (
+ "Y0",
+ r#"custom_openai API error (400 Bad Request): {"error":{"message":"{'error': '/chat/completions: Invalid model name passed in model=reasoning-v1. Call `/v1/models` to view available models for your key.'}","type":"None"}}"#,
+ ),
+ (
+ "JN",
+ r#"custom_openai Responses API error: {"error":{"message":"No active credentials for provider: openai","type":"invalid_request_error","code":"model_not_found"}}"#,
+ ),
+ (
+ "KB",
+ r#"OpenHuman API error (404 Not Found): {"error":{"message":"No active credentials for provider: openai","type":"invalid_request_error","code":"model_not_found"}}"#,
+ ),
+ (
+ "JK",
+ r#"custom_openai API error (400 Bad Request): {"error":{"message":"litellm.BadRequestError: Github_copilotException - Bad Request. Received Model Group=github_copilot/claude-haiku-4.5\nAvailable Model Group Fallbacks=None","type":null}}"#,
+ ),
+ (
+ "J2",
+ r#"custom_openai Responses API error: {"error":{"message":"model 'llama3.3' not found","type":"not_found_error","param":null,"code":null}}"#,
+ ),
+ (
+ "J5",
+ r#"custom_openai API error (404 Not Found): {"error":{"message":"model 'llama3.3' not found","type":"not_found_error","param":null,"code":null}}"#,
+ ),
+ (
+ "J4",
+ r#"custom_openai streaming API error (404 Not Found): {"error":{"message":"model 'llama3.3' not found","type":"not_found_error","param":null,"code":null}}"#,
+ ),
+ // TAURI-RUST-ADC — OpenRouter router-level "no tool-use endpoint"
+ // 404, surfaced by the autonomous Subconscious loop on a
+ // content-safety model that supports no tools.
+ (
+ "ADC",
+ r#"openrouter API error (404 Not Found): {"error":{"message":"No endpoints found that support tool use. Try disabling \"spawn_async_subagent\". To learn more about provider routing, visit: https://openrouter.ai/docs/guides/routing/provider-selection"}}"#,
+ ),
+ // TAURI-RUST-4NM — nvidia-nim (and compatible providers) return
+ // this body when the request body has an empty `"model":""`.
+ // This is user-configuration state: the provider string had no
+ // model id and the config entry has no default_model set.
+ (
+ "4NM",
+ r#"nvidia-nim API error (400 Bad Request): {"error":{"message":"model field is required","type":"invalid_request_error","param":null,"code":"missing_required_field"}}"#,
+ ),
+ (
+ "TAURI-RUST-4XK",
+ r#"ollama API error (403 Forbidden): {"error":"this model requires a subscription, upgrade for access: https://ollama.com/upgrade (ref: bc48f3c8-fba1-40b6-93a9-786a167d16f9)"}"#,
+ ),
+ // TAURI-RUST-4P6 — user picked an embedding model
+ // (`bge-m3:latest`) as their Ollama chat model. Ollama 400s every
+ // chat turn. Verbatim wire body from Sentry issue 5338.
+ (
+ "TAURI-RUST-4P6",
+ r#"ollama API error (400 Bad Request): {"error":{"message":"\"bge-m3:latest\" does not support chat","type":"invalid_request_error","param":null,"code":null}}"#,
+ ),
+ // Same shape after `not_chat_capable_guard` (compatible.rs)
+ // rewrites it into the actionable message — must still classify so
+ // the re-reported error stays demoted.
+ (
+ "TAURI-RUST-4P6-enriched",
+ "ollama API error: model 'bge-m3:latest' does not support chat — it appears to be an embedding or non-chat model. Assign a chat-capable model to this provider (e.g. in Connections → API keys → LLM), or pick a different model.",
+ ),
+ ] {
+ assert!(
+ is_provider_config_rejection_message(body),
+ "OPENHUMAN-TAURI-{sentry_id} body must classify as provider config-rejection: {body:?}"
+ );
+ }
+}
+
+/// TAURI-RUST-4ZF — a user's custom BYO-key DeepSeek provider returns
+/// HTTP 402 with `{"error":{"message":"… Insufficient Balance …"}}`
+/// when their DeepSeek account is out of credits. Same user-billing
+/// class as the OpenRouter S5 "requires more credits" 402 already in
+/// the list — the remediation is "top up the provider account", which
+/// Sentry cannot act on. The DeepSeek wire token is `Insufficient
+/// Balance` (vs OpenRouter's `requires more credits`).
+#[test]
+fn detects_insufficient_balance_402_family() {
+ for (sentry_id, body) in [
+ // TAURI-RUST-4ZF — verbatim (truncated) from issue 5679,
+ // model=`ds/deepseek-v4-flash`, provider=custom, status=402.
+ (
+ "4ZF",
+ r#"custom API error (402 Payment Required): {"error":{"message":"[deepseek/deepseek-v4-flash] [402]: {\"error\":{\"message\":\"Insufficient Balance\",\"type\":\"unknown_error\",\"param\":null,\"code\":\"invali (reset after 57s)"}}"#,
+ ),
+ // Bare upstream envelope — what a future caller might re-emit
+ // after unwrapping one layer.
+ (
+ "bare",
+ r#"{"error":{"message":"Insufficient Balance","type":"unknown_error"}}"#,
+ ),
+ ] {
+ assert!(
+ is_provider_config_rejection_message(body),
+ "TAURI-RUST-{sentry_id} insufficient-balance 402 must classify as provider config-rejection: {body:?}"
+ );
+ }
+}
+
+#[test]
+fn detects_reliable_aggregate_no_fallbacks_envelope() {
+ // OPENHUMAN-TAURI-4JS — `reliable::format_failure_aggregate`
+ // (no-configured-fallbacks branch) wraps every exhausted turn.
+ // Pin a few realistic shapes:
+ //
+ // 1. Verbatim Sentry 4JS payload (auth wall as the per-attempt cause).
+ // 2. Same aggregate, unknown-model upstream body (proves the matcher
+ // is per-emit-site, not per-underlying-cause).
+ // 3. Same aggregate, region-block per-attempt body (R1-sibling cause).
+ // 4. Bare two-line aggregate (only the literal prefix + an empty
+ // attempts dump).
+ //
+ // All four must classify; the unique anchor is the
+ // `reliability.model_fallbacks` config path the message literally
+ // tells the user to set.
+ for raw in [
+ // 1) Verbatim 4JS payload.
+ "The model `reasoning-quick-v1` may not be available on your provider. \
+ Configure a fallback chain via `reliability.model_fallbacks` in your \
+ OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
+ All providers/models failed. Attempts:\n\
+ provider=openhuman model=reasoning-quick-v1 attempt 1/3: non_retryable; \
+ error=OpenHuman API error (401 Unauthorized): {\"success\":false,\"error\":\"Invalid token\"}",
+ // 2) Unknown-model upstream cause.
+ "The model `gpt-5.5` may not be available on your provider. \
+ Configure a fallback chain via `reliability.model_fallbacks` in your \
+ OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
+ All providers/models failed. Attempts:\n\
+ provider=custom_openai model=gpt-5.5 attempt 1/3: non_retryable; \
+ error=custom_openai API error (404 Not Found): {\"error\":\"model not found\"}",
+ // 3) Region-block (R1-sibling) per-attempt cause.
+ "The model `gpt-4o` may not be available on your provider. \
+ Configure a fallback chain via `reliability.model_fallbacks` in your \
+ OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
+ All providers/models failed. Attempts:\n\
+ provider=custom_openai model=gpt-4o attempt 1/3: non_retryable; \
+ error=custom_openai API error (403 Forbidden): {\"error\":{\"message\":\"This model is not available in your region.\"}}",
+ // 4) Bare aggregate — minimal anchor surface.
+ "The model `x` may not be available on your provider. \
+ Configure a fallback chain via `reliability.model_fallbacks` in your \
+ OpenHuman config, or change your default model in Connections → API keys → LLM.\n\n\
+ All providers/models failed. Attempts:\n",
+ ] {
+ assert!(
+ is_provider_config_rejection_message(raw),
+ "OPENHUMAN-TAURI-4JS aggregate must classify as provider config-rejection: {raw:?}"
+ );
+ }
+}
+
+#[test]
+fn does_not_classify_reliable_aggregate_with_configured_fallbacks() {
+ // The configured-fallbacks branch of `format_failure_aggregate`
+ // emits ONLY the attempts dump (`"All providers/models failed.
+ // Attempts:\n…"`), with no `reliability.model_fallbacks`
+ // remediation hint — the user has already engaged with the knob,
+ // so the aggregate is closer to a real diagnostic surface than a
+ // user-config nudge. Without the anchor phrase, this matcher
+ // must NOT fire on its own — only the per-attempt body
+ // classifiers (#2786 SessionExpired, config_rejection siblings,
+ // …) can demote it on a per-shape basis.
+ let aggregate_with_fallbacks = "All providers/models failed. Attempts:\n\
+ provider=openhuman model=gpt-5.5 attempt 1/3: non_retryable; \
+ error=OpenHuman API error (404 Not Found): {\"error\":\"unknown model\"}";
+ assert!(
+ !is_provider_config_rejection_message(aggregate_with_fallbacks),
+ "configured-fallbacks aggregate (no `reliability.model_fallbacks` anchor) \
+ must NOT classify on the aggregate phrase alone"
+ );
+}
+
+#[test]
+fn aggregate_does_not_hide_transient_attempts() {
+ let timeout = "The model `x` may not be available on your provider. Configure a fallback \
+ chain via `reliability.model_fallbacks`. All providers/models failed. Attempts: \
+ provider=custom model=x: timed out";
+ let unavailable = "The model `x` may not be available on your provider. Configure a fallback \
+ chain via `reliability.model_fallbacks`. All providers/models failed. Attempts: \
+ provider=custom model=x: 503 Service Unavailable";
+ assert!(!is_provider_config_rejection_message(timeout));
+ assert!(!is_provider_config_rejection_message(unavailable));
+}
+
+#[test]
+fn thinking_history_contract_failures_remain_reportable() {
+ assert!(!is_provider_config_rejection_message(
+ "The reasoning_content in the thinking mode must be passed back to the API."
+ ));
+}
+
+#[test]
+fn detection_is_case_insensitive() {
+ assert!(is_provider_config_rejection_message(
+ "INVALID TEMPERATURE: ONLY 1 IS ALLOWED FOR THIS MODEL"
+ ));
+ assert!(is_provider_config_rejection_message(
+ "The Supported API Model Names Are gpt-4o or gpt-4o-mini"
+ ));
+}
+
+#[test]
+fn ignores_transient_and_server_and_unrelated() {
+ // Must NOT demote: transient/server failures and generic 4xx
+ // that carry no config-rejection signal — those stay Sentry
+ // actionable. (A real backend bug must not be silenced.)
+ for body in [
+ "Internal server error",
+ "503 Service Unavailable",
+ "Bad request: missing field",
+ "rate limit exceeded, retry after 1s",
+ "insufficient budget — add credits",
+ "",
+ ] {
+ assert!(
+ !is_provider_config_rejection_message(body),
+ "{body:?} must NOT classify as a provider config-rejection"
+ );
+ }
+}
+
+#[test]
+fn detects_reliable_chain_exhaustion_rollup() {
+ // TAURI-RUST-1V — `reliable.rs:325` rolls every attempt into
+ // `All providers/models failed. Attempts:\n…\nThe model `<id>`
+ // may not be available on your provider. Configure a fallback
+ // chain via `reliability.model_fallbacks` in …`. The wrapped err
+ // bubbles to `memory_sync::composio::bus` which previously
+ // emitted it as a raw `tracing::error!` — 10.7k events / 14d on
+ // self-hosted Sentry. The remediation lives entirely in the
+ // user's `reliability.model_fallbacks` config; Sentry has no
+ // remediation path.
+ let rollup = "All providers/models failed. Attempts:\n\
+ provider=openhuman model=gemini-3-flash-preview attempt 1/3: \
+ non_retryable; error=custom_openai API error (404 Not Found): \
+ <html>...</html>\n\
+ The model `gemini-3-flash-preview` may not be available on \
+ your provider. Configure a fallback chain via \
+ `reliability.model_fallbacks` in your config to route around \
+ unavailable models.";
+ assert!(
+ is_provider_config_rejection_message(rollup),
+ "TAURI-RUST-1V multi-line rollup must classify as provider config-rejection"
+ );
+
+ // Single-line `reliable.rs:332` emission (without the outer
+ // rollup wrapper) also matches — defensive against callers that
+ // surface only the inner remediation message.
+ let bare = "The model `chat-v1` may not be available on your provider. \
+ Configure a fallback chain via `reliability.model_fallbacks` in …";
+ assert!(
+ is_provider_config_rejection_message(bare),
+ "bare `may not be available on your provider` phrase must classify"
+ );
+}
+
+#[test]
+fn unknown_model_helper_matches_openai_compatible_bodies() {
+ // TAURI-RUST-2Z1 — the OpenHuman hosted backend now emits the
+ // OpenAI-compatible "Model 'X' is not available" wire body for
+ // user-configured unknown model ids. The helper is anchored on
+ // the `/openai/v1/models` remediation hint so the same body shape
+ // matches whether it came from a third-party `custom_openai`
+ // upstream or our own backend.
+ for body in [
+ r#"OpenHuman API error (400 Bad Request): {"success":false,"error":"Model 'MiniMax-M2.7-highspeed' is not available. Use GET /openai/v1/models to list available models."}"#,
+ r#"OpenHuman API error (400 Bad Request): {"success":false,"error":"Model 'custom:MiniMax-M2.7' is not available. Use GET /openai/v1/models to list available models."}"#,
+ "Model 'deepseek-v4-pro' is not available. Use GET /openai/v1/models to list available models.",
+ ] {
+ assert!(
+ is_openai_compatible_unknown_model_message(body),
+ "TAURI-RUST-2Z1 body must classify as openai-compatible unknown model: {body:?}"
+ );
+ // Sanity: must remain a member of the broader phrase set so
+ // the message-only classifier in
+ // `crate::core::observability::expected_error_kind` keeps
+ // demoting the aggregate (TAURI-RUST-2Z2).
+ assert!(
+ is_provider_config_rejection_message(body),
+ "broader classifier must continue to match: {body:?}"
+ );
+ }
+}
+
+#[test]
+fn detects_nvidia_nim_missing_model_body() {
+ // TAURI-RUST-4NM — nvidia-nim rejects requests with model="" with
+ // `{"error":{"message":"model field is required",...}}`.
+ let body = r#"nvidia-nim API error (400 Bad Request): {"error":{"message":"model field is required","type":"invalid_request_error","code":"missing_required_field"}}"#;
+ assert!(
+ is_provider_config_rejection_message(body),
+ "TAURI-RUST-4NM body must classify as provider config-rejection: {body:?}"
+ );
+ // Also verify the bare phrase on its own (defense-in-depth path).
+ assert!(is_provider_config_rejection_message(
+ "model field is required"
+ ));
+}
+
+#[test]
+fn detects_chat_factory_empty_model_local_bail() {
+ // TAURI-RUST-GKV — the #2784 cloud-slug resolution guard catches the
+ // empty-model state
+ // BEFORE the provider HTTP call (the local form of 4NM) and bails
+ // with this body (role/slug interpolated). Verbatim from Sentry
+ // issue 18482 (role='chat', slug='nvidia').
+ let body = "[chat-factory] no model configured: role 'chat' resolved to an empty model id \
+ for slug 'nvidia'. Include a model in the provider string (e.g. \
+ 'nvidia:<model-id>') or set default_model on the cloud_providers entry for \
+ slug 'nvidia'.";
+ assert!(
+ is_provider_config_rejection_message(body),
+ "TAURI-RUST-GKV empty-model bail must classify as provider config-rejection: {body:?}"
+ );
+ // Bare anchor on its own (the literal shared with
+ // `factory::NO_MODEL_CONFIGURED_ANCHOR`).
+ assert!(is_provider_config_rejection_message(
+ "resolved to an empty model id"
+ ));
+ // Negative: a near-miss model-resolution error that does NOT carry
+ // the anchor (or any other phrase) must stay Sentry-actionable.
+ assert!(
+ !is_provider_config_rejection_message(
+ "could not resolve the model registry for slug 'nvidia'"
+ ),
+ "unrelated model-resolution error must not classify on the GKV anchor"
+ );
+}
+
+#[test]
+fn unknown_model_helper_rejects_other_config_rejection_phrases() {
+ // Polarity exception must stay narrow: other config-rejection
+ // shapes (DeepSeek `supported api model names are`, Moonshot
+ // `invalid temperature`, OpenRouter `requires more credits`, …)
+ // must still go through the provider-polarity guard so a
+ // hypothetical regression where our own backend emits one of
+ // those phrases reaches Sentry.
+ for body in [
+ "The supported API model names are deepseek-v4-pro or deepseek-v4-flash, but you passed reasoning-v1.",
+ "invalid temperature: only 1 is allowed for this model",
+ "The model `gpt-5.5` does not exist or you do not have access to it.",
+ r#"{"error":{"message":"model not found","code":"model_not_found"}}"#,
+ "This request requires more credits, or fewer max_tokens.",
+ ] {
+ assert!(
+ !is_openai_compatible_unknown_model_message(body),
+ "{body:?} must NOT match the narrow openai-compatible-unknown-model helper"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/inference/provider/error_code.rs b/crates/openhuman-core/src/inference/provider/error_code.rs
new file mode 100644
index 0000000000..b61407d5e4
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/error_code.rs
@@ -0,0 +1,220 @@
+//! Backend `errorCode` extraction + Sentry-ownership decision.
+//!
+//! The OpenHuman **managed backend** (PR #870 / backend `tinyhumansai/backend#870`)
+//! stamps every inference error response with a stable machine-readable
+//! `errorCode` field in the JSON body, e.g.
+//!
+//! ```json
+//! {"error":{"message":"Rate limited","errorCode":"RATE_LIMITED","retryAfter":30}}
+//! ```
+//!
+//! That body is the only thing that distinguishes a **managed** failure (our
+//! operator key / account / quota / routing) from a **BYO** failure (the user
+//! runs their own provider key, no `errorCode` is present). The presence of an
+//! `errorCode` is therefore the single load-bearing signal for two decisions:
+//!
+//! 1. **Classification** ([`super::super::super::web_chat::web_errors::classify_inference_error`]):
+//! when an `errorCode` is present, branch on it FIRST and ignore the
+//! substring heuristics; when it is absent, fall back to the substring
+//! ladder (the BYO / direct-provider path, whose "check your API key" /
+//! "check your model settings" copy is correct there).
+//! 2. **Sentry ownership** (`api_error` / `before_send` / `expected_error_kind`):
+//! any response carrying an `errorCode` is owned by the backend (it already
+//! paged, or it is expected user-state) so the FE must **not** double-report
+//! — with the single exception of a backend-flagged **malformed**
+//! `BAD_REQUEST`, which means the client built a payload the backend
+//! couldn't parse (a client bug worth paging). See the spec's "golden rule"
+//! (F2) and the malformed-`BAD_REQUEST` carve-out (F8/B8).
+//!
+//! Everything in this module operates on the **already-flattened error string**
+//! (`"OpenHuman API error (429 …): {…errorCode…}"`) because the typed provider
+//! error is collapsed to a `String` at the native-bus boundary before it
+//! reaches the channel classifier or the higher-layer re-report sites.
+
+use super::openhuman_backend_model;
+
+/// A recognised backend `errorCode` token (PR #870).
+///
+/// Unknown / future tokens are intentionally NOT represented here — they are
+/// still detected as "an `errorCode` is present" by
+/// [`extract_backend_error_code_token`] (so the Sentry golden rule still
+/// applies), but they fall through to the substring ladder for *display*
+/// classification rather than guessing a bucket.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BackendErrorCode {
+ RateLimited,
+ UserInsufficientCredits,
+ UpstreamUnavailable,
+ ModelUnavailable,
+ PayloadTooLarge,
+ ContextLengthExceeded,
+ BadRequest,
+ InternalError,
+}
+
+impl BackendErrorCode {
+ /// Parse a canonical (upper-cased) token into a known variant.
+ pub fn from_token(token: &str) -> Option<Self> {
+ match token {
+ "RATE_LIMITED" => Some(Self::RateLimited),
+ "USER_INSUFFICIENT_CREDITS" => Some(Self::UserInsufficientCredits),
+ "UPSTREAM_UNAVAILABLE" => Some(Self::UpstreamUnavailable),
+ "MODEL_UNAVAILABLE" => Some(Self::ModelUnavailable),
+ "PAYLOAD_TOO_LARGE" => Some(Self::PayloadTooLarge),
+ "CONTEXT_LENGTH_EXCEEDED" => Some(Self::ContextLengthExceeded),
+ "BAD_REQUEST" => Some(Self::BadRequest),
+ "INTERNAL_ERROR" => Some(Self::InternalError),
+ _ => None,
+ }
+ }
+}
+
+/// Extract the raw (upper-cased) `errorCode` token from a flattened error
+/// string, or `None` when the body carries no `errorCode` field.
+///
+/// Returns the token **even if it is not a recognised [`BackendErrorCode`]** —
+/// the mere presence of an `errorCode` means the error came through the managed
+/// backend, which is what the Sentry golden rule keys on. Display
+/// classification narrows further via [`BackendErrorCode::from_token`].
+///
+/// The key match is case-insensitive (`"errorCode"` / `"errorcode"` /
+/// `"ERRORCODE"`) so a re-cased or re-serialised body still resolves; the
+/// extracted **value** is upper-cased before return so callers can compare
+/// against the canonical tokens regardless of how the backend cased them.
+pub fn extract_backend_error_code_token(err: &str) -> Option<String> {
+ // `to_ascii_lowercase` is byte-length preserving (it only remaps ASCII
+ // bytes in place), so a byte index found in `lower` is also valid in the
+ // original `err` — we search the lowercased copy for the key but read the
+ // value out of the original to keep the token's casing intact for the
+ // (defensive) upper-casing below.
+ let lower = err.to_ascii_lowercase();
+ const KEY: &str = "\"errorcode\"";
+ let key_idx = lower.find(KEY)?;
+ let after_key = &err[key_idx + KEY.len()..];
+ // Skip ONLY the JSON separators (whitespace + the colon) and then require a
+ // quoted string value. A non-string value (`"errorCode":null` / a number)
+ // must NOT be treated as a present code — otherwise the old
+ // `trim_start_matches(|c| c != '"')` skipped past the `null` and latched
+ // onto the *next* key's opening quote, returning a bogus token and wrongly
+ // marking the error backend-owned (CodeRabbit). `strip_prefix('"')` returns
+ // `None` for a non-string value, so we bail correctly.
+ let after_colon = after_key.trim_start_matches(|c: char| c.is_ascii_whitespace() || c == ':');
+ let stripped = after_colon.strip_prefix('"')?;
+ let end = stripped.find('"')?;
+ let token = stripped[..end].trim().to_ascii_uppercase();
+ if token.is_empty() {
+ None
+ } else {
+ Some(token)
+ }
+}
+
+/// Whether the flattened error string is a **managed-backend** envelope (the
+/// `errorCode` contract only holds for errors that came through the OpenHuman
+/// managed backend, `"OpenHuman API error (...)"` /
+/// `"OpenHuman streaming API error (...)"`).
+///
+/// Load-bearing for the managed-vs-BYO distinction: a BYO / direct-provider
+/// body that merely happens to carry an `errorCode`-shaped field must NOT be
+/// treated as backend-owned (CodeRabbit). The provider HTTP emit sites gate on
+/// the known `provider` value instead; this helper is for the string-only
+/// downstream sites (`expected_error_kind`, `before_send`) that no longer carry
+/// the typed provider.
+pub fn is_managed_backend_envelope(err: &str) -> bool {
+ let label = openhuman_backend_model::PROVIDER_LABEL.to_ascii_lowercase();
+ let lower = err.to_ascii_lowercase();
+ lower.starts_with(&format!("{label} api error"))
+ || lower.starts_with(&format!("{label} streaming api error"))
+}
+
+/// Managed-backend Sentry-ownership decision for **string-only** call sites:
+/// the error must both be a managed-backend envelope AND carry a backend
+/// `errorCode` the backend owns. Wraps [`backend_error_code_skips_sentry`] with
+/// the [`is_managed_backend_envelope`] gate so a BYO payload that contains an
+/// `errorCode` token can't suppress FE Sentry.
+pub fn managed_error_skips_sentry(err: &str) -> bool {
+ is_managed_backend_envelope(err) && backend_error_code_skips_sentry(err)
+}
+
+/// Parse a recognised [`BackendErrorCode`] out of a flattened error string.
+pub fn extract_backend_error_code(err: &str) -> Option<BackendErrorCode> {
+ extract_backend_error_code_token(err).and_then(|t| BackendErrorCode::from_token(&t))
+}
+
+/// Whether the managed backend explicitly flagged this `BAD_REQUEST` as a
+/// **malformed** payload (the client built a request the backend couldn't
+/// parse), as opposed to a user-parameter rejection (an unsupported model /
+/// parameter combination the user can fix).
+///
+/// Contract consumed from backend PR #870: the malformed variant carries a
+/// `"malformed": true` flag alongside `"errorCode":"BAD_REQUEST"`. Only this
+/// variant keeps paging the FE Sentry (F8/B8) — every other `errorCode` (the
+/// user-param `BAD_REQUEST` included) is owned by the backend and must not
+/// double-report.
+pub fn body_flags_malformed(err: &str) -> bool {
+ let lower = err.to_ascii_lowercase();
+ const KEY: &str = "\"malformed\"";
+ let Some(key_idx) = lower.find(KEY) else {
+ return false;
+ };
+ // Whitespace-tolerant: accept `"malformed":true`, `"malformed": true`, and
+ // pretty-printed `"malformed" : true` (CodeRabbit) — skip arbitrary
+ // whitespace and the colon before matching the boolean literal.
+ let after_key = &lower[key_idx + KEY.len()..];
+ let after_colon = after_key.trim_start_matches(|c: char| c.is_ascii_whitespace() || c == ':');
+ after_colon.starts_with("true")
+}
+
+/// Whether the error is a backend-flagged malformed `BAD_REQUEST` — the single
+/// `errorCode` case the FE *does* page (a client-built payload the backend
+/// rejected as unparseable).
+pub fn is_backend_malformed_bad_request(err: &str) -> bool {
+ matches!(
+ extract_backend_error_code(err),
+ Some(BackendErrorCode::BadRequest)
+ ) && body_flags_malformed(err)
+}
+
+/// Whether the `errorCode` names a limit the **client enforces before sending**,
+/// so a backend rejection means our pre-send guard leaked — a client-side bug
+/// worth paging, not expected user-state.
+///
+/// - `PAYLOAD_TOO_LARGE`: the client gates attachment size up front
+/// (`app/src/lib/attachments.ts` — per-image / per-file byte caps + a
+/// `too_large` reject), so an over-limit request reaching the backend means
+/// the aggregate slipped past those gates.
+/// - `CONTEXT_LENGTH_EXCEEDED`: the client manages context before send (the
+/// context stats state's `context_window`, `crates/openhuman-core/src/agent/context/stats.rs`),
+/// so a backend rejection means that fitting / trimming failed.
+///
+/// The backend does not ops-alert either (they are 4xx, not 500), so if the FE
+/// also suppressed them the guard leak would be invisible to everyone. Display
+/// classification is unchanged — the user still sees the actionable copy.
+pub fn is_backend_client_guard_leak(err: &str) -> bool {
+ matches!(
+ extract_backend_error_code(err),
+ Some(BackendErrorCode::PayloadTooLarge | BackendErrorCode::ContextLengthExceeded)
+ )
+}
+
+/// Sentry-ownership decision (F2 golden rule): a response carrying any backend
+/// `errorCode` must **not** page the FE — the backend owns it (it already
+/// paged) or it is expected user-state — *except* errors the **client** caused
+/// and so still page:
+/// - a backend-flagged malformed `BAD_REQUEST` (unparseable client payload), and
+/// - a client-guard-leak code (`PAYLOAD_TOO_LARGE` / `CONTEXT_LENGTH_EXCEEDED`)
+/// the client should have caught before sending — see
+/// [`is_backend_client_guard_leak`].
+///
+/// Shared by the provider HTTP layer (`api_error`), the higher-layer re-report
+/// classifier (`observability::expected_error_kind`), and the Sentry
+/// `before_send` defense-in-depth filter so the three layers can't drift.
+pub fn backend_error_code_skips_sentry(err: &str) -> bool {
+ extract_backend_error_code_token(err).is_some()
+ && !is_backend_malformed_bad_request(err)
+ && !is_backend_client_guard_leak(err)
+}
+
+#[cfg(test)]
+#[path = "error_code_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/inference/provider/error_code_tests.rs b/crates/openhuman-core/src/inference/provider/error_code_tests.rs
new file mode 100644
index 0000000000..5e49d71545
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/error_code_tests.rs
@@ -0,0 +1,135 @@
+use super::*;
+
+#[test]
+fn extracts_known_tokens() {
+ let body = r#"OpenHuman API error (429 Too Many Requests): {"error":{"message":"slow down","errorCode":"RATE_LIMITED","retryAfter":30}}"#;
+ assert_eq!(
+ extract_backend_error_code_token(body).as_deref(),
+ Some("RATE_LIMITED")
+ );
+ assert_eq!(
+ extract_backend_error_code(body),
+ Some(BackendErrorCode::RateLimited)
+ );
+}
+
+#[test]
+fn extraction_is_case_insensitive_on_key_and_normalises_value() {
+ let body = r#"{"ErrorCode":"rate_limited"}"#;
+ assert_eq!(
+ extract_backend_error_code_token(body).as_deref(),
+ Some("RATE_LIMITED")
+ );
+}
+
+#[test]
+fn unknown_token_is_present_but_not_recognised() {
+ let body = r#"{"errorCode":"SOME_FUTURE_CODE"}"#;
+ assert_eq!(
+ extract_backend_error_code_token(body).as_deref(),
+ Some("SOME_FUTURE_CODE")
+ );
+ assert_eq!(extract_backend_error_code(body), None);
+ // Golden rule still applies: an unknown code is a managed error.
+ assert!(backend_error_code_skips_sentry(body));
+}
+
+#[test]
+fn no_error_code_means_byo_path() {
+ let body =
+ r#"custom_openai API error (401 Unauthorized): {"error":{"message":"invalid api key"}}"#;
+ assert_eq!(extract_backend_error_code_token(body), None);
+ assert!(!backend_error_code_skips_sentry(body));
+}
+
+#[test]
+fn malformed_bad_request_is_the_one_paging_exception() {
+ let malformed = r#"OpenHuman API error (400 Bad Request): {"error":{"errorCode":"BAD_REQUEST","malformed":true}}"#;
+ assert!(is_backend_malformed_bad_request(malformed));
+ assert!(!backend_error_code_skips_sentry(malformed));
+
+ let malformed_spaced = r#"{"errorCode":"BAD_REQUEST","malformed": true,"message":"bad"}"#;
+ assert!(is_backend_malformed_bad_request(malformed_spaced));
+}
+
+#[test]
+fn user_param_bad_request_does_not_page() {
+ let user_param = r#"OpenHuman API error (400 Bad Request): {"error":{"errorCode":"BAD_REQUEST","message":"unsupported parameter"}}"#;
+ assert!(!is_backend_malformed_bad_request(user_param));
+ assert!(backend_error_code_skips_sentry(user_param));
+}
+
+#[test]
+fn client_guard_leak_codes_page_but_other_state_codes_do_not() {
+ // PAYLOAD_TOO_LARGE / CONTEXT_LENGTH_EXCEEDED are limits the client
+ // enforces before sending, so a backend rejection is a guard leak that
+ // must page the FE — unlike genuinely backend-owned / user-state codes.
+ let payload = r#"OpenHuman API error (413 Payload Too Large): {"error":{"errorCode":"PAYLOAD_TOO_LARGE","message":"too big"}}"#;
+ assert!(is_backend_client_guard_leak(payload));
+ assert!(!backend_error_code_skips_sentry(payload));
+ assert!(!managed_error_skips_sentry(payload));
+
+ let context = r#"OpenHuman API error (400 Bad Request): {"error":{"errorCode":"CONTEXT_LENGTH_EXCEEDED","message":"start a new chat"}}"#;
+ assert!(is_backend_client_guard_leak(context));
+ assert!(!backend_error_code_skips_sentry(context));
+
+ // Contrast: these remain backend-owned / expected user-state -> suppress.
+ let rate = r#"OpenHuman API error (429): {"error":{"errorCode":"RATE_LIMITED"}}"#;
+ let credits =
+ r#"OpenHuman API error (402): {"error":{"errorCode":"USER_INSUFFICIENT_CREDITS"}}"#;
+ assert!(!is_backend_client_guard_leak(rate));
+ assert!(backend_error_code_skips_sentry(rate));
+ assert!(backend_error_code_skips_sentry(credits));
+}
+
+#[test]
+fn malformed_flag_without_bad_request_is_ignored() {
+ // A stray `malformed` flag on a non-BAD_REQUEST code must not turn a
+ // backend-owned error into a paging one.
+ let body = r#"{"errorCode":"INTERNAL_ERROR","malformed":true}"#;
+ assert!(!is_backend_malformed_bad_request(body));
+ assert!(backend_error_code_skips_sentry(body));
+}
+
+#[test]
+fn non_string_error_code_is_not_treated_as_present_code() {
+ // `"errorCode":null` (or a numeric value) must NOT latch onto the next
+ // quoted key and return a bogus token (CodeRabbit).
+ let body = r#"{"error":{"errorCode":null,"message":"x"}}"#;
+ assert_eq!(extract_backend_error_code_token(body), None);
+ assert!(!backend_error_code_skips_sentry(body));
+}
+
+#[test]
+fn malformed_flag_with_spaced_colon_is_detected() {
+ // Pretty-printed JSON `"malformed" : true` must still flag malformed.
+ let body =
+ r#"OpenHuman API error (400 Bad Request): {"errorCode":"BAD_REQUEST","malformed" : true}"#;
+ assert!(is_backend_malformed_bad_request(body));
+ assert!(!managed_error_skips_sentry(body));
+}
+
+#[test]
+fn managed_envelope_gate_rejects_byo_payload_carrying_error_code() {
+ // A BYO / direct-provider envelope that merely contains an
+ // `errorCode`-shaped field must NOT be treated as backend-owned —
+ // otherwise it would wrongly suppress FE Sentry.
+ let byo = r#"custom_openai API error (429 Too Many Requests): {"error":{"errorCode":"RATE_LIMITED"}}"#;
+ assert!(!is_managed_backend_envelope(byo));
+ assert!(!managed_error_skips_sentry(byo));
+
+ let embedded = r#"custom_openai API error (429): {"error":{"message":"OpenHuman API error from upstream","errorCode":"RATE_LIMITED"}}"#;
+ assert!(!is_managed_backend_envelope(embedded));
+ assert!(!managed_error_skips_sentry(embedded));
+
+ // The same body under the managed envelope IS backend-owned.
+ let managed =
+ r#"OpenHuman API error (429 Too Many Requests): {"error":{"errorCode":"RATE_LIMITED"}}"#;
+ assert!(is_managed_backend_envelope(managed));
+ assert!(managed_error_skips_sentry(managed));
+
+ // The streaming envelope variant is also recognised.
+ let managed_stream = r#"OpenHuman streaming API error (500): {"errorCode":"INTERNAL_ERROR"}"#;
+ assert!(is_managed_backend_envelope(managed_stream));
+ assert!(managed_error_skips_sentry(managed_stream));
+}
diff --git a/crates/openhuman-core/src/inference/provider/mod.rs b/crates/openhuman-core/src/inference/provider/mod.rs
index 4399e5c922..e952f688d5 100644
--- a/crates/openhuman-core/src/inference/provider/mod.rs
+++ b/crates/openhuman-core/src/inference/provider/mod.rs
@@ -5,7 +5,9 @@
//! inference concerns (local runtime, cloud providers, HTTP endpoint) share
//! a single domain root.
+pub mod config_rejection;
pub mod error_classify;
+pub mod error_code;
pub mod factory;
pub(crate) mod openai_codex;
/// Crate-native managed OpenHuman backend as a host `ChatModel` (issue #4727).
@@ -19,6 +21,17 @@ pub use types::{
ChatRequest, ChatResponse, ProviderDelta, ToolCall, UsageInfo, AGENT_TURN_MAX_OUTPUT_TOKENS,
};
+pub use config_rejection::{
+ is_openai_compatible_unknown_model_message, is_provider_config_rejection_message,
+ NO_MODEL_CONFIGURED_ANCHOR,
+};
+pub use error_code::{
+ backend_error_code_skips_sentry, body_flags_malformed, extract_backend_error_code,
+ extract_backend_error_code_token, is_backend_client_guard_leak,
+ is_backend_malformed_bad_request, is_managed_backend_envelope, managed_error_skips_sentry,
+ BackendErrorCode,
+};
+
#[cfg(feature = "flows")]
pub(crate) use factory::is_raw_passthrough_model;
pub use factory::{
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 9af6fb05d0..e89f528e8c 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
@@ -136,10 +136,13 @@ pub fn log_byo_provider_auth_failure(
// 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 tinyinference::auth_errors::record(provider, status_code) {
+ 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: tinyinference::auth_errors::auth_error_message(provider, status_code),
+ message: crate::inference::auth_error_registry::auth_error_message(
+ provider,
+ status_code,
+ ),
});
}
}
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 0ce393b0c6..b63c8badd7 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
@@ -87,12 +87,12 @@ pub fn log_provider_access_policy_denied_http_403(
/// 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
-/// [`tinyinference::classification::backend_error_code_skips_sentry`]
+/// [`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
- && tinyinference::classification::backend_error_code_skips_sentry(body)
+ && crate::inference::provider::backend_error_code_skips_sentry(body)
}
pub fn log_backend_error_code_owned(
@@ -103,7 +103,7 @@ pub fn log_backend_error_code_owned(
body: &str,
) {
let code =
- tinyinference::classification::extract_backend_error_code_token(body).unwrap_or_default();
+ crate::inference::provider::extract_backend_error_code_token(body).unwrap_or_default();
tracing::info!(
domain = "llm_provider",
operation = operation,
@@ -210,14 +210,14 @@ pub fn is_provider_config_rejection_http(
if !matches!(status.as_u16(), 400 | 403 | 404 | 422) {
return false;
}
- if !tinyinference::classification::is_provider_config_rejection_message(body) {
+ if !crate::inference::provider::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::classification::is_openai_compatible_unknown_model_message(body) {
+ if crate::inference::provider::is_openai_compatible_unknown_model_message(body) {
return true;
}
// Remaining config-rejection phrases (DeepSeek `supported api model
diff --git a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs
index b4118565b2..7ef11265e4 100644
--- a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs
+++ b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs
@@ -368,7 +368,7 @@ pub async fn list_configured_models_from_config(
// returned for "missing field" vs "field present but wrong type"
// (TAURI-RUST-4Y). The ChatGPT Codex backend uses a sibling `models`
// array keyed by `slug`, so that shape is accepted here too.
- let mut models = parse_models_response(&body)?;
+ let mut models = parse_models_response(&body).map_err(|error| error.to_string())?;
if routing.using_oauth {
merge_openai_codex_model_hints(&mut models);
}
diff --git a/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rs b/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rs
index 473c902a3a..d3cf890274 100644
--- a/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/ops_tests_models_parsing_tests.rs
@@ -91,6 +91,7 @@ fn parse_models_response_distinguishes_missing_data_field_from_wrong_type() {
// OpenAI-compatible `data`.
let body = serde_json::json!({ "object": "list", "items": [] });
let err = parse_models_response(&body).expect_err("no model catalog field must fail");
+ let err = err.to_string();
assert!(
err.contains("missing `data` or `models` field"),
"no-data error should say `missing`: {err}"
@@ -117,6 +118,7 @@ fn parse_models_response_distinguishes_missing_data_field_from_wrong_type() {
] {
let body = serde_json::json!({ "object": "list", "data": value });
let err = parse_models_response(&body).expect_err("wrong-type data must fail");
+ let err = err.to_string();
assert!(
!err.contains("missing"),
"wrong-type error must not say `missing` ({label}): {err}"
@@ -179,6 +181,7 @@ fn parse_models_response_rejects_null_data_on_error_envelope() {
),
Err(err) => err,
};
+ let err = err.to_string();
assert!(
!err.contains("missing"),
"error-envelope null `{field}` must not say `missing`: {err}"
diff --git a/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs b/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs
index e9280abfc6..644a1dc59e 100644
--- a/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/provider_credentials.rs
@@ -63,7 +63,7 @@ pub async fn store_provider_credentials(
/// bare slug (`openrouter`) the inference classifier records under.
fn clear_provider_auth_error(provider: &str) {
let slug = provider.strip_prefix("provider:").unwrap_or(provider);
- tinyinference::auth_errors::clear(slug);
+ crate::inference::auth_error_registry::clear(slug);
}
pub async fn remove_provider_credentials(
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 12823a9237..47595034c1 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
@@ -24,7 +24,7 @@ pub(super) fn classify_by_backend_error_code(
provider: Option<String>,
fallback_available: Option<bool>,
) -> Option<ClassifiedError> {
- use tinyinference::classification::{
+ use crate::inference::provider::{
body_flags_malformed, extract_backend_error_code, is_managed_backend_envelope,
BackendErrorCode,
};
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 a879f49902..a947c73550 100644
--- a/crates/openhuman-core/src/web_chat/web_errors/classify.rs
+++ b/crates/openhuman-core/src/web_chat/web_errors/classify.rs
@@ -424,7 +424,7 @@ pub(crate) fn classify_inference_error(err: &str) -> ClassifiedError {
provider,
fallback_available: None,
}
- } else if tinyinference::classification::is_provider_config_rejection_message(err) {
+ } else if crate::inference::provider::is_provider_config_rejection_message(err) {
// #2079 / #2076 / #2202: an OpenHuman abstract tier alias leaked to
// a custom provider, a stale model pin, or a model-specific
// temperature constraint. Checked BEFORE the generic
diff --git a/vendor/tinyagents b/vendor/tinyagents
index bed4b05eaf..5d9a1a5c75 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit bed4b05eafa5557a304d9c6fc73f074671ecb083
+Subproject commit 5d9a1a5c750216c1f441ca1fb0db999301d44f78