Skip to content

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

refactor: move JSON-RPC dispatch and classification from core to rpc server crate

Steven Enamakelb4f15a04e808
diff --git a/crates/openhuman-core/src/core/jsonrpc/classify.rs b/crates/openhuman-core/src/core/jsonrpc/classify.rs
deleted file mode 100644
index 53daa14762..0000000000
--- a/crates/openhuman-core/src/core/jsonrpc/classify.rs
+++ /dev/null
@@ -1,210 +0,0 @@
-//! How a failed RPC is classified at the transport boundary.
-//!
-//! Two decisions hang off an error string: whether it is a confirmed OpenHuman
-//! session expiry (which signs the user out, see
-//! [`invoke_method`](super::invoke_method)), and how loudly the `/rpc` handler
-//! reports it ([`classify_failure`]). Both are pure so they can be tested
-//! without a server.
-
-/// Helper to determine if an error message indicates an expired or invalid
-/// OpenHuman backend session.
-///
-/// **Narrower than the previous implementation** (fixed in issue #2286):
-///
-/// The old predicate matched ANY `"401 + unauthorized"` pattern, which caused
-/// downstream provider 401s (Discord bot token failures, BYO-key OpenAI /
-/// Anthropic failures, Composio direct-mode errors) to clear the user's session
-/// and log them out. The fix distinguishes between:
-///
-/// - **OpenHuman backend 401s** (`authed_json` in `crates/openhuman-core/src/api/rest.rs`): formatted
-/// as `"{METHOD} /path failed (401 Unauthorized): {body}"`, e.g.
-/// `"GET /teams failed (401 Unauthorized): {"success":false}"`. These always
-/// start with an HTTP method verb followed by a space and a forward slash.
-/// - **Provider / downstream 401s** (`api_error` in
-/// `crates/openhuman-core/src/inference/provider/ops.rs`): formatted as
-/// `"{ProviderName} API error (401 Unauthorized): {body}"` or
-/// `"Discord API error: ... (401): Unauthorized"`. These start with a
-/// provider name, NOT an HTTP method verb.
-///
-/// **What still triggers session expiry:**
-/// - `"Session expired"` — explicit body text from the OpenHuman backend.
-/// - `"no backend session token"` — pre-flight guard; auth profile is missing.
-/// - `"session jwt required"` — local guard; JWT already cleared by a prior 401.
-/// - `"SESSION_EXPIRED"` — scheduler-gate sentinel (exact case).
-/// - HTTP-method-prefixed 401s (`GET /`, `POST /`, etc.) — backend path format.
-///
-/// **What no longer triggers session expiry (fixed in #2286):**
-/// - Provider-prefixed 401s (`"Discord API error: ..."`, `"OpenAI API error ..."`)
-/// - `"invalid token"` — too broad; also matches Discord / OAuth provider tokens.
-///
-/// Note: for inference-path OpenHuman backend 401s, `api_error` (in
-/// `inference/provider/ops.rs` lines 479–497) ALREADY publishes `SessionExpired`
-/// directly, so there is no regression if this predicate misses them — the
-/// subscriber is idempotent and a harmless double-publish would still be correct.
-pub(super) fn is_session_expired_error(msg: &str) -> bool {
- // Explicit session-expired markers from the OpenHuman backend / local
- // guards — delegated to the shared observability classifier so both the
- // Sentry expected-error pipeline and the JSON-RPC publish boundary stay
- // in lock-step.
- if crate::core::observability::is_session_expired_message(msg) {
- return true;
- }
- // OpenHuman backend path 401s via `authed_json`:
- // format is "{METHOD} /path failed (401 Unauthorized): {body}"
- // The HTTP-method prefix distinguishes these from provider-prefixed errors.
- // HEAD and OPTIONS are intentionally excluded — `authed_json` only issues
- // the five listed verbs (GET/POST/PUT/DELETE/PATCH) for REST JSON endpoints.
- let lower = msg.to_ascii_lowercase();
- if (lower.contains("401") && lower.contains("unauthorized"))
- && (msg.starts_with("GET /")
- || msg.starts_with("POST /")
- || msg.starts_with("PUT /")
- || msg.starts_with("DELETE /")
- || msg.starts_with("PATCH /"))
- {
- return true;
- }
- false
-}
-
-/// Detect auth-looking failures that are not specific enough to clear the
-/// OpenHuman session. This is only for diagnostics; it must not feed the
-/// `SessionExpired` publish path.
-///
-/// Matches a generic `401 Unauthorized` OR a bare `"invalid token"` string,
-/// either of which can come from BYO-key providers, Composio, channels, or
-/// other scoped downstream calls. Used exclusively for diagnostic logging
-/// at the `invoke_method` call site so provider auth failures are visible
-/// in the logs without being misclassified as session expiry.
-pub(super) fn is_unconfirmed_unauthorized_error(msg: &str) -> bool {
- let lower = msg.to_ascii_lowercase();
- (lower.contains("401") && lower.contains("unauthorized")) || lower.contains("invalid token")
-}
-
-/// Returns `true` when the error is the wallet's "not configured yet" message.
-///
-/// Wallet-backed RPCs return
-/// [`crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE`] before
-/// setup. That is expected user state, not an internal failure.
-///
-/// Matched against the shared wallet constant (exact equality) so a wording
-/// change in the wallet layer fails the coupling test in `classify_tests.rs`
-/// rather than silently letting the noise back into Sentry.
-#[cfg(feature = "http-server")]
-pub(super) fn is_wallet_not_configured_error(msg: &str) -> bool {
- msg == crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE
-}
-
-/// How the `/rpc` handler reports a failed call, in priority order.
-///
-/// Only [`FailureDisposition::Unexpected`] is an error-level Sentry event. The
-/// rest are either expected boundary conditions or already reported elsewhere.
-/// The JSON-RPC error returned to the caller is the same for every variant,
-/// except that [`FailureDisposition::UsageProbeBackoff`] replaces the message.
-#[cfg(feature = "http-server")]
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(super) enum FailureDisposition {
- /// The controller's structured envelope set `expected_user_state` (stale
- /// thread refs and similar). Domains that surface their own expected
- /// user-state errors skip Sentry here uniformly.
- ExpectedUserState,
- /// A wallet-backed RPC cannot run before wallet setup. This is expected
- /// user state, not an internal failure.
- WalletNotConfigured,
- /// Param-validation failures ("unknown param 'x' for ns.fn", "missing
- /// required param 'x'", "invalid params: …") are pure boundary
- /// mismatches: either the caller is a frontend on a different release than
- /// the running core (OPENHUMAN-TAURI-20: v0.53.22 UI shipped `api_key`
- /// before the matching schema input landed in #1467) or it is straight
- /// client-bug input. Sentry cannot help — we can neither retro-fix
- /// already-shipped installs nor learn anything from the noise.
- ///
- /// Logged structurally with the body redacted: these messages embed
- /// caller-supplied param names and, for the `invalid params: …` shape, can
- /// carry deserialized values.
- ParamValidation,
- /// Session-expired bubbles up as an "error" but is an expected boundary
- /// condition (the auth handler clears the local token and the UI
- /// re-auths). Its messages are a small set of fixed strings with no
- /// caller-supplied content, so the full text is safe to log.
- SessionExpired,
- /// A `/teams/me/usage` probe that the failure-backoff in `team::ops`
- /// short-circuited within its window — i.e. an already-reported repeat.
- /// The first failure of the streak already hit the backend and reported
- /// normally; demoting the repeats is the flood control GH #4153 asks for
- /// (backpressure, not silent drop).
- ///
- /// The internal demotion marker must never reach the RPC client as the
- /// error message (CodeRabbit on #4153), so the handler replaces it with
- /// [`USAGE_BACKOFF_CLIENT_MESSAGE`].
- UsageProbeBackoff,
- /// A downstream call (backend_api / integrations / provider) already
- /// demoted the underlying transient failure to a warn. Re-reporting at
- /// error level would re-create the Sentry noise the lower-layer demote was
- /// meant to avoid (#8Z, #93, #8W, #96).
- ///
- /// The message is upstream-derived (backend / provider response) and can
- /// carry URL fragments, query params, or provider error text that
- /// includes tokens, so it is logged only after `sanitize_api_error`.
- TransientDownstream,
- /// An unrecognised RPC method is a transport-boundary mismatch (infra
- /// probe traffic, or a client on a different release than the running
- /// core), not an actionable core defect (#3567).
- ///
- /// Known external probes (`probe == true`) never become real methods, so
- /// they are debug-only and never reach Sentry. Any other unknown method is
- /// still recorded for triage, at warn severity (captured, no page).
- UnknownMethod { probe: bool },
- /// The caller submitted an ingest payload that does not match the
- /// canonicaliser schema for its `source_kind` (#5169). The handler already
- /// returned a precise error naming the missing or malformed field, and no
- /// core-side change can fix a producer sending the wrong shape. Still
- /// captured for triage (a spike means a producer regressed), but at warn
- /// severity so it does not page.
- InvalidIngestPayload,
- /// Everything else: reported through
- /// `observability::report_error_or_expected`.
- Unexpected,
-}
-
-/// What the caller sees instead of the usage-probe backoff marker.
-#[cfg(feature = "http-server")]
-pub(super) const USAGE_BACKOFF_CLIENT_MESSAGE: &str =
- "Usage temporarily unavailable — the last fetch failed and is backing off; \
- it will refresh shortly.";
-
-/// Classify a failed call's display message. `expected_user_state` is the
-/// flag from the controller's structured envelope, when it emitted one.
-///
-/// The order is significant: the first matching rule wins, exactly as the
-/// handler's `if`/`else` chain did before it was extracted.
-#[cfg(feature = "http-server")]
-pub(super) fn classify_failure(message: &str, expected_user_state: bool) -> FailureDisposition {
- use crate::core::observability;
-
- if expected_user_state {
- FailureDisposition::ExpectedUserState
- } else if is_wallet_not_configured_error(message) {
- FailureDisposition::WalletNotConfigured
- } else if crate::core::params::is_param_validation_error(message) {
- FailureDisposition::ParamValidation
- } else if is_session_expired_error(message) {
- FailureDisposition::SessionExpired
- } else if observability::is_suppressed_usage_probe_backoff(message) {
- FailureDisposition::UsageProbeBackoff
- } else if observability::is_transient_message_failure(message) {
- FailureDisposition::TransientDownstream
- } else if let Some(unknown_method) = crate::core::dispatch::unknown_method_name(message) {
- FailureDisposition::UnknownMethod {
- probe: crate::core::dispatch::is_known_probe_method(unknown_method),
- }
- } else if crate::memory::tree::tree::rpc::is_invalid_ingest_payload_message(message) {
- FailureDisposition::InvalidIngestPayload
- } else {
- FailureDisposition::Unexpected
- }
-}
-
-#[cfg(test)]
-#[path = "classify_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/core/jsonrpc/classify_tests.rs b/crates/openhuman-core/src/core/jsonrpc/classify_tests.rs
deleted file mode 100644
index 11e3710471..0000000000
--- a/crates/openhuman-core/src/core/jsonrpc/classify_tests.rs
+++ /dev/null
@@ -1,336 +0,0 @@
-#[cfg(feature = "http-server")]
-use super::{classify_failure, is_wallet_not_configured_error, FailureDisposition};
-use super::{is_session_expired_error, is_unconfirmed_unauthorized_error};
-
-#[test]
-fn is_session_expired_error_matches_backend_path_401() {
- // Issue #2286: only OpenHuman backend path 401s (HTTP-method prefix) should
- // match, not generic 401/Unauthorized strings.
- assert!(is_session_expired_error(
- "GET /teams failed (401 Unauthorized): {\"success\":false}"
- ));
- assert!(is_session_expired_error(
- "POST /auth/token failed (401 Unauthorized): session expired"
- ));
- assert!(is_session_expired_error(
- "DELETE /sessions/abc failed (401 Unauthorized): unauthorized"
- ));
-}
-
-#[test]
-fn is_session_expired_error_matches_flattened_backend_unauthorized() {
- // #3297: after #2781 the backend 401 is a typed `BackendApiError::Unauthorized`
- // that team/billing ops flatten via `api::flatten_authed_error`. The dispatcher
- // classifier MUST recognise that flattened string as session expiry, so the
- // 401 is suppressed from Sentry (TAURI-RUST-8WY on `/teams/me/usage`,
- // TAURI-RUST-8WZ on `/payments/stripe/currentPlan`) AND triggers the
- // `SessionExpired` publish. End-to-end: build the typed error → flatten → classify.
- let flat = crate::api::flatten_authed_error(anyhow::Error::new(
- crate::api::BackendApiError::Unauthorized {
- method: "GET".to_string(),
- path: "/teams/me/usage".to_string(),
- },
- ));
- assert!(
- is_session_expired_error(&flat),
- "flattened backend Unauthorized must classify as session expiry: {flat}"
- );
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_generic_401_unauthorized() {
- // Generic 401+unauthorized strings without HTTP-method prefix must NOT match.
- assert!(!is_session_expired_error(
- "backend returned 401 Unauthorized"
- ));
- assert!(!is_session_expired_error("401 UNAUTHORIZED"));
- assert!(!is_session_expired_error("got 401 and unauthorized body"));
-}
-
-#[test]
-fn unconfirmed_unauthorized_error_matches_generic_401_for_diagnostics_only() {
- // Generic 401+unauthorized text feeds the diagnostic-only branch — never
- // SessionExpired publication.
- assert!(is_unconfirmed_unauthorized_error(
- "backend returned 401 Unauthorized"
- ));
- assert!(is_unconfirmed_unauthorized_error("401 UNAUTHORIZED"));
- assert!(is_unconfirmed_unauthorized_error(
- "got 401 and unauthorized body"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_partial_auth_text() {
- // 401 alone is not sufficient — could be HTTP/3.01 nonsense or
- // unrelated text. We require the string "unauthorized" too, plus an
- // HTTP-method prefix for the 401 path.
- assert!(!is_session_expired_error("server returned 401"));
- assert!(!is_session_expired_error("unauthorized without code"));
-}
-
-#[test]
-fn is_session_expired_error_matches_openhuman_backend_path_401() {
- // OpenHuman backend calls via authed_json use the format:
- // "{METHOD} /path failed (401 Unauthorized): {body}"
- assert!(is_session_expired_error(
- "GET /teams failed (401 Unauthorized): {\"success\":false}"
- ));
- assert!(is_session_expired_error(
- "POST /auth/token failed (401 Unauthorized): session expired"
- ));
- assert!(is_session_expired_error(
- "GET /teams/me/usage failed (401 Unauthorized): unauthorized"
- ));
- assert!(is_session_expired_error(
- "PUT /profile failed (401 Unauthorized): token expired"
- ));
- assert!(is_session_expired_error(
- "PATCH /settings failed (401 Unauthorized): unauthorized"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_discord_api_error() {
- // Issue #2286: Discord bot token 401 must not clear the user session.
- assert!(!is_session_expired_error(
- "Discord API error: Discord list guilds failed (401): Unauthorized"
- ));
- assert!(!is_session_expired_error(
- "Discord API error: Discord get bot user failed (401): bad token"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_byo_key_provider_401() {
- // BYO-key provider 401 should not clear the user session.
- assert!(!is_session_expired_error(
- "OpenAI API error (401 Unauthorized): invalid api key"
- ));
- assert!(!is_session_expired_error(
- "Anthropic API error (401 Unauthorized): authentication error"
- ));
- assert!(!is_session_expired_error(
- "Composio v3 API error: HTTP 401: Unauthorized"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_backend_wrapped_composio_invalid_api_key() {
- // Issue #2537: the backend can return a 500 whose body wraps a Composio
- // upstream 401. That is a scoped integration/service failure, not proof
- // that the user's OpenHuman app session expired.
- let msg = r#"[composio] list_connections failed: Backend returned 500 Internal Server Error for GET https://api.tinyhumans.ai/agent-integrations/composio/connections: 401 {"error":{"message":"Invalid API key: ak_o1Og5*****","code":10401,"slug":"HTTP_Unauthorized","status":401}}"#;
-
- assert!(
- !is_session_expired_error(msg),
- "Composio upstream 401 wrapped by the backend must not publish SessionExpired"
- );
- assert!(
- is_unconfirmed_unauthorized_error(msg),
- "auth-looking upstream failures should still be logged diagnostically"
- );
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_invalid_token_case_insensitive() {
- // "invalid token" is no longer a session-expiry trigger (issue #2286):
- // it was too broad and caught Discord/OAuth provider token errors. It is
- // still surfaced via the diagnostic-only `is_unconfirmed_unauthorized_error`.
- assert!(!is_session_expired_error("Invalid Token"));
- assert!(!is_session_expired_error("got an invalid token here"));
- assert!(is_unconfirmed_unauthorized_error("Invalid Token"));
- assert!(is_unconfirmed_unauthorized_error(
- "got an invalid token here"
- ));
-}
-
-#[test]
-fn is_session_expired_error_matches_openhuman_session_expired_body() {
- // Even without an HTTP-method prefix, an explicit "Session expired" body
- // text triggers session expiry via the shared observability classifier.
- assert!(is_session_expired_error(
- r#"OpenHuman API error (401 Unauthorized): {"success":false,"error":"Session expired. Please log in again."}"#
- ));
-}
-
-#[test]
-fn is_session_expired_error_matches_session_expired_sentinel() {
- // The SESSION_EXPIRED sentinel is case-sensitive by design.
- assert!(is_session_expired_error("SESSION_EXPIRED: please re-auth"));
- assert!(!is_session_expired_error("session_expired lowercase"));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_unrelated_errors() {
- assert!(!is_session_expired_error("network timeout"));
- assert!(!is_session_expired_error("500 internal server error"));
- assert!(!is_session_expired_error(""));
-}
-
-#[test]
-fn is_session_expired_error_skips_discord_rewrap_for_2285() {
- // Cross-module regression guard for #2285: the Discord domain
- // controller intentionally formats its upstream-auth failures so
- // they do NOT match this dispatch-time classifier. If anyone
- // changes the wording on either side back into a string that
- // contains both "401" and "unauthorized", a connected-Discord
- // card click would once again log the user out of OpenHuman.
- //
- // We pin the exact substrings the Discord rewrap was designed
- // to avoid, plus the canonical post-rewrap message body, so
- // either-side drift fails loudly.
- let canonical_rewrap = "Discord API error: Discord list_guilds: bot token was rejected \
- (upstream HTTP four-oh-one). Open Connections → Channels → Discord \
- and rotate / reconnect the bot token.";
- assert!(
- !is_session_expired_error(canonical_rewrap),
- "Discord rewrap must NOT trip the session-expired classifier: {canonical_rewrap}"
- );
- // Defensive: also pin the 403 variant. Same rewrap path, same
- // requirement — neither '403' nor 'forbidden' is part of the
- // session classifier today, but locking the message in keeps a
- // future regression visible.
- let canonical_rewrap_403 =
- "Discord API error: Discord list_channels: bot token lacks required Discord permissions \
- (upstream HTTP four-oh-three). Open Connections → Channels → Discord \
- and rotate / reconnect the bot token.";
- assert!(!is_session_expired_error(canonical_rewrap_403));
-}
-
-#[test]
-fn is_session_expired_error_matches_missing_backend_session_token() {
- // Composio / web search / billing / team / webhooks / referral all surface
- // a "no backend session token" variant when the auth profile is gone. Each
- // of these should funnel into the auto-cleanup path instead of being
- // reported to Sentry as a fresh error on every 5 s poll.
- assert!(is_session_expired_error(
- "composio unavailable: no backend session token. Sign in first (auth_store_session)."
- ));
- assert!(is_session_expired_error(
- "no backend session token; run auth_store_session first"
- ));
- assert!(is_session_expired_error(
- "Web search unavailable: no backend session token. Sign in first so the server can proxy search."
- ));
- // Case-insensitive match — the helper lowercases first.
- assert!(is_session_expired_error("NO BACKEND SESSION TOKEN"));
-}
-
-#[test]
-fn is_session_expired_error_matches_session_jwt_required() {
- // Regression: Sentry issue 7472592145.
- // A prior 401 clears the stored JWT; the very next RPC call (e.g.
- // channels_telegram_login_start) finds no token and returns "session JWT
- // required; complete login first". This is the same auth-boundary condition
- // and must not be reported to Sentry.
- assert!(is_session_expired_error(
- "session JWT required; complete login first"
- ));
- assert!(is_session_expired_error(
- "session JWT required; complete login and store_session first"
- ));
- assert!(is_session_expired_error("session JWT required"));
- // Case-insensitive.
- assert!(is_session_expired_error("SESSION JWT REQUIRED"));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_wallet_not_configured_error_matches_wallet_constant() {
- // The classifier keys off the wallet layer's exact "not configured"
- // message so wallet-backed RPCs stay out of Sentry.
- assert!(is_wallet_not_configured_error(
- crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE
- ));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_wallet_not_configured_error_is_coupled_to_the_wallet_constant() {
- // Drift guard: if the wallet wording changes without updating the shared
- // constant the classifier matches, this fails — preventing the noise from
- // silently returning to Sentry. Mirrors the param-validation prefix locks.
- assert_eq!(
- crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE,
- "wallet is not configured; run wallet setup first"
- );
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_wallet_not_configured_error_does_not_match_other_errors() {
- // Other wallet/seed-derivation failures (decrypt, key derivation, locked
- // keychain) are real defects and must keep reaching Sentry.
- assert!(!is_wallet_not_configured_error(
- "wallet signer init: bad seed"
- ));
- assert!(!is_wallet_not_configured_error(
- "decrypt secret: kms timeout"
- ));
- assert!(!is_wallet_not_configured_error(""));
- // Substring-only must not qualify — exact equality is required.
- assert!(!is_wallet_not_configured_error(
- "rpc failed: wallet is not configured; run wallet setup first"
- ));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn classify_failure_expected_user_state_flag_wins() {
- // The envelope flag outranks every message-based rule, even a message
- // that would otherwise read as a session expiry.
- assert_eq!(
- classify_failure("Session expired", true),
- FailureDisposition::ExpectedUserState
- );
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn classify_failure_routes_each_boundary_class() {
- assert_eq!(
- classify_failure(crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE, false),
- FailureDisposition::WalletNotConfigured
- );
- assert_eq!(
- classify_failure(
- &crate::core::params::unknown_param_message("api_key", "config", "update_model_settings"),
- false
- ),
- FailureDisposition::ParamValidation
- );
- assert_eq!(
- classify_failure("GET /teams failed (401 Unauthorized): {}", false),
- FailureDisposition::SessionExpired
- );
- assert_eq!(
- classify_failure(
- &format!(
- "{}totally.made.up.method",
- crate::core::dispatch::UNKNOWN_METHOD_PREFIX
- ),
- false
- ),
- FailureDisposition::UnknownMethod { probe: false }
- );
- assert_eq!(
- classify_failure("config.update_model_settings: store write failed", false),
- FailureDisposition::Unexpected
- );
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn classify_failure_param_validation_outranks_session_expiry() {
- // A param description that happens to contain a session marker is still a
- // params mismatch: validation runs before the handler, so no backend call
- // could have expired anything.
- assert_eq!(
- classify_failure(
- &crate::core::params::missing_required_param_message("token", "Session expired token"),
- false
- ),
- FailureDisposition::ParamValidation
- );
-}
diff --git a/crates/openhuman-core/src/core/jsonrpc/invoke.rs b/crates/openhuman-core/src/core/jsonrpc/invoke.rs
deleted file mode 100644
index e537851bb8..0000000000
--- a/crates/openhuman-core/src/core/jsonrpc/invoke.rs
+++ /dev/null
@@ -1,132 +0,0 @@
-//! In-process JSON-RPC dispatch: the one entry point every transport calls.
-//!
-//! The HTTP `/rpc` handler, Socket.IO `rpc:request`, the CLI, the device
-//! tunnel and [`CoreRuntime::invoke`](crate::core::runtime::CoreRuntime::invoke)
-//! all resolve a method through [`invoke_method`]. It validates params against
-//! the controller registry, dispatches, and on a confirmed session expiry
-//! publishes the event that signs the user out.
-
-use serde_json::Value;
-
-use super::classify::{is_session_expired_error, is_unconfirmed_unauthorized_error};
-use crate::core::all;
-use crate::core::types::AppState;
-
-/// Invokes a JSON-RPC method by name.
-///
-/// This is a high-level wrapper around [`invoke_method_inner`] that adds
-/// automatic session management logic. If a call fails with a confirmed
-/// OpenHuman session-expired error, it publishes the event that clears a
-/// backend session. The offline local credential has no backend session to
-/// expire and receives a recoverable hosted-unavailable error instead.
-///
-/// # Arguments
-///
-/// * `state` - The application state.
-/// * `method` - The name of the method to invoke.
-/// * `params` - The JSON parameters for the method.
-pub async fn invoke_method(state: AppState, method: &str, params: Value) -> Result<Value, String> {
- let mut result = invoke_method_inner(state, method, params).await;
-
- // Session auto-cleanup: if the OpenHuman auth session is explicitly
- // expired, publish a `SessionExpired` event. The credentials subscriber
- // clears the stored token, flips the scheduler-gate signed-out override
- // so background workers stand down, and (eventually) pushes a sign-out to
- // the UI. Generic downstream/provider 401s must stay recoverable errors;
- // otherwise a scoped integration failure can log the user out.
- if let Err(ref msg) = result {
- let sanitized_reason = tinyinference_core::sanitize::sanitize_api_error(msg);
- if is_session_expired_error(msg) {
- // The subscriber ignores an offline local session, but Socket.IO
- // also hears this event and broadcasts sign-out independently.
- // Suppress it at the publisher for backend-only routes that the
- // local credential cannot use. This extra config read happens only
- // on a classified session-expiry error, never on the normal path.
- let local =
- crate::security::credentials::session_support::current_session_is_local().await;
- if should_publish_session_expired(msg, local) {
- log::warn!(
- "[jsonrpc] confirmed session expiry for method='{}' — publishing SessionExpired: {}",
- method,
- sanitized_reason
- );
- // `sanitize_api_error` scrubs pasted-through provider replies.
- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
- source: format!("jsonrpc.invoke_method:{method}"),
- reason: sanitized_reason,
- });
- } else {
- log::info!(
- "[jsonrpc] backend session unavailable for local offline credential method='{}' — leaving local auth intact",
- method
- );
- // The RPC error is also observed by the renderer's auth
- // classifier. Keep the background hosted probe recoverable
- // without asking it to infer the core's credential kind.
- result = Err(translate_local_session_error(msg, local)
- .expect("classified local session error"));
- }
- } else if is_unconfirmed_unauthorized_error(msg) {
- log::info!(
- "[jsonrpc] unconfirmed unauthorized error for method='{}' (not session expiry) — leaving session intact: {}",
- method,
- sanitized_reason
- );
- }
- }
-
- result
-}
-
-fn should_publish_session_expired(msg: &str, credential_is_local: bool) -> bool {
- is_session_expired_error(msg) && !credential_is_local
-}
-
-fn translate_local_session_error(msg: &str, credential_is_local: bool) -> Option<String> {
- (credential_is_local && is_session_expired_error(msg)).then(|| {
- format!(
- "{}Hosted account data is unavailable in local offline mode",
- crate::core::observability::BACKEND_UNAVAILABLE_PREFIX
- )
- })
-}
-
-/// Internal method invocation logic.
-///
-/// It first attempts to match the method name against the static controller
-/// registry (schemas). If a schema is found, it validates the input parameters
-/// before execution. If no schema matches, it falls back to the dynamic
-/// [`crate::core::dispatch::dispatch`] system.
-async fn invoke_method_inner(
- state: AppState,
- method: &str,
- params: Value,
-) -> Result<Value, String> {
- // Phase 1: Check static controller registry.
- if let Some(schema) = all::schema_for_rpc_method(method) {
- let params_obj = crate::core::params::params_to_object(params.clone())?;
- // Validate inputs against the schema before calling the handler.
- all::validate_params(&schema, &params_obj)?;
- if let Some(result) = all::try_invoke_registered_rpc(method, params_obj).await {
- return result;
- }
- log::debug!(
- "[jsonrpc] schema matched without registered handler; falling back method={}",
- method
- );
- }
-
- // Phase 2: Fall back to dynamic dispatch (internal core methods or legacy paths).
- crate::core::dispatch::dispatch(state, method, params).await
-}
-
-/// Returns the default application state.
-pub fn default_state() -> AppState {
- AppState {
- core_version: env!("CARGO_PKG_VERSION").to_string(),
- }
-}
-
-#[cfg(test)]
-#[path = "invoke_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/core/jsonrpc/invoke_tests.rs b/crates/openhuman-core/src/core/jsonrpc/invoke_tests.rs
deleted file mode 100644
index 21223ef65d..0000000000
--- a/crates/openhuman-core/src/core/jsonrpc/invoke_tests.rs
+++ /dev/null
@@ -1,271 +0,0 @@
-use serde_json::json;
-
-use super::super::classify::is_session_expired_error;
-use super::{
- default_state, invoke_method, should_publish_session_expired, translate_local_session_error,
-};
-
-#[tokio::test]
-async fn invoke_health_snapshot_via_registry() {
- let result = invoke_method(default_state(), "openhuman.health_snapshot", json!({}))
- .await
- .expect("health snapshot should succeed");
- assert!(result.get("result").is_some());
-}
-
-#[tokio::test]
-async fn invoke_encrypt_secret_missing_required_param_fails_validation() {
- let err = invoke_method(default_state(), "openhuman.encrypt_secret", json!({}))
- .await
- .expect_err("missing plaintext should fail");
- assert!(err.contains("missing required param 'plaintext'"));
-}
-
-#[tokio::test]
-async fn invoke_doctor_models_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.doctor_models",
- json!({ "invalid": true }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'invalid'"));
-}
-
-// Uses a `flows.*` method as its gated-family vehicle: without the `flows`
-// feature there is no flows controller in the registry and the `.expect()`
-// below would panic. The transport-layer gating it proves is orthogonal to the
-// compile-time gate (#4797).
-#[cfg(feature = "flows")]
-#[tokio::test]
-async fn gated_method_is_unknown_at_transport_even_with_malformed_params() {
- // #4808 review (CodeRabbit): prove the schema-gate fix at the JSON-RPC
- // TRANSPORT layer (`invoke_method`), not only via direct dispatch. Under a
- // harness() ambient context a gated method must return an unknown-method
- // error for BOTH well-formed and malformed params — never the controller's
- // param-validation error, which would leak that the hidden method exists.
- use crate::core::runtime::context::CoreContext;
- use crate::core::runtime::DomainSet;
-
- let gated_method = crate::core::all::all_registered_controllers()
- .into_iter()
- .find(|c| c.schema.namespace == "flows")
- .map(|c| c.rpc_method_name())
- .expect("a flows.* method exists in the full registry");
-
- for params in [json!({}), json!({ "obviously_not_a_real_param_xyz": true })] {
- let ctx = CoreContext::for_test(DomainSet::harness(), None, None);
- let err = CoreContext::scope(
- ctx,
- invoke_method(default_state(), &gated_method, params.clone()),
- )
- .await
- .expect_err("gated flows method must error under harness()");
- assert!(
- err.contains("unknown method"),
- "gated `{gated_method}` with params {params} must be unknown-method at transport, got: {err}"
- );
- assert!(
- !err.contains("param"),
- "gated `{gated_method}` must NOT leak a param-validation error (surface leak), got: {err}"
- );
- }
-}
-
-#[tokio::test]
-async fn invoke_config_get_runtime_flags_via_registry() {
- let result = invoke_method(
- default_state(),
- "openhuman.config_get_runtime_flags",
- json!({}),
- )
- .await
- .expect("runtime flags should succeed");
- assert!(result.get("result").is_some());
-}
-
-#[tokio::test]
-async fn invoke_auth_store_session_missing_token_fails_validation() {
- let err = invoke_method(default_state(), "openhuman.auth_store_session", json!({}))
- .await
- .expect_err("missing token should fail");
- assert!(err.contains("missing required param 'token'"));
-}
-
-#[tokio::test]
-async fn invoke_service_status_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.service_status",
- json!({ "x": 1 }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'x'"));
-}
-
-#[tokio::test]
-async fn invoke_memory_init_accepts_empty_params() {
- // jwt_token is optional (accepted for backward compat but ignored).
- // The call may still fail for workspace reasons in test, but must NOT
- // fail with a missing-param error for jwt_token.
- let result = invoke_method(default_state(), "openhuman.memory_init", json!({})).await;
- if let Err(ref e) = result {
- assert!(
- !e.contains("missing required param") || !e.contains("jwt_token"),
- "jwt_token should be optional, got: {e}"
- );
- }
-}
-
-#[tokio::test]
-async fn invoke_memory_list_namespaces_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.memory_list_namespaces",
- json!({ "extra": true }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("extra"));
-}
-
-#[tokio::test]
-async fn invoke_memory_query_namespace_missing_namespace_fails() {
- let err = invoke_method(
- default_state(),
- "openhuman.memory_query_namespace",
- json!({ "query": "who owns atlas" }),
- )
- .await
- .expect_err("missing namespace should fail");
- assert!(err.contains("namespace"));
-}
-
-#[tokio::test]
-async fn invoke_memory_recall_memories_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.memory_recall_memories",
- json!({ "namespace": "team", "extra": true }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("extra"));
-}
-
-#[tokio::test]
-async fn invoke_migrate_openclaw_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.migrate_openclaw",
- json!({ "x": 1 }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'x'"));
-}
-
-#[tokio::test]
-async fn invoke_migrate_hermes_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.migrate_hermes",
- json!({ "x": 1 }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'x'"));
-}
-
-#[test]
-fn local_offline_credential_does_not_publish_backend_session_expiry() {
- let local = crate::security::credentials::session_support::is_local_session_token(
- "header.payload.local",
- );
- let jwt = crate::security::credentials::session_support::is_local_session_token(
- "header.payload.signature",
- );
- for error in [
- "composio unavailable: no backend session token. Sign in first (auth_store_session).",
- "SESSION_EXPIRED: backend rejected session token on GET /teams/me/usage",
- ] {
- assert!(!should_publish_session_expired(error, local), "{error}");
- assert!(should_publish_session_expired(error, jwt), "{error}");
- let translated = translate_local_session_error(error, local).expect("local fallback");
- assert!(
- translated.starts_with(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX),
- "{translated}"
- );
- assert!(!is_session_expired_error(&translated));
- assert!(translate_local_session_error(error, jwt).is_none());
- }
-}
-
-#[tokio::test]
-async fn invoke_method_rejects_array_params_for_registered_method() {
- // Registered controllers expect named-argument style (JSON object).
- // Passing an array must fail with a clear "invalid params" error
- // instead of silently calling the handler with no args.
- let err = invoke_method(
- default_state(),
- "openhuman.health_snapshot",
- json!([1, 2, 3]),
- )
- .await
- .expect_err("array params should be rejected");
- assert!(err.contains("invalid params"));
- assert!(err.contains("array"));
-}
-
-#[tokio::test]
-async fn invoke_method_rejects_string_params_for_registered_method() {
- let err = invoke_method(default_state(), "openhuman.health_snapshot", json!("oops"))
- .await
- .expect_err("string params should be rejected");
- assert!(err.contains("invalid params"));
- assert!(err.contains("string"));
-}
-
-#[tokio::test]
-async fn invoke_method_accepts_null_params_for_registered_method() {
- // JSON-RPC 2.0 allows omitting params; null must be treated like {}.
- let result = invoke_method(default_state(), "openhuman.health_snapshot", json!(null)).await;
- // Call should succeed or fail for domain reasons — but must NOT
- // fail with the "invalid params" shape error.
- if let Err(e) = result {
- assert!(
- !e.contains("invalid params"),
- "null should be accepted as empty object, got: {e}"
- );
- }
-}
-
-#[tokio::test]
-async fn invoke_method_unknown_method_returns_unknown_error() {
- let err = invoke_method(default_state(), "openhuman.totally_made_up_xyz", json!({}))
- .await
- .expect_err("unknown methods must error");
- assert!(err.contains("unknown method"));
-}
-
-#[tokio::test]
-async fn invoke_method_core_ping_via_tier1() {
- // core.* methods aren't in the registry; they route through tier 1.
- let result = invoke_method(default_state(), "core.ping", json!({}))
- .await
- .expect("core.ping should succeed via tier 1");
- assert_eq!(result, json!({ "ok": true }));
-}
-
-#[tokio::test]
-async fn invoke_method_core_version_via_tier1_reflects_state() {
- let state = super::AppState {
- core_version: "0.0.1-abc".into(),
- };
- let result = invoke_method(state, "core.version", json!({}))
- .await
- .expect("core.version should succeed");
- assert_eq!(result, json!({ "version": "0.0.1-abc" }));
-}
diff --git a/crates/openhuman-core/src/core/jsonrpc/mod.rs b/crates/openhuman-core/src/core/jsonrpc/mod.rs
deleted file mode 100644
index f77aa02dbf..0000000000
--- a/crates/openhuman-core/src/core/jsonrpc/mod.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-//! JSON-RPC 2.0 for OpenHuman: in-process dispatch plus the HTTP transport.
-//!
-//! | Module | Owns |
-//! |---|---|
-//! | `invoke` | [`invoke_method`] — the dispatch every transport and the CLI call |
-//! | `classify` | session-expiry and Sentry-routing classification of failures |
-//! | `server` | the `run_server*` shims over `CoreBuilder` |
-//! | `http` | the axum router and handlers (`http-server` feature only) |
-//!
-//! The wire contract — envelopes, params shape, the browser-origin
-//! allowlist — lives in [`crate::rpc`] (`crates/openhuman-rpc`), shared with
-//! the app and TUI clients. Runtime boot (event-bus subscribers, ledgers, the
-//! approval gate) lives in [`crate::core::runtime`].
-
-mod classify;
-// The axum server surface — router, handlers, middleware, extractors, SSE — is
-// exclusive to the `http-server` feature (#5048). The dispatch surface and the
-// `run_server*` CoreBuilder shims stay compiled; a slim build drives dispatch
-// over the CLI / native path without binding a listener.
-#[cfg(feature = "http-server")]
-pub(crate) mod http;
-mod invoke;
-mod server;
-#[cfg(test)]
-mod testing;
-
-#[cfg(feature = "http-server")]
-pub use http::{build_core_http_router, rpc_handler};
-pub use invoke::{default_state, invoke_method};
-#[cfg(feature = "http-server")]
-pub(crate) use server::{core_host, core_port};
-pub use server::{
- run_server, run_server_embedded, run_server_embedded_with_ready, run_server_headless,
- EmbeddedReadySignal,
-};
diff --git a/crates/openhuman-core/src/core/dev_connect.rs b/crates/openhuman-rpc/src/server/dev_connect.rs
similarity index 100%
rename from crates/openhuman-core/src/core/dev_connect.rs
rename to crates/openhuman-rpc/src/server/dev_connect.rs
diff --git a/crates/openhuman-core/src/core/dev_connect_tests.rs b/crates/openhuman-rpc/src/server/dev_connect_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/core/dev_connect_tests.rs
rename to crates/openhuman-rpc/src/server/dev_connect_tests.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/cors.rs b/crates/openhuman-rpc/src/server/http/cors.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/cors.rs
rename to crates/openhuman-rpc/src/server/http/cors.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/cors_tests.rs b/crates/openhuman-rpc/src/server/http/cors_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/cors_tests.rs
rename to crates/openhuman-rpc/src/server/http/cors_tests.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/dictation.rs b/crates/openhuman-rpc/src/server/http/dictation.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/dictation.rs
rename to crates/openhuman-rpc/src/server/http/dictation.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/events.rs b/crates/openhuman-rpc/src/server/http/events.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/events.rs
rename to crates/openhuman-rpc/src/server/http/events.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/health.rs b/crates/openhuman-rpc/src/server/http/health.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/health.rs
rename to crates/openhuman-rpc/src/server/http/health.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/health_tests.rs b/crates/openhuman-rpc/src/server/http/health_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/health_tests.rs
rename to crates/openhuman-rpc/src/server/http/health_tests.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/mod.rs b/crates/openhuman-rpc/src/server/http/mod.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/mod.rs
rename to crates/openhuman-rpc/src/server/http/mod.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/oauth_mcp.rs b/crates/openhuman-rpc/src/server/http/oauth_mcp.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/oauth_mcp.rs
rename to crates/openhuman-rpc/src/server/http/oauth_mcp.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/pages.rs b/crates/openhuman-rpc/src/server/http/pages.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/pages.rs
rename to crates/openhuman-rpc/src/server/http/pages.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/pages_tests.rs b/crates/openhuman-rpc/src/server/http/pages_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/pages_tests.rs
rename to crates/openhuman-rpc/src/server/http/pages_tests.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/rpc_handler.rs b/crates/openhuman-rpc/src/server/http/rpc_handler.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/rpc_handler.rs
rename to crates/openhuman-rpc/src/server/http/rpc_handler.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/rpc_handler_tests.rs b/crates/openhuman-rpc/src/server/http/rpc_handler_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/http/rpc_handler_tests.rs
rename to crates/openhuman-rpc/src/server/http/rpc_handler_tests.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/server.rs b/crates/openhuman-rpc/src/server/shims.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/server.rs
rename to crates/openhuman-rpc/src/server/shims.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/server_tests.rs b/crates/openhuman-rpc/src/server/shims_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/server_tests.rs
rename to crates/openhuman-rpc/src/server/shims_tests.rs
diff --git a/crates/openhuman-core/src/core/socketio.rs b/crates/openhuman-rpc/src/server/socketio.rs
similarity index 75%
rename from crates/openhuman-core/src/core/socketio.rs
rename to crates/openhuman-rpc/src/server/socketio.rs
index 5deede350a..c8454e9a39 100644
--- a/crates/openhuman-core/src/core/socketio.rs
+++ b/crates/openhuman-rpc/src/server/socketio.rs
@@ -198,410 +198,6 @@ fn drop_unauthed(socket: &SocketRef, reason: &'static str) {
let _ = socket.clone().disconnect();
}
-/// Standard event payload for the web channel transport.
-///
-/// This structure defines the data sent to Socket.IO clients for various
-/// chat-related events, such as message delivery, tool execution, and errors.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct WebChannelEvent {
- /// The event name (e.g., `chat_message`, `tool_call`).
- pub event: String,
- /// Unique identifier for the Socket.IO client.
- pub client_id: String,
- /// Identifier for the specific chat thread.
- pub thread_id: String,
- /// Unique identifier for the individual request/turn.
- pub request_id: String,
- /// The full text of the assistant's response (sent on completion).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub full_response: Option<String>,
- /// A partial message segment or an error description.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub message: Option<String>,
- /// Type of error, if the event represents a failure.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error_type: Option<String>,
- /// Structured rate-limit / error metadata produced by
- /// `classify_inference_error` (issue #2606). All four fields are
- /// additive — older FE clients that only read `message`/`error_type`
- /// keep working; new clients can read these to render countdown,
- /// retry-button, and fallback-CTA UI without regexing the message.
- ///
- /// Where the limit originated:
- /// `"provider"` | `"openhuman_budget"` | `"agent_loop"`
- /// | `"openhuman_billing"` | `"transport"` | `"config"`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error_source: Option<String>,
- /// Whether the same prompt can be retried in this same thread.
- /// `false` for non-retryable business 429s, auth, model_unavailable,
- /// context_overflow, and billing exhaustion.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error_retryable: Option<bool>,
- /// Milliseconds to wait before retrying, as supplied by the upstream
- /// `Retry-After:` / `retry_after:` header. `None` when the upstream
- /// didn't supply one or the error class has no retry-after concept.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error_retry_after_ms: Option<u64>,
- /// Provider name extracted from `"<provider> API error (...)"`
- /// envelopes. `None` for non-provider errors (OpenHuman budget cap,
- /// agent loop) and for transport failures without a provider prefix.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error_provider: Option<String>,
- /// `Some(false)` once the reliable-provider chain has exhausted
- /// every configured `model_fallbacks` entry. `None` means "unknown
- /// — FE should not promise a fallback".
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error_fallback_available: Option<bool>,
- /// Name of the tool being called.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub tool_name: Option<String>,
- /// ID of the skill owning the tool.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub skill_id: Option<String>,
- /// Arguments passed to the tool.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub args: Option<serde_json::Value>,
- /// The raw output from the tool execution.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub output: Option<String>,
- /// Whether the tool execution or request was successful.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub success: Option<bool>,
- /// The current iteration/round number in a tool-call loop.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub round: Option<u32>,
- /// Emoji reaction the assistant wants to add to the user's message.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub reaction_emoji: Option<String>,
- /// 0-based index when a response is delivered as multiple segments.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub segment_index: Option<u32>,
- /// Total number of segments in a segmented delivery.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub segment_total: Option<u32>,
- /// Fine-grained streaming payload for `text_delta`, `thinking_delta`,
- /// and `tool_args_delta` events. Concatenating `delta`s in order
- /// yields the full text/thinking/arguments string.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub delta: Option<String>,
- /// Discriminator for the `delta` payload: `"text"`, `"thinking"`,
- /// or `"tool_args"`. Only set on streaming delta events.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub delta_kind: Option<String>,
- /// Provider-assigned tool call id that groups `tool_args_delta`
- /// chunks together and ties them to the eventual `tool_call` /
- /// `tool_result` events.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub tool_call_id: Option<String>,
- /// Structured, user-facing classification of a failed tool call (class,
- /// category, plain-language cause + next action). Present on `tool_result`
- /// events when the tool failed; the chat "View processing" timeline renders
- /// the "why / what to do next" pair. `None` on success.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub failure: Option<serde_json::Value>,
- /// Optional citations attached to `chat_done` payloads.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub citations: Option<serde_json::Value>,
- /// Sub-agent specific progress detail. Populated on
- /// `subagent_spawned`, `subagent_completed`, `subagent_iteration_start`,
- /// `subagent_tool_call`, and `subagent_tool_result` events so the UI
- /// can attribute child activity to the parent's live subagent row
- /// without overloading the flat top-level fields. `None` for any
- /// non-subagent event.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub subagent: Option<SubagentProgressDetail>,
- /// Server-computed human label for a tool call (on `tool_call` /
- /// `subagent_tool_call`), e.g. "Reading messages". The frontend renders
- /// this verbatim for dynamic Composio/MCP/integration tools it can't
- /// label itself, falling back to its own formatter when absent.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub tool_display_label: Option<String>,
- /// Server-computed contextual detail for a tool call (on `tool_call` /
- /// `subagent_tool_call`), e.g. "[email protected]" — the bracketed target
- /// shown after [`Self::tool_display_label`].
- #[serde(skip_serializing_if = "Option::is_none")]
- pub tool_display_detail: Option<String>,
- /// Milliseconds the tool call took to execute. Present on `tool_result` /
- /// `subagent_tool_result`, mirroring `AgentProgress::ToolCallCompleted`'s
- /// `elapsed_ms` / `SubagentToolCallCompleted`'s `elapsed_ms` — carried
- /// as a plain top-level field (in addition to `subagent.elapsed_ms` for
- /// the sub-agent case) so a frontend that only reads flat fields still
- /// gets real timing instead of guessing from wall-clock deltas.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub elapsed_ms: Option<u64>,
- /// Structured, tool-specific result payload copied from a tool's
- /// `ToolResult::metadata` when it is a JSON object carrying a `"kind"`
- /// discriminator, e.g.
- /// `{"kind":"web_search","query":"...","provider":"...","results":[...]}`.
- /// Present on `tool_result` / `subagent_tool_result` only for tools that
- /// populate metadata of that shape (currently the web-search tools); the
- /// model-facing `output` text is unaffected and stays byte-identical to
- /// what the model itself saw.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub structured: Option<serde_json::Value>,
- /// Holistic token/cost/context usage for a completed turn (parent +
- /// sub-agents), carried on `chat_done`. Lets the UI footer show session
- /// tokens, USD cost, and real context-window utilisation, with a
- /// per-sub-agent hover breakdown. `None` for every non-`chat_done` event and
- /// for synthetic done events that never ran a real turn.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub usage: Option<TurnUsagePayload>,
- /// Additive per-request monotonic ordering key stamped by the web-channel
- /// progress bridge on every event it emits (conversations-timeline-refactor,
- /// Phase 4). Together with the always-present `request_id`, the frontend
- /// dedups replayed vs live events by `(request_id, seq)` and orders them
- /// identically to the persisted turn-state snapshot. `None` on events not
- /// emitted through the stamping bridge and on older cores — older frontends
- /// simply ignore it.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub seq: Option<u64>,
- /// Epoch milliseconds this event was emitted at. Additive wall-clock
- /// stamp so a frontend can order/annotate events without deriving time
- /// from arrival order. `None` on emit sites not yet updated to stamp it.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub ts: Option<u64>,
- /// RFC3339 timestamp of when a pending approval / plan review expires,
- /// mirrored from `PendingApproval::expires_at` (`security::approval::types`).
- /// Present on `approval_request` / `plan_review_request` events.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub expires_at: Option<String>,
- /// The turn/request id a lifecycle event (approval, plan review, queue
- /// item, cancellation) correlates back to, when distinct from the
- /// top-level `request_id` (e.g. a decision event fired outside the
- /// original turn's request context).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub turn_request_id: Option<String>,
- /// Time-to-first-visible timing summary, carried on `chat_done`. See
- /// `web_chat::turn_timing`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub timing: Option<TurnTimingPayload>,
- /// Follow-up prompt suggestions offered to the user after a turn.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub suggestions: Option<Vec<ChatSuggestion>>,
- /// Guardrail verdict attached to a blocked/flagged turn.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub guardrail: Option<GuardrailPayload>,
- /// Run-queue item this event reports on (queued/delivered/removed).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub queue_item: Option<QueueItemPayload>,
- /// Session goal snapshot, carried on goal-lifecycle events. Left as a
- /// raw `Value` because the goal shape is owned by `tinyagents-graph`,
- /// not this crate.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub goal: Option<serde_json::Value>,
- /// Session todo-list snapshot, carried on todo-lifecycle events. Raw
- /// `Value` for the same reason as `goal`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub todos: Option<serde_json::Value>,
- /// Human-readable reason a turn/queue item was cancelled.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub cancel_reason: Option<String>,
- /// Id of the turn/request that superseded this one (e.g. a steer
- /// requeue), when applicable.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub superseded_by: Option<String>,
-}
-
-/// Time-to-first-visible timing summary for a completed turn. See
-/// `web_chat::turn_timing::TurnTiming`.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct TurnTimingPayload {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub first_token_ms: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub first_tool_ms: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub total_ms: Option<u64>,
- /// `usage.output_tokens / (total_ms / 1000)`, computed at delivery time
- /// when both a timing snapshot and the turn's output-token count are
- /// available. `None` when either input is missing (e.g. a budget-
- /// exhausted synthetic result, or a turn that produced no completion
- /// tokens). Added by C4 — not in the original wire-contract prep pass;
- /// see wire-contract.md "Added by C4".
- #[serde(skip_serializing_if = "Option::is_none")]
- pub tokens_per_second: Option<f64>,
-}
-
-/// One follow-up prompt suggestion offered after a turn.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct ChatSuggestion {
- pub prompt: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub label: Option<String>,
-}
-
-/// One guardrail rejection reason code + message.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct GuardrailReason {
- pub code: String,
- pub message: String,
-}
-
-/// Guardrail verdict attached to a blocked/flagged turn (`chat_error` with
-/// `error_type = "guardrail"`).
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct GuardrailPayload {
- pub verdict: String,
- pub score: f64,
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub reasons: Vec<GuardrailReason>,
-}
-
-/// A run-queue item summary (`queue_item_queued` / `queue_item_delivered` /
-/// `queue_item_removed`).
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct QueueItemPayload {
- pub id: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub lane: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub text_preview: Option<String>,
-}
-
-/// Token/cost/context totals for one completed turn, attached to `chat_done`.
-///
-/// Every numeric is a turn total (parent agent **plus** any sub-agents spawned
-/// during the turn); the `subagents` list breaks the same spend down per child
-/// for the UI hover. `context_window` is `0` when the core couldn't resolve the
-/// model's window (e.g. an unknown cloud model) — the UI falls back to a
-/// default in that case.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct TurnUsagePayload {
- pub input_tokens: u64,
- pub output_tokens: u64,
- pub cached_input_tokens: u64,
- pub cost_usd: f64,
- pub context_window: u64,
- /// Per-sub-agent spend, omitted from the wire when no sub-agents ran.
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub subagents: Vec<SubagentUsagePayload>,
-}
-
-/// One sub-agent's token/cost contribution within a turn (hover breakdown).
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct SubagentUsagePayload {
- pub task_id: String,
- pub agent_id: String,
- pub input_tokens: u64,
- pub output_tokens: u64,
- pub cost_usd: f64,
-}
-
-/// Per-event subagent progress detail attached to `WebChannelEvent`.
-///
-/// Carries the fields the parent thread's UI needs to render a live
-/// subagent block — child iteration counters, mode, child task/agent
-/// ids when distinct from the flat `tool_name` (which already carries
-/// the agent id on top-level subagent events but not on nested
-/// `subagent_tool_*` events where `tool_name` is the *child's* tool),
-/// and final-run statistics on `subagent_completed`.
-///
-/// Every field is optional and skipped from the JSON payload when
-/// absent — this keeps the wire format compact for non-subagent events
-/// (where the whole struct is `None`) and lets new fields land
-/// non-breakingly behind older clients.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct SubagentProgressDetail {
- /// Resolved spawn mode — `"typed"` or `"fork"`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub mode: Option<String>,
- /// Whether the spawn requested a dedicated worker thread.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub dedicated_thread: Option<bool>,
- /// Character length of the delegation prompt (on `subagent_spawned`).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub prompt_chars: Option<u64>,
- /// Sub-agent's child iteration counter (on `subagent_iteration_start`,
- /// `subagent_tool_call`, `subagent_tool_result`). 1-based.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub child_iteration: Option<u32>,
- /// Sub-agent's configured iteration cap.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub child_max_iterations: Option<u32>,
- /// Child agent id (on nested `subagent_tool_*` events where the flat
- /// `tool_name` is the child's tool, not the agent).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub agent_id: Option<String>,
- /// Spawn task id (on nested `subagent_tool_*` events).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub task_id: Option<String>,
- /// Elapsed wall-clock for the call/run in milliseconds.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub elapsed_ms: Option<u64>,
- /// This child's own token + cost spend (on `subagent_completed`), and
- /// **only when it is not already inside the parent turn's totals**.
- ///
- /// The consumer adds these unconditionally, so an emit site that leaves
- /// them absent contributes nothing — the safe direction. Populating them
- /// for a child whose usage DID reach `parent_subagent_usage` silently
- /// doubles the user's reported tokens and money, because
- /// `holistic_last_turn_usage` already folded both into `chat_done`. See
- /// `AgentProgress::SubagentCompleted::usage`.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub input_tokens: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub output_tokens: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub cached_input_tokens: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub cost_usd: Option<f64>,
- /// Total iterations the sub-agent used (on `subagent_completed`).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub iterations: Option<u32>,
- /// Character length of the sub-agent's final assistant text
- /// (on `subagent_completed`) or the tool result
- /// (on `subagent_tool_result`).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub output_chars: Option<u64>,
- /// Persistent worker sub-thread id backing the delegation (on
- /// `subagent_spawned`). The frontend stores it on the subagent row and
- /// uses it to reopen the full parent↔subagent conversation from memory.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub worker_thread_id: Option<String>,
- /// Human-readable display name from the agent registry (e.g.
- /// "Researcher", "Coding Agent"). The frontend uses this for
- /// consistent agent labels across timeline, sub-mascots, and drawer.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub display_name: Option<String>,
- /// Absolute path to the worker's isolated `git worktree` checkout
- /// (on `subagent_completed`, when the worker ran with
- /// `isolation = "worktree"`). Drives the inline worktree row's
- /// open/diff/remove actions. `None` for non-isolated workers (#3376).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub worktree_path: Option<String>,
- /// Files (relative to the worktree root) the worker changed, snapshot
- /// after the run (on `subagent_completed`). Absent for non-isolated
- /// workers and clean worktrees.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub changed_files: Option<Vec<String>>,
- /// Whether the worker's worktree had uncommitted changes after the run
- /// (on `subagent_completed`). A dirty worktree must not be auto-removed —
- /// the UI requires an explicit user decision. `None` for non-isolated.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub dirty_status: Option<bool>,
- /// The parent turn's tool-call id that this sub-agent spawn is
- /// attributed to (on `subagent_spawned`), mirroring
- /// `AgentProgress::SubagentSpawned::parent_call_id`. Lets the UI
- /// attach a spawn to the exact `spawn_subagent`/dispatch tool call
- /// that created it instead of inferring it from arrival order.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub parent_call_id: Option<String>,
- /// The sub-agent's final output text (on `subagent_completed`),
- /// mirrored alongside the top-level `output` field so a consumer that
- /// only reads `subagent.*` still gets the result text.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub output: Option<String>,
-}
-
#[cfg(feature = "http-server")]
#[derive(Debug, Deserialize)]
struct SocketRpcRequest {
diff --git a/crates/openhuman-core/src/core/socketio_tests.rs b/crates/openhuman-rpc/src/server/socketio_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/core/socketio_tests.rs
rename to crates/openhuman-rpc/src/server/socketio_tests.rs
diff --git a/crates/openhuman-core/src/core/jsonrpc/testing.rs b/crates/openhuman-rpc/src/server/testing.rs
similarity index 100%
rename from crates/openhuman-core/src/core/jsonrpc/testing.rs
rename to crates/openhuman-rpc/src/server/testing.rs