Skip to content

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

refactor(channels): route channel control decisions through the module

Steven Enamakel9b71bf0c516f
diff --git a/crates/openhuman-core/src/channels/context.rs b/crates/openhuman-core/src/channels/context.rs
index 9821ec0f4f..24e00ad1f2 100644
--- a/crates/openhuman-core/src/channels/context.rs
+++ b/crates/openhuman-core/src/channels/context.rs
@@ -12,15 +12,15 @@ use std::sync::{Arc, Mutex};
use tinyagents_session::transcript::TranscriptMessage;
use tinytools::Tool;
-pub(crate) use tinychannels::context::{
- effective_channel_message_timeout_secs, ChannelRouteSelection,
+pub(crate) use tinychannels_bus::context::{
+ ChannelRouteSelection,
CHANNEL_HISTORY_COMPACT_CONTENT_CHARS, CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES,
CHANNEL_MESSAGE_TIMEOUT_SECS, CHANNEL_TYPING_REFRESH_INTERVAL_SECS,
DEFAULT_CHANNEL_INITIAL_BACKOFF_SECS, DEFAULT_CHANNEL_MAX_BACKOFF_SECS, MAX_CHANNEL_HISTORY,
};
#[cfg(test)]
-pub(crate) use tinychannels::context::MIN_CHANNEL_MESSAGE_TIMEOUT_SECS;
+pub(crate) use tinychannels::context::{MIN_CHANNEL_MESSAGE_TIMEOUT_SECS, effective_channel_message_timeout_secs};
/// Per-sender conversation history for channel messages.
pub(crate) type ConversationHistoryMap = Arc<Mutex<HashMap<String, Vec<TranscriptMessage>>>>;
@@ -68,6 +68,7 @@ pub(crate) async fn module_client(ctx: &ChannelRuntimeContext) -> crate::modules
crate::modules::client::ModuleClient::new(ctx.config.as_deref().cloned().unwrap_or_default())
}
+#[cfg(test)]
pub(crate) fn conversation_history_key(msg: &super::traits::ChannelMessage) -> String {
tinychannels::context::conversation_history_key(msg)
}
@@ -109,8 +110,15 @@ pub(crate) fn compact_sender_history(ctx: &ChannelRuntimeContext, sender_key: &s
true
}
-pub(crate) fn is_context_window_overflow_error(err: &anyhow::Error) -> bool {
- tinychannels::context::is_context_window_overflow_message(&err.to_string())
+pub(crate) async fn is_context_window_overflow_error(ctx: &ChannelRuntimeContext, err: &anyhow::Error) -> Result<bool, crate::modules::client::ModuleCallError> {
+ use tinychannels_bus::module_control::{ChannelControlRequest, ChannelControlResult};
+ match module_client(ctx).await.call_confidential("tinychannels", tinychannels_bus::methods::PREPARE_CHANNEL_CONTROL, (ChannelControlRequest::Overflow { message: err.to_string() },)).await? {
+ ChannelControlResult::Overflow(overflow) => Ok(overflow),
+ _ => {
+ crate::modules::client::ModuleClient::report_malformed_reply("tinychannels");
+ Err(crate::modules::client::ModuleCallError::ModuleFault)
+ }
+ }
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index 7b39011c63..6f2a7fdc17 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -139,7 +139,12 @@ pub(crate) async fn run_relay_turn(
let mut channels_by_name: HashMap<String, Arc<dyn crate::channels::Channel>> = HashMap::new();
channels_by_name.insert(params.channel.clone(), channel.clone());
- let ctx = Arc::new(runtime_context(&config, parts, Arc::new(channels_by_name)));
+ let ctx = Arc::new(runtime_context(
+ &config,
+ parts,
+ Arc::new(channels_by_name),
+ None,
+ ));
// The thread is the conversation's memory: seed the pipeline's per-chat
// history from it, since this runtime context lives for one message.
diff --git a/crates/openhuman-core/src/channels/routes.rs b/crates/openhuman-core/src/channels/routes.rs
index cbb1a811d1..39d3492dd2 100644
--- a/crates/openhuman-core/src/channels/routes.rs
+++ b/crates/openhuman-core/src/channels/routes.rs
@@ -145,7 +145,7 @@ pub(crate) async fn handle_runtime_command_if_needed(
let operation = async {
let lease = crate::modules::channel_runtime::ChannelRuntimeLease::open(client, RouteCallbacks {
context: ctx.clone(),
- cancellation: super::runtime::session::capture_channel_cancellation(),
+ cancellation: super::runtime::session::channel_session(),
}).await?;
let response: Result<ChannelControlResult, _> = lease.object().call_confidential(tinychannels_bus::methods::PREPARE_CHANNEL_CONTROL, (ChannelControlRequest::Route {
workspace_dir: ctx.workspace_dir.to_string_lossy().into_owned(),
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs b/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs
index 3ec2a7d5c1..cc1c43d933 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs
@@ -6,7 +6,12 @@ use crate::channels::traits;
/// Maximum characters shown in the debug reply println.
pub(super) const REPLY_LOG_TRUNCATE_CHARS: usize = 200;
-pub(super) use tinychannels::runtime::{log_worker_join_result, select_acknowledgment_reaction};
+#[cfg(test)]
+pub(super) use tinychannels::runtime::select_acknowledgment_reaction;
+
+pub(super) fn log_worker_join_result(result: Result<(), tokio::task::JoinError>) {
+ if let Err(error) = result { tracing::warn!("channel worker failed: {error}"); }
+}
/// Start the portable typing lifecycle with OpenHuman's configured interval.
pub(super) fn spawn_scoped_typing_task(
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs b/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
index 7c7de72daa..433662df47 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
@@ -28,7 +28,9 @@ use processor::channel_has_approval_surface;
// Re-export internal helpers accessed by test_support (cfg(any(test,
// debug_assertions))) and the inline #[cfg(test)] modules via `super::*`.
#[cfg(any(test, debug_assertions))]
-use helpers::{build_channel_context_block, select_acknowledgment_reaction};
+use helpers::build_channel_context_block;
+#[cfg(test)]
+use helpers::select_acknowledgment_reaction;
#[cfg(test)]
use routing::{build_visible_tool_set, AgentScoping};
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 f13bca1104..1bf21a7c7e 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -22,8 +22,7 @@ use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
use super::super::helpers::{
- build_channel_context_block, log_worker_join_result, select_acknowledgment_reaction,
- spawn_scoped_typing_task, REPLY_LOG_TRUNCATE_CHARS,
+ build_channel_context_block, log_worker_join_result, spawn_scoped_typing_task, REPLY_LOG_TRUNCATE_CHARS,
};
use super::super::host_agent::{self, run_host_agent_turn, seed_rows, HostChannelTurn, HostRoute};
use super::approval::{channel_has_approval_surface, try_route_approval_reply};
@@ -158,7 +157,13 @@ pub(crate) async fn process_channel_runtime_message(
let mut _acknowledgment_task = None;
if let Some(channel) = target_channel.as_ref() {
if channel.supports_reactions() && msg.thread_ts.is_some() {
- let ack_emoji = select_acknowledgment_reaction(&msg.content);
+ let ack_result = crate::channels::context::module_client(&ctx).await.call_confidential::<tinychannels_bus::module_control::ChannelControlResult>("tinychannels", tinychannels_bus::methods::PREPARE_CHANNEL_CONTROL, (tinychannels_bus::module_control::ChannelControlRequest::Acknowledgment { content: msg.content.clone() },)).await;
+ let ack_emoji = match ack_result {
+ Ok(tinychannels_bus::module_control::ChannelControlResult::Acknowledgment(emoji)) => Some(emoji),
+ Ok(_) => { crate::modules::client::ModuleClient::report_malformed_reply("tinychannels"); None },
+ Err(_) => None,
+ };
+ if let Some(ack_emoji) = ack_emoji {
tracing::debug!(
channel = msg.channel,
emoji = ack_emoji,
@@ -176,6 +181,7 @@ pub(crate) async fn process_channel_runtime_message(
tracing::debug!("[dispatch] Acknowledgment reaction failed: {e}");
}
})));
+ }
}
}
@@ -498,7 +504,7 @@ pub(crate) async fn process_channel_runtime_message(
(true, response_text, resolved_provider, resolved_model)
}
Ok(Err(e)) => {
- if is_context_window_overflow_error(&e) {
+ if is_context_window_overflow_error(&ctx, &e).await.unwrap_or(false) {
let compacted = compact_sender_history(ctx.as_ref(), &history_key);
let error_text = if compacted {
"⚠️ Context window exceeded for this conversation. I compacted recent history and kept the latest context. Please resend your last message."
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 be4c33508e..a7f3b77dea 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -129,6 +129,39 @@ impl ModuleChannelRuntime {
Arc::clone(&self.channels)
}
+ pub(super) async fn runtime_limits(
+ &self,
+ timeout_secs: u64,
+ listener_count: usize,
+ ) -> Result<(u64, usize)> {
+ use tinychannels_bus::module_control::{ChannelControlRequest, ChannelControlResult};
+
+ let result: ChannelControlResult = self
+ .lease
+ .object()
+ .call_confidential(
+ tinychannels_bus::methods::PREPARE_CHANNEL_CONTROL,
+ (ChannelControlRequest::RuntimeLimits {
+ timeout_secs,
+ listener_count,
+ },),
+ )
+ .await?;
+ match result {
+ ChannelControlResult::RuntimeLimits {
+ timeout_secs,
+ max_in_flight,
+ } if timeout_secs >= 30 && max_in_flight > 0 => {
+ Ok((timeout_secs, max_in_flight))
+ }
+ _ => {
+ ModuleClient::report_malformed_reply("tinychannels");
+ Err(anyhow::Error::new(ModuleCallError::ModuleFault)
+ .context("channel runtime returned invalid runtime limits"))
+ }
+ }
+ }
+
pub(super) async fn start(&mut self, config: &Config) -> Result<()> {
let policy = ChannelSupervisionPolicy {
initial_backoff_secs: config
diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
index d910093374..ac035a582a 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
@@ -239,8 +239,11 @@ async fn start_channels_inner(mut config: Config, session: CancellationToken) ->
tracing::debug!("[channels] registered turn-state and approval-surface subscribers");
let listener_count = channels.len() + usize::from(relay_configured);
- let max_in_flight_messages =
- tinychannels::runtime::compute_max_in_flight_messages(listener_count);
+ let (message_timeout_secs, max_in_flight_messages) = module_runtime
+ .as_ref()
+ .expect("runtime prepared when providers are configured")
+ .runtime_limits(config.channels_config.message_timeout_secs, listener_count)
+ .await?;
println!(" 🚦 In-flight message limit: {max_in_flight_messages}");
@@ -248,6 +251,7 @@ async fn start_channels_inner(mut config: Config, session: CancellationToken) ->
&config,
parts,
Arc::clone(&channels_by_name),
+ Some(message_timeout_secs),
));
context_slot
.set(Arc::downgrade(&runtime_ctx))
diff --git a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
index e1abec1d33..57eae582c6 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
@@ -232,6 +232,7 @@ pub(crate) fn runtime_context(
config: &Config,
parts: ChannelTurnParts,
channels_by_name: Arc<HashMap<String, Arc<dyn crate::channels::Channel>>>,
+ prepared_message_timeout_secs: Option<u64>,
) -> ChannelRuntimeContext {
ChannelRuntimeContext {
channels_by_name,
@@ -250,9 +251,9 @@ pub(crate) fn runtime_context(
reliability: Arc::new(config.reliability.clone()),
provider_runtime_options: parts.provider_runtime_options,
workspace_dir: Arc::new(config.workspace_dir.clone()),
- message_timeout_secs: effective_channel_message_timeout_secs(
- config.channels_config.message_timeout_secs,
- ),
+ message_timeout_secs: prepared_message_timeout_secs.unwrap_or_else(|| {
+ effective_channel_message_timeout_secs(config.channels_config.message_timeout_secs)
+ }),
multimodal: config.multimodal.clone(),
multimodal_files: config.multimodal_files.clone(),
// Crate-native turn models for the channel turn (Phase 3 P3-B).