Skip to content

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

refactor(channels): migrate inbound handling to envelope-based source

Steven Enamakel5de782522586
diff --git a/crates/openhuman-core/src/channels/host/channel_events.rs b/crates/openhuman-core/src/channels/host/channel_events.rs
index 4af65d06ca..3bcdc5ac45 100644
--- a/crates/openhuman-core/src/channels/host/channel_events.rs
+++ b/crates/openhuman-core/src/channels/host/channel_events.rs
@@ -92,20 +92,32 @@ impl EventHandler<DomainEvent> for ChannelApprovalSurfaceSubscriber {
tinychannels_bus::module_inbound::PrepareChannelInboundRequest {
namespace: "main".into(),
session_policy: Default::default(),
- source: tinychannels_bus::module_inbound::ChannelInboundSource::Legacy {
- message: ChannelMessage {
- id: message_id.clone(),
- channel: channel.clone(),
- sender: sender.clone(),
- reply_target: reply_target.clone(),
- content: content.clone(),
- timestamp: 0,
- thread_ts: thread_ts.clone(),
- sender_name: None,
- reply_to_id: None,
- topic_id: None,
- },
- envelope: inbound_envelope.clone(),
+ source: tinychannels_bus::module_inbound::ChannelInboundSource::Envelope {
+ envelope: inbound_envelope.clone().unwrap_or_else(|| {
+ tinychannels_bus::ChannelInboundEnvelope {
+ channel: tinychannels_bus::ChannelRef {
+ id: channel.clone(),
+ account_id: None,
+ },
+ message_id: message_id.clone(),
+ conversation: tinychannels_bus::ConversationRef {
+ id: reply_target.clone(),
+ thread_id: thread_ts.clone(),
+ ..Default::default()
+ },
+ sender: tinychannels_bus::SenderRef {
+ id: sender.clone(),
+ ..Default::default()
+ },
+ text: content.clone(),
+ parts: vec![tinychannels_bus::channel::ContentPart::Text {
+ text: content.clone(),
+ markdown_dialect: None,
+ }],
+ ..Default::default()
+ }
+ }),
+ timestamp: 0,
},
},
)
@@ -117,8 +129,8 @@ impl EventHandler<DomainEvent> for ChannelApprovalSurfaceSubscriber {
.insert(
prepared.history_key,
ReplyContext {
- reply_target: reply_target.clone(),
- thread_ts: thread_ts.clone(),
+ reply_target: prepared.envelope.conversation.id,
+ thread_ts: prepared.envelope.conversation.thread_id,
},
);
}
@@ -167,10 +179,12 @@ impl EventHandler<DomainEvent> for ChannelApprovalSurfaceSubscriber {
return;
}
let _ = channel
- .send_with_outbound_intent(
- &SendMessage::new(body, &reply.reply_target)
- .in_thread(reply.thread_ts),
- )
+ .send_typed(&text_message(
+ channel.name(),
+ &reply.reply_target,
+ body,
+ reply.thread_ts,
+ ))
.await;
}
Ok(_) => {
diff --git a/crates/openhuman-core/src/channels/outbound.rs b/crates/openhuman-core/src/channels/outbound.rs
index 118228f0c4..f600cf685d 100644
--- a/crates/openhuman-core/src/channels/outbound.rs
+++ b/crates/openhuman-core/src/channels/outbound.rs
@@ -1,7 +1,7 @@
//! Host adapters for canonical TinyChannels outbound messages.
use tinychannels_bus::{
- ChannelOutboundMessage, ChannelOutboundIntent, ChannelRef, ConversationRef, DeliveryDurability,
+ ChannelOutboundIntent, ChannelOutboundMessage, ChannelRef, ConversationRef, DeliveryDurability,
OutboundPayload,
};
@@ -48,8 +48,6 @@ pub(crate) async fn send_draft(
thread_id: Option<String>,
) -> anyhow::Result<Option<String>> {
channel
- .send_draft(
- &tinychannels_bus::SendMessage::new(text, conversation).in_thread(thread_id),
- )
+ .send_draft(&tinychannels_bus::SendMessage::new(text, conversation).in_thread(thread_id))
.await
}
diff --git a/crates/openhuman-core/src/channels/providers/relay/channel.rs b/crates/openhuman-core/src/channels/providers/relay/channel.rs
index d3426ddf8d..0f67ca541b 100644
--- a/crates/openhuman-core/src/channels/providers/relay/channel.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/channel.rs
@@ -11,7 +11,8 @@ use async_trait::async_trait;
use serde_json::json;
use crate::web_chat::{publish_web_channel_event, WebChannelEvent};
-use tinychannels_bus::{Channel, ChannelMessage, SendMessage};
+use tinychannels_bus::channel::{ContentPart, OutboundContentPart};
+use tinychannels_bus::{Channel, ChannelOutboundMessage};
/// The event name a relayed reply is published under.
pub const CHANNEL_OUTBOUND_EVENT: &str = "channel_outbound";
@@ -59,23 +60,27 @@ impl RelayChannel {
/// (`agent`, `profile`) are left for `publish_web_channel_event`, which
/// takes them from the publishing context's tenant, so `/events` hands the
/// reply only to the caller's own stream.
- pub fn outbound_event(&self, message: &SendMessage) -> WebChannelEvent {
- WebChannelEvent {
+ pub fn outbound_event(
+ &self,
+ message: &ChannelOutboundMessage,
+ ) -> anyhow::Result<WebChannelEvent> {
+ let text = outbound_text(message)?;
+ Ok(WebChannelEvent {
event: CHANNEL_OUTBOUND_EVENT.to_string(),
client_id: self.client_id.clone(),
thread_id: self.thread_id.clone(),
request_id: self.request_id.clone(),
- full_response: Some(message.content.clone()),
+ full_response: Some(text),
structured: Some(json!({
"kind": CHANNEL_OUTBOUND_EVENT,
"channel": self.channel,
- "chat_id": message.recipient,
- "thread_ts": message.thread_ts,
+ "chat_id": message.conversation_id,
+ "thread_ts": message.thread_id,
"reply_to_message_id": self.reply_to,
"idempotency_key": message.idempotency_key,
})),
..Default::default()
- }
+ })
}
}
@@ -85,29 +90,80 @@ impl Channel for RelayChannel {
&self.channel
}
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 requires the v21 Channel::send bridge; host sends use send_typed"
+ )]
+ async fn send(&self, message: &tinychannels_bus::SendMessage) -> anyhow::Result<()> {
+ let typed = ChannelOutboundMessage {
+ channel_id: self.channel.clone(),
+ conversation_id: message.recipient.clone(),
+ channel_ref: None,
+ conversation_ref: Some(tinychannels_bus::ConversationRef {
+ id: message.recipient.clone(),
+ thread_id: message.thread_ts.clone(),
+ topic_id: message.topic_id.clone(),
+ ..Default::default()
+ }),
+ reply_to_id: message.reply_to_id.clone(),
+ thread_id: message.thread_ts.clone(),
+ turn_id: None,
+ idempotency_key: message.idempotency_key.clone().unwrap_or_default(),
+ parts: vec![OutboundContentPart::Content {
+ part: ContentPart::Text {
+ text: message.content.clone(),
+ markdown_dialect: None,
+ },
+ }],
+ };
+ self.send_typed(&typed).await
+ }
+
+ async fn send_typed(&self, message: &ChannelOutboundMessage) -> anyhow::Result<()> {
+ let event = self.outbound_event(message)?;
+ let content = outbound_text(message)?;
tracing::debug!(
channel = %self.channel,
thread_id = %self.thread_id,
request_id = %self.request_id,
- chars = message.content.chars().count(),
+ chars = content.chars().count(),
"[channels::relay] publishing channel_outbound"
);
self.sent
.lock()
.unwrap_or_else(|e| e.into_inner())
- .push(message.content.clone());
- publish_web_channel_event(self.outbound_event(message));
+ .push(content);
+ publish_web_channel_event(event);
Ok(())
}
- async fn listen(&self, _tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 still requires the legacy listener method on Channel"
+ )]
+ async fn listen(
+ &self,
+ _tx: tokio::sync::mpsc::Sender<tinychannels_bus::ChannelMessage>,
+ ) -> anyhow::Result<()> {
anyhow::bail!(
"a relayed channel has no listener: its messages arrive through channel_relay_inbound"
)
}
}
+fn outbound_text(message: &ChannelOutboundMessage) -> anyhow::Result<String> {
+ let mut text = String::new();
+ for part in &message.parts {
+ match part {
+ OutboundContentPart::Content {
+ part: ContentPart::Text { text: segment, .. },
+ } => text.push_str(segment),
+ _ => anyhow::bail!("channel relay supports text outbound content only"),
+ }
+ }
+ Ok(text)
+}
+
#[cfg(test)]
#[path = "channel_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index 73869968f5..658d23ceaf 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -9,9 +9,10 @@ use super::channel::RelayChannel;
use super::params::RelayInboundParams;
use super::store::{self, Recorded};
use crate::channels::context::MAX_CHANNEL_HISTORY;
+use crate::channels::outbound::text_message;
use crate::channels::runtime::{
build_channel_turn_parts, prepare_runtime_limits, process_channel_runtime_message,
- runtime_context, PromptToolDescs,
+ runtime_context, PromptToolDescs, RuntimeChannelMessage,
};
use crate::config::Config;
use crate::core::Outcome;
@@ -133,9 +134,9 @@ pub(crate) async fn run_relay_turn(
tracing::warn!("relayed channel runtime limits unavailable: {error}");
let reply =
"⚠️ This chat's assistant is not available right now. Please try again later.";
- let _ = tinychannels_bus::Channel::send(
+ let _ = tinychannels_bus::Channel::send_typed(
channel.as_ref(),
- &crate::channels::SendMessage::new(reply, &params.chat_id),
+ &text_message(&params.channel, &params.chat_id, reply, None),
)
.await;
record(
@@ -170,9 +171,9 @@ pub(crate) async fn run_relay_turn(
);
let reply =
"⚠️ This chat's assistant is not available right now. Please try again later.";
- let _ = tinychannels_bus::Channel::send(
+ let _ = tinychannels_bus::Channel::send_typed(
channel.as_ref(),
- &crate::channels::SendMessage::new(reply, &params.chat_id),
+ &text_message(&params.channel, &params.chat_id, reply, None),
)
.await;
record(
@@ -201,13 +202,13 @@ pub(crate) async fn run_relay_turn(
// The thread is the conversation's memory: seed the pipeline's per-chat
// history from it, since this runtime context lives for one message.
- let message = params.to_channel_message();
+ let message = params.to_inbound_envelope();
let prepared = match crate::modules::channel_controller::prepare_inbound(
&crate::modules::client(config.clone()),
tinychannels_bus::module_inbound::PrepareChannelInboundRequest {
- source: tinychannels_bus::module_inbound::ChannelInboundSource::Legacy {
- message: message.clone(),
- envelope: None,
+ source: tinychannels_bus::module_inbound::ChannelInboundSource::Envelope {
+ envelope: message.clone(),
+ timestamp: 0,
},
namespace: "main".into(),
session_policy: Default::default(),
@@ -250,7 +251,11 @@ pub(crate) async fn run_relay_turn(
request_id = %request_id,
"[channels::relay] dispatching relayed turn"
);
- let mut runtime_message = crate::channels::runtime::RuntimeChannelMessage::from(message);
+ let mut runtime_message = RuntimeChannelMessage {
+ message,
+ authenticated_relay: false,
+ prepared_inbound: Some(prepared),
+ };
runtime_message.prepared_inbound = Some(prepared);
let turn = process_channel_runtime_message(ctx, runtime_message);
if let Some(context) = dispatch_ctx.core() {
diff --git a/crates/openhuman-core/src/channels/providers/relay/params.rs b/crates/openhuman-core/src/channels/providers/relay/params.rs
index 4ea16ce77c..01eb1edb69 100644
--- a/crates/openhuman-core/src/channels/providers/relay/params.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/params.rs
@@ -6,7 +6,9 @@ use serde_json::Value;
#[cfg(test)]
use crate::channels::bus::derive_inbound_thread_id;
-use tinychannels_bus::ChannelMessage;
+use tinychannels_bus::{
+ channel::ContentPart, ChannelInboundEnvelope, ChannelRef, ConversationRef, SenderRef,
+};
/// Longest channel name: `telegram`, `imessage`, `discord`, ...
pub const MAX_CHANNEL_LEN: usize = 32;
@@ -136,24 +138,37 @@ impl RelayInboundParams {
}
/// The message as the channel dispatch pipeline takes it.
- pub(crate) fn to_channel_message(&self) -> ChannelMessage {
- ChannelMessage {
- id: self.message_id.clone(),
- sender: self.sender_id.clone(),
- reply_target: self.chat_id.clone(),
- content: self.text.clone(),
- channel: self.channel.clone(),
- timestamp: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or_default(),
- thread_ts: None,
- sender_name: self
- .sender_name
- .clone()
- .filter(|name| !name.trim().is_empty()),
- reply_to_id: None,
- topic_id: None,
+ pub(crate) fn to_inbound_envelope(&self) -> ChannelInboundEnvelope {
+ ChannelInboundEnvelope {
+ channel: ChannelRef {
+ id: self.channel.clone(),
+ account_id: None,
+ },
+ message_id: self.message_id.clone(),
+ conversation: ConversationRef {
+ id: self.chat_id.clone(),
+ ..Default::default()
+ },
+ sender: SenderRef {
+ id: self.sender_id.clone(),
+ name: self
+ .sender_name
+ .clone()
+ .filter(|name| !name.trim().is_empty()),
+ ..Default::default()
+ },
+ timestamp_unix_ms: Some(
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|duration| duration.as_millis().min(u64::MAX as u128) as u64)
+ .unwrap_or_default(),
+ ),
+ text: self.text.clone(),
+ parts: vec![ContentPart::Text {
+ text: self.text.clone(),
+ markdown_dialect: None,
+ }],
+ ..Default::default()
}
}
}
diff --git a/crates/openhuman-core/src/channels/routes.rs b/crates/openhuman-core/src/channels/routes.rs
index e9662eb629..22e5fae376 100644
--- a/crates/openhuman-core/src/channels/routes.rs
+++ b/crates/openhuman-core/src/channels/routes.rs
@@ -204,7 +204,7 @@ pub(crate) async fn handle_runtime_command_if_needed(
}
Err(_) => {
if let Some(channel) = target_channel {
- let _ = channel
+ let _ = channel
.send_typed(&text_message(
&msg.channel.id,
&msg.conversation.id,
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
index d71268d328..8a38dcdfc6 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
@@ -45,9 +45,7 @@ pub(crate) struct RuntimeChannelMessage {
}
impl RuntimeChannelMessage {
- pub(crate) fn with_inbound_envelope(
- message: ChannelInboundEnvelope,
- ) -> Self {
+ pub(crate) fn with_inbound_envelope(message: ChannelInboundEnvelope) -> Self {
Self {
message,
authenticated_relay: false,
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 1de453b733..f1f6a3c780 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -6,8 +6,8 @@ use crate::agent::bus::AgentTurnResponse;
use crate::channels::context::{
compact_sender_history, is_context_window_overflow_error, ChannelRuntimeContext,
};
-use crate::channels::routes::{get_or_create_turn_model_source, get_route_selection};
use crate::channels::outbound::text_message;
+use crate::channels::routes::{get_or_create_turn_model_source, get_route_selection};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use crate::progress::AgentProgress;
diff --git a/crates/openhuman-core/src/channels/runtime/startup/callback.rs b/crates/openhuman-core/src/channels/runtime/startup/callback.rs
index 2bfe27c65f..e381fd7805 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/callback.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/callback.rs
@@ -82,13 +82,13 @@ impl ChannelHostCallbacks {
return Ok(());
}
- let message: tinychannels_bus::ChannelMessage = serde_json::from_value(message)
+ let message: tinychannels_bus::ChannelInboundEnvelope = serde_json::from_value(message)
.map_err(|_| Error::failed("invalid inbound message"))?;
- if message.channel != channel {
+ if message.channel.id != channel {
return Err(Error::failed("callback channel does not match message"));
}
self.dispatch
- .send(RuntimeChannelMessage::from(message))
+ .send(RuntimeChannelMessage::with_inbound_envelope(message))
.await
.map_err(|_| Error::failed("channel dispatch is closed"))
}
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 b284dd90f7..4c01e2654d 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -14,7 +14,7 @@ use tinychannels_bus::module_runtime::{
ChannelIngressKind, ChannelMessagePreparation, ConfiguredChannelInfo,
};
use tinychannels_bus::module_supervision::ChannelSupervisionPolicy;
-use tinychannels_bus::{Channel, ChannelMessage, SendMessage};
+use tinychannels_bus::Channel;
use tinychannels_bus::{ChannelInteraction, ChannelInteractionResult};
use tokio::sync::mpsc;
@@ -309,15 +309,30 @@ impl Channel for ModuleChannel {
.clone()
}
- async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
- self.send_prepared(message).await
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 requires this v21 trait method; production sends use send_typed"
+ )]
+ async fn send(&self, message: &tinychannels_bus::SendMessage) -> anyhow::Result<()> {
+ let typed = self.legacy_outbound(message);
+ self.send_typed(&typed).await
}
- async fn send_idempotent(&self, message: &SendMessage) -> anyhow::Result<()> {
+ async fn send_typed(
+ &self,
+ message: &tinychannels_bus::ChannelOutboundMessage,
+ ) -> anyhow::Result<()> {
self.send_prepared(message).await
}
- async fn listen(&self, _tx: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 still requires the legacy listener method on Channel"
+ )]
+ async fn listen(
+ &self,
+ _tx: mpsc::Sender<tinychannels_bus::ChannelMessage>,
+ ) -> anyhow::Result<()> {
anyhow::bail!("TinyChannels module owns provider listeners")
}
@@ -393,7 +408,14 @@ impl Channel for ModuleChannel {
self.interaction.capabilities.streaming_reply_pipeline
}
- async fn send_draft(&self, message: &SendMessage) -> anyhow::Result<Option<String>> {
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 exposes drafts only through its v21 interaction DTO"
+ )]
+ async fn send_draft(
+ &self,
+ message: &tinychannels_bus::SendMessage,
+ ) -> anyhow::Result<Option<String>> {
match self
.object
.call_confidential::<ChannelInteractionResult>(
@@ -445,15 +467,61 @@ impl Channel for ModuleChannel {
}
impl ModuleChannel {
- async fn send_prepared(&self, message: &SendMessage) -> anyhow::Result<()> {
+ #[allow(
+ deprecated,
+ reason = "only the required TinyChannels v21 Channel::send bridge accepts SendMessage"
+ )]
+ fn legacy_outbound(
+ &self,
+ message: &tinychannels_bus::SendMessage,
+ ) -> tinychannels_bus::ChannelOutboundMessage {
+ use tinychannels_bus::channel::{ContentPart, OutboundContentPart};
+ tinychannels_bus::ChannelOutboundMessage {
+ channel_id: self.name.clone(),
+ conversation_id: message.recipient.clone(),
+ channel_ref: None,
+ conversation_ref: Some(tinychannels_bus::ConversationRef {
+ id: message.recipient.clone(),
+ thread_id: message.thread_ts.clone(),
+ topic_id: message.topic_id.clone(),
+ ..Default::default()
+ }),
+ reply_to_id: message.reply_to_id.clone(),
+ thread_id: message.thread_ts.clone(),
+ turn_id: None,
+ idempotency_key: message.idempotency_key.clone().unwrap_or_default(),
+ parts: vec![OutboundContentPart::Content {
+ part: ContentPart::Text {
+ text: message.content.clone(),
+ markdown_dialect: None,
+ },
+ }],
+ }
+ }
+
+ async fn send_prepared(
+ &self,
+ message: &tinychannels_bus::ChannelOutboundMessage,
+ ) -> anyhow::Result<()> {
+ let intent = tinychannels_bus::ChannelOutboundIntent {
+ channel_id: message.channel_id.clone(),
+ conversation_id: message.conversation_id.clone(),
+ channel_ref: message.channel_ref.clone(),
+ conversation_ref: message.conversation_ref.clone(),
+ reply_to_id: message.reply_to_id.clone(),
+ thread_id: message.thread_id.clone(),
+ turn_id: message.turn_id.clone(),
+ idempotency_key: message.idempotency_key.clone(),
+ payload: tinychannels_bus::OutboundPayload::Parts {
+ parts: message.parts.clone(),
+ },
+ ..Default::default()
+ };
let prepared: tinychannels_bus::module_runtime::PreparedChannelIntent = self
.object
.call_confidential(
tinychannels_bus::methods::PREPARE_OUTBOUND_INTENT,
- (
- self.name.clone(),
- ChannelMessagePreparation::Typed(message.clone()),
- ),
+ (self.name.clone(), ChannelMessagePreparation::Intent(intent)),
)
.await
.map_err(anyhow::Error::new)?;
diff --git a/crates/openhuman-core/src/channels/runtime/startup/relay.rs b/crates/openhuman-core/src/channels/runtime/startup/relay.rs
index d44f29551e..dd22db139d 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/relay.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/relay.rs
@@ -29,9 +29,8 @@ impl tinychannels::relay::RelayInboundHandler for RelayInboundMessageHandler {
"invalid inbound envelope: {error}"
))
})?;
- let msg = tinychannels::legacy_message_from_inbound_envelope(&envelope, 0);
self.tx
- .send(RuntimeChannelMessage::with_inbound_envelope(msg, envelope))
+ .send(RuntimeChannelMessage::with_inbound_envelope(envelope))
.await
.map_err(|_| tinychannels::relay::RelayTransportError::Closed)
}
diff --git a/crates/openhuman-core/src/channels/runtime/test_support.rs b/crates/openhuman-core/src/channels/runtime/test_support.rs
index 60c78488dd..1b6efbe5bb 100644
--- a/crates/openhuman-core/src/channels/runtime/test_support.rs
+++ b/crates/openhuman-core/src/channels/runtime/test_support.rs
@@ -22,7 +22,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tinychannels_bus::context::ChatMessage;
-use tinychannels_bus::{ChannelMessage, SendMessage};
+use tinychannels_bus::{ChannelInboundEnvelope, ChannelOutboundMessage, ChannelRef, ConversationRef, SenderRef};
use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};
use tinytools::{Tool, ToolResult};
@@ -158,7 +158,11 @@ impl Channel for HarnessChannel {
&self.name
}
- async fn send(&self, message: &SendMessage) -> Result<()> {
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 requires the v21 Channel::send test-double method"
+ )]
+ async fn send(&self, message: &tinychannels_bus::SendMessage) -> Result<()> {
self.state.sends.lock().await.push(ObservedSend {
kind: "send",
recipient: message.recipient.clone(),
@@ -168,7 +172,24 @@ impl Channel for HarnessChannel {
Ok(())
}
- async fn listen(&self, _tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> Result<()> {
+ async fn send_typed(&self, message: &ChannelOutboundMessage) -> Result<()> {
+ self.state.sends.lock().await.push(ObservedSend {
+ kind: "send",
+ recipient: message.conversation_id.clone(),
+ content: outbound_text(message)?,
+ thread_ts: message.thread_id.clone(),
+ });
+ Ok(())
+ }
+
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 still requires the legacy listener method on Channel"
+ )]
+ async fn listen(
+ &self,
+ _tx: tokio::sync::mpsc::Sender<tinychannels_bus::ChannelMessage>,
+ ) -> Result<()> {
Ok(())
}
@@ -190,7 +211,14 @@ impl Channel for HarnessChannel {
self.streaming
}
- async fn send_draft(&self, message: &SendMessage) -> Result<Option<String>> {
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v0.1.39 exposes drafts only through its v21 test-double method"
+ )]
+ async fn send_draft(
+ &self,
+ message: &tinychannels_bus::SendMessage,
+ ) -> Result<Option<String>> {
self.state.sends.lock().await.push(ObservedSend {
kind: "draft",
recipient: message.recipient.clone(),
@@ -227,6 +255,19 @@ impl Channel for HarnessChannel {
}
}
+fn outbound_text(message: &ChannelOutboundMessage) -> Result<String> {
+ let mut text = String::new();
+ for part in &message.parts {
+ match part {
+ tinychannels_bus::channel::OutboundContentPart::Content {
+ part: tinychannels_bus::channel::ContentPart::Text { text: segment, .. },
+ } => text.push_str(segment),
+ _ => anyhow::bail!("test channel supports text outbound content only"),
+ }
+ }
+ Ok(text)
+}
+
struct HarnessModel;
#[async_trait]
@@ -437,27 +478,34 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHa
let expected_event_channel = options.channel_name.clone();
- let message = ChannelMessage {
- id: "m1".to_string(),
- sender: "alice".to_string(),
- reply_target: "reply".to_string(),
- content: options.content,
- channel: options.channel_name,
- timestamp: 1,
- thread_ts: options.thread_ts,
- sender_name: None,
- reply_to_id: None,
- topic_id: None,
- };
- if let Some(inbound_envelope) = options.inbound_envelope {
- process_channel_runtime_message(
- Arc::clone(&ctx),
- RuntimeChannelMessage::with_inbound_envelope(message, inbound_envelope),
- )
- .await;
- } else {
- process_channel_message(Arc::clone(&ctx), message).await;
- }
+ let message = options.inbound_envelope.unwrap_or_else(|| ChannelInboundEnvelope {
+ channel: ChannelRef {
+ id: options.channel_name,
+ account_id: None,
+ },
+ message_id: "m1".to_string(),
+ conversation: ConversationRef {
+ id: "reply".to_string(),
+ thread_id: options.thread_ts,
+ ..Default::default()
+ },
+ sender: SenderRef {
+ id: "alice".to_string(),
+ ..Default::default()
+ },
+ timestamp_unix_ms: Some(1),
+ text: options.content.clone(),
+ parts: vec![tinychannels_bus::channel::ContentPart::Text {
+ text: options.content,
+ markdown_dialect: None,
+ }],
+ ..Default::default()
+ });
+ process_channel_runtime_message(
+ Arc::clone(&ctx),
+ RuntimeChannelMessage::with_inbound_envelope(message),
+ )
+ .await;
let received_event_envelope = loop {
match event_rx.try_recv() {
diff --git a/crates/openhuman-core/src/cron/channel_bridge.rs b/crates/openhuman-core/src/cron/channel_bridge.rs
index 5feffb8fe5..9c9c0f0208 100644
--- a/crates/openhuman-core/src/cron/channel_bridge.rs
+++ b/crates/openhuman-core/src/cron/channel_bridge.rs
@@ -11,7 +11,10 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use tinychannels_bus::context::ChatMessage;
-use tinychannels_bus::{Channel, SendMessage};
+use tinychannels_bus::{
+ Channel, ChannelOutboundIntent, ChannelRef, ConversationRef, DeliveryDurability,
+ OutboundPayload,
+};
/// Same shape as `channels::context::ConversationHistoryMap`, spelled out so
/// cron does not depend on the feature-gated `channels` module.
@@ -120,9 +123,27 @@ pub async fn send_to_channel(
// Run-specific key: a retry after an ambiguous send must not duplicate the
// reminder, while identical reminders from different runs must not collide
// (the content-derived default key would reuse one key for both).
- let mut message = SendMessage::new(text, reply_target).in_thread(thread_id.map(str::to_string));
- message.idempotency_key = Some(idempotency_key.to_string());
- ch.send(&message)
+ let message = tinychannels_bus::ChannelOutboundMessage::from_intent(&ChannelOutboundIntent {
+ idempotency_key: idempotency_key.to_owned(),
+ channel_id: key.clone(),
+ conversation_id: reply_target.to_owned(),
+ channel_ref: Some(ChannelRef {
+ id: key,
+ account_id: None,
+ }),
+ conversation_ref: Some(ConversationRef {
+ id: reply_target.to_owned(),
+ thread_id: thread_id.map(str::to_owned),
+ ..Default::default()
+ }),
+ thread_id: thread_id.map(str::to_owned),
+ durability: DeliveryDurability::Required,
+ payload: OutboundPayload::Text {
+ text: text.to_owned(),
+ },
+ ..Default::default()
+ });
+ ch.send_typed(&message)
.await
.map_err(|e| format!("channel send failed: {e}"))
}
diff --git a/crates/openhuman-core/src/cron/channel_bridge_tests.rs b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
index ac9be981e8..bbcadd7b6f 100644
--- a/crates/openhuman-core/src/cron/channel_bridge_tests.rs
+++ b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
@@ -1,7 +1,12 @@
use super::*;
use async_trait::async_trait;
use std::sync::atomic::{AtomicUsize, Ordering};
-use tinychannels_bus::ChannelMessage;
+use tinychannels_bus::ChannelOutboundMessage;
+#[allow(
+ deprecated,
+ reason = "the v22 Channel trait retains these required compatibility signatures"
+)]
+use tinychannels_bus::{ChannelMessage, SendMessage};
use tokio::sync::mpsc;
struct MockChannel {
@@ -14,6 +19,10 @@ impl Channel for MockChannel {
fn name(&self) -> &str {
"telegram"
}
+ #[allow(
+ deprecated,
+ reason = "the v22 Channel trait retains this required compatibility method"
+ )]
async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
self.sends.fetch_add(1, Ordering::SeqCst);
*self.last_target.lock().unwrap() = format!(
@@ -23,6 +32,21 @@ impl Channel for MockChannel {
);
Ok(())
}
+ async fn send_typed(&self, message: &ChannelOutboundMessage) -> anyhow::Result<()> {
+ self.sends.fetch_add(1, Ordering::SeqCst);
+ *self.last_target.lock().unwrap() = format!(
+ "{}|{}|{}|{}",
+ message.conversation_id,
+ message.thread_id.as_deref().unwrap_or_default(),
+ message.idempotency_key,
+ message.channel_id,
+ );
+ Ok(())
+ }
+ #[allow(
+ deprecated,
+ reason = "the v22 Channel trait retains this required compatibility method"
+ )]
async fn listen(&self, _tx: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
Ok(())
}
@@ -68,8 +92,8 @@ async fn bridge_reads_appends_trims_and_sends() {
assert_eq!(sends.load(Ordering::SeqCst), 1);
assert_eq!(
*last_target.lock().unwrap(),
- "42|cron:j:r1",
- "the send carries the run-specific idempotency key"
+ "42||cron:j:r1|telegram",
+ "the typed send carries its address and run-specific idempotency key"
);
assert!(send_to_channel("slack", "42", None, "hi", "k")
.await
diff --git a/crates/openhuman-core/src/threads/store/bus.rs b/crates/openhuman-core/src/threads/store/bus.rs
index 1a793edefe..7769b52df5 100644
--- a/crates/openhuman-core/src/threads/store/bus.rs
+++ b/crates/openhuman-core/src/threads/store/bus.rs
@@ -32,9 +32,11 @@ use serde_json::json;
use crate::core::events::DomainEvent;
use tinybus::EventHandler;
use tinybus::SubscriptionHandle;
-use tinychannels_bus::ChannelMessage;
+use tinychannels_bus::{
+ ChannelInboundEnvelope, ChannelRef, ContentPart, ConversationRef, SenderRef,
+};
#[cfg(test)]
-use tinychannels_runtime::context::conversation_history_key;
+use tinychannels_runtime::context::conversation_history_key_parts;
use super::{
append_message, ensure_thread, get_messages, ConversationMessage, CreateConversationThread,
@@ -340,7 +342,7 @@ struct ChannelTurnDescriptor<'a> {
sender: &'a str,
reply_target: &'a str,
thread_ts: Option<&'a str>,
- inbound_envelope: Option<&'a tinychannels_bus::ChannelInboundEnvelope>,
+ inbound_envelope: Option<&'a ChannelInboundEnvelope>,
content: &'a str,
role: &'a str,
success: Option<bool>,
@@ -350,6 +352,47 @@ struct ChannelTurnDescriptor<'a> {
source: &'a str,
}
+/// Project the older event fields into the v22 envelope used by the module
+/// persistence contract. Match TinyChannels' legacy projection, including its
+/// Telegram topic interpretation, while keeping deprecated wire DTOs out of
+/// the host call.
+fn legacy_descriptor_envelope(descriptor: &ChannelTurnDescriptor<'_>) -> ChannelInboundEnvelope {
+ let thread_ts = descriptor
+ .thread_ts
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(str::to_owned);
+ let provider = descriptor.channel.split(':').next().unwrap_or_default();
+ let (thread_id, topic_id) = if matches!(provider, "telegram" | "tg") {
+ (None, thread_ts)
+ } else {
+ (thread_ts, None)
+ };
+ ChannelInboundEnvelope {
+ channel: ChannelRef {
+ id: descriptor.channel.to_owned(),
+ account_id: None,
+ },
+ message_id: descriptor.message_id.to_owned(),
+ conversation: ConversationRef {
+ id: descriptor.reply_target.to_owned(),
+ thread_id,
+ topic_id,
+ ..Default::default()
+ },
+ sender: SenderRef {
+ id: descriptor.sender.to_owned(),
+ ..Default::default()
+ },
+ text: descriptor.content.to_owned(),
+ parts: vec![ContentPart::Text {
+ text: descriptor.content.to_owned(),
+ markdown_dialect: None,
+ }],
+ ..Default::default()
+ }
+}
+
async fn persist_channel_turn(
_ctx: &DispatchCtx,
workspace_dir: &Path,
@@ -374,20 +417,14 @@ async fn persist_channel_turn(
tinychannels_bus::module_inbound::PrepareChannelInboundRequest {
namespace: "main".into(),
session_policy: Default::default(),
- source: tinychannels_bus::module_inbound::ChannelInboundSource::Legacy {
- message: ChannelMessage {
- id: descriptor.message_id.into(),
- sender: descriptor.sender.into(),
- reply_target: descriptor.reply_target.into(),
- content: descriptor.content.into(),
- channel: descriptor.channel.into(),
- timestamp: 0,
- thread_ts: descriptor.thread_ts.map(ToOwned::to_owned),
- sender_name: None,
- reply_to_id: None,
- topic_id: None,
- },
- envelope: descriptor.inbound_envelope.cloned(),
+ source: tinychannels_bus::module_inbound::ChannelInboundSource::Envelope {
+ envelope: descriptor
+ .inbound_envelope
+ .cloned()
+ .unwrap_or_else(|| legacy_descriptor_envelope(&descriptor)),
+ // The old host-side projection used timestamp 0; keep that value when
+ // reconstructing the module's prepared legacy message.
+ timestamp: 0,
},
},
),
@@ -480,18 +517,7 @@ fn persisted_channel_thread_id(
reply_target: &str,
thread_ts: Option<&str>,
) -> String {
- let key = conversation_history_key(&ChannelMessage {
- id: String::new(),
- sender: sender.to_string(),
- reply_target: reply_target.to_string(),
- content: String::new(),
- channel: channel.to_string(),
- timestamp: 0,
- thread_ts: thread_ts.map(ToOwned::to_owned),
- sender_name: None,
- reply_to_id: None,
- topic_id: None,
- });
+ let key = conversation_history_key_parts(channel, sender, reply_target, thread_ts);
format!("channel:{key}")
}