Skip to content

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

feat(core): add runtime context and socketio support

Steven Enamakelde3e88d96199
diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rs
index e481f36557..34b520051d 100644
--- a/crates/openhuman-core/src/core/all.rs
+++ b/crates/openhuman-core/src/core/all.rs
@@ -1489,18 +1489,19 @@ pub fn validate_params(
) -> Result<(), String> {
for input in &schema.inputs {
if input.required && !params.contains_key(input.name) {
- return Err(format!(
- "missing required param '{}': {}",
- input.name, input.comment
+ return Err(crate::rpc::missing_required_param_message(
+ input.name,
+ input.comment,
));
}
}
for key in params.keys() {
if !schema.inputs.iter().any(|f| f.name == key) {
- return Err(format!(
- "unknown param '{}' for {}.{}",
- key, schema.namespace, schema.function
+ return Err(crate::rpc::unknown_param_message(
+ key,
+ schema.namespace,
+ schema.function,
));
}
}
@@ -1514,7 +1515,7 @@ pub fn validate_params(
check_type(value, &input.ty).map_err(|mismatch| {
let (expected, got) = match mismatch {
TypeMismatch::Kind(expected) => {
- (expected.to_string(), json_type_name(value).to_string())
+ (expected.to_string(), crate::rpc::json_type_name(value).to_string())
}
TypeMismatch::OutOfRange { min, max, got } => {
log::debug!(
@@ -1553,19 +1554,6 @@ enum TypeMismatch {
OutOfRange { min: u64, max: u64, got: u64 },
}
-/// A short, human-readable name for the JSON kind of `value`, used in
-/// `validate_params` type-mismatch errors.
-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",
- }
-}
-
/// Validate a JSON `value` against a declared [`TypeSchema`].
///
/// Returns `Ok(())` on a match, or a [`TypeMismatch`] describing what was
diff --git a/crates/openhuman-core/src/core/all_tests.rs b/crates/openhuman-core/src/core/all_tests.rs
index b6186a483f..757e1e747c 100644
--- a/crates/openhuman-core/src/core/all_tests.rs
+++ b/crates/openhuman-core/src/core/all_tests.rs
@@ -1576,7 +1576,7 @@ fn every_domain_group_is_accounted_for_in_store_init_plan() {
/// subscribers or is declared subscriber-less.
#[test]
fn every_domain_group_is_accounted_for_in_subscriber_plan() {
- use crate::core::jsonrpc::DomainSubscriberPlan;
+ use crate::core::runtime::subscribers::DomainSubscriberPlan;
const REGISTERS: &[DomainGroup] = &[
DomainGroup::Platform,
@@ -2255,7 +2255,7 @@ async fn rpc_method_from_parts_stays_unfiltered_by_capability() {
// WIRING is right, using the tree family as the named vehicle. They target
// `try_invoke_registered_rpc`, `schema_for_rpc_method` and
// `all_controller_schemas` — the same three functions the HTTP layer calls
-// (`core::jsonrpc::invoke_method_inner` resolves the schema then dispatches;
+// (`core::jsonrpc::invoke::invoke_method_inner` resolves the schema then dispatches;
// `/schema` renders `all_http_method_schemas()`, which extends from
// `all_controller_schemas()`). Asserting on them IS asserting on the wire
// surface; there is no more faithful vehicle available at this level, and an
diff --git a/crates/openhuman-core/src/core/cli.rs b/crates/openhuman-core/src/core/cli.rs
index f35f43041f..413635beb4 100644
--- a/crates/openhuman-core/src/core/cli.rs
+++ b/crates/openhuman-core/src/core/cli.rs
@@ -9,7 +9,8 @@ use serde_json::{Map, Value};
use std::collections::BTreeMap;
use crate::core::all;
-use crate::core::jsonrpc::{default_state, invoke_method, parse_json_params};
+use crate::core::jsonrpc::{default_state, invoke_method};
+use crate::rpc::parse_json_params;
use crate::core::logging::CliLogDefault;
use crate::core::{ControllerSchema, TypeSchema};
diff --git a/crates/openhuman-core/src/core/jsonrpc/http/rpc_handler_tests.rs b/crates/openhuman-core/src/core/jsonrpc/http/rpc_handler_tests.rs
index c85d45288b..885d4fa126 100644
--- a/crates/openhuman-core/src/core/jsonrpc/http/rpc_handler_tests.rs
+++ b/crates/openhuman-core/src/core/jsonrpc/http/rpc_handler_tests.rs
@@ -23,7 +23,7 @@ async fn structured_rpc_error_envelope_passes_through_generic_dispatch() {
workspace.path().as_os_str().to_os_string(),
)]);
- let stale_thread_request = crate::core::types::RpcRequest {
+ let stale_thread_request = crate::rpc::RpcRequest {
jsonrpc: "2.0".to_string(),
id: json!(7),
method: "openhuman.threads_generate_title".to_string(),
@@ -92,7 +92,7 @@ async fn thread_not_found_rpc_error_does_not_report_to_sentry() {
);
let _subscriber_guard = tracing::subscriber::set_default(subscriber);
- let stale_thread_request = crate::core::types::RpcRequest {
+ let stale_thread_request = crate::rpc::RpcRequest {
jsonrpc: "2.0".to_string(),
id: json!(1),
method: "openhuman.threads_message_append".to_string(),
@@ -119,7 +119,7 @@ async fn thread_not_found_rpc_error_does_not_report_to_sentry() {
"ThreadNotFound should not reach Sentry"
);
- let unrelated_error_request = crate::core::types::RpcRequest {
+ let unrelated_error_request = crate::rpc::RpcRequest {
jsonrpc: "2.0".to_string(),
id: json!(2),
method: "core.not_a_real_method".to_string(),
@@ -210,7 +210,7 @@ async fn unknown_method_severity_split_by_probe_allow_list() {
let _subscriber_guard = tracing::subscriber::set_default(subscriber);
// (1) Allow-listed probe → debug-only, never reaches Sentry.
- let probe_request = crate::core::types::RpcRequest {
+ let probe_request = crate::rpc::RpcRequest {
jsonrpc: "2.0".to_string(),
id: json!(1),
method: "rpc.discover".to_string(),
@@ -234,7 +234,7 @@ async fn unknown_method_severity_split_by_probe_allow_list() {
);
// (2) Genuinely-unknown method → still captured, but at warn for triage.
- let unknown_request = crate::core::types::RpcRequest {
+ let unknown_request = crate::rpc::RpcRequest {
jsonrpc: "2.0".to_string(),
id: json!(2),
method: "totally.made.up.method".to_string(),
@@ -321,7 +321,7 @@ async fn invalid_ingest_payload_is_captured_at_warn_not_error() {
// `platform` is genuinely required by `ChatBatch` (unlike `timestamp`,
// which now defaults — see `chat_payload_without_timestamp_is_accepted`),
// so this reaches the invalid-payload branch rather than succeeding.
- let request = crate::core::types::RpcRequest {
+ let request = crate::rpc::RpcRequest {
jsonrpc: "2.0".to_string(),
id: json!(1),
method: "openhuman.memory_tree_ingest".to_string(),
diff --git a/crates/openhuman-core/src/core/jsonrpc/mod.rs b/crates/openhuman-core/src/core/jsonrpc/mod.rs
index f0f8d79023..f77aa02dbf 100644
--- a/crates/openhuman-core/src/core/jsonrpc/mod.rs
+++ b/crates/openhuman-core/src/core/jsonrpc/mod.rs
@@ -21,8 +21,9 @@ mod classify;
pub(crate) mod http;
mod invoke;
mod server;
+#[cfg(test)]
+mod testing;
-pub use crate::rpc::parse_json_params;
#[cfg(feature = "http-server")]
pub use http::{build_core_http_router, rpc_handler};
pub use invoke::{default_state, invoke_method};
diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rs
index 52a947fb1f..d9e95bec3b 100644
--- a/crates/openhuman-core/src/core/runtime/builder.rs
+++ b/crates/openhuman-core/src/core/runtime/builder.rs
@@ -1009,7 +1009,7 @@ impl CoreRuntime {
/// each service keeps its own runtime config gate.
async fn start_selected_services(&self) {
use crate::core::runtime::services;
- jsonrpc::start_core_runtime_services(self.services, self.config.as_ref()).await;
+ super::bootstrap::start_core_runtime_services(self.services, self.config.as_ref()).await;
if self.services.heartbeat {
services::spawn_login_gated_services(self.ctx.host_kind().is_desktop_shell());
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 21274d3f2a..ceacf549a6 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -342,7 +342,7 @@ impl CoreContext {
.as_ref()
.map(|cfg| cfg.subsystems.memory.clone())
.unwrap_or_default();
- crate::core::jsonrpc::bootstrap_core_runtime(host_kind, config, domains).await;
+ super::bootstrap::bootstrap_core_runtime(host_kind, config, domains).await;
let ctx = Arc::new(CoreContext {
host_kind,
diff --git a/crates/openhuman-core/src/core/runtime/mod.rs b/crates/openhuman-core/src/core/runtime/mod.rs
index 0057663788..1493dbc759 100644
--- a/crates/openhuman-core/src/core/runtime/mod.rs
+++ b/crates/openhuman-core/src/core/runtime/mod.rs
@@ -42,9 +42,11 @@ pub const AGENT_WORKER_STACK_BYTES: usize = 16 * 1024 * 1024;
/// `.thread_stack_size(AGENT_WORKER_STACK_BYTES)` on every such runtime.
pub const MAX_BLOCKING_THREADS: usize = 64;
+mod bootstrap;
pub mod builder;
pub mod context;
pub mod services;
+pub(crate) mod subscribers;
pub use builder::{CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};
pub use context::{ContextOverlay, CoreContext};
diff --git a/crates/openhuman-core/src/core/socketio.rs b/crates/openhuman-core/src/core/socketio.rs
index ff40f588ef..c60905dc64 100644
--- a/crates/openhuman-core/src/core/socketio.rs
+++ b/crates/openhuman-core/src/core/socketio.rs
@@ -116,15 +116,12 @@ struct HandshakeAuth {
/// A missing `Origin` header is treated as a native (non-browser) client
/// and accepted — only the cross-origin browser-page case is the targeted
/// bad actor here.
-/// Same env var the JSON-RPC CORS layer reads (`jsonrpc::ALLOWED_ORIGINS_ENV`).
-/// Comma-separated, exact-match origins for operator-controlled surfaces that
-/// are not on loopback — a tailnet host, an E2E driver, a reverse proxy.
-#[cfg(feature = "http-server")]
-const ALLOWED_ORIGINS_ENV: &str = "OPENHUMAN_CORE_ALLOWED_ORIGINS";
-
#[cfg(feature = "http-server")]
pub(crate) fn origin_is_allowed(origin: Option<&str>) -> bool {
- origin_is_allowed_with_extra(origin, std::env::var(ALLOWED_ORIGINS_ENV).ok().as_deref())
+ origin_is_allowed_with_extra(
+ origin,
+ std::env::var(crate::rpc::ALLOWED_ORIGINS_ENV).ok().as_deref(),
+ )
}
/// Origin gate with the extra allowlist passed explicitly so tests do not have
diff --git a/crates/openhuman-core/src/core/types.rs b/crates/openhuman-core/src/core/types.rs
index 400114208c..a3348262a4 100644
--- a/crates/openhuman-core/src/core/types.rs
+++ b/crates/openhuman-core/src/core/types.rs
@@ -22,7 +22,7 @@ pub struct CommandResponse<T> {
/// Success payload from a core RPC handler before JSON-RPC wrapping.
///
/// This internal type allows handlers to return a generic JSON value along
-/// with optional logs. It is transformed into a [`RpcSuccess`] or a
+/// with optional logs. It is transformed into a [`crate::rpc::RpcSuccess`] or a
/// combined object by [`invocation_to_rpc_json`].
#[derive(Debug, Clone)]
pub struct InvocationResult {
@@ -72,66 +72,6 @@ pub fn invocation_to_rpc_json(inv: InvocationResult) -> serde_json::Value {
crate::rpc::apply_log_envelope(inv.value, inv.logs)
}
-/// Standard JSON-RPC 2.0 request format.
-///
-/// As defined in the [JSON-RPC 2.0 Specification](https://www.jsonrpc.org/specification).
-#[derive(Debug, Deserialize)]
-pub struct RpcRequest {
- /// The JSON-RPC version. MUST be exactly "2.0".
- #[allow(dead_code)]
- pub jsonrpc: String,
- /// Unique identifier for the request. MUST be a String, Number, or Null.
- /// The server will return this same ID in the response.
- pub id: serde_json::Value,
- /// The name of the method to be invoked (e.g., `openhuman.memory_doc_put`).
- pub method: String,
- /// Parameters for the method call. MUST be a structured value (Object or Array).
- /// Defaults to null if not provided.
- #[serde(default)]
- pub params: serde_json::Value,
-}
-
-/// Standard JSON-RPC 2.0 success response format.
-#[derive(Debug, Serialize)]
-pub struct RpcSuccess {
- /// The JSON-RPC version. ALWAYS "2.0".
- pub jsonrpc: &'static str,
- /// The identifier mirrored from the original request.
- pub id: serde_json::Value,
- /// The result of the successful method invocation.
- pub result: serde_json::Value,
-}
-
-/// Standard JSON-RPC 2.0 error response format.
-#[derive(Debug, Serialize)]
-pub struct RpcFailure {
- /// The JSON-RPC version. ALWAYS "2.0".
- pub jsonrpc: &'static str,
- /// The identifier mirrored from the original request.
- pub id: serde_json::Value,
- /// Information about the error that occurred.
- pub error: RpcError,
-}
-
-/// Detail about an RPC invocation error.
-///
-/// Contains a code, a message, and optional extra data for debugging.
-#[derive(Debug, Serialize)]
-pub struct RpcError {
- /// Standardized error code.
- /// - -32700: Parse error
- /// - -32600: Invalid Request
- /// - -32601: Method not found
- /// - -32602: Invalid params
- /// - -32603: Internal error
- /// - -32000 to -32099: Reserved for implementation-defined server-errors.
- pub code: i64,
- /// A short, human-readable error message.
- pub message: String,
- /// Optional additional diagnostic data, which can be any JSON value.
- pub data: Option<serde_json::Value>,
-}
-
/// Global core-level application state.
///
/// Currently holds shared metadata like the core version.
diff --git a/crates/openhuman-core/src/core/types_tests.rs b/crates/openhuman-core/src/core/types_tests.rs
index 818fd5202f..05440ff819 100644
--- a/crates/openhuman-core/src/core/types_tests.rs
+++ b/crates/openhuman-core/src/core/types_tests.rs
@@ -93,64 +93,6 @@ fn command_response_serde_roundtrip() {
assert_eq!(back.logs.len(), 1);
}
-#[test]
-fn rpc_request_deserializes() {
- let json = r#"{"jsonrpc":"2.0","id":1,"method":"test","params":{}}"#;
- let req: RpcRequest = serde_json::from_str(json).unwrap();
- assert_eq!(req.method, "test");
- assert_eq!(req.id, json!(1));
-}
-
-#[test]
-fn rpc_request_params_default_to_null() {
- let json = r#"{"jsonrpc":"2.0","id":"abc","method":"foo"}"#;
- let req: RpcRequest = serde_json::from_str(json).unwrap();
- assert!(req.params.is_null());
-}
-
-#[test]
-fn rpc_success_serializes() {
- let resp = RpcSuccess {
- jsonrpc: "2.0",
- id: json!(42),
- result: json!({"ok": true}),
- };
- let json = serde_json::to_string(&resp).unwrap();
- assert!(json.contains("\"jsonrpc\":\"2.0\""));
- assert!(json.contains("\"id\":42"));
-}
-
-#[test]
-fn rpc_failure_serializes() {
- let resp = RpcFailure {
- jsonrpc: "2.0",
- id: json!("req-1"),
- error: RpcError {
- code: -32601,
- message: "Method not found".into(),
- data: Some(json!({"detail": "unknown"})),
- },
- };
- let json = serde_json::to_string(&resp).unwrap();
- assert!(json.contains("-32601"));
- assert!(json.contains("Method not found"));
-}
-
-#[test]
-fn rpc_failure_serializes_without_data() {
- let resp = RpcFailure {
- jsonrpc: "2.0",
- id: json!(null),
- error: RpcError {
- code: -32700,
- message: "Parse error".into(),
- data: None,
- },
- };
- let json = serde_json::to_string(&resp).unwrap();
- assert!(json.contains("-32700"));
-}
-
#[test]
fn app_state_clone() {
let state = AppState {