The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(core): add Outcome, Params, and StructuredError modules
Steven Enamakel3f142ef40cf7
diff --git a/crates/openhuman-core/src/core/outcome.rs b/crates/openhuman-core/src/core/outcome.rsnew file mode 100644index 0000000000..d7bc6be1c5--- /dev/null+++ b/crates/openhuman-core/src/core/outcome.rs@@ -0,0 +1,107 @@+//! The result every controller returns: [`Outcome`].+//!+//! Domain `ops.rs` operations return `Outcome<T>`; the registry and the CLI+//! turn it into JSON through [`Outcome::into_cli_compatible_json`], whose+//! shape is decided by [`apply_log_envelope`]. [`unwrap_rpc`] is the inverse+//! a caller uses to reach the value again.++use serde::Serialize;+use serde_json::json;++/// Unwrap the optional log and API envelopes used by OpenHuman RPC handlers.+pub fn unwrap_rpc(mut value: &serde_json::Value) -> &serde_json::Value {+ loop {+ if let Some(next) = value.get("result").or_else(|| value.get("data")) {+ value = next;+ } else {+ return value;+ }+ }+}++/// Successful RPC handler result: serialized JSON value plus optional log lines.+///+/// This type represents the result of a domain-specific RPC call, including+/// any log messages generated during execution.+#[derive(Debug)]+pub struct Outcome<T> {+ /// The actual data returned by the RPC call.+ pub value: T,+ /// A collection of log messages for auditing or debugging.+ pub logs: Vec<String>,+}++impl<T> Outcome<T> {+ /// Creates a new `Outcome` with a value and a list of logs.+ pub fn new(value: T, logs: Vec<String>) -> Self {+ Self { value, logs }+ }+}++impl<T: Serialize> Outcome<T> {+ /// Creates a new `Outcome` with a value and a single log message.+ pub fn single_log(value: T, log: impl Into<String>) -> Self {+ Self {+ value,+ logs: vec![log.into()],+ }+ }++ /// Converts the outcome into a CLI-compatible JSON value.+ ///+ /// The shape is decided by [`apply_log_envelope`], which is the single+ /// definition of the rule — see its docs for the rule itself and for why+ /// having one definition matters (#6080).+ ///+ /// # Errors+ ///+ /// Returns an error if serialization to JSON fails.+ pub fn into_cli_compatible_json(self) -> Result<serde_json::Value, String> {+ let Outcome { value, logs } = self;+ let value = serde_json::to_value(value).map_err(|e| e.to_string())?;+ Ok(apply_log_envelope(value, logs))+ }+}++/// Apply the log envelope to an already-serialized handler value.+///+/// **This is the one definition of the rule.** Both controller return paths go+/// through it:+///+/// * the registry path — every `Outcome::into_cli_compatible_json` call+/// across the domains, and+/// * the dynamic-dispatch path — `core::types::invocation_to_rpc_json`, used+/// by `core::dispatch` for internal / legacy methods.+///+/// # The rule, and the defect it currently encodes (#6080)+///+/// ```text+/// logs.is_empty() -> value (bare)+/// otherwise -> { "result": value, "logs": … } (wrapped)+/// ```+///+/// So a controller's **wire shape is decided by its log vector, not by its+/// schema**. Two methods in one namespace can answer differently, and a handler+/// that later gains a log line silently changes its own response shape with no+/// schema change — which is #6080. That defect is deliberately **preserved+/// byte-for-byte here**: normalising it is a wire change across every+/// controller and needs a maintainer's ruling, not a quiet fix inside a+/// refactor.+///+/// What this function buys today is that the rule exists **once**. Before it,+/// the same six lines were written independently in `Outcome` and in+/// `core::types::invocation_to_rpc_json`; a fix applied to one would have left+/// the other on the old behaviour, and nothing linked them. When the ruling+/// lands, this is the only body that has to change.+#[must_use]+pub fn apply_log_envelope(value: serde_json::Value, logs: Vec<String>) -> serde_json::Value {+ if logs.is_empty() {+ value+ } else {+ json!({ "result": value, "logs": logs })+ }+}++#[cfg(test)]+#[path = "outcome_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/outcome_tests.rs b/crates/openhuman-core/src/core/outcome_tests.rsnew file mode 100644index 0000000000..1dde380e86--- /dev/null+++ b/crates/openhuman-core/src/core/outcome_tests.rs@@ -0,0 +1,87 @@+use super::*;+use serde_json::json;++#[test]+fn new_preserves_value_and_logs() {+ let outcome: Outcome<i64> = Outcome::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 = Outcome::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 = Outcome::single_log(json!(1), "static str");+ let b = Outcome::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 = Outcome::<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 = Outcome::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 = Outcome::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: Outcome<Option<i32>> = Outcome::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 = Outcome::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 = Outcome::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-core/src/core/params.rs b/crates/openhuman-core/src/core/params.rsnew file mode 100644index 0000000000..45a4acc359--- /dev/null+++ b/crates/openhuman-core/src/core/params.rs@@ -0,0 +1,101 @@+//! JSON-RPC params shape and the transport-level validation messages.+//!+//! 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-core/src/core/params_tests.rs b/crates/openhuman-core/src/core/params_tests.rsnew file mode 100644index 0000000000..f46cf3bb42--- /dev/null+++ b/crates/openhuman-core/src/core/params_tests.rs@@ -0,0 +1,124 @@+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(+ ¶ms_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-core/src/core/structured_error.rs b/crates/openhuman-core/src/core/structured_error.rsnew file mode 100644index 0000000000..c14b70411d--- /dev/null+++ b/crates/openhuman-core/src/core/structured_error.rs@@ -0,0 +1,70 @@+//! 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-core/src/core/structured_error_tests.rs b/crates/openhuman-core/src/core/structured_error_tests.rsnew file mode 100644index 0000000000..944cb581c0--- /dev/null+++ b/crates/openhuman-core/src/core/structured_error_tests.rs@@ -0,0 +1,38 @@+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);+}