Skip to content

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

feat(channels): route progressive transport through module channels

Steven Enamakel1bda7231d5c6
diff --git a/crates/openhuman-core/src/channels/runtime/startup/callback.rs b/crates/openhuman-core/src/channels/runtime/startup/callback.rs
index 14f2003d32..e46a926e1f 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/callback.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/callback.rs
@@ -6,12 +6,14 @@ use crate::config::Config;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock, Weak};
use tinybus::{Error, Result};
+use tinychannels_bus::module_progressive::{
+ ProgressiveTransportRequest, ProgressiveTransportResult,
+};
use tinychannels_bus::{
ChannelBackendRequest, ChannelBackendResult, HostEventPublication, HostSpeechSynthesisRequest,
HostSpeechSynthesisResult, HostTranscriptionRequest, HostTranscriptionResult,
HostVoiceReplyPolicy, HostVoiceReplyPolicyRequest, HostVoiceTranscriptionRequest,
};
-use tinychannels_bus::module_progressive::{ProgressiveTransportRequest, ProgressiveTransportResult};
use tokio::sync::mpsc;
const MAX_CALLBACK_BYTES: usize = 128 * 1024;
@@ -46,7 +48,9 @@ impl ChannelHostCallbacks {
ctx: &crate::core::runtime::DispatchCtx,
config: Arc<Config>,
context: Arc<OnceLock<Weak<ChannelRuntimeContext>>>,
- progressive_channels: Arc<OnceLock<Arc<HashMap<String, Arc<dyn ProgressiveChannelTransport>>>>>,
+ progressive_channels: Arc<
+ OnceLock<Arc<HashMap<String, Arc<dyn ProgressiveChannelTransport>>>>,
+ >,
dispatch: mpsc::Sender<RuntimeChannelMessage>,
) -> Self {
Self {
@@ -250,9 +254,7 @@ impl ChannelHostCallbacks {
ChannelBackendRequest::ProgressiveTransport(request) => self
.dispatch_progressive_transport(*request)
.await
- .map(|result| {
- ChannelBackendResult::ProgressiveTransport(Box::new(result))
- }),
+ .map(|result| ChannelBackendResult::ProgressiveTransport(Box::new(result))),
request => {
crate::channels::controllers::OpenHumanChannelBackend::new((*self.config).clone())
.dispatch_callback(request)
@@ -266,15 +268,74 @@ impl ChannelHostCallbacks {
&self,
request: ProgressiveTransportRequest,
) -> Result<ProgressiveTransportResult> {
+ if let ProgressiveTransportRequest::OutputEvent {
+ channel_ref: Some(channel),
+ conversation: Some(conversation),
+ turn_id: Some(turn_id),
+ sequence,
+ event,
+ ..
+ } = &request
+ {
+ let event_kind = serde_json::to_value(event.as_ref())
+ .ok()
+ .and_then(|value| {
+ value
+ .get("type")
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_owned)
+ })
+ .ok_or_else(|| Error::failed("invalid progressive output event"))?;
+ let publication = crate::core::events::DomainEvent::ChannelOutputObserved {
+ channel: channel.clone(),
+ conversation: conversation.clone(),
+ turn_id: turn_id.clone(),
+ sequence: *sequence,
+ event_kind,
+ };
+ let publish = async {
+ crate::core::bus::BUS.publish(publication);
+ Ok(ProgressiveTransportResult::Acknowledged)
+ };
+ return match &self.core_context {
+ Some(core_context) => {
+ crate::core::runtime::CoreContext::scope(Arc::clone(core_context), publish)
+ .await
+ }
+ None => publish.await,
+ };
+ }
let (channel, channel_ref) = match &request {
- ProgressiveTransportRequest::OutputEvent { channel, channel_ref, .. }
- | ProgressiveTransportRequest::Send { channel, channel_ref, .. }
- | ProgressiveTransportRequest::SendTyped { channel, channel_ref, .. }
- | ProgressiveTransportRequest::Edit { channel, channel_ref, .. }
- | ProgressiveTransportRequest::Delete { channel, channel_ref, .. }
- | ProgressiveTransportRequest::Typing { channel, channel_ref, .. } => {
- (channel.as_str(), channel_ref.as_ref())
+ ProgressiveTransportRequest::OutputEvent {
+ channel,
+ channel_ref,
+ ..
+ }
+ | ProgressiveTransportRequest::Send {
+ channel,
+ channel_ref,
+ ..
+ }
+ | ProgressiveTransportRequest::SendTyped {
+ channel,
+ channel_ref,
+ ..
+ }
+ | ProgressiveTransportRequest::Edit {
+ channel,
+ channel_ref,
+ ..
+ }
+ | ProgressiveTransportRequest::Delete {
+ channel,
+ channel_ref,
+ ..
}
+ | ProgressiveTransportRequest::Typing {
+ channel,
+ channel_ref,
+ ..
+ } => (channel.as_str(), channel_ref.as_ref()),
};
self.progressive_channel(channel, channel_ref)?
.dispatch_progressive(request)
@@ -299,11 +360,14 @@ impl ChannelHostCallbacks {
.get(account)
.cloned()
.ok_or_else(|| Error::failed("configured channel account is unavailable"))?;
- let configured_provider = tinychannels_bus::capabilities::provider_id(adapter.configured_name());
+ let configured_provider =
+ tinychannels_bus::capabilities::provider_id(adapter.configured_name());
if configured_provider != reference.id
|| tinychannels_bus::capabilities::provider_id(channel) != reference.id
{
- return Err(Error::failed("configured channel account does not match request"));
+ return Err(Error::failed(
+ "configured channel account does not match request",
+ ));
}
Ok(adapter)
}
diff --git a/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs b/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
index 43831bf0e3..23c6240bc6 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
@@ -1,3 +1,4 @@
+use super::ProgressiveChannelTransport;
use super::*;
use crate::channels::Channel;
@@ -67,8 +68,53 @@ impl Channel for RecordingChannel {
}
}
+#[async_trait::async_trait]
+impl ProgressiveChannelTransport for RecordingChannel {
+ fn configured_name(&self) -> &str {
+ &self.name
+ }
+
+ async fn dispatch_progressive(
+ &self,
+ request: ProgressiveTransportRequest,
+ ) -> Result<ProgressiveTransportResult> {
+ let ProgressiveTransportRequest::SendTyped {
+ channel,
+ turn_id,
+ channel_ref,
+ conversation,
+ idempotency_key,
+ parts,
+ ..
+ } = request
+ else {
+ return Ok(ProgressiveTransportResult::Unavailable);
+ };
+ let outbound = tinychannels_bus::channel::ChannelOutboundMessage {
+ channel_id: channel,
+ conversation_id: conversation
+ .as_ref()
+ .map(|reference| reference.id.clone())
+ .unwrap_or_default(),
+ channel_ref,
+ conversation_ref: conversation,
+ reply_to_id: None,
+ thread_id: None,
+ turn_id,
+ idempotency_key: idempotency_key.unwrap_or_default(),
+ parts,
+ };
+ let outcome = self
+ .send_typed_with_receipt(&outbound)
+ .await
+ .map_err(|_| Error::failed("test channel send failed"))?;
+ Ok(ProgressiveTransportResult::Outcome(Box::new(outcome)))
+ }
+}
+
fn callback_for_channels(
channels: HashMap<String, Arc<dyn Channel>>,
+ progressive_channels: HashMap<String, Arc<dyn ProgressiveChannelTransport>>,
) -> (ChannelHostCallbacks, Arc<ChannelRuntimeContext>) {
let context = Arc::new(ChannelRuntimeContext {
relay_thread: None,
@@ -96,12 +142,15 @@ fn callback_for_channels(
});
let context_slot: Arc<OnceLock<Weak<ChannelRuntimeContext>>> = Arc::new(OnceLock::new());
assert!(context_slot.set(Arc::downgrade(&context)).is_ok());
+ let progressive_slot = Arc::new(OnceLock::new());
+ assert!(progressive_slot.set(Arc::new(progressive_channels)).is_ok());
let (dispatch, _receiver) = tokio::sync::mpsc::channel::<RuntimeChannelMessage>(1);
(
ChannelHostCallbacks::new(
&crate::core::runtime::DispatchCtx::host_default(),
Arc::new(crate::config::Config::default()),
context_slot,
+ progressive_slot,
dispatch,
),
context,
@@ -122,7 +171,18 @@ async fn native_progressive_transport_dispatches_typed_content_through_configure
selected_account.clone() as Arc<dyn Channel>,
),
]);
- let (callback, _context) = callback_for_channels(channels);
+ let progressive_channels: HashMap<String, Arc<dyn ProgressiveChannelTransport>> =
+ HashMap::from([
+ (
+ "telegram:bot-a".into(),
+ other_account.clone() as Arc<dyn ProgressiveChannelTransport>,
+ ),
+ (
+ "telegram:bot-b".into(),
+ selected_account.clone() as Arc<dyn ProgressiveChannelTransport>,
+ ),
+ ]);
+ let (callback, _context) = callback_for_channels(channels, progressive_channels);
let parts = vec![OutboundContentPart::Content {
part: tinychannels_bus::ContentPart::Image {
media: tinychannels_bus::MediaReference {
@@ -216,7 +276,18 @@ async fn native_progressive_transport_rejects_unconfigured_account_without_provi
second_account.clone() as Arc<dyn Channel>,
),
]);
- let (callback, _context) = callback_for_channels(channels);
+ let progressive_channels: HashMap<String, Arc<dyn ProgressiveChannelTransport>> =
+ HashMap::from([
+ (
+ "telegram:bot-a".into(),
+ first_account.clone() as Arc<dyn ProgressiveChannelTransport>,
+ ),
+ (
+ "telegram:bot-b".into(),
+ second_account.clone() as Arc<dyn ProgressiveChannelTransport>,
+ ),
+ ]);
+ let (callback, _context) = callback_for_channels(channels, progressive_channels);
let result = callback
.dispatch_controller_backend(ChannelBackendRequest::ProgressiveTransport(Box::new(
diff --git a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
index 748446293f..8875923489 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -139,23 +139,25 @@ impl ModuleChannelRuntime {
let mut channels = HashMap::new();
let mut progressive = HashMap::new();
for info in &infos {
- let channel = ModuleChannel {
- name: info.name.clone(),
- object: lease.object().clone(),
- interaction: legacy_interaction(&info.interaction),
- relay: relay.clone(),
- relay_fronted: relay_fronts(&info.name),
- };
- let channel = Arc::new(channel);
- channels.insert(info.name.clone(), channel.clone() as Arc<dyn Channel>);
- progressive.insert(
- info.name.clone(),
- channel as Arc<dyn ProgressiveChannelTransport>,
- );
+ let channel = ModuleChannel {
+ name: info.name.clone(),
+ object: lease.object().clone(),
+ interaction: legacy_interaction(&info.interaction),
+ relay: relay.clone(),
+ relay_fronted: relay_fronts(&info.name),
+ };
+ let channel = Arc::new(channel);
+ channels.insert(info.name.clone(), channel.clone() as Arc<dyn Channel>);
+ progressive.insert(
+ info.name.clone(),
+ channel as Arc<dyn ProgressiveChannelTransport>,
+ );
}
progressive_channels
.set(Arc::new(progressive))
- .map_err(|_| anyhow::anyhow!("progressive channel adapters were already initialized"))?;
+ .map_err(|_| {
+ anyhow::anyhow!("progressive channel adapters were already initialized")
+ })?;
Ok(Self {
client,
lease,
@@ -363,10 +365,7 @@ impl Channel for ModuleChannel {
.object
.call_confidential(
tinychannels_bus::methods::PREPARE_OUTBOUND_INTENT,
- (
- self.name.clone(),
- ChannelMessagePreparation::Intent(intent),
- ),
+ (self.name.clone(), ChannelMessagePreparation::Intent(intent)),
)
.await
.map_err(anyhow::Error::new)?;
@@ -587,3 +586,183 @@ impl ModuleChannel {
}
}
}
+
+#[async_trait]
+impl ProgressiveChannelTransport for ModuleChannel {
+ fn configured_name(&self) -> &str {
+ &self.name
+ }
+
+ async fn dispatch_progressive(
+ &self,
+ request: tinychannels_bus::module_progressive::ProgressiveTransportRequest,
+ ) -> tinybus::Result<tinychannels_bus::module_progressive::ProgressiveTransportResult> {
+ use tinychannels_bus::module_progressive::{
+ ProgressiveTransportRequest as Request, ProgressiveTransportResult as Result,
+ };
+
+ match request {
+ Request::SendTyped {
+ channel,
+ turn_id,
+ channel_ref,
+ conversation,
+ sequence: _,
+ segment_index: _,
+ idempotency_key,
+ parts,
+ ..
+ } => {
+ let outbound = tinychannels_bus::channel::ChannelOutboundMessage {
+ channel_id: channel,
+ conversation_id: conversation
+ .as_ref()
+ .map(|reference| reference.id.clone())
+ .unwrap_or_default(),
+ channel_ref,
+ conversation_ref: conversation,
+ reply_to_id: None,
+ thread_id: None,
+ turn_id,
+ idempotency_key: idempotency_key.unwrap_or_default(),
+ parts,
+ };
+ let outcome = self
+ .send_typed_with_receipt(&outbound)
+ .await
+ .map_err(|_| tinybus::Error::failed("progressive channel send failed"))?;
+ Ok(Result::Outcome(Box::new(outcome)))
+ }
+ Request::Send {
+ channel,
+ turn_id,
+ channel_ref,
+ conversation,
+ idempotency_key,
+ message,
+ ..
+ } => {
+ let legacy: SendMessage = serde_json::from_value(message)
+ .map_err(|_| tinybus::Error::failed("invalid progressive send payload"))?;
+ let mut outbound =
+ tinychannels_bus::channel::ChannelOutboundMessage::from_legacy_message(
+ channel_ref
+ .as_ref()
+ .map(|reference| reference.id.as_str())
+ .unwrap_or(&channel),
+ &legacy,
+ );
+ outbound.channel_ref = channel_ref;
+ outbound.conversation_ref = conversation.or(outbound.conversation_ref);
+ outbound.turn_id = turn_id;
+ if let Some(key) = idempotency_key {
+ outbound.idempotency_key = key;
+ }
+ let outcome = self
+ .send_typed_with_receipt(&outbound)
+ .await
+ .map_err(|_| tinybus::Error::failed("progressive channel send failed"))?;
+ Ok(Result::Outcome(Box::new(outcome)))
+ }
+ Request::Edit {
+ channel,
+ turn_id,
+ channel_ref,
+ conversation,
+ message_id: _,
+ receipt,
+ text,
+ } => {
+ let Some(receipt) = receipt else {
+ return Ok(Result::Unavailable);
+ };
+ let channel_id = channel_ref
+ .as_ref()
+ .map(|reference| reference.id.clone())
+ .unwrap_or(channel);
+ let conversation_id = conversation
+ .as_ref()
+ .map(|reference| reference.id.clone())
+ .unwrap_or_default();
+ let intent = tinychannels_bus::channel::ChannelOutboundIntent {
+ idempotency_key: format!(
+ "progressive-edit:{}:{}",
+ turn_id.as_deref().unwrap_or("unscoped"),
+ receipt
+ .primary_platform_message_id
+ .as_deref()
+ .unwrap_or("unknown")
+ ),
+ channel_id,
+ conversation_id,
+ channel_ref,
+ conversation_ref: conversation.clone(),
+ reply_to_id: receipt.reply_to_id.clone(),
+ thread_id: receipt.thread_id.clone(),
+ turn_id,
+ durability: tinychannels_bus::channel::DeliveryDurability::Required,
+ payload: tinychannels_bus::channel::OutboundPayload::Text { text },
+ };
+ match self
+ .object
+ .call_confidential::<ChannelInteractionResult>(
+ tinychannels_bus::methods::CHANNEL_INTERACTION,
+ tinychannels_bus::ChannelInteractionRequest {
+ channel: self.name.clone(),
+ interaction: ChannelInteraction::EditMessage { receipt, intent },
+ },
+ )
+ .await
+ {
+ Ok(ChannelInteractionResult::Sent(outcome)) => {
+ match outcome.error.as_ref().map(|error| error.kind) {
+ Some(tinychannels_bus::channel::SendErrorKind::NotFound) => {
+ Ok(Result::MessageGone)
+ }
+ Some(tinychannels_bus::channel::SendErrorKind::Forbidden) => {
+ Ok(Result::EditUnsupported)
+ }
+ _ => Ok(Result::Outcome(outcome)),
+ }
+ }
+ Ok(_) => Err(tinybus::Error::failed(
+ "channel returned an invalid edit result",
+ )),
+ Err(error) => Err(error),
+ }
+ }
+ Request::Delete { receipt, .. } => {
+ let Some(receipt) = receipt else {
+ return Ok(Result::Unavailable);
+ };
+ match self
+ .object
+ .call_confidential::<ChannelInteractionResult>(
+ tinychannels_bus::methods::CHANNEL_INTERACTION,
+ tinychannels_bus::ChannelInteractionRequest {
+ channel: self.name.clone(),
+ interaction: ChannelInteraction::DeleteMessage { receipt },
+ },
+ )
+ .await
+ {
+ Ok(ChannelInteractionResult::Completed) => Ok(Result::Acknowledged),
+ Ok(_) => Err(tinybus::Error::failed(
+ "channel returned an invalid delete result",
+ )),
+ Err(error) => Err(error),
+ }
+ }
+ Request::Typing { conversation, .. } => {
+ let recipient = conversation
+ .map(|reference| reference.id)
+ .unwrap_or_default();
+ self.interact(ChannelInteraction::StartTyping { recipient })
+ .await
+ .map_err(|_| tinybus::Error::failed("progressive typing callback failed"))?;
+ Ok(Result::Acknowledged)
+ }
+ Request::OutputEvent { .. } => Ok(Result::Unavailable),
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/core/events_tests.rs b/crates/openhuman-core/src/core/events_tests.rs
index 39b17b5dd4..70ff0442f3 100644
--- a/crates/openhuman-core/src/core/events_tests.rs
+++ b/crates/openhuman-core/src/core/events_tests.rs
@@ -781,19 +781,23 @@ fn a_long_error_is_clipped_on_a_character_boundary() {
/// Every other variant is unchanged: no detail, so its row renders as before.
#[test]
fn events_outside_the_supervisor_have_no_event_log_detail() {
- assert!(DomainEvent::CronJobCompleted {
- job_id: "job-1".into(),
- success: true,
- output: "done".into(),
- }
- .log_detail()
- .is_none());
- assert!(DomainEvent::McpServerConnected {
- server_id: "srv-1".into(),
- tool_count: 25,
- }
- .log_detail()
- .is_none());
+ assert!(
+ DomainEvent::CronJobCompleted {
+ job_id: "job-1".into(),
+ success: true,
+ output: "done".into(),
+ }
+ .log_detail()
+ .is_none()
+ );
+ assert!(
+ DomainEvent::McpServerConnected {
+ server_id: "srv-1".into(),
+ tool_count: 25,
+ }
+ .log_detail()
+ .is_none()
+ );
}
// ── workspace_dir ────────────────────────────────────────────────────────