Skip to content

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

fix(agent): handle auth failure in subagent graph execution

Steven Enamakel495346c1d44f
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs
index 972470a4ef..f4d51ec943 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs
@@ -27,8 +27,41 @@
//! and a graceful model-call-cap checkpoint summary
//! (`SubagentCheckpoint::summarize_cap_hit`).
+// Split by responsibility rather than by line count:
+//
+// - [`dispatch`] — drives one sub-agent turn through the shared tinyagents
+// seam, builds its context middleware, and folds a cap-hit checkpoint
+// summary back into the result.
+// - [`transcript`] — persists a sub-agent turn's (or a failed run's) raw
+// transcript to `session_raw`.
+// - [`worker_mirror`] — mirrors a sub-agent turn's conversation onto its
+// spawn's worker thread.
+mod dispatch;
+mod transcript;
+mod worker_mirror;
+
+// Re-exported under the original flat `graph::` path so external callers
+// (`ops/mod.rs`, `ops/runner.rs`, `graph_tests.rs`'s `use super::*`) are
+// unaffected by the responsibility split.
+pub(crate) use dispatch::run_agent_turn_request_via_default_graph;
+pub(super) use dispatch::{run_subagent_via_graph, AggregatedUsage};
+
+// Only what `graph_tests.rs`'s `use super::*` still needs directly (the rest
+// of the original flat imports now live with the code that uses them, in
+// `dispatch.rs` / `transcript.rs` / `worker_mirror.rs`).
+#[cfg(test)]
+use crate::agent::messages::{ChatMessage, ConversationMessage};
+#[cfg(test)]
+use crate::agent::progress::AgentProgress;
+#[cfg(test)]
+use crate::inference::tokenjuice::AgentTokenjuiceCompression;
+#[cfg(test)]
+use crate::tools::Tool;
+#[cfg(test)]
+use std::collections::HashSet;
+#[cfg(test)]
+use std::sync::Arc;
+
#[cfg(test)]
#[path = "graph_tests.rs"]
mod tests;
-include!("graph_part_01.rs");
-include!("graph_part_02.rs");
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs
new file mode 100644
index 0000000000..46bfd00cff
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs
@@ -0,0 +1,136 @@
+//! Aborting sub-agents: by task id (the user-facing "Cancel" affordance), by
+//! durable session id, by owning parent thread (thread deletion), or all at
+//! once (a full thread purge).
+
+use std::collections::HashSet;
+use std::path::{Path, PathBuf};
+
+use tinyagents_harness::ids::TaskId;
+
+use super::registry::registry;
+use super::resolve::{task_id_for_session, task_id_for_session_in_workspace};
+use super::task_ledger::record_cancelled;
+
+/// Metadata captured when a sub-agent is cancelled, so the caller can surface
+/// the cancellation back in the parent chat (record a "cancelled" completion
+/// for idle-gated delivery).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct CancelledSubagent {
+ pub(crate) agent_id: String,
+ pub(crate) parent_session: String,
+ pub(crate) subagent_session_id: Option<String>,
+ pub(crate) workspace_dir: PathBuf,
+ pub(crate) parent_thread_id: Option<String>,
+}
+
+/// Abort and drop the sub-agent with `task_id`, returning its metadata so the
+/// caller can deliver a "cancelled" notice into the parent chat. Returns `None`
+/// if no such sub-agent is registered (already finished, or unknown id).
+///
+/// Unlike the parent-session-owned steering and close paths, this is keyed by
+/// `task_id` alone with no ownership check — it backs the user-facing "Cancel"
+/// affordance, and the desktop user owns every sub-agent in their own core.
+pub(crate) fn cancel_by_task(task_id: &str) -> Option<CancelledSubagent> {
+ let cancelled = registry().cancel_trusted(&TaskId::new(task_id)).ok()?;
+ let metadata = cancelled.metadata;
+ record_cancelled(&metadata.workspace_dir, task_id);
+ log::debug!(
+ "[running_subagents] cancel_by_task task_id={} agent_id={} parent_thread_id={:?} live_entries={}",
+ task_id,
+ metadata.agent_id,
+ metadata.parent_thread_id,
+ registry()
+ .len()
+ .expect("detached task registry lock poisoned")
+ );
+ Some(CancelledSubagent {
+ agent_id: metadata.agent_id,
+ parent_session: cancelled.owner_id,
+ subagent_session_id: metadata.subagent_session_id,
+ workspace_dir: metadata.workspace_dir,
+ parent_thread_id: metadata.parent_thread_id,
+ })
+}
+
+pub(crate) fn cancel_by_session(
+ subagent_session_id: &str,
+ parent_session: &str,
+) -> Option<CancelledSubagent> {
+ let task_id = task_id_for_session(subagent_session_id, parent_session).ok()?;
+ cancel_by_task(&task_id)
+}
+
+pub(crate) fn cancel_by_session_in_workspace(
+ subagent_session_id: &str,
+ parent_session: &str,
+ workspace_dir: &Path,
+) -> Option<CancelledSubagent> {
+ let task_id =
+ task_id_for_session_in_workspace(subagent_session_id, parent_session, workspace_dir)
+ .ok()?;
+ cancel_by_task(&task_id)
+}
+
+/// Abort and drop every running sub-agent whose parent chat thread is
+/// `thread_id`. Called when that thread is deleted so detached children don't
+/// keep running (and later try to deliver) against a thread that no longer
+/// exists. Returns the number of sub-agents cancelled.
+pub(crate) fn cancel_for_thread(thread_id: &str) -> usize {
+ let cancelled = registry()
+ .cancel_where(|metadata| metadata.parent_thread_id.as_deref() == Some(thread_id))
+ .expect("detached task registry lock poisoned");
+ for entry in &cancelled {
+ record_cancelled(&entry.metadata.workspace_dir, entry.task_id.as_str());
+ }
+ let count = cancelled.len();
+ log::debug!(
+ "[running_subagents] cancel_for_thread thread_id={} cancelled={} live_entries={}",
+ thread_id,
+ count,
+ registry()
+ .len()
+ .expect("detached task registry lock poisoned")
+ );
+ count
+}
+
+/// Abort and drop **every** registered sub-agent. Called on a full thread purge
+/// where no parent thread survives. Returns the **distinct parent thread ids**
+/// that had sub-agents, so the purge path can tombstone them in
+/// [`super::super::background_completions`] and drop any straggler completion
+/// that wins the cooperative-abort race. Headless sub-agents (no parent thread)
+/// are still aborted but contribute no id.
+pub(crate) fn cancel_all() -> Vec<String> {
+ let cancelled = registry()
+ .cancel_all()
+ .expect("detached task registry lock poisoned");
+ let count = cancelled.len();
+ let mut thread_ids: Vec<String> = Vec::new();
+ let mut seen: HashSet<String> = HashSet::new();
+ for entry in cancelled {
+ record_cancelled(&entry.metadata.workspace_dir, entry.task_id.as_str());
+ if let Some(thread_id) = entry.metadata.parent_thread_id {
+ if seen.insert(thread_id.clone()) {
+ thread_ids.push(thread_id);
+ }
+ }
+ }
+ log::debug!(
+ "[running_subagents] cancel_all cancelled={} distinct_threads={}",
+ count,
+ thread_ids.len()
+ );
+ thread_ids
+}
+
+#[allow(dead_code)]
+pub(crate) fn prune(task_id: &str) {
+ let _ = registry().cancel_trusted(&TaskId::new(task_id));
+}
+
+pub(crate) fn now_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
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
new file mode 100644
index 0000000000..e89f528e8c
--- /dev/null
+++ b/crates/openhuman-core/src/inference/provider/ops/http_error/auth_failure.rs
@@ -0,0 +1,296 @@
+//! Auth-failure classification: backend app-session expiry, BYO API-key
+//! rejection, and OpenAI OAuth (ChatGPT/Codex) session expiry.
+
+use super::*;
+
+/// Whether a provider non-2xx response is the OpenHuman **backend** rejecting
+/// the app session JWT (`401`/`403`). This is expected user-session state
+/// (token expired / revoked / rotated server-side), not a product bug — the
+/// auth domain owns recovery, so the predicate is provider-scoped to
+/// [`openhuman_backend_model::PROVIDER_LABEL`]. A `401`/`403` from **other** providers
+/// with an auth-key envelope (missing/invalid BYO key) is demoted separately by
+/// [`is_byo_provider_auth_failure_http`]; anything else still reaches Sentry.
+pub fn is_backend_auth_failure(provider: &str, status: reqwest::StatusCode) -> bool {
+ matches!(status.as_u16(), 401 | 403) && provider == openhuman_backend_model::PROVIDER_LABEL
+}
+
+/// Whether a non-backend provider's `401`/`403` carries an OpenAI-style
+/// authentication-error body — i.e. a missing or invalid BYO API key.
+///
+/// This is deterministic **user-config** state (the user pasted a bad or empty
+/// key into a custom OpenAI-compatible provider), not a product bug. Sentry has
+/// no remediation path, yet retry loops (memory-tree extraction, memory jobs,
+/// cron) hammer the known-bad credential and flood Sentry with thousands of
+/// identical events from a single user — TAURI-RUST-DHM (5,636 events from a
+/// `kiro` custom provider with no key), the same class as the Cohere
+/// "no api key supplied" flood (#3354) and the backend session-expiry flood
+/// (#2786 / [`is_backend_auth_failure`]).
+///
+/// Provider-scoped and body-shape-anchored, mirroring the sibling rules:
+/// - The OpenHuman **backend** keeps its [`is_backend_auth_failure`] →
+/// [`publish_backend_session_expired`] branch (a backend `401`/`403` is
+/// app-session expiry, not a BYO key), so this predicate excludes
+/// [`openhuman_backend_model::PROVIDER_LABEL`].
+/// - A `401`/`403` whose body does **not** look like an auth-key envelope
+/// (e.g. a gateway returning `401` on quota / geo-block) still reaches Sentry
+/// — the gate keys on the body, not the bare status.
+pub fn is_byo_provider_auth_failure_http(
+ provider: &str,
+ status: reqwest::StatusCode,
+ body: &str,
+) -> bool {
+ if !matches!(status.as_u16(), 401 | 403) {
+ tracing::debug!(
+ domain = "llm_provider",
+ operation = "http_error_classifier",
+ provider = provider,
+ status = status.as_u16(),
+ matched = false,
+ reason = "byo_provider_auth_failure_probe:non_auth_status",
+ "[llm_provider] BYO auth-failure classifier skipped — status is not 401/403"
+ );
+ return false;
+ }
+ if provider == openhuman_backend_model::PROVIDER_LABEL {
+ tracing::debug!(
+ domain = "llm_provider",
+ operation = "http_error_classifier",
+ provider = provider,
+ status = status.as_u16(),
+ matched = false,
+ reason = "byo_provider_auth_failure_probe:backend_excluded",
+ "[llm_provider] BYO auth-failure classifier skipped — backend owns session-expiry recovery"
+ );
+ return false;
+ }
+ let lower = body.to_ascii_lowercase();
+ // OpenAI-style auth envelopes across the BYO providers seen in Sentry:
+ // `"type":"authentication_error"` (kiro / Anthropic-style), OpenAI's
+ // `"code":"invalid_api_key"` + "Incorrect API key provided", and the
+ // bare-message variants Cohere / litellm gateways emit (#3354).
+ const AUTH_ERROR_MARKERS: &[&str] = &[
+ "authentication_error",
+ "invalid_api_key",
+ "invalid api key",
+ "invalid or missing api key",
+ "missing api key",
+ "no api key supplied",
+ "incorrect api key",
+ "invalid authentication",
+ ];
+ let matched = AUTH_ERROR_MARKERS
+ .iter()
+ .any(|marker| lower.contains(marker))
+ // OpenRouter's wording for a key that resolves to no account
+ // (revoked / deleted user): `401 {"error":{"message":"User not
+ // found.","code":401}}`. Same invalid-BYO-key user-state as the
+ // markers above — OpenHuman has no lever to make the user's
+ // third-party account exist. Kept OpenRouter-gated (not a global
+ // marker): `"user not found"` is generic prose another provider
+ // could emit for an unrelated 401/403, and demoting that would
+ // suppress a real error and show the wrong remediation. Without this
+ // anchor the 401 leaks to Sentry once per memory-summarization retry
+ // (TAURI-RUST-4RC: ~9k events / 6 users). A verbatim-body test
+ // couples it to this payload so a wording drift fails CI instead of
+ // silently leaking.
+ || (provider == "openrouter" && lower.contains("user not found"));
+ // Body content is intentionally omitted from the log — it can carry the
+ // raw (sanitized-or-not) provider payload; only the match outcome is logged.
+ tracing::debug!(
+ domain = "llm_provider",
+ operation = "http_error_classifier",
+ provider = provider,
+ status = status.as_u16(),
+ matched,
+ reason = "byo_provider_auth_failure_probe",
+ "[llm_provider] evaluated BYO auth-failure classifier"
+ );
+ matched
+}
+
+pub fn log_byo_provider_auth_failure(
+ operation: &str,
+ provider: &str,
+ model: Option<&str>,
+ status: reqwest::StatusCode,
+) {
+ tracing::info!(
+ domain = "llm_provider",
+ operation = operation,
+ provider = provider,
+ model = model.unwrap_or(""),
+ status = status.as_u16(),
+ failure = "non_2xx",
+ kind = "provider_user_state",
+ reason = "byo_provider_auth_failure",
+ "[llm_provider] {operation} BYO provider auth failure ({status}) — \
+ user API key missing/invalid, not reporting to Sentry"
+ );
+
+ // Demoting from Sentry hides the failure from us, so it must not also be
+ // invisible to the user — the failing path is often a silent background
+ // loop (memory summarization) that just degrades to regex-only. Record the
+ // rejection into the process registry that backs the AI-settings
+ // provider-error notice, and on the *first* record of this episode publish
+ // a one-shot notification. The 401 repeats per retry (~9k events for
+ // TAURI-RUST-4RC), so the registry latch is what keeps this from
+ // re-flooding the notification center the way the raw error flooded Sentry.
+ let status_code = status.as_u16();
+ if crate::inference::auth_error_registry::record(provider, status_code) {
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ProviderApiKeyRejected {
+ provider: provider.to_string(),
+ message: crate::inference::auth_error_registry::auth_error_message(
+ provider,
+ status_code,
+ ),
+ });
+ }
+}
+
+/// Whether a `401` is the OpenAI **OAuth** (ChatGPT-subscription / Codex)
+/// access token having expired — distinct from a misconfigured BYO API key.
+///
+/// The ChatGPT/Codex OAuth Responses endpoint returns
+/// `{"error":{"code":"token_expired","message":"Provided authentication token
+/// is expired. Please try signing in again."}}` once the OAuth access token
+/// lapses. The valid-`refresh_token` case already self-heals at credential
+/// resolution time (`openai_oauth::lookup_openai_oauth_credentials` refreshes
+/// proactively within a 2-min skew, and the chat provider is rebuilt per
+/// request), so the residual events that reach this 401 are ones where the
+/// refresh token is **absent or revoked** — the user must reconnect OpenAI.
+/// That is deterministic user-state, not a server bug, and reporting it spams
+/// Sentry (TAURI-RUST-8FQ: 97,938 events / 31 users).
+///
+/// Keyed on the OAuth-expiry body markers, which an API-key rejection never
+/// emits (those say "incorrect api key" — caught by
+/// [`is_byo_provider_auth_failure_http`] instead). The OpenHuman **backend**
+/// provider is excluded — its `401`/`403` is app-session expiry handled by
+/// [`publish_backend_session_expired`]. Unlike that path, this does **not**
+/// publish [`crate::core::events::DomainEvent::SessionExpired`]: an expired
+/// *provider* OAuth token must not tear down the OpenHuman app session.
+pub fn is_openai_oauth_session_expired_http(
+ provider: &str,
+ status: reqwest::StatusCode,
+ body: &str,
+) -> bool {
+ if status.as_u16() != 401 {
+ tracing::debug!(
+ domain = "llm_provider",
+ operation = "http_error_classifier",
+ provider = provider,
+ status = status.as_u16(),
+ matched = false,
+ reason = "openai_oauth_session_expired_probe:non_401",
+ "[llm_provider] OpenAI OAuth session-expiry classifier skipped — status is not 401"
+ );
+ return false;
+ }
+ if provider == openhuman_backend_model::PROVIDER_LABEL {
+ tracing::debug!(
+ domain = "llm_provider",
+ operation = "http_error_classifier",
+ provider = provider,
+ status = status.as_u16(),
+ matched = false,
+ reason = "openai_oauth_session_expired_probe:backend_excluded",
+ "[llm_provider] OpenAI OAuth session-expiry classifier skipped — backend owns app-session expiry"
+ );
+ return false;
+ }
+ let matched = is_openai_oauth_session_expired_message(body);
+ tracing::debug!(
+ domain = "llm_provider",
+ operation = "http_error_classifier",
+ provider = provider,
+ status = status.as_u16(),
+ matched,
+ reason = "openai_oauth_session_expired_probe",
+ "[llm_provider] evaluated OpenAI OAuth session-expiry classifier"
+ );
+ matched
+}
+
+/// Message-level half of [`is_openai_oauth_session_expired_http`]: matches the
+/// OpenAI OAuth session-expiry body markers without a status/provider gate.
+///
+/// The provider HTTP layer demotes its own per-attempt event via the `_http`
+/// gate, but the same `anyhow::bail!` string is re-raised at the JSON-RPC
+/// boundary (`core::jsonrpc` → `report_error_or_expected` →
+/// `core::observability::expected_error_kind`), which has only the message
+/// string — no status. This predicate lets that central classifier demote the
+/// re-report too, so an RPC-triggered chat/test call does not leak the event
+/// the `_http` gate already suppressed (TAURI-RUST-8FQ). Mirrors the
+/// `is_provider_config_rejection_message` / `_http` split.
+///
+/// `token_expired` is OpenAI's OAuth error code; the prose variants cover
+/// sanitized/reworded bodies. An API-key rejection never carries these (it
+/// emits "incorrect api key" / "invalid_api_key"), and the backend app-session
+/// "invalid token" / "please sign in again" wording differs, so this cannot
+/// swallow a real misconfig or a backend session-expiry.
+pub fn is_openai_oauth_session_expired_message(message: &str) -> bool {
+ const OAUTH_EXPIRY_MARKERS: &[&str] = &[
+ "token_expired",
+ "authentication token is expired",
+ "please try signing in again",
+ ];
+ let lower = message.to_ascii_lowercase();
+ OAUTH_EXPIRY_MARKERS
+ .iter()
+ .any(|marker| lower.contains(marker))
+}
+
+/// Demote an OpenAI OAuth session-expiry `401` to an info log (user-state,
+/// not a server bug) instead of reporting it to Sentry. The message tells the
+/// user to reconnect OpenAI, which is the only recovery once the refresh token
+/// is gone. See [`is_openai_oauth_session_expired_http`].
+pub fn log_openai_oauth_session_expired(
+ operation: &str,
+ provider: &str,
+ model: Option<&str>,
+ status: reqwest::StatusCode,
+) {
+ tracing::info!(
+ domain = "llm_provider",
+ operation = operation,
+ provider = provider,
+ model = model.unwrap_or(""),
+ status = status.as_u16(),
+ failure = "non_2xx",
+ kind = "provider_user_state",
+ reason = "openai_oauth_session_expired",
+ "[llm_provider] {operation} OpenAI OAuth session expired ({status}) — \
+ ChatGPT/Codex token lapsed without a usable refresh token; user must \
+ reconnect OpenAI, not reporting to Sentry"
+ );
+}
+
+/// Handle a backend session-expiry auth failure: publish a
+/// [`crate::core::events::DomainEvent::SessionExpired`] so the credentials
+/// subscriber clears the session and flips the scheduler-gate signed-out
+/// override (halting downstream LLM work — see OPENHUMAN-TAURI-1T), and skip
+/// the Sentry report. Mirrors the `is_auth_failure && is_backend` arm in
+/// [`super::dispatch::api_error`], factored out for adapter error paths that
+/// already consumed the response body and cannot delegate to `api_error`.
+///
+/// `message` is the already-formatted `"{provider} API error ({status}): …"`
+/// string; it embeds the sanitized body, but the prefix and caller-controlled
+/// provider name aren't scrubbed, so re-run [`sanitize_api_error`] on the final
+/// string before it reaches the SessionExpired subscriber's logs.
+pub fn publish_backend_session_expired(
+ operation: &str,
+ provider: &str,
+ status: reqwest::StatusCode,
+ message: &str,
+) {
+ tracing::warn!(
+ domain = "llm_provider",
+ operation = operation,
+ provider = provider,
+ status = status.as_u16(),
+ "[llm_provider] backend auth failure ({status}) — publishing SessionExpired"
+ );
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
+ source: "llm_provider.openhuman_backend".to_string(),
+ reason: sanitize_api_error(message),
+ });
+}