Skip to content

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

fix(channels): deliver callbacks through the bus instead of direct slots

Steven Enamakel21dfdaaa644b
diff --git a/crates/openhuman-core/src/channels/bus/delivery.rs b/crates/openhuman-core/src/channels/bus/delivery.rs
index ecbe152fd3..5e896d78b3 100644
--- a/crates/openhuman-core/src/channels/bus/delivery.rs
+++ b/crates/openhuman-core/src/channels/bus/delivery.rs
@@ -134,6 +134,54 @@ impl ManagedTransport {
}
}
+/// The callback a registered channel callback
+/// ([`crate::channels::callback_slot`]) serves progressive delivery through,
+/// in place of [`ManagedTransport`].
+struct SlotTransport {
+ callback: crate::channels::callback_slot::ChannelCallback,
+ config: crate::config::Config,
+ channel: String,
+ session: tokio_util::sync::CancellationToken,
+}
+
+#[tinybus::interface(name = "ai.tinyhumans.tinychannels.ChannelsHost")]
+impl SlotTransport {
+ async fn dispatch_controller_backend(
+ &self,
+ request: ChannelBackendRequest,
+ ) -> tinybus::Result<ChannelBackendResult> {
+ let ChannelBackendRequest::ProgressiveTransport(request) = request else {
+ return Err(tinybus::Error::failed("callback capability unavailable"));
+ };
+ if request_channel(&request) != self.channel {
+ return Ok(ChannelBackendResult::ProgressiveTransport(
+ ProgressiveTransportResult::Failed,
+ ));
+ }
+ let ctx = crate::channels::callback_slot::ChannelCallbackCtx {
+ config: self.config.clone(),
+ channel: Some(self.channel.clone()),
+ session: self.session.clone(),
+ };
+ let call = (self.callback)(ctx, ChannelBackendRequest::ProgressiveTransport(request));
+ tokio::select! {
+ biased;
+ _ = self.session.cancelled() => Ok(ChannelBackendResult::ProgressiveTransport(
+ ProgressiveTransportResult::Unavailable,
+ )),
+ result = call => match result {
+ Ok(result) => Ok(result),
+ Err(error) => {
+ tracing::debug!(%error, "[channels][delivery] registered callback failed");
+ Ok(ChannelBackendResult::ProgressiveTransport(
+ map_backend_error(error),
+ ))
+ }
+ },
+ }
+ }
+}
+
/// The host projects ordered turn facts; the module owns timers and delivery state.
pub(super) struct ModuleProgressiveReply {
runtime: ChannelRuntimeLease,
@@ -146,7 +194,26 @@ impl ModuleProgressiveReply {
channel: String,
session: tokio_util::sync::CancellationToken,
) -> anyhow::Result<Self> {
+ if let Some(callback) = crate::channels::callback_slot::current() {
+ tracing::debug!("[channels][delivery] progressive delivery via the registered callback");
+ anyhow::ensure!(!session.is_cancelled(), "Channel session closed");
+ let transport = SlotTransport {
+ callback,
+ config: config.clone(),
+ channel: channel.clone(),
+ session,
+ };
+ return Self::open_with(config, channel, transport).await;
+ }
let callback = ManagedTransport::capture(&config, channel.clone(), session)?;
+ Self::open_with(config, channel, callback).await
+ }
+
+ async fn open_with(
+ config: crate::config::Config,
+ channel: String,
+ callback: impl tinybus::service::Interface + 'static,
+ ) -> anyhow::Result<Self> {
let runtime = ChannelRuntimeLease::open(crate::modules::client(config), callback).await?;
let result: ProgressiveResult = runtime
.object()
diff --git a/crates/openhuman-core/src/channels/callback_slot.rs b/crates/openhuman-core/src/channels/callback_slot.rs
new file mode 100644
index 0000000000..308452d7d4
--- /dev/null
+++ b/crates/openhuman-core/src/channels/callback_slot.rs
@@ -0,0 +1,85 @@
+//! The channel callback slot: where an outside crate plugs in the transport a
+//! channel module's host callbacks run through.
+//!
+//! The channel module (`tinychannels`) calls back into the host with a
+//! [`ChannelBackendRequest`] and expects a [`ChannelBackendResult`]. The core
+//! answers the requests it can itself; a registered callback answers the
+//! progressive-delivery transport (send, edit, delete, typing) in place of the
+//! built-in managed path. The callback is a plain closure over the vendor
+//! contract types: the core defines no trait for it.
+//!
+//! With nothing registered [`bus::delivery`](super::bus) uses its built-in
+//! managed transport, unchanged.
+
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::Arc;
+
+use tinychannels_bus::{ChannelBackendRequest, ChannelBackendResult};
+use tokio_util::sync::CancellationToken;
+
+use crate::config::Config;
+use crate::core::slots::{Extensions, HookSlot};
+
+/// A boxed `Send` future.
+pub type CallbackFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
+
+/// What a registered callback is told about the request's origin.
+#[derive(Clone)]
+pub struct ChannelCallbackCtx {
+ /// The configuration the channel session was opened with.
+ pub config: Config,
+ /// The channel the session serves, when the caller knows it.
+ pub channel: Option<String>,
+ /// Cancelled when the channel session closes.
+ pub session: CancellationToken,
+}
+
+/// A registered channel callback.
+pub type ChannelCallback = Arc<
+ dyn Fn(ChannelCallbackCtx, ChannelBackendRequest) -> CallbackFuture<anyhow::Result<ChannelBackendResult>>
+ + Send
+ + Sync,
+>;
+
+static CALLBACKS: HookSlot<ChannelCallback> = HookSlot::new("channels::callback");
+
+/// Registers the channel callback `id` for the whole process. The first
+/// registered callback (registration order) serves requests.
+pub fn register_channel_callback<F>(id: impl Into<String>, callback: F)
+where
+ F: Fn(ChannelCallbackCtx, ChannelBackendRequest) -> CallbackFuture<anyhow::Result<ChannelBackendResult>>
+ + Send
+ + Sync
+ + 'static,
+{
+ CALLBACKS.register(id, Arc::new(callback));
+}
+
+/// Registers the channel callback `id` for the context built from `extensions`.
+pub fn register_channel_callback_in<F>(
+ extensions: &Extensions,
+ id: impl Into<String>,
+ callback: F,
+) where
+ F: Fn(ChannelCallbackCtx, ChannelBackendRequest) -> CallbackFuture<anyhow::Result<ChannelBackendResult>>
+ + Send
+ + Sync
+ + 'static,
+{
+ CALLBACKS.register_in(extensions, id, Arc::new(callback));
+}
+
+/// Removes the process-wide channel callback `id`.
+pub fn unregister_channel_callback(id: &str) -> bool {
+ CALLBACKS.unregister(id)
+}
+
+/// The callback that serves requests now, if one is registered.
+pub(crate) fn current() -> Option<ChannelCallback> {
+ CALLBACKS.first()
+}
+
+#[cfg(test)]
+#[path = "callback_slot_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/channels/controllers/backend.rs b/crates/openhuman-core/src/channels/controllers/backend.rs
index 004644c6e9..62b77a0bd7 100644
--- a/crates/openhuman-core/src/channels/controllers/backend.rs
+++ b/crates/openhuman-core/src/channels/controllers/backend.rs
@@ -59,6 +59,22 @@ impl OpenHumanChannelBackend {
) -> anyhow::Result<tinychannels_bus::ChannelBackendResult> {
use tinychannels_bus::{ChannelBackendRequest as Request, ChannelBackendResult as Result};
+ // A registered callback (`channels::callback_slot`) serves the
+ // progressive transport ahead of the "separate adapter" refusal below.
+ if matches!(request, Request::ProgressiveTransport(_)) {
+ if let Some(callback) = crate::channels::callback_slot::current() {
+ return callback(
+ crate::channels::callback_slot::ChannelCallbackCtx {
+ config: self.config.clone(),
+ channel: None,
+ session: tokio_util::sync::CancellationToken::new(),
+ },
+ request,
+ )
+ .await;
+ }
+ }
+
match request {
Request::RemoteControl(_) | Request::ProgressiveTransport(_) => {
anyhow::bail!("request is served by a separate callback adapter")
diff --git a/crates/openhuman-core/src/channels/mod.rs b/crates/openhuman-core/src/channels/mod.rs
index 05ceb3485d..0d652805a1 100644
--- a/crates/openhuman-core/src/channels/mod.rs
+++ b/crates/openhuman-core/src/channels/mod.rs
@@ -15,6 +15,8 @@ pub use tinychannels_bus::{Channel, ChannelSendExt, SendMessage};
#[cfg(feature = "channels")]
pub mod bus;
#[cfg(feature = "channels")]
+pub mod callback_slot;
+#[cfg(feature = "channels")]
mod commands;
#[cfg(feature = "channels")]
pub(crate) use commands::{configured_providers, has_listener_configuration};
diff --git a/crates/openhuman-core/src/inference/registry_tests.rs b/crates/openhuman-core/src/inference/registry_tests.rs
index 77badfcad4..a6d99e8470 100644
--- a/crates/openhuman-core/src/inference/registry_tests.rs
+++ b/crates/openhuman-core/src/inference/registry_tests.rs
@@ -113,7 +113,7 @@ async fn a_registered_catalog_answers_the_model_listing_for_its_provider() {
limits: None,
},
);
- let listing = crate::inference::provider::ops::models::list_configured_models_from_config(
+ let listing = crate::inference::provider::ops::list_configured_models_from_config(
"fake-catalog",
&Config::default(),
)
@@ -124,7 +124,7 @@ async fn a_registered_catalog_answers_the_model_listing_for_its_provider() {
#[tokio::test]
async fn without_a_catalog_an_unknown_provider_still_errors() {
- let error = crate::inference::provider::ops::models::list_configured_models_from_config(
+ let error = crate::inference::provider::ops::list_configured_models_from_config(
"fake-catalog",
&Config::default(),
)