Skip to content

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

feat(core): add extension dispatch to the core invoke path

Steven Enamakel906468c51acf
diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rs
index a91b2cb6ba..75192c19d1 100644
--- a/crates/openhuman-core/src/core/all.rs
+++ b/crates/openhuman-core/src/core/all.rs
@@ -1144,65 +1144,6 @@ fn kind(matches: bool, expected: &'static str) -> Result<(), TypeMismatch> {
matches.then_some(()).ok_or(TypeMismatch::Kind(expected))
}
-/// Attempts to invoke a registered RPC method by name.
-///
-/// Checks both the agent-facing controller registry and the internal-only registry,
-/// so internal-only write paths (e.g. the MCP write-audit list) are routable
-/// even though they are not included in agent tool listings.
-///
-/// Returns `None` if the method is not found in either registry.
-pub async fn try_invoke_registered_rpc(
- ctx: DispatchCtx,
- method: &str,
- params: Map<String, Value>,
-) -> Option<Result<Value, String>> {
- let view = registry_view();
- let grouped = view
- .iter()
- .chain(internal_registry().iter())
- .find(|g| g.controller.rpc_method_name() == method)?;
-
- // DomainSet gate (#4796): a method whose group is disabled under the ambient
- // context reports as an unknown method (`None`) — the same result a caller
- // gets for a genuinely-unregistered method, so a gated domain's controllers
- // are indistinguishable from absent. Enforced HERE (dispatch), not in
- // schema/validation lookups, to avoid a validate/dispatch split.
- if !visible(grouped) {
- log::debug!(
- "[rpc][domain-gate] method '{method}' suppressed — group {:?} disabled or method \
- outside the user surface in the active scope",
- grouped.group
- );
- return None;
- }
-
- let handler = grouped.controller.handler;
-
- // The handler gets the call's context as an argument. Until every reader
- // below it has moved off the ambient context (#7801), the same context is
- // also scoped for the duration of the call, so `CoreContext::current()`
- // inside the handler resolves to it. A call that arrived without a bound
- // context inherits the active scope (a handler that dispatches a nested RPC
- // stays in its tenant) or the process default, as before.
- //
- // The scoped future is re-boxed back into a `ControllerFuture` so the
- // concrete `TaskLocalFuture` type does not escape into this fn's future —
- // without the type erasure the `Send` auto-trait solver overflows on the
- // largest handler futures (E0275).
- use crate::core::runtime::context::CoreContext;
- let core = ctx.into_core().or_else(CoreContext::current);
- let ctx = match &core {
- Some(core) => DispatchCtx::new(core.clone()),
- None => DispatchCtx::unbound(),
- };
- let fut = handler(ctx, params);
- let scoped: ControllerFuture = match core {
- Some(core) => Box::pin(CoreContext::scope(core, fut)),
- None => fut,
- };
- Some(scoped.await)
-}
-
#[derive(Debug, Clone)]
pub struct HttpMethodSchemaDefinition {
pub method: String,
@@ -1280,6 +1221,10 @@ pub(crate) fn assert_schema_controller_parity(
);
}
+#[path = "all_invoke.rs"]
+mod invoke_registered;
+pub use invoke_registered::try_invoke_registered_rpc;
+
#[cfg(test)]
#[path = "all_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/core/all_extensions_tests.rs b/crates/openhuman-core/src/core/all_extensions_tests.rs
index 7708d23966..52fd50eb9e 100644
--- a/crates/openhuman-core/src/core/all_extensions_tests.rs
+++ b/crates/openhuman-core/src/core/all_extensions_tests.rs
@@ -3,14 +3,6 @@ use serde_json::Map;
use super::*;
-/// Dispatches under the calling task's ambient context.
-pub(super) async fn ambient_rpc(
- method: &str,
- params: Map<String, serde_json::Value>,
-) -> Option<Result<serde_json::Value, String>> {
- try_invoke_registered_rpc(DispatchCtx::ambient(), method, params).await
-}
-
// ── Controller extensions (crates above the core) ──────────────────────────
fn ext_controller(namespace: &'static str, function: &'static str) -> RegisteredController {
@@ -48,13 +40,13 @@ async fn registry_extension_is_visible_to_every_lookup_and_dispatches() {
);
let result = try_invoke_registered_rpc(
- DispatchCtx::ambient(),
+ DispatchCtx::unbound(),
"openhuman.ext_probe_ping",
Map::new(),
)
.await
- .expect("extension method is dispatchable")
- .expect("handler succeeds");
+ .expect("extension method is dispatchable")
+ .expect("handler succeeds");
assert_eq!(result, serde_json::json!({"ext": true}));
}
@@ -109,13 +101,9 @@ async fn registry_extension_is_gated_by_its_domain_group() {
let ctx = CoreContext::for_test(domains, None);
let hidden = CoreContext::scope(ctx, async {
(
- try_invoke_registered_rpc(
- DispatchCtx::ambient(),
- "openhuman.ext_gate_ping",
- Map::new(),
- )
- .await
- .is_none(),
+ try_invoke_registered_rpc("openhuman.ext_gate_ping", Map::new())
+ .await
+ .is_none(),
schema_for_rpc_method("openhuman.ext_gate_ping").is_none(),
)
})
diff --git a/crates/openhuman-core/src/core/all_invoke.rs b/crates/openhuman-core/src/core/all_invoke.rs
new file mode 100644
index 0000000000..e4ac7f3f12
--- /dev/null
+++ b/crates/openhuman-core/src/core/all_invoke.rs
@@ -0,0 +1,75 @@
+//! Dispatch of a registered controller: the gate, then the handler.
+
+use std::future::Future;
+use std::pin::Pin;
+
+use serde_json::{Map, Value};
+
+use super::{internal_registry, registry_view, visible, ControllerFuture};
+use crate::core::runtime::{CoreContext, DispatchCtx};
+
+type Dispatched = Pin<Box<dyn Future<Output = Option<Result<Value, String>>> + Send + 'static>>;
+
+/// Attempts to invoke a registered RPC method by name.
+///
+/// Checks both the agent-facing controller registry and the internal-only registry,
+/// so internal-only write paths (e.g. the MCP write-audit list) are routable
+/// even though they are not included in agent tool listings.
+///
+/// The handler receives `ctx` as its first argument. A call that arrives with no
+/// bound context inherits the calling task's scope, or the process default.
+/// Until every reader below the handler has moved off the ambient context
+/// (#7801), the resolved context is also scoped onto the task for the whole
+/// call (registry view, domain gate, handler), so those readers resolve to the
+/// context the caller named rather than to whatever the task carried.
+///
+/// Returns `None` if the method is not found in either registry.
+pub async fn try_invoke_registered_rpc(
+ ctx: DispatchCtx,
+ method: &str,
+ params: Map<String, Value>,
+) -> Option<Result<Value, String>> {
+ let core = ctx.into_core().or_else(CoreContext::current);
+ let ctx = match &core {
+ Some(core) => DispatchCtx::new(core.clone()),
+ None => DispatchCtx::unbound(),
+ };
+ // Boxed so the concrete `TaskLocalFuture` type does not escape into this
+ // fn's future: without the type erasure the `Send` auto-trait solver
+ // overflows on the largest handler futures (E0275).
+ let call: Dispatched = Box::pin(invoke_registered(ctx, method.to_owned(), params));
+ match core {
+ Some(core) => CoreContext::scope(core, call).await,
+ None => call.await,
+ }
+}
+
+async fn invoke_registered(
+ ctx: DispatchCtx,
+ method: String,
+ params: Map<String, Value>,
+) -> Option<Result<Value, String>> {
+ let view = registry_view();
+ let grouped = view
+ .iter()
+ .chain(internal_registry().iter())
+ .find(|g| g.controller.rpc_method_name() == method)?;
+
+ // DomainSet gate (#4796): a method whose group is disabled under the call's
+ // context reports as an unknown method (`None`) — the same result a caller
+ // gets for a genuinely-unregistered method, so a gated domain's controllers
+ // are indistinguishable from absent. Enforced HERE (dispatch), not in
+ // schema/validation lookups, to avoid a validate/dispatch split.
+ if !visible(grouped) {
+ log::debug!(
+ "[rpc][domain-gate] method '{method}' suppressed — group {:?} disabled or method \
+ outside the user surface in the active scope",
+ grouped.group
+ );
+ return None;
+ }
+
+ let handler = grouped.controller.handler;
+ let fut: ControllerFuture = handler(ctx, params);
+ Some(fut.await)
+}
diff --git a/crates/openhuman-core/src/core/all_tests.rs b/crates/openhuman-core/src/core/all_tests.rs
index fda093d95b..590455d8ed 100644
--- a/crates/openhuman-core/src/core/all_tests.rs
+++ b/crates/openhuman-core/src/core/all_tests.rs
@@ -1,6 +1,7 @@
use serde_json::Map;
use super::*;
+use crate::core::runtime::DispatchCtx;
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
fn schema(
@@ -17,10 +18,7 @@ fn schema(
}
}
-fn noop_handler(
- _ctx: crate::core::runtime::DispatchCtx,
- _params: Map<String, Value>,
-) -> ControllerFuture {
+fn noop_handler(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async { Ok(Value::Null) })
}
@@ -802,8 +800,7 @@ fn validate_registry_rejects_duplicate_registered_controllers() {
#[tokio::test]
async fn try_invoke_registered_rpc_returns_none_for_unknown_method() {
- let out =
- extensions_tests::ambient_rpc("openhuman.not_a_real_method_xyz_123", Map::new()).await;
+ let out = try_invoke_registered_rpc(DispatchCtx::unbound(), "openhuman.not_a_real_method_xyz_123", Map::new()).await;
assert!(out.is_none(), "unknown methods must return None");
}
@@ -811,7 +808,7 @@ async fn try_invoke_registered_rpc_returns_none_for_unknown_method() {
async fn try_invoke_registered_rpc_returns_some_for_known_method() {
// `openhuman.health_snapshot` is registered at startup and takes no
// required params — it must route and produce Some(_).
- let out = extensions_tests::ambient_rpc("openhuman.health_snapshot", Map::new()).await;
+ let out = try_invoke_registered_rpc(DispatchCtx::unbound(), "openhuman.health_snapshot", Map::new()).await;
assert!(out.is_some(), "known method must route");
}
@@ -823,9 +820,10 @@ async fn try_invoke_registered_rpc_routes_security_policy_info() {
config.action_dir = workspace.path().to_path_buf();
config.config_path = workspace.path().join("config.toml");
let ctx = CoreContext::for_test_with_config(DomainSet::full(), config);
- let out = CoreContext::scope(
- ctx,
- extensions_tests::ambient_rpc("openhuman.security_policy_info", Map::new()),
+ let out = try_invoke_registered_rpc(
+ DispatchCtx::new(ctx),
+ "openhuman.security_policy_info",
+ Map::new(),
)
.await
.expect("security policy info should be registered")
@@ -970,11 +968,8 @@ async fn dispatch_returns_none_for_gated_method() {
.expect("a flows.* method exists in the full registry");
let ctx = CoreContext::for_test(DomainSet::harness(), None);
- let out = CoreContext::scope(
- ctx,
- extensions_tests::ambient_rpc(&gated_method, Map::new()),
- )
- .await;
+ let out =
+ try_invoke_registered_rpc(DispatchCtx::new(ctx), &gated_method, Map::new()).await;
assert!(
out.is_none(),
"gated method `{gated_method}` must dispatch as None under harness()"
@@ -983,9 +978,10 @@ async fn dispatch_returns_none_for_gated_method() {
// A harness-family method still routes (Some) — security.policy_info needs
// no workspace, so it is a clean positive control.
let ctx = CoreContext::for_test(DomainSet::harness(), None);
- let out = CoreContext::scope(
- ctx,
- extensions_tests::ambient_rpc("openhuman.security_policy_info", Map::new()),
+ let out = try_invoke_registered_rpc(
+ DispatchCtx::new(ctx),
+ "openhuman.security_policy_info",
+ Map::new(),
)
.await;
assert!(
diff --git a/crates/openhuman-core/src/core/invoke.rs b/crates/openhuman-core/src/core/invoke.rs
index ecf05a9fdc..c1400039c4 100644
--- a/crates/openhuman-core/src/core/invoke.rs
+++ b/crates/openhuman-core/src/core/invoke.rs
@@ -10,7 +10,7 @@ use serde_json::Value;
use super::session_expiry::{is_session_expired_error, is_unconfirmed_unauthorized_error};
use crate::core::all;
-use crate::core::runtime::DispatchCtx;
+use crate::core::runtime::{CoreContext, DispatchCtx};
use crate::core::types::AppState;
/// Invokes a JSON-RPC method by name.
@@ -34,7 +34,7 @@ pub async fn invoke_method(
method: &str,
params: Value,
) -> Result<Value, String> {
- let mut result = invoke_method_inner(ctx, state, method, params).await;
+ let mut result = invoke_scoped(ctx, state, method, params).await;
// Session auto-cleanup: if the OpenHuman auth session is explicitly
// expired, publish a `SessionExpired` event. The credentials subscriber
@@ -86,6 +86,25 @@ pub async fn invoke_method(
result
}
+/// [`invoke_method_inner`] with `ctx` also scoped onto the task, so the schema
+/// lookup, parameter validation and fallback dispatch that precede the handler
+/// read the context the caller named. Transitional (#7801): goes away with the
+/// ambient context once those readers take the context explicitly.
+async fn invoke_scoped(
+ ctx: DispatchCtx,
+ state: AppState,
+ method: &str,
+ params: Value,
+) -> Result<Value, String> {
+ let core = ctx.core().cloned();
+ let call: std::pin::Pin<Box<dyn std::future::Future<Output = Result<Value, String>> + Send + '_>> =
+ Box::pin(invoke_method_inner(ctx, state, method, params));
+ match core {
+ Some(core) => CoreContext::scope(core, call).await,
+ None => call.await,
+ }
+}
+
fn should_publish_session_expired(msg: &str, credential_is_local: bool) -> bool {
is_session_expired_error(msg) && !credential_is_local
}