The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(platform): correct socket module path references
Steven Enamakelcfa5a650bd95
diff --git a/crates/openhuman-core/src/integrations/composio/tools/visibility.rs b/crates/openhuman-core/src/integrations/composio/tools/visibility.rsindex 9ab00c7718..5e7a1b3d8c 100644--- a/crates/openhuman-core/src/integrations/composio/tools/visibility.rs+++ b/crates/openhuman-core/src/integrations/composio/tools/visibility.rs@@ -18,7 +18,7 @@ use super::super::providers::{};/// Decision returned by [`evaluate_tool_visibility`].-enum ToolDecision {+pub(super) enum ToolDecision {/// Action is curated for this toolkit and user scope allows it.Allow,/// Action exists in the curated list but the user's scope blocksdiff --git a/crates/openhuman-core/src/platform/socket/ws_loop_connect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rssimilarity index 100%rename from crates/openhuman-core/src/platform/socket/ws_loop_connect.rsrename to crates/openhuman-core/src/platform/socket/ws_loop/connect.rsdiff --git a/crates/openhuman-core/src/platform/socket/ws_loop_dispatch.rs b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rssimilarity index 100%rename from crates/openhuman-core/src/platform/socket/ws_loop_dispatch.rsrename to crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rsdiff --git a/crates/openhuman-core/src/platform/socket/ws_loop_reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rssimilarity index 100%rename from crates/openhuman-core/src/platform/socket/ws_loop_reconnect.rsrename to crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rsdiff --git a/crates/openhuman-core/src/security/credentials/ops/session_store.rs b/crates/openhuman-core/src/security/credentials/ops/session_store.rsnew file mode 100644index 0000000000..3043cd7f2e--- /dev/null+++ b/crates/openhuman-core/src/security/credentials/ops/session_store.rs@@ -0,0 +1,436 @@+//! Persisting the app-session auth profile: secret encryption helpers and+//! the `store_session` / `store_session_with_deferred_validation` entry+//! points and their shared worker.++use serde_json::Value;++use crate::api::config::effective_backend_api_url;+use crate::api::jwt::decode_jwt_exp;+use crate::api::rest::{user_id_from_profile_payload, BackendOAuthClient};+use crate::config::Config;+use crate::config::{default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, user_openhuman_dir, write_active_user_id};+use crate::memory::conversations;+use crate::rpc::RpcOutcome;+use crate::security::credentials::session_support::{+ is_local_session_token, local_session_user_id, summarize_auth_profile, LOCAL_SESSION_USER_ID,+};+use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};+use crate::security::keyring::SecretStore;++use super::login_services::{is_embedder_host, start_login_gated_services};+use super::session_validation::{+ auth_me_store_failure_is_transient, fallback_session_user_for_deferred_validation,+ fetch_current_user_for_session_store, jwt_exp_live_at, normalize_local_session_user,+ sanitize_stored_session_user,+};++pub(super) fn secret_store_for_config(config: &Config) -> SecretStore {+ let data_dir = config+ .config_path+ .parent()+ .map_or_else(|| std::path::PathBuf::from("."), std::path::PathBuf::from);+ SecretStore::new(&data_dir, true)+}++pub async fn encrypt_secret(+ config: &Config,+ plaintext: &str,+) -> Result<RpcOutcome<String>, String> {+ let store = secret_store_for_config(config);+ let ciphertext = store.encrypt(plaintext).map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(ciphertext, "secret encrypted"))+}++pub async fn decrypt_secret(+ config: &Config,+ ciphertext: &str,+) -> Result<RpcOutcome<String>, String> {+ let store = secret_store_for_config(config);+ let plaintext = store.decrypt(ciphertext).map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(plaintext, "secret decrypted"))+}++pub async fn store_session(+ config: &Config,+ token: &str,+ user_id: Option<String>,+ user: Option<serde_json::Value>,+) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {+ store_session_inner(config, token, user_id, user, false).await+}++/// Store a session from a callback flow that already exchanged a backend+/// login token. Generic callers should use `store_session`, which requires+/// immediate `/auth/me` proof before persisting remote JWTs.+pub async fn store_session_with_deferred_validation(+ config: &Config,+ token: &str,+ user_id: Option<String>,+ user: Option<serde_json::Value>,+) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {+ store_session_inner(config, token, user_id, user, true).await+}++async fn store_session_inner(+ config: &Config,+ token: &str,+ user_id: Option<String>,+ user: Option<serde_json::Value>,+ allow_pending_backend_validation: bool,+) -> Result<RpcOutcome<super::super::responses::AuthProfileSummary>, String> {+ let trimmed_token = token.trim();+ if trimmed_token.is_empty() {+ return Err("token is required".to_string());+ }++ let api_url = effective_backend_api_url(&config.api_url);+ let local_session = is_local_session_token(trimmed_token);+ let local_user_id = local_session.then(local_session_user_id);+ let mut session_validation_logs = Vec::new();+ let settings = if local_session {+ sanitize_stored_session_user(user.clone())+ .map(|value| {+ normalize_local_session_user(+ value,+ local_user_id.as_deref().unwrap_or(LOCAL_SESSION_USER_ID),+ )+ })+ .ok_or_else(|| "local session requires a user payload".to_string())?+ } else {+ let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;+ match fetch_current_user_for_session_store(&client, trimmed_token).await {+ Ok(fetched_user) => {+ session_validation_logs.push(format!(+ "session JWT verified via GET /auth/me on {}",+ api_url.trim_end_matches('/')+ ));+ fetched_user+ }+ Err(reason) => {+ // This is the store-time validation gate: if it fails the profile+ // is NEVER persisted, so the user bounces straight back to the+ // signin page after a "successful" OAuth. Timeouts/gateway 5xx are+ // otherwise dropped by the Sentry transient classifier, so log an+ // explicit, grep-friendly WARN to the app log regardless.+ if !auth_me_store_failure_is_transient(&reason) {+ tracing::warn!(+ domain = "credentials",+ operation = "store_session",+ "[credentials][auth-store] GET /auth/me validation FAILED on {} — session NOT persisted; user will bounce to signin: {reason}",+ api_url.trim_end_matches('/')+ );+ return Err(format!(+ "Session validation failed (GET /auth/me): {reason}"+ ));+ }++ if !allow_pending_backend_validation {+ tracing::warn!(+ domain = "credentials",+ operation = "store_session",+ "[credentials][auth-store] GET /auth/me transient validation failed on {} — session NOT persisted; backend proof required before storing remote JWT: {reason}",+ api_url.trim_end_matches('/')+ );+ return Err(format!(+ "Session validation failed (GET /auth/me): {reason}"+ ));+ }++ let Some(exp) = jwt_exp_live_at(trimmed_token, chrono::Utc::now()) else {+ tracing::warn!(+ domain = "credentials",+ operation = "store_session",+ "[credentials][auth-store] GET /auth/me transient validation failed on {} but JWT has no live local exp — session NOT persisted: {reason}",+ api_url.trim_end_matches('/')+ );+ return Err(format!(+ "Session validation failed (GET /auth/me): {reason}"+ ));+ };++ tracing::warn!(+ domain = "credentials",+ operation = "store_session",+ exp = %exp,+ "[credentials][auth-store] GET /auth/me transient validation failed on {} — persisting caller-authorized pending session for backend revalidation: {reason}",+ api_url.trim_end_matches('/')+ );+ session_validation_logs.push(format!(+ "session JWT accepted with deferred GET /auth/me validation on {} after transient failure",+ api_url.trim_end_matches('/')+ ));+ fallback_session_user_for_deferred_validation()+ }+ }+ };++ let mut metadata = std::collections::HashMap::new();+ if let Some(uid) = if local_session {+ local_user_id.clone()+ } else {+ user_id+ .and_then(|v| {+ let t = v.trim().to_string();+ (!t.is_empty()).then_some(t)+ })+ .or_else(|| user_id_from_profile_payload(&settings))+ } {+ metadata.insert("user_id".to_string(), uid);+ }+ let pending_backend_validation = settings+ .as_object()+ .and_then(|map| map.get("pendingBackendValidation"))+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let user_for_store = if local_session || pending_backend_validation {+ settings.clone()+ } else {+ sanitize_stored_session_user(user).unwrap_or(settings)+ };+ metadata.insert("user_json".to_string(), user_for_store.to_string());++ // Record the JWT `exp` so `require_live_session_token` can reject an expired+ // token locally instead of firing a doomed backend 401 (#3297 RCA — the+ // TAURI-RUST-8WY/8WZ flood). Local offline sessions aren't JWTs and carry no+ // `exp`; `decode_jwt_exp` returns None for them and the key is simply omitted+ // (presence-only check + the `flatten_authed_error` 401 net still apply).+ if !local_session {+ match decode_jwt_exp(trimmed_token) {+ Some(exp) => {+ metadata.insert(+ crate::security::credentials::session_support::SESSION_EXPIRES_AT_META+ .to_string(),+ exp.to_rfc3339(),+ );+ tracing::info!(+ domain = "credentials",+ operation = "store_session",+ "[credentials] recorded app-session expiry exp={exp} for local precheck"+ );+ }+ None => tracing::debug!(+ domain = "credentials",+ operation = "store_session",+ "[credentials] app-session token has no decodable `exp`; local expiry precheck disabled (falls back to 401 net)"+ ),+ }+ }++ // Determine user_id so we can scope the openhuman directory to this user.+ let resolved_user_id = metadata.get("user_id").cloned();+ if pending_backend_validation && resolved_user_id.is_none() && !is_embedder_host() {+ if let Ok(root_dir) = default_root_openhuman_dir() {+ if let Some(active_user_id) = read_active_user_id(&root_dir) {+ let active_user_dir = user_openhuman_dir(&root_dir, &active_user_id);+ if config.config_path.parent() == Some(active_user_dir.as_path()) {+ tracing::warn!(+ domain = "credentials",+ operation = "store_session",+ active_user_id = %active_user_id,+ "[credentials][auth-store] unresolved pending session would replace active user's app-session; session NOT persisted"+ );+ return Err(+ "Session validation failed (GET /auth/me): backend user id required before replacing the active session"+ .to_string(),+ );+ }+ }+ }+ }++ // If we know the user_id, activate the user-scoped directory BEFORE storing+ // the auth profile so that credentials land in the correct place.+ let mut logs = if local_session {+ vec!["local session accepted without backend validation".to_string()]+ } else {+ session_validation_logs+ };++ // An embedder host (the harness) keeps session state under its own+ // `config_path` scope and must never touch the operator's global+ // `~/.openhuman/active_user.toml` or `users/` tree. Writing it would change+ // which user the operator's real install believes is active purely by+ // virtue of running a library call — the exact global side effect an+ // ephemeral harness exists to avoid. The scoped auth profile is still+ // stored below; only the global activation is skipped.+ let operator_user_activation = !is_embedder_host();++ if let Some(ref uid) = resolved_user_id+ .as_ref()+ .filter(|_| operator_user_activation)+ {+ if let Ok(root_dir) = default_root_openhuman_dir() {+ // Snapshot before we overwrite `active_user.toml` so we can tell+ // first activation from signed-out vs an in-place account switch.+ let previous_active = read_active_user_id(&root_dir);+ let user_dir = user_openhuman_dir(&root_dir, uid);+ if let Err(e) = std::fs::create_dir_all(&user_dir) {+ tracing::warn!(+ user_id = %uid,+ error = %e,+ "failed to create user directory"+ );+ } else if let Err(e) = write_active_user_id(&root_dir, uid) {+ tracing::warn!(+ user_id = %uid,+ error = %e,+ "failed to write active_user.toml"+ );+ } else {+ logs.push(format!("user directory activated for {uid}"));+ tracing::info!(+ user_id = %uid,+ user_dir = %user_dir.display(),+ "User-scoped directory activated"+ );+ // Onboarding and other pre-auth flows write threads under the+ // `users/local/workspace` tree. After the first successful login+ // there was no previous `active_user.toml`, wipe that anonymous+ // conversation store so a fresh account never inherits demo or+ // scratch threads from the pre-login bucket (#1157).+ //+ // This shares `memory::conversations`' process-wide mutex with+ // `list_threads` / `purge_threads` on any workspace, so purge and+ // concurrent thread RPC in this process cannot interleave.+ if previous_active.is_none() {+ let pre_ws = pre_login_user_dir(&root_dir).join("workspace");+ let pre_ws_log = pre_ws.display().to_string();+ match conversations::purge_threads(pre_ws) {+ Ok(stats) => {+ tracing::info!(+ pre_login_workspace = %pre_ws_log,+ threads = stats.thread_count,+ messages = stats.message_count,+ "[credentials] purged pre-login conversation threads after first session activation"+ );+ logs.push(format!(+ "purged pre-login conversation history (threads={}, messages={})",+ stats.thread_count, stats.message_count+ ));+ }+ Err(e) => {+ tracing::debug!(+ error = %e,+ pre_login_workspace = %pre_ws_log,+ "[credentials] pre-login conversation purge skipped (non-fatal)"+ );+ }+ }+ }+ }+ }+ }++ // Reload config so it picks up the newly activated user directory.+ // This ensures auth-profiles.json, encryption key, etc. are written+ // to the user-scoped location.+ let effective_config = if resolved_user_id.is_some() {+ match crate::config::load_config_with_timeout().await {+ Ok(c) => c,+ Err(_) => config.clone(),+ }+ } else {+ config.clone()+ };++ if let Err(error) = crate::cron::seed::prune_retired_jobs(&effective_config) {+ tracing::warn!(+ error = %error,+ "[credentials] failed to prune retired cron jobs after user workspace activation"+ );+ }++ if local_session {+ match crate::config::ops::set_onboarding_completed(false).await {+ Ok(_) => logs.push("onboarding left incomplete for local session setup".to_string()),+ Err(error) => logs.push(format!(+ "onboarding setup warning for local session: {error}"+ )),+ }+ }++ let auth = AuthService::from_config(&effective_config);+ let profile = auth+ .store_provider_token(+ APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+ trimmed_token,+ metadata,+ true,+ )+ .map_err(|e| e.to_string())?;++ logs.push("session stored".to_string());++ // ── No explicit memory re-point here any more (#5560) ──────────────────+ //+ // This site used to call `tinymemory_core::global::init(...)` before the+ // context rebind below. That was load-bearing for the *engine singleton*: a+ // single process-global slot that keeps writing into the pre-login+ // workspace until something re-points it, which is why it needed its own+ // call at every login / logout / revalidation site.+ //+ // `memory::binding` is a workspace-keyed cache, not a slot, and+ // `CoreContext::memory_binding`'s own docs already state the consequence:+ // "there is **no** explicit 'rebind the memory driver' call at the login /+ // logout / revalidation sites the way `memory::global::init` needs one: the+ // accessor keys on the workspace dir and the subsystem config, both of+ // which those sites already re-point." The `rebind_default_workspace` call+ // immediately below re-points both, so memory follows it by construction.+ //+ // The binding is resolved lazily on the next memory call rather than warmed+ // here. Warming it would mean naming `binding::for_workspace` at a site+ // that never touches memory content, which the memory-guard bypass ratchet+ // is right to treat as reach-through.+ match crate::core::runtime::context::CoreContext::rebind_default_workspace(+ &effective_config.workspace_dir,+ effective_config.subsystems.memory.clone(),+ ) {+ Ok(_) => logs.push(format!(+ "core context bound to workspace {}",+ effective_config.workspace_dir.display()+ )),+ Err(e) => {+ tracing::warn!(error = %e, "[credentials] failed to rebind core context after login");+ logs.push(format!("core context bind warning: {e}"));+ }+ }+ // No people-store rebind here any more: people is served by the bound+ // memory driver, and `rebind_default_workspace` above already moved that+ // binding to the per-user workspace. Seeding a host-side global as well+ // opened the engine's database a second time in this process (#4378 fixed+ // the workspace it pointed at; the module port removes the second reader).+ crate::memory::conversations::register_conversation_persistence_subscriber(+ effective_config.workspace_dir.clone(),+ );+ logs.push("conversation persistence bound to active workspace".to_string());++ // Start all login-gated services (voice and local AI).+ // Uses the effective config so services see the user-scoped workspace+ // directory.+ start_login_gated_services(&effective_config).await;+ logs.push("login-gated services started".to_string());++ // Clear the scheduler-gate signed-out override now that a fresh JWT is+ // in place. Workers that were sleeping in the paused poll loop will+ // pick this up at their next iteration and resume LLM-bound work.+ crate::cron::scheduler_gate::set_signed_out(false);+ tracing::debug!(+ domain = "credentials",+ operation = "store_session",+ "[credentials][auth-store] scheduler gate cleared; ensuring re-embed backfill after login"+ );+ crate::memory::ops::maintenance::reembed_best_effort(&effective_config, "session stored").await;+ logs.push("memory re-embed backfill checked after login".to_string());++ // Bind the Sentry scope to this user so background events that fire+ // before the frontend's `app_state_snapshot` warms the user cache still+ // carry `user.id` — issue #3135. The `before_send` filter is now a+ // fallback for legacy cache-warming paths; setting scope here is the+ // primary source.+ if let Some(ref uid) = resolved_user_id {+ crate::security::credentials::sentry_scope::bind(uid);+ }++ Ok(RpcOutcome::new(summarize_auth_profile(&profile), logs))+}diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/state.rs b/crates/openhuman-core/src/threads/turn_state/mirror/state.rsnew file mode 100644index 0000000000..29d369138d--- /dev/null+++ b/crates/openhuman-core/src/threads/turn_state/mirror/state.rs@@ -0,0 +1,49 @@+use super::super::store::TurnStateStore;+use super::super::types::TurnState;++/// In-process cursor that keeps the authoritative [`TurnState`] in sync+/// with the agent loop and writes it through to a [`TurnStateStore`].+pub struct TurnStateMirror {+ pub(super) store: TurnStateStore,+ pub(super) state: TurnState,+ /// Set to `true` once we observe `TurnCompleted` so `finish` knows+ /// to delete the snapshot rather than mark it interrupted.+ pub(super) turn_completed: bool,+ /// Monotonic ordering key for [`TranscriptItem`]s. Round alone can't+ /// order narration vs thinking vs tool calls *within* one iteration, so+ /// every transcript push stamps and increments this.+ pub(super) next_seq: u32,+ /// Separate monotonic ordering key for [`ToolTimelineEntry::seq`] — the flat+ /// timeline is an independent projection from the interleaved transcript, so+ /// it gets its own space (sharing `next_seq` would leave gaps in the+ /// transcript's contiguous ordering).+ pub(super) next_tool_seq: u64,+}++impl TurnStateMirror {+ /// Build a mirror primed with a `Started` snapshot and immediately+ /// flush so a crash before the first agent event still leaves a+ /// recoverable record.+ pub fn new(+ store: TurnStateStore,+ thread_id: impl Into<String>,+ request_id: impl Into<String>,+ ) -> Self {+ let now = chrono::Utc::now().to_rfc3339();+ let state = TurnState::started(thread_id, request_id, 0, now);+ let mut mirror = Self {+ store,+ state,+ turn_completed: false,+ next_seq: 0,+ next_tool_seq: 0,+ };+ mirror.flush();+ mirror+ }++ #[cfg(test)]+ pub(crate) fn snapshot(&self) -> &TurnState {+ &self.state+ }+}diff --git a/crates/openhuman-core/src/web_chat/web_errors/classify.rs b/crates/openhuman-core/src/web_chat/web_errors/classify.rsnew file mode 100644index 0000000000..009b067662--- /dev/null+++ b/crates/openhuman-core/src/web_chat/web_errors/classify.rs@@ -0,0 +1,617 @@+//! The chat-error classification ladder: turning a flattened inference error+//! string into a [`ClassifiedError`] envelope the frontend can render a+//! recovery UI from.++use super::backend_error_code::classify_by_backend_error_code;+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::timeout::is_turn_timeout_error;++/// Structured chat-error envelope produced by [`classify_inference_error`].+///+/// Carries the typed metadata the frontend needs to render a recovery UI+/// (retry-after countdown, retry button, fallback CTA) without having to+/// regex the human-readable `message`. Issue #2606.+///+/// `error_type` and `message` preserve the wire shape PR #2371 established+/// — existing FE handlers that read those fields keep working. The new+/// fields are additive and `Option`-typed where the value isn't always+/// known at the classifier layer.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ClassifiedError {+ /// Stable token: `rate_limited`, `action_budget_exceeded`,+ /// `max_iterations`, `turn_timeout`, `timeout`, `auth_error`,+ /// `session_expired`, `budget_exhausted`, `provider_error`,+ /// `context_overflow`, `model_unavailable`, `payload_too_large`,+ /// `provider_request_rejected`, `capability_unsupported`,+ /// `chat_template_rejected`, `empty_response`, `network`, `inference`.+ pub(crate) error_type: &'static str,+ /// User-facing copy (already includes provider detail block and the+ /// retry-after countdown sentence when available).+ pub(crate) message: String,+ /// Where the limit originated. One of:+ /// - `"provider"` — upstream LLM provider 429 / rate limit+ /// - `"openhuman_budget"` — local SecurityPolicy per-hour action cap+ /// - `"agent_loop"` — agent ran out of tool iterations+ /// - `"openhuman_billing"` — OpenHuman credit/quota exhaustion+ /// - `"transport"` — network / DNS / TLS / timeout+ /// - `"config"` — auth, model, context, generic+ pub(crate) source: &'static str,+ /// Can the user retry the same prompt in the same thread? `false` for+ /// non-retryable business 429s, auth failures, model_unavailable,+ /// context_overflow, and OpenHuman billing exhaustion.+ pub(crate) retryable: bool,+ /// Milliseconds the upstream asked us to wait. Surfaced verbatim from+ /// `Retry-After:` / `retry_after:` headers when present; `None` when+ /// the upstream didn't supply one OR the error class doesn't have a+ /// concept of retry-after (auth, config, etc.).+ pub(crate) retry_after_ms: Option<u64>,+ /// Provider name extracted from the leading+ /// `"<provider> API error (...)"` envelope emitted by+ /// `inference::provider::ops::api_error`. `None` for non-provider+ /// errors (OpenHuman budget cap, agent loop) and for transport+ /// failures that don't carry an identifiable provider prefix.+ pub(crate) provider: Option<String>,+ /// `Some(false)` once the reliable-provider chain has exhausted every+ /// configured `model_fallbacks` entry (the aggregate "All+ /// providers/models failed" branch). `None` means the classifier+ /// can't tell from the error string alone — the FE should treat it+ /// as "unknown, don't promise a fallback".+ pub(crate) fallback_available: Option<bool>,+}++pub(crate) fn classify_inference_error(err: &str) -> ClassifiedError {+ let lower = err.to_lowercase();+ let provider = extract_provider_name(err);+ let fallback_available = if is_fallback_chain_exhausted(err) {+ Some(false)+ } else {+ None+ };++ // F2: when the managed backend stamped a stable `errorCode` on the body,+ // trust it and branch on it FIRST — ignoring the substring heuristics+ // below, which are tuned for the BYO / direct-provider path (no+ // `errorCode`). Only a recognised code short-circuits; an absent or+ // unrecognised code falls through to the substring ladder unchanged, so+ // the BYO "check your API key / model settings" copy stays intact.+ if let Some(classified) =+ classify_by_backend_error_code(err, provider.clone(), fallback_available)+ {+ log::debug!(+ "[chat-error][classify] error_type={} source={} retryable={} provider={:?} (via errorCode)",+ classified.error_type,+ classified.source,+ classified.retryable,+ classified.provider,+ );+ return classified;+ }++ // Order matters: the SecurityPolicy hourly cap and the+ // agent-loop max-iterations error both surface as strings that+ // contain "rate limit" / "iteration", so they MUST be checked+ // before the generic provider-429 branch — otherwise users see+ // a confusing "your AI provider is rate-limiting you" message+ // for limits OpenHuman itself enforced (issue #2364).+ // Codex-specific sentinel emitted by `openai_oauth::store` on refresh+ // failure. Checked before `is_session_expired_message` because the sentinel+ // contains "authentication token is expired", which would also match the+ // broader "session expired" substring test and route to the wrong sign-in+ // flow. We require "codex" in the message so generic provider errors that+ // happen to contain "token_expired" or "please try signing in again" are+ // not misclassified as Codex OAuth failures. (#5869)+ const CODEX_SENTINEL: &str = "codex authentication token is expired";+ let classified = if err.to_ascii_lowercase().contains(CODEX_SENTINEL) {+ // The Codex OAuth token has expired and the refresh failed. This is a+ // provider-specific re-auth — the user must reconnect Codex in+ // Settings → Integrations, NOT sign into OpenHuman.+ ClassifiedError {+ error_type: "provider_error",+ message: "Your Codex session has expired. Please reconnect it in \+ Settings → Integrations."+ .to_string(),+ source: "auth",+ retryable: false,+ retry_after_ms: None,+ provider: Some("openai_codex".to_string()),+ fallback_available: None,+ }+ } else if crate::core::observability::is_session_expired_message(err) {+ // The OpenHuman app-session JWT expired (or the scheduler gate flagged+ // signed-out / `SESSION_EXPIRED` sentinel). There is NO client-side+ // refresh — recovery is an interactive re-auth only — so this is+ // non-retryable and must route the user to sign-in. Checked after the+ // Codex OAuth arm because "authentication token is expired" would also+ // match `is_session_expired_message`'s broad "session expired" substring.+ // The `auth_error` arm below can't claim the backend's `401 "Invalid token"`+ // envelope (it contains "401") and mislead managed-backend users with+ // "check your API key". `is_session_expired_message` is conjunctively+ // scoped to the OpenHuman/Embedding "Invalid token" envelopes + the+ // `SESSION_EXPIRED` / "no backend session" / "session jwt required"+ // sentinels, so a BYO provider's own 401 still falls through to+ // `auth_error`.+ ClassifiedError {+ error_type: "session_expired",+ message: "Your OpenHuman session has expired. \+ Please sign in again to continue."+ .to_string(),+ source: "auth",+ retryable: false,+ retry_after_ms: None,+ // OpenHuman's own session — provider name (if any leaked into the+ // surrounding chain) is irrelevant to a sign-in prompt.+ provider: None,+ fallback_available: None,+ }+ } else if is_action_budget_exhausted(&lower) {+ ClassifiedError {+ error_type: "action_budget_exceeded",+ message: with_provider_detail(+ "You've hit OpenHuman's per-hour action budget — this is a local safety cap, \+ not your AI provider. The window decays gradually; you can keep chatting in \+ this thread and tool-heavy steps will resume as the budget refills.",+ err,+ ),+ source: "openhuman_budget",+ // The window decays gradually so the same thread CAN recover+ // — we just can't predict the exact wait.+ retryable: true,+ retry_after_ms: None,+ // OpenHuman's own cap — provider name (if any was in the+ // surrounding error chain) is irrelevant; the limit isn't+ // from a provider.+ provider: None,+ fallback_available: None,+ }+ } else if crate::agent::error::is_max_iterations_error(err) {+ ClassifiedError {+ error_type: "max_iterations",+ message: with_provider_detail(+ "The agent ran the maximum number of tool steps for one turn without \+ finishing. This usually means a tool kept failing (often a rate limit on a \+ web fetch). You can retry the same question in this thread once the \+ underlying limit clears.",+ err,+ ),+ source: "agent_loop",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available: None,+ }+ } else if is_turn_timeout_error(err) {+ // The web turn driver's wall-clock backstop fired: the turn ran past its+ // time budget without ever producing a terminal event — a wedged main+ // agent (stuck mid tool-call) or a delegated sub-agent that never+ // returned. Surface a graceful, retryable chat_error so the client stops+ // "processing" instead of receiving an empty reply / spinning on+ // `inference_heartbeat` until the socket dies (issue #4746). Anchored+ // next to max_iterations — both are deterministic agent-loop outcomes+ // that must not be shadowed by the broad provider-429 / 5xx arms below.+ // No `with_provider_detail`: the marker string carries no provider body.+ ClassifiedError {+ error_type: "turn_timeout",+ message: "This turn ran past its time budget without finishing and was \+ stopped so it wouldn't hang. This usually means a tool call or a \+ delegated sub-agent stalled. You can retry your question in this thread."+ .to_string(),+ source: "agent_loop",+ retryable: true,+ retry_after_ms: None,+ provider: None,+ fallback_available: None,+ }+ } else if is_empty_provider_response_text(&lower) {+ // The agent harness bailed because the provider/model completed a+ // turn with a completely empty body (text_chars=0 thinking_chars=0+ // tool_calls=0) — `AgentError::EmptyProviderResponse`, flattened to+ // a `String` at the native-bus boundary. Without this arm the+ // message falls through to the generic catch-all and the user sees a+ // bare "Something went wrong" with no remedy (Sentry TAURI-RUST-4JW,+ // the single largest source of the #3092 / #3119 chat-error+ // cluster). Placed early next to max_iterations: both are+ // deterministic agent-state outcomes with a specific anchor, so+ // neither can be shadowed by the broad provider-429 / 5xx arms below.+ // No `with_provider_detail` — an empty response carries no JSON body+ // to quote.+ //+ // Issue #3335: the prior copy ("Try a different model or check your+ // local provider in Connections → API keys → LLM") sent Managed users in+ // exactly the wrong direction — there is no local provider on the+ // Managed route, and the common underlying cause is credit+ // exhaustion (see #3386). The provider name is not available here+ // because `EmptyProviderResponse`'s flattened Display carries no+ // `" API error"` infix for `extract_provider_name` to anchor on,+ // and routing the typed provider through every layer is out of+ // scope for this fix. So the copy is rewritten to be accurate for+ // ALL providers: it names the three real remedies (credits, model+ // health, configuration) without claiming any single one of them+ // applies, and lets the user pick which is relevant to their+ // setup. The companion empty-2xx-stream diagnostic in+ // `compatible.rs::stream_native_chat` records elapsed_ms,+ // chunk_count, and has_usage so the next iteration of this arm+ // can be provider-aware once we have evidence on which path is+ // dominant in production.+ ClassifiedError {+ error_type: "empty_response",+ message: "The model returned an empty response. This usually means your inference \+ credits are exhausted (Settings → Billing), the upstream model is temporarily \+ unhealthy, or your provider configuration is rejecting the request \+ (Connections → API keys → LLM). Try one of those, or pick a different model."+ .to_string(),+ source: "agent_loop",+ retryable: true,+ retry_after_ms: None,+ provider: None,+ fallback_available: None,+ }+ } else if crate::inference::provider::is_chat_template_rejection_message(err) {+ // #5291: a local runtime (LM Studio / llama.cpp / Ollama) rendered the+ // request through the model's OWN Jinja chat template and the template+ // raised — `No user query found in messages.` on Qwen 3, against the+ // prompt-guided tool loop's message shape. Neither the model nor the+ // sampling params are at fault, and the request never reached the model.+ //+ // Placed HERE, with the other specific-anchor arms and above the broad+ // substring ladder, because both renderings of this failure are claimed+ // by an earlier-or-lower arm that misdiagnoses them:+ // - the retry aggregate that wraps the failed attempts ends with+ // "…change your default model in Connections → API keys → LLM",+ // and the `auth_error` arm below matches on the bare substring+ // "api key" — the user gets "check your API key" for a template+ // failure;+ // - that same aggregate carries "may not be available on your+ // provider", which the config-rejection arm renders as "your+ // provider rejected the model or temperature setting" (#5291's+ // reported symptom).+ // Both point at a credential/model/temperature that was never the+ // problem, so every remediation they offer is a dead end. The anchors+ // in `is_chat_template_rejection_message` are template-engine strings+ // ("jinja exception", the raised guard text), which no unrelated+ // provider error emits — so claiming the error this early is safe.+ //+ // Retryable: the failure needs a tool-step history with no resolvable+ // user turn, and a fresh turn starts from the user's new message, so+ // the same model can succeed on the next attempt. The harness-side fix+ // (guaranteeing a user turn for non-native-tool models) removes the+ // shape that triggers it at all.+ ClassifiedError {+ error_type: "chat_template_rejected",+ message: with_provider_detail(+ "This model's chat template rejected the request — it isn't the model, the \+ temperature, or your API key. Local models without native tool calling are \+ driven through their own chat template, and some templates refuse the \+ message shape of a tool step. Start a new chat to reset the history, or \+ pick a model with native tool support in Connections → API keys → LLM.",+ err,+ ),+ source: "provider",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else if lower.contains("rate limit") || lower.contains("429") {+ let retry_secs = parse_retry_after_secs_from_str(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+ // the "Retry" button and route the user to settings/billing.+ let non_retryable = is_non_retryable_rate_limit_text(&lower);+ let summary = if non_retryable {+ "Your AI provider is rejecting requests for billing or plan reasons \+ (out of credits, plan limit, or unavailable model). Retrying won't \+ help — open Settings to top up, upgrade your plan, or pick a \+ different model."+ .to_string()+ } else {+ format!(+ "Your AI provider is rate-limiting requests. This is a transient upstream \+ limit, not a thread-level block — you can retry in this thread.{}",+ retry_after_hint(retry_secs)+ )+ };+ ClassifiedError {+ error_type: "rate_limited",+ message: with_provider_detail(summary.as_str(), err),+ source: "provider",+ retryable: !non_retryable,+ retry_after_ms: retry_secs.map(|s| s.saturating_mul(1000)),+ provider,+ fallback_available,+ }+ } else if lower.contains("timeout") || lower.contains("timed out") {+ ClassifiedError {+ error_type: "timeout",+ message: with_provider_detail(+ "The request timed out. Please check your connection and try again.",+ err,+ ),+ source: "transport",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else if lower.contains("401") || lower.contains("unauthorized") || lower.contains("api key") {+ ClassifiedError {+ error_type: "auth_error",+ message: with_provider_detail(+ "There's an authentication issue with the AI provider. Please check your API key in settings.",+ err,+ ),+ source: "config",+ retryable: false,+ retry_after_ms: None,+ provider,+ fallback_available: None,+ }+ } else if lower.contains("402")+ || lower.contains("payment required")+ || lower.contains("insufficient balance")+ // Issue #3088: the OpenHuman managed backend reports no-credits as a+ // 400 with "Insufficient budget" (not a 402), which previously fell+ // through to the generic "Something went wrong" branch. Catch the+ // canonical budget phrases here so the user gets the actionable+ // top-up / switch-to-your-own-model guidance instead.+ || is_inference_budget_exceeded_error(err)+ {+ // `openhuman_billing` means OpenHuman's own credit/quota system —+ // a 402 carrying the "openhuman" envelope (or no envelope at all,+ // since OpenHuman's backend is the only origin without one in+ // practice). When the 402 comes from an upstream provider envelope+ // (`<provider> API error (402)`), the limit belongs to that+ // provider, not OpenHuman billing, so tag the source as `provider`.+ let source: &'static str = match provider.as_deref() {+ Some("openhuman") | None => "openhuman_billing",+ Some(_) => "provider",+ };+ ClassifiedError {+ error_type: "budget_exhausted",+ message: with_provider_detail(inference_budget_exceeded_user_message(), err),+ source,+ retryable: false,+ retry_after_ms: None,+ provider,+ fallback_available: None,+ }+ } else if lower.contains("500")+ || lower.contains("internal server")+ || lower.contains("service unavailable")+ || lower.contains("503")+ {+ ClassifiedError {+ error_type: "provider_error",+ message: with_provider_detail(+ "The AI provider is temporarily unavailable. Please try again later.",+ err,+ ),+ source: "provider",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else if lower.contains("context")+ && (lower.contains("length")+ || lower.contains("limit")+ || lower.contains("exceed")+ || lower.contains("token"))+ {+ ClassifiedError {+ error_type: "context_overflow",+ message: with_provider_detail(+ "The conversation is too long. Please start a new chat.",+ err,+ ),+ source: "config",+ retryable: false,+ retry_after_ms: None,+ provider,+ fallback_available: None,+ }+ } 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+ // model-unavailable arm so config-rejection bodies that also+ // contain "model"/"does not exist"/"does not have access" get the+ // specific "Settings → LLM" remediation instead of the generic+ // copy. Shared predicate keeps this in lockstep with the+ // Sentry-demotion classifier.+ ClassifiedError {+ error_type: "model_unavailable",+ message: with_provider_detail(+ "Your AI provider rejected the request's model or temperature setting. \+ Check your model and routing in Settings → LLM.",+ err,+ ),+ source: "config",+ retryable: false,+ retry_after_ms: None,+ provider,+ fallback_available: None,+ }+ } else if lower.contains("model")+ && (lower.contains("not found")+ || lower.contains("unavailable")+ || lower.contains("does not exist")+ || lower.contains("does not have access"))+ {+ // #5503: this arm previously flattened two distinct failures into one+ // non-retryable "check your model settings" misconfiguration verdict.+ // A TRANSIENT upstream outage ("the model is temporarily unavailable",+ // "currently overloaded") is NOT a user misconfiguration — labelling it+ // `config`/non-retryable tells the user to go fix settings that are+ // fine, and hides the Retry button on a failure a retry would clear. So+ // split on transience: a body carrying a temporary-outage marker routes+ // to the retryable "temporarily unavailable" provider copy (the same+ // class as the `500`/`503` arm above), while a genuine model rejection+ // ("does not exist", "does not have access", "model unavailable on this+ // endpoint" — a stale pin / wrong endpoint) keeps the non-retryable+ // config copy. Genuine config-rejection bodies (`does not exist`,+ // `model_not_found`, `/openai/v1/models`, …) are already claimed by the+ // provider-config-rejection arm above and never reach here.+ if is_transient_unavailability_text(&lower) {+ ClassifiedError {+ error_type: "provider_error",+ message: with_provider_detail(+ "The AI provider is temporarily unavailable. Please try again later.",+ err,+ ),+ source: "provider",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else {+ ClassifiedError {+ error_type: "model_unavailable",+ message: with_provider_detail(+ "The selected model isn't available on your provider. Check your model settings.",+ err,+ ),+ source: "config",+ retryable: false,+ retry_after_ms: None,+ provider,+ fallback_available: None,+ }+ }+ } else if lower.contains("does not support vision") || lower.contains("capability=vision") {+ // A multimodal turn sent image markers to a text-only model+ // (`provider_capability_error … capability=vision … does not support+ // vision input`, raised by the tinyagents model adapter). Without+ // this arm it dead-ends on the generic catch-all. Retrying the same+ // image against the same model can't help — the user must drop the+ // attachment or pick a vision-capable model, so this is non-retryable.+ ClassifiedError {+ error_type: "capability_unsupported",+ message: "This model can't process images. Remove the attachment or switch to a \+ vision-capable model in Connections → API keys → LLM."+ .to_string(),+ source: "config",+ retryable: false,+ retry_after_ms: None,+ provider: None,+ fallback_available: None,+ }+ } else if is_provider_request_rejected_text(&lower) && is_malformed_tool_history_text(&lower) {+ // Same poisoned-history rejection as the managed `BAD_REQUEST` branch,+ // but on a BYO/direct provider (e.g. OpenAI "messages with role 'tool'+ // must be a response to a preceding message with 'tool_calls'"). The+ // de-poison guard already evicted the warm session, so resending works.+ // Checked BEFORE the generic 4xx arm so the actionable copy wins.+ ClassifiedError {+ error_type: "provider_request_rejected",+ message: malformed_history_user_message().to_string(),+ source: "provider",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else if is_provider_request_rejected_text(&lower) {+ // A provider rejected the request with a 4xx that none of the+ // specific arms above claimed (generic 400 Bad Request, 404, 422).+ // The DeepSeek thinking-mode `reasoning_content` round-trip 400+ // (deeper fix tracked separately in #3197) and other model/parameter+ // incompatibilities land here. MUST stay below the+ // provider-config-rejection (invalid temperature, stale model pin)+ // and model-unavailable arms so their more specific 4xx verdicts win+ // first. 4xx is a client/request problem — identical retry fails, so+ // non-retryable. The real provider reason is already secret-scrubbed+ // and length-capped by `with_provider_detail` and quoted to the user.+ ClassifiedError {+ error_type: "provider_request_rejected",+ message: with_provider_detail(+ "The AI provider rejected the request — this is usually a model or \+ parameter incompatibility. Try a different model in Connections → API keys → LLM.",+ err,+ ),+ source: "provider",+ retryable: false,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else if is_connection_dropped_text(&lower) {+ // A transport-level drop with no provider status and no managed+ // `errorCode`: a stale keep-alive socket reused after sleep/wake, a+ // network change, or a RAW mid-stream SSE drop — the managed backend+ // intentionally omits `errorCode` for raw upstream/network drops+ // (backend `routes/inference.ts`), so those reach here as+ // `"OpenHuman streaming API error: <body>"` with nothing to branch on.+ // These previously fell to the generic catch-all ("Something went+ // wrong"). The turn's history is NOT poisoned — the agent loop bails+ // before committing the failed iteration (`engine/core.rs`) — so this is+ // cleanly retryable and the warm session is kept. Placed LAST so every+ // specific provider-status / 4xx arm claims its shape first; only an+ // otherwise-unclassified transport error lands here.+ ClassifiedError {+ error_type: "network",+ message: with_provider_detail(+ "The connection to the AI service dropped mid-response — usually a \+ sleep/wake or network change. Please try again.",+ err,+ ),+ source: "transport",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else if is_transient_unavailability_text(&lower) {+ // A transient upstream-outage marker that no more specific arm above+ // claimed (e.g. a bare 5xx "overloaded" such as Anthropic's 529, or+ // "please retry later") is a temporary provider outage — surface the+ // retryable "temporarily unavailable" provider copy rather than the flat+ // inference bucket, so the user gets an accurate, retryable error (#5503).+ ClassifiedError {+ error_type: "provider_error",+ message: "The AI provider is temporarily unavailable. Please try again later."+ .to_string(),+ source: "provider",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ } else {+ ClassifiedError {+ error_type: "inference",+ message: with_provider_detail(generic_inference_error_user_message(), err),+ source: "provider",+ retryable: true,+ retry_after_ms: None,+ provider,+ fallback_available,+ }+ };++ // Verbose diagnostics on the classification flow (per CLAUDE.md). Stable+ // grep-friendly prefix + low-cardinality fields only — the raw `err` (which+ // may carry provider payload / PII) is intentionally NOT logged here; the+ // caller (`web.rs::run_chat_task`) already records it at warn level and+ // routes it through `report_error_or_expected`.+ log::debug!(+ "[chat-error][classify] error_type={} source={} retryable={} provider={:?}",+ classified.error_type,+ classified.source,+ classified.retryable,+ classified.provider,+ );++ classified+}