Skip to content

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

feat(channels): prepare inbound messages through the module bus

Steven Enamakelce5dace729c0
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs
index c429d138eb..bad81104c9 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs
@@ -1,7 +1,6 @@
//! Gating and intercepting approval-gate replies on channels that surface
//! approvals in chat.
-use crate::channels::context::conversation_history_key;
use crate::channels::traits;
/// Whether a channel surfaces approvals in chat: the
@@ -18,7 +17,7 @@ use crate::channels::traits;
/// [`ApprovalChatContext`]: crate::security::approval::ApprovalChatContext
/// [`ApprovalGate`]: crate::security::approval::ApprovalGate
pub(crate) fn channel_has_approval_surface(channel: &str) -> bool {
- tinychannels::capabilities_for(channel).chat_approvals
+ tinychannels_bus::capabilities_for(channel).chat_approvals
}
/// If the inbound message is a yes/no reply for a parked approval on
@@ -29,12 +28,14 @@ pub(crate) fn channel_has_approval_surface(channel: &str) -> bool {
/// `web_chat/`.
///
/// [`ApprovalGate::decide`]: crate::security::approval::ApprovalGate::decide
-pub(super) async fn try_route_approval_reply(msg: &traits::ChannelMessage) -> bool {
+pub(super) async fn try_route_approval_reply(
+ msg: &traits::ChannelMessage,
+ thread_id: &str,
+) -> bool {
let Some(gate) = crate::security::approval::ApprovalGate::try_global() else {
return false;
};
- let thread_id = conversation_history_key(msg);
- let Some(request_id) = gate.pending_for_thread(&thread_id) else {
+ let Some(request_id) = gate.pending_for_thread(thread_id) else {
return false;
};
let Some(decision) = crate::security::approval::parse_approval_reply(&msg.content) else {
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
index f6ed313e68..9de2ee4f1b 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -5,8 +5,7 @@
use crate::agent::bus::AgentTurnResponse;
use crate::agent::progress::AgentProgress;
use crate::channels::context::{
- compact_sender_history, conversation_history_key, is_context_window_overflow_error,
- ChannelRuntimeContext,
+ compact_sender_history, is_context_window_overflow_error, ChannelRuntimeContext,
};
use crate::channels::routes::{
get_or_create_turn_model_source, get_route_selection, handle_runtime_command_if_needed,
@@ -42,10 +41,53 @@ pub(crate) async fn process_channel_runtime_message(
ctx: Arc<ChannelRuntimeContext>,
runtime_msg: RuntimeChannelMessage,
) {
+ use tinychannels_bus::module_inbound::{ChannelInboundSource, PrepareChannelInboundRequest};
let RuntimeChannelMessage {
- message: msg,
+ message,
inbound_envelope,
+ authenticated_relay,
+ prepared_inbound,
} = runtime_msg;
+ let prepared = match prepared_inbound {
+ Some(prepared) => prepared,
+ None => {
+ let config = ctx.config.as_deref().cloned().unwrap_or_default();
+ let source = if message.channel.is_empty() {
+ let Some(envelope) = inbound_envelope else {
+ return;
+ };
+ ChannelInboundSource::Envelope {
+ envelope,
+ timestamp: 0,
+ }
+ } else {
+ ChannelInboundSource::Legacy {
+ message,
+ envelope: inbound_envelope,
+ }
+ };
+ match crate::modules::channel_controller::prepare_inbound(
+ &crate::modules::client::ModuleClient::new(config),
+ PrepareChannelInboundRequest {
+ source,
+ namespace: "main".into(),
+ session_policy: Default::default(),
+ },
+ )
+ .await
+ {
+ Ok(prepared) => prepared,
+ Err(error) => {
+ tracing::warn!("[dispatch] channel preparation failed: {error}");
+ return;
+ }
+ }
+ }
+ };
+ let msg = prepared.message;
+ let history_key = prepared.history_key;
+ let mut envelope = prepared.envelope;
+ envelope.delivered_via_upstream_relay = authenticated_relay;
println!(
" 💬 [{}] from {}: {}",
@@ -61,10 +103,7 @@ pub(crate) async fn process_channel_runtime_message(
reply_target: msg.reply_target.clone(),
content: msg.content.clone(),
thread_ts: msg.thread_ts.clone(),
- inbound_envelope: Some(
- inbound_envelope
- .unwrap_or_else(|| tinychannels::inbound_envelope_from_legacy_message(&msg)),
- ),
+ inbound_envelope: Some(envelope),
workspace_dir: ctx.workspace_dir.as_ref().clone(),
});
@@ -79,7 +118,9 @@ pub(crate) async fn process_channel_runtime_message(
// a fresh agent turn would cancel the parked tool call. Any other text
// falls through to the normal dispatch (the user is redirecting). Mirrors
// the same intercept in `web_chat/`.
- if channel_has_approval_surface(&msg.channel) && try_route_approval_reply(&msg).await {
+ if channel_has_approval_surface(&msg.channel)
+ && try_route_approval_reply(&msg, &history_key).await
+ {
return;
}
@@ -139,7 +180,6 @@ pub(crate) async fn process_channel_runtime_message(
}
}
- let history_key = conversation_history_key(&msg);
let route = get_route_selection(ctx.as_ref(), &history_key);
let active_turn_model_source = if ctx.config.is_none() {
match get_or_create_turn_model_source(ctx.as_ref(), &route.provider).await {
diff --git a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
new file mode 100644
index 0000000000..b7b1860812
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -0,0 +1,412 @@
+//! Host adapters over one identity-scoped TinyChannels module object.
+
+use super::callback::ChannelHostCallbacks;
+use super::credentials::hydrate_channel_credentials;
+use crate::channels::runtime::dispatch::RuntimeChannelMessage;
+use crate::channels::traits::{Channel, ChannelMessage, SendMessage};
+use crate::config::Config;
+use crate::modules::channel_runtime::ChannelRuntimeLease;
+use crate::modules::client::{ModuleCallError, ModuleClient, ModuleObjectClient};
+use anyhow::{Context, Result};
+use async_trait::async_trait;
+use std::collections::HashMap;
+use std::sync::{Arc, OnceLock, Weak};
+use std::time::Duration;
+use tinychannels_bus::module_runtime::{
+ ChannelIngressKind, ChannelMessagePreparation, ConfiguredChannelInfo,
+};
+use tinychannels_bus::module_supervision::ChannelSupervisionPolicy;
+use tinychannels_bus::{ChannelInteraction, ChannelInteractionResult, ChannelOutboundIntent};
+use tokio::sync::mpsc;
+
+/// Channel objects sharing one captured config, callback object and module lease.
+pub(super) struct ModuleChannelRuntime {
+ lease: ChannelRuntimeLease,
+ client: ModuleClient,
+ config: tinychannels_bus::ChannelsConfig,
+ proxy: tinychannels_bus::HttpProxyPolicy,
+ infos: Vec<ConfiguredChannelInfo>,
+ relay: Option<tinychannels_bus::module_relay::RelayReservation>,
+ channels: Arc<HashMap<String, Arc<dyn Channel>>>,
+ closed: bool,
+}
+
+#[derive(Clone)]
+struct ModuleChannel {
+ name: String,
+ object: ModuleObjectClient,
+ interaction: tinychannels_bus::ChannelInteractionInfo,
+ relay: Option<tinychannels_bus::module_relay::RelayReservation>,
+ relay_fronted: bool,
+}
+
+impl ModuleChannelRuntime {
+ pub(super) async fn prepare(
+ config: Arc<Config>,
+ context: Arc<OnceLock<Weak<crate::channels::context::ChannelRuntimeContext>>>,
+ dispatch: mpsc::Sender<RuntimeChannelMessage>,
+ ) -> Result<Self> {
+ let client = ModuleClient::new((*config).clone());
+ let callback = ChannelHostCallbacks::new(Arc::clone(&config), context, dispatch);
+ let lease = ChannelRuntimeLease::open(client.clone(), callback)
+ .await
+ .map_err(anyhow::Error::new)
+ .context("channel module runtime unavailable")?;
+ let hydrated = hydrate_channel_credentials(&config);
+ let proxy = channel_proxy(&config);
+ let infos = match lease
+ .object()
+ .call_confidential::<Vec<ConfiguredChannelInfo>>(
+ tinychannels_bus::methods::DESCRIBE_CONFIGURED_CHANNELS,
+ (hydrated.clone(), proxy.clone()),
+ )
+ .await
+ {
+ Ok(infos) => infos,
+ Err(error) => {
+ let _ = lease.close().await;
+ return Err(anyhow::Error::new(error).context("could not describe configured channels"));
+ }
+ };
+ if infos.is_empty() && !relay_configured(&hydrated) {
+ let _ = lease.close().await;
+ anyhow::bail!("no configured channel providers are available");
+ }
+ let relay = if relay_configured(&hydrated) {
+ match lease
+ .object()
+ .call::<tinychannels_bus::module_relay::RelayReservation>(
+ tinychannels_bus::methods::RESERVE_RELAY,
+ (),
+ )
+ .await
+ {
+ Ok(reservation) => Some(reservation),
+ Err(error) => {
+ let _ = lease.close().await;
+ return Err(anyhow::Error::new(error).context("could not reserve channel relay"));
+ }
+ }
+ } else {
+ None
+ };
+ let relay_fronts = |channel: &str| {
+ hydrated.relay.as_ref().is_some_and(|relay| {
+ relay_configured(&hydrated)
+ && relay.identities.iter().any(|identity| identity.platform == channel)
+ })
+ };
+ let channels = infos
+ .iter()
+ .map(|info| {
+ let channel = ModuleChannel {
+ name: info.name.clone(),
+ object: lease.object().clone(),
+ interaction: info.interaction.clone(),
+ relay: relay.clone(),
+ relay_fronted: relay_fronts(&info.name),
+ };
+ (info.name.clone(), Arc::new(channel) as Arc<dyn Channel>)
+ })
+ .collect();
+ Ok(Self {
+ lease,
+ client,
+ config: hydrated,
+ proxy,
+ infos,
+ relay,
+ channels: Arc::new(channels),
+ closed: false,
+ })
+ }
+
+ pub(super) fn channels(&self) -> Arc<HashMap<String, Arc<dyn Channel>>> {
+ Arc::clone(&self.channels)
+ }
+
+ pub(super) async fn start(&mut self, config: &Config) -> Result<()> {
+ let policy = ChannelSupervisionPolicy {
+ initial_backoff_secs: config
+ .reliability
+ .channel_initial_backoff_secs
+ .max(crate::channels::context::DEFAULT_CHANNEL_INITIAL_BACKOFF_SECS),
+ max_backoff_secs: config
+ .reliability
+ .channel_max_backoff_secs
+ .max(crate::channels::context::DEFAULT_CHANNEL_MAX_BACKOFF_SECS),
+ };
+ for info in &self.infos {
+ let member = match info.ingress {
+ ChannelIngressKind::Listener => tinychannels_bus::methods::START_CHANNEL_SUPERVISED,
+ ChannelIngressKind::ExternalWebhook => tinychannels_bus::methods::START_OUTBOUND_CHANNEL,
+ };
+ let result: Result<(), ModuleCallError> = if info.ingress == ChannelIngressKind::Listener {
+ self.lease
+ .object()
+ .call_confidential(
+ member,
+ (info.name.clone(), self.config.clone(), self.proxy.clone(), policy),
+ )
+ .await
+ } else {
+ self.lease
+ .object()
+ .call_confidential(
+ member,
+ (info.name.clone(), self.config.clone(), self.proxy.clone()),
+ )
+ .await
+ };
+ if let Err(error) = result {
+ let _ = self.close().await;
+ return Err(anyhow::Error::new(error).context("channel provider startup failed"));
+ }
+ }
+ if let (Some(reservation), Some(relay)) = (&self.relay, &self.config.relay) {
+ if let Err(error) = self
+ .lease
+ .object()
+ .call_confidential::<()>(
+ tinychannels_bus::methods::START_RELAY,
+ (reservation.clone(), relay.clone()),
+ )
+ .await
+ {
+ let _ = self.close().await;
+ return Err(anyhow::Error::new(error).context("channel relay startup failed"));
+ }
+ }
+ Ok(())
+ }
+
+ pub(super) async fn close(&mut self) -> Result<()> {
+ if self.closed {
+ return Ok(());
+ }
+ self.closed = true;
+ let mut failure = None;
+ if let Some(relay) = &self.relay {
+ if let Err(error) = self
+ .lease
+ .object()
+ .call::<()>(tinychannels_bus::methods::STOP_RELAY, (relay.clone(),))
+ .await
+ {
+ failure = Some(anyhow::Error::new(error));
+ }
+ }
+ if let Err(error) = self.lease.object().call::<()>(tinychannels_bus::methods::SHUTDOWN, ()).await {
+ failure.get_or_insert_with(|| anyhow::Error::new(error));
+ }
+ if let Err(error) = self.lease.close().await {
+ failure.get_or_insert_with(|| anyhow::Error::new(error));
+ }
+ match failure {
+ Some(error) => Err(error),
+ None => Ok(()),
+ }
+ }
+}
+
+impl Drop for ModuleChannelRuntime {
+ fn drop(&mut self) {
+ if self.closed {
+ return;
+ }
+ let lease = self.lease.clone();
+ if let Ok(handle) = tokio::runtime::Handle::try_current() {
+ handle.spawn(async move {
+ let _ = lease.object().call::<()>(tinychannels_bus::methods::SHUTDOWN, ()).await;
+ let _ = lease.close().await;
+ });
+ }
+ }
+}
+
+fn relay_configured(config: &tinychannels_bus::ChannelsConfig) -> bool {
+ config
+ .relay
+ .as_ref()
+ .is_some_and(|relay| !relay.url.is_empty() && !relay.identities.is_empty())
+}
+
+fn channel_proxy(config: &Config) -> tinychannels_bus::HttpProxyPolicy {
+ let configured = crate::channels::commands::configured_providers(config);
+ let selectors = configured
+ .iter()
+ .map(|channel| format!("channel.{channel}"))
+ .filter(|service| config.proxy.should_apply_to_service(service))
+ .collect::<Vec<_>>();
+ if selectors.is_empty() {
+ return tinychannels_bus::HttpProxyPolicy::default();
+ }
+ tinychannels_bus::HttpProxyPolicy {
+ http_proxy: config.proxy.http_proxy.clone(),
+ https_proxy: config.proxy.https_proxy.clone(),
+ all_proxy: config.proxy.all_proxy.clone(),
+ no_proxy: config.proxy.normalized_no_proxy(),
+ service_selectors: selectors,
+ }
+}
+
+#[async_trait]
+impl Channel for ModuleChannel {
+ fn name(&self) -> &str {
+ &self.name
+ }
+
+ fn proactive_target(&self) -> Option<String> {
+ self.interaction.proactive_target.clone()
+ }
+
+ async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
+ self.send_prepared(message).await
+ }
+
+ async fn send_idempotent(&self, message: &SendMessage) -> anyhow::Result<()> {
+ self.send_prepared(message).await
+ }
+
+ async fn listen(&self, _tx: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
+ anyhow::bail!("TinyChannels module owns provider listeners")
+ }
+
+ async fn health_check(&self) -> bool {
+ self.object
+ .call::<String>(tinychannels_bus::methods::CHANNEL_STATUS, (self.name.clone(),))
+ .await
+ .is_ok_and(|state| state == "connected")
+ }
+
+ async fn start_typing(&self, recipient: &str) -> anyhow::Result<()> {
+ self.interact(ChannelInteraction::StartTyping {
+ recipient: recipient.to_owned(),
+ })
+ .await
+ }
+
+ async fn stop_typing(&self, recipient: &str) -> anyhow::Result<()> {
+ self.interact(ChannelInteraction::StopTyping {
+ recipient: recipient.to_owned(),
+ })
+ .await
+ }
+
+ fn capabilities(&self) -> tinychannels_bus::ChannelCapabilities {
+ self.interaction.capabilities.clone()
+ }
+
+ fn supports_reactions(&self) -> bool {
+ self.interaction.supports_reactions
+ }
+
+ fn supports_draft_updates(&self) -> bool {
+ self.interaction.supports_draft_updates
+ }
+
+ async fn send_draft(&self, message: &SendMessage) -> anyhow::Result<Option<String>> {
+ match self
+ .object
+ .call_confidential::<ChannelInteractionResult>(
+ tinychannels_bus::methods::CHANNEL_INTERACTION,
+ tinychannels_bus::ChannelInteractionRequest {
+ channel: self.name.clone(),
+ interaction: ChannelInteraction::SendDraft {
+ message: message.clone(),
+ },
+ },
+ )
+ .await
+ .map_err(anyhow::Error::new)?
+ {
+ ChannelInteractionResult::Draft(id) => Ok(id),
+ _ => anyhow::bail!("channel returned an invalid draft result"),
+ }
+ }
+
+ async fn update_draft(
+ &self,
+ recipient: &str,
+ message_id: &str,
+ text: &str,
+ ) -> anyhow::Result<()> {
+ self.interact(ChannelInteraction::UpdateDraft {
+ recipient: recipient.into(),
+ message_id: message_id.into(),
+ text: text.into(),
+ })
+ .await
+ }
+
+ async fn finalize_draft(
+ &self,
+ recipient: &str,
+ message_id: &str,
+ text: &str,
+ thread_ts: Option<&str>,
+ ) -> anyhow::Result<()> {
+ self.interact(ChannelInteraction::FinalizeDraft {
+ recipient: recipient.into(),
+ message_id: message_id.into(),
+ text: text.into(),
+ thread_ts: thread_ts.map(str::to_owned),
+ })
+ .await
+ }
+}
+
+impl ModuleChannel {
+ async fn send_prepared(&self, message: &SendMessage) -> anyhow::Result<()> {
+ let prepared: tinychannels_bus::module_runtime::PreparedChannelIntent = self
+ .object
+ .call_confidential(
+ tinychannels_bus::methods::PREPARE_OUTBOUND_INTENT,
+ (
+ self.name.clone(),
+ ChannelMessagePreparation::Typed(message.clone()),
+ ),
+ )
+ .await
+ .map_err(anyhow::Error::new)?;
+ let method = if self.relay_fronted && self.relay.is_some() {
+ let result: tinychannels_bus::controllers::ChannelSendMessageResult = self
+ .object
+ .call_confidential(
+ tinychannels_bus::methods::SEND_RELAY_INTENT,
+ (self.relay.clone().expect("checked relay handle"), prepared.intent),
+ )
+ .await
+ .map_err(anyhow::Error::new)?;
+ result
+ } else {
+ self.object
+ .call_confidential::<tinychannels_bus::controllers::ChannelSendMessageResult>(
+ tinychannels_bus::methods::SEND_CHANNEL_INTENT,
+ (self.name.clone(), prepared.intent),
+ )
+ .await
+ .map_err(anyhow::Error::new)?
+ };
+ let _ = method;
+ Ok(())
+ }
+
+ async fn interact(&self, interaction: ChannelInteraction) -> anyhow::Result<()> {
+ match self
+ .object
+ .call_confidential::<ChannelInteractionResult>(
+ tinychannels_bus::methods::CHANNEL_INTERACTION,
+ tinychannels_bus::ChannelInteractionRequest {
+ channel: self.name.clone(),
+ interaction,
+ },
+ )
+ .await
+ .map_err(anyhow::Error::new)?
+ {
+ ChannelInteractionResult::Completed => Ok(()),
+ _ => anyhow::bail!("channel returned an invalid interaction result"),
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/modules/channel_controller.rs b/crates/openhuman-core/src/modules/channel_controller.rs
index 2e3e4e087f..2d966ff17f 100644
--- a/crates/openhuman-core/src/modules/channel_controller.rs
+++ b/crates/openhuman-core/src/modules/channel_controller.rs
@@ -91,6 +91,16 @@ pub(crate) async fn prepare_identity(
.await
}
+/// Prepare provider projections and persisted keys without a linked implementation.
+pub(crate) async fn prepare_inbound(
+ client: &ModuleClient,
+ request: tinychannels_bus::module_inbound::PrepareChannelInboundRequest,
+) -> Result<tinychannels_bus::module_inbound::PreparedChannelInbound, ModuleCallError> {
+ client
+ .call_confidential("tinychannels", methods::PREPARE_CHANNEL_INBOUND, (request,))
+ .await
+}
+
/// Resolve OpenHuman's proxy scope before transmitting provider configuration.
pub(crate) fn discord_proxy(config: &crate::config::Config) -> HttpProxyPolicy {
let proxy = &config.proxy;