Skip to content

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

feat(rpc): add structured error handling and parameter validation

Steven Enamakel203462f9d2da
diff --git a/crates/openhuman-rpc/Cargo.toml b/crates/openhuman-rpc/Cargo.toml
index 6c4d5b0db6..19b6a9d9f9 100644
--- a/crates/openhuman-rpc/Cargo.toml
+++ b/crates/openhuman-rpc/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "openhuman-rpc"
-description = "Shared OpenHuman RPC contracts and HTTP client"
+description = "OpenHuman's JSON-RPC protocol: envelopes, the HTTP client, and the core's JSON-RPC server"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,12 +8,53 @@ repository.workspace = true
publish = false
[features]
-default = ["http-client"]
-http-client = ["dep:log", "dep:reqwest", "dep:url"]
+default = ["http-client", "server"]
+# Authenticated HTTP client for reaching a core's `/rpc` endpoint.
+http-client = ["dep:reqwest"]
+# The core's JSON-RPC server: HTTP router, Socket.IO, and the listener bind.
+# Turns on the core's `http-server` gate, which carries the domain-owned HTTP
+# handlers (the `/v1` inference router, the dictation WebSocket) the router
+# mounts.
+server = [
+ "openhuman-core/http-server",
+ "dep:axum",
+ "dep:socketioxide",
+ "dep:tokio",
+ "dep:tokio-stream",
+ "dep:tokio-util",
+ "dep:futures",
+ "dep:tracing",
+ "dep:chrono",
+ "dep:anyhow",
+ "dep:once_cell",
+ "dep:tinyinference-core",
+]
+# Forwarded so the server's Sentry-routing tests run against a core that
+# reports to Sentry.
+crash-reporting = ["openhuman-core/crash-reporting"]
[dependencies]
-log = { version = "0.4", optional = true }
-reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"], optional = true }
+openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false }
+log = "0.4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
-url = { version = "2", optional = true }
+url = "2"
+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"], optional = true }
+axum = { version = "0.8", default-features = false, features = ["http1", "json", "tokio", "query", "ws", "macros"], optional = true }
+socketioxide = { version = "0.15", features = ["extensions"], optional = true }
+tokio = { version = "1", features = ["full"], optional = true }
+tokio-stream = { version = "0.1.18", default-features = false, features = ["sync"], optional = true }
+tokio-util = { version = "0.7", features = ["rt", "io"], optional = true }
+futures = { version = "0.3", optional = true }
+tracing = { version = "0.1", default-features = false, optional = true }
+chrono = { version = "0.4", features = ["serde"], optional = true }
+anyhow = { version = "1.0", optional = true }
+once_cell = { version = "1.19", optional = true }
+tinyinference-core = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-core", optional = true }
+
+[dev-dependencies]
+sentry = { version = "0.47.0", default-features = false, features = ["test"] }
+tempfile = "3"
+tokio = { version = "1", features = ["full", "test-util"] }
+tower = { version = "0.5", default-features = false }
+tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "ansi", "env-filter"] }
diff --git a/crates/openhuman-rpc/src/lib_tests.rs b/crates/openhuman-rpc/src/lib_tests.rs
deleted file mode 100644
index e1037cf3e2..0000000000
--- a/crates/openhuman-rpc/src/lib_tests.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn new_preserves_value_and_logs() {
- let outcome: RpcOutcome<i64> = RpcOutcome::new(7, vec!["a".into(), "b".into()]);
- assert_eq!(outcome.value, 7);
- assert_eq!(outcome.logs, vec!["a".to_string(), "b".to_string()]);
-}
-
-#[test]
-fn single_log_stores_exactly_one_log() {
- let outcome = RpcOutcome::single_log(json!({"ok": true}), "hello");
- assert_eq!(outcome.logs.len(), 1);
- assert_eq!(outcome.logs[0], "hello");
- assert_eq!(outcome.value, json!({"ok": true}));
-}
-
-#[test]
-fn single_log_accepts_string_and_str_via_into() {
- let a = RpcOutcome::single_log(json!(1), "static str");
- let b = RpcOutcome::single_log(json!(1), String::from("owned string"));
- assert_eq!(a.logs[0], "static str");
- assert_eq!(b.logs[0], "owned string");
-}
-
-#[test]
-fn into_cli_compatible_json_no_logs_returns_bare_value() {
- let outcome = RpcOutcome::<serde_json::Value>::new(json!({"x": 1}), vec![]);
- let out = outcome.into_cli_compatible_json().unwrap();
- assert_eq!(out, json!({"x": 1}));
- assert!(out.get("logs").is_none());
-}
-
-#[test]
-fn into_cli_compatible_json_with_logs_wraps_in_envelope() {
- let outcome = RpcOutcome::single_log(json!(42), "did something");
- let out = outcome.into_cli_compatible_json().unwrap();
- assert_eq!(out["result"], json!(42));
- assert_eq!(out["logs"], json!(["did something"]));
- // And only those two keys exist.
- assert_eq!(out.as_object().unwrap().len(), 2);
-}
-
-#[test]
-fn into_cli_compatible_json_serializes_typed_value() {
- #[derive(serde::Serialize)]
- struct Payload<'a> {
- name: &'a str,
- count: u32,
- }
- let outcome = RpcOutcome::new(
- Payload {
- name: "atlas",
- count: 3,
- },
- vec![],
- );
- let out = outcome.into_cli_compatible_json().unwrap();
- assert_eq!(out, json!({"name": "atlas", "count": 3}));
-}
-
-#[test]
-fn into_cli_compatible_json_treats_null_value_as_bare_when_no_logs() {
- let outcome: RpcOutcome<Option<i32>> = RpcOutcome::new(None, vec![]);
- let out = outcome.into_cli_compatible_json().unwrap();
- assert!(out.is_null());
-}
-
-#[test]
-fn into_cli_compatible_json_preserves_log_order() {
- let outcome = RpcOutcome::new(
- json!({"ok": true}),
- vec!["first".into(), "second".into(), "third".into()],
- );
- let out = outcome.into_cli_compatible_json().unwrap();
- assert_eq!(out["logs"], json!(["first", "second", "third"]));
-}
-
-#[test]
-fn into_cli_compatible_json_empty_string_logs_still_envelope() {
- // An empty log string is still a log — envelope shape must kick in.
- let outcome = RpcOutcome::new(json!("x"), vec!["".into()]);
- let out = outcome.into_cli_compatible_json().unwrap();
- assert!(out.get("result").is_some());
- assert_eq!(out["logs"], json!([""]));
-}
diff --git a/crates/openhuman-rpc/src/params.rs b/crates/openhuman-rpc/src/params.rs
deleted file mode 100644
index 97c4bd4a2e..0000000000
--- a/crates/openhuman-rpc/src/params.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! JSON-RPC params shape and the transport-level validation messages.
-//!
-//! OpenHuman controllers take named arguments, so `params` must be an object
-//! (or absent). The strings emitted here, and by the controller registry's
-//! schema check through [`unknown_param_message`] and
-//! [`missing_required_param_message`], are what [`is_param_validation_error`]
-//! recognises. The emitters and the matcher live together so a wording change
-//! cannot break one side silently.
-
-use serde_json::{Map, Value};
-
-/// Prefix of the error for a param the method's schema does not declare.
-const UNKNOWN_PARAM_PREFIX: &str = "unknown param '";
-/// Prefix of the error for a required param the caller omitted.
-const MISSING_REQUIRED_PARAM_PREFIX: &str = "missing required param '";
-/// Prefix of the error for a `params` member that is not an object or null.
-const INVALID_PARAMS_PREFIX: &str = "invalid params: ";
-
-/// Converts JSON parameters into a map, ensuring they are in object format.
-///
-/// JSON-RPC allows parameters to be an Object, an Array, or Null. This implementation
-/// primarily supports Object parameters for named-argument style calls.
-pub fn params_to_object(params: Value) -> Result<Map<String, Value>, String> {
- match params {
- Value::Object(map) => Ok(map),
- Value::Null => Ok(Map::new()),
- other => Err(format!(
- "{INVALID_PARAMS_PREFIX}expected object or null, got {}",
- json_type_name(&other)
- )),
- }
-}
-
-/// Returns a human-readable string representation of a JSON value's type.
-#[must_use]
-pub fn json_type_name(value: &Value) -> &'static str {
- match value {
- Value::Null => "null",
- Value::Bool(_) => "bool",
- Value::Number(_) => "number",
- Value::String(_) => "string",
- Value::Array(_) => "array",
- Value::Object(_) => "object",
- }
-}
-
-/// Parses a JSON string into a `Value`.
-pub fn parse_json_params(raw: &str) -> Result<Value, String> {
- serde_json::from_str(raw).map_err(|e| format!("invalid JSON params: {e}"))
-}
-
-/// The error for a param `key` that `namespace.function`'s schema does not declare.
-#[must_use]
-pub fn unknown_param_message(key: &str, namespace: &str, function: &str) -> String {
- format!("{UNKNOWN_PARAM_PREFIX}{key}' for {namespace}.{function}")
-}
-
-/// The error for a required param `key` the caller omitted; `comment` is the
-/// field's schema description.
-#[must_use]
-pub fn missing_required_param_message(key: &str, comment: &str) -> String {
- format!("{MISSING_REQUIRED_PARAM_PREFIX}{key}': {comment}")
-}
-
-/// Returns `true` when the error message comes from JSON-RPC params validation
-/// rather than the underlying handler.
-///
-/// Three shapes, all emitted before the handler ever runs:
-/// * `"unknown param '<key>' for <ns>.<fn>"` — [`unknown_param_message`] (extra field)
-/// * `"missing required param '<key>': <comment>"` — [`missing_required_param_message`] (omitted required field)
-/// * `"invalid params: expected object or null, got <type>"` — [`params_to_object`] (wrong params shape)
-///
-/// These only fire when caller and server schemas drift at the transport layer
-/// — either a frontend on a different release than the running core, or a buggy
-/// external client. Reporting them to Sentry produces unactionable noise (we
-/// cannot patch an already-shipped install, and the message itself already
-/// names the bad field).
-///
-/// Note: domain-level validation errors (e.g. type/format checks emitted *inside*
-/// a controller's `rpc.rs` handler such as `"param 'x' must be a UUID"`) are
-/// intentionally *not* matched here — only the three shapes emitted by the
-/// transport-layer validators before the handler runs. Longer-term a typed
-/// `RpcError::ParamValidation` variant would remove the string-matching
-/// brittleness.
-///
-/// `starts_with` (not `.contains()`) is deliberate: validator errors are always
-/// emitted as the full message body, so an anchored match avoids false positives
-/// from upstream handler text that happens to mention `"unknown param"`. The
-/// core's session-expired predicate uses `.contains()` because session-expired
-/// markers can appear mid-message — flip these to match and the test
-/// `is_param_validation_error_does_not_match_unrelated_errors` will break.
-#[must_use]
-pub fn is_param_validation_error(msg: &str) -> bool {
- msg.starts_with(UNKNOWN_PARAM_PREFIX)
- || msg.starts_with(MISSING_REQUIRED_PARAM_PREFIX)
- || msg.starts_with(INVALID_PARAMS_PREFIX)
-}
-
-#[cfg(test)]
-#[path = "params_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-rpc/src/params_tests.rs b/crates/openhuman-rpc/src/params_tests.rs
deleted file mode 100644
index f46cf3bb42..0000000000
--- a/crates/openhuman-rpc/src/params_tests.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn params_to_object_accepts_object() {
- let map = params_to_object(json!({"a": 1, "b": "x"})).unwrap();
- assert_eq!(map.len(), 2);
- assert_eq!(map.get("a"), Some(&json!(1)));
-}
-
-#[test]
-fn params_to_object_accepts_null_as_empty_map() {
- let map = params_to_object(json!(null)).unwrap();
- assert!(map.is_empty());
-}
-
-#[test]
-fn params_to_object_rejects_array() {
- let err = params_to_object(json!([1, 2, 3])).unwrap_err();
- assert!(err.contains("invalid params"));
- assert!(err.contains("array"));
-}
-
-#[test]
-fn params_to_object_rejects_scalars() {
- assert!(params_to_object(json!(42)).unwrap_err().contains("number"));
- assert!(params_to_object(json!("hi"))
- .unwrap_err()
- .contains("string"));
- assert!(params_to_object(json!(true)).unwrap_err().contains("bool"));
-}
-
-#[test]
-fn json_type_name_labels_every_json_variant() {
- assert_eq!(json_type_name(&json!(null)), "null");
- assert_eq!(json_type_name(&json!(true)), "bool");
- assert_eq!(json_type_name(&json!(3)), "number");
- assert_eq!(json_type_name(&json!("s")), "string");
- assert_eq!(json_type_name(&json!([])), "array");
- assert_eq!(json_type_name(&json!({})), "object");
-}
-
-#[test]
-fn parse_json_params_roundtrips_object() {
- let v = parse_json_params(r#"{"k":1}"#).unwrap();
- assert_eq!(v, json!({"k": 1}));
-}
-
-#[test]
-fn parse_json_params_reports_error_message() {
- let err = parse_json_params("{not json").unwrap_err();
- assert!(err.contains("invalid JSON params"));
-}
-
-#[test]
-fn validation_messages_keep_their_wire_wording() {
- assert_eq!(
- unknown_param_message("api_key", "config", "update_model_settings"),
- "unknown param 'api_key' for config.update_model_settings"
- );
- assert_eq!(
- missing_required_param_message("session_id", "active session identifier"),
- "missing required param 'session_id': active session identifier"
- );
- assert_eq!(
- params_to_object(json!([])).unwrap_err(),
- "invalid params: expected object or null, got array"
- );
-}
-
-#[test]
-fn is_param_validation_error_matches_every_emitted_shape() {
- // Driven from the emitters rather than literals, so the matcher and the
- // messages cannot drift apart.
- assert!(is_param_validation_error(&unknown_param_message(
- "x", "ns", "fn"
- )));
- assert!(is_param_validation_error(&missing_required_param_message(
- "x", "comment"
- )));
- assert!(is_param_validation_error(
- &params_to_object(json!("s")).unwrap_err()
- ));
-}
-
-#[test]
-fn is_param_validation_error_matches_the_three_validator_shapes() {
- // Regression guard for OPENHUMAN-TAURI-20: pre-#1467 cores rejected
- // `api_key` because it wasn't in the schema yet. The error string
- // must keep matching here so it gets logged at info level and never
- // reaches Sentry as an unactionable client/server skew event.
- assert!(is_param_validation_error(
- "unknown param 'api_key' for config.update_model_settings"
- ));
- // `all::validate_params` — missing required field.
- assert!(is_param_validation_error(
- "missing required param 'session_id': active session identifier"
- ));
- // `params_to_object` — params field is the wrong JSON shape.
- assert!(is_param_validation_error(
- "invalid params: expected object or null, got array"
- ));
-}
-
-#[test]
-fn is_param_validation_error_does_not_match_unrelated_errors() {
- // Handler-side / network / auth failures must still be reported.
- assert!(!is_param_validation_error(
- "backend returned 401 Unauthorized"
- ));
- assert!(!is_param_validation_error("network timeout"));
- assert!(!is_param_validation_error(
- "config.update_model_settings: store write failed"
- ));
- // Empty and substring-only matches don't qualify either.
- assert!(!is_param_validation_error(""));
- assert!(!is_param_validation_error(
- "rpc failed: unknown param 'x' for ns.fn"
- ));
- // The JSON-string parse error is a CLI input error, not a params-shape one.
- assert!(!is_param_validation_error(
- &parse_json_params("{").unwrap_err()
- ));
-}
diff --git a/crates/openhuman-rpc/src/structured_error.rs b/crates/openhuman-rpc/src/structured_error.rs
deleted file mode 100644
index c14b70411d..0000000000
--- a/crates/openhuman-rpc/src/structured_error.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-//! Generic structured error envelope for the JSON-RPC controller boundary.
-//!
-//! Domains expose typed errors (e.g. `ThreadsError::NotFound`) and convert
-//! them — at their own boundary — into [`StructuredRpcError`]s. The envelope
-//! is then encoded as a sentinel-prefixed string so it can travel through
-//! the existing `Result<Value, String>` channel that controller handlers
-//! already use, without changing every handler signature.
-//!
-//! The JSON-RPC transport layer (`crates/openhuman-core/src/core/jsonrpc/http/rpc_handler.rs`) decodes the envelope
-//! transparently — it has zero knowledge of which domain produced the error,
-//! and never branches on the RPC method name. New domains that want
-//! structured RPC errors just emit a [`StructuredRpcError`] at their
-//! controller boundary; the transport handles the rest.
-//!
-//! Wire shape is unchanged: the human-readable `message` populates
-//! `RpcError.message` and the typed `data` populates `RpcError.data`. The
-//! `expected_user_state` flag is consumed by the boundary itself to decide
-//! whether to forward the error to Sentry; it does not appear on the wire.
-
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-
-/// Sentinel prefix that marks a [`StructuredRpcError`] encoded as a `String`.
-///
-/// The prefix is intentionally noisy and unlikely to collide with a real
-/// human-readable error message. If a controller error string starts with
-/// this prefix, the boundary decodes the rest as JSON.
-pub const STRUCTURED_RPC_ERROR_SENTINEL: &str = "__OPENHUMAN_STRUCTURED_RPC_ERROR_V1__:";
-
-/// Generic structured error emitted by a controller / domain boundary.
-///
-/// The transport layer decodes this without inspecting the RPC method name
-/// or the message contents, so new domains can adopt it without touching
-/// `crates/openhuman-core/src/core/jsonrpc/http/rpc_handler.rs`.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct StructuredRpcError {
- /// Human-readable error text for the JSON-RPC `error.message` field.
- pub message: String,
- /// Typed payload for the JSON-RPC `error.data` field. Must include a
- /// stable `kind` discriminator so frontends can branch on it.
- pub data: Option<Value>,
- /// When `true`, the boundary skips Sentry reporting — this is an
- /// expected user-visible state (stale thread, missing resource, etc.)
- /// not an internal failure.
- #[serde(default)]
- pub expected_user_state: bool,
-}
-
-impl StructuredRpcError {
- /// Encode into a sentinel-prefixed string suitable for the controller
- /// `Result<_, String>` error channel.
- pub fn encode(&self) -> String {
- // serde_json::to_string on a struct of String/Option<Value>/bool
- // cannot fail in practice, so unwrap is acceptable.
- let json = serde_json::to_string(self)
- .expect("StructuredRpcError serialization cannot fail: struct contains only String, Option<Value>, and bool");
- format!("{STRUCTURED_RPC_ERROR_SENTINEL}{json}")
- }
-
- /// Decode a controller error string if it carries the sentinel prefix.
- /// Returns `None` for plain error strings.
- pub fn decode(raw: &str) -> Option<Self> {
- let body = raw.strip_prefix(STRUCTURED_RPC_ERROR_SENTINEL)?;
- serde_json::from_str(body).ok()
- }
-}
-
-#[cfg(test)]
-#[path = "structured_error_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-rpc/src/structured_error_tests.rs b/crates/openhuman-rpc/src/structured_error_tests.rs
deleted file mode 100644
index 944cb581c0..0000000000
--- a/crates/openhuman-rpc/src/structured_error_tests.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn encode_then_decode_round_trips() {
- let original = StructuredRpcError {
- message: "thread thread-123 not found".to_string(),
- data: Some(json!({ "kind": "ThreadNotFound", "thread_id": "thread-123" })),
- expected_user_state: true,
- };
- let encoded = original.encode();
- assert!(
- encoded.starts_with(STRUCTURED_RPC_ERROR_SENTINEL),
- "encoded string must carry the sentinel prefix"
- );
- let decoded = StructuredRpcError::decode(&encoded).expect("decoded");
- assert_eq!(decoded, original);
-}
-
-#[test]
-fn decode_returns_none_for_plain_strings() {
- assert!(StructuredRpcError::decode("plain error").is_none());
- assert!(StructuredRpcError::decode("").is_none());
- assert!(StructuredRpcError::decode("__OPENHUMAN_STRUCTURED_RPC_ERROR_V1__").is_none());
-}
-
-#[test]
-fn decode_returns_none_for_corrupt_envelope() {
- let bad = format!("{STRUCTURED_RPC_ERROR_SENTINEL}not-json");
- assert!(StructuredRpcError::decode(&bad).is_none());
-}
-
-#[test]
-fn expected_user_state_defaults_to_false_when_absent() {
- let raw = format!("{STRUCTURED_RPC_ERROR_SENTINEL}{{\"message\":\"x\",\"data\":null}}");
- let decoded = StructuredRpcError::decode(&raw).expect("decoded");
- assert!(!decoded.expected_user_state);
-}