The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(channels): route runtime commands through the channel module
Steven Enamakelca9714cfe14a
diff --git a/crates/openhuman-core/src/channels/routes.rs b/crates/openhuman-core/src/channels/routes.rsindex fcd83626bf..cbb1a811d1 100644--- a/crates/openhuman-core/src/channels/routes.rs+++ b/crates/openhuman-core/src/channels/routes.rs@@ -1,27 +1,26 @@//! Per-sender routing and runtime command handling.use super::context::{- clear_sender_history, conversation_history_key, ChannelRouteSelection, ChannelRuntimeContext,+ clear_sender_history, ChannelRouteSelection, ChannelRuntimeContext,};use super::traits;use super::{Channel, ChannelSendExt, SendMessage};use crate::inference::provider;use std::sync::Arc;-use tinychannels::remote::RemoteCommandContext;-use tinychannels::remote::{execute_remote_command, parse_remote_command, RemoteCommand};-use tinychannels::routes::{- build_models_help_response, build_providers_help_response,- parse_runtime_command as parse_portable_runtime_command,- resolve_provider_alias as resolve_portable_provider_alias,- ChannelRuntimeCommand as PortableCommand, ProviderDescriptor,-};+#[cfg(test)]+use tinychannels::remote::{parse_remote_command, RemoteCommand};+use tinychannels_bus::module_control::{ChannelControlRequest, ChannelControlResult, ProviderDescriptor};+#[cfg(test)]+use tinychannels::routes::{parse_runtime_command as parse_portable_runtime_command, resolve_provider_alias as resolve_portable_provider_alias, ChannelRuntimeCommand as PortableCommand};+#[cfg(test)]#[derive(Debug, Clone, PartialEq, Eq)]enum ChannelRuntimeCommand {Portable(PortableCommand),Remote(RemoteCommand),}+#[cfg(test)]fn parse_runtime_command(channel_name: &str, content: &str) -> Option<ChannelRuntimeCommand> {let trimmed = content.trim();if !trimmed.starts_with('/') {@@ -37,6 +36,7 @@ fn parse_runtime_command(channel_name: &str, content: &str) -> Option<ChannelRunparse_portable_runtime_command(channel_name, trimmed).map(ChannelRuntimeCommand::Portable)}+#[cfg(test)]fn resolve_provider_alias(name: &str) -> Option<String> {resolve_portable_provider_alias(name, &provider_descriptors())}@@ -108,90 +108,80 @@ pub(crate) async fn get_or_create_turn_model_source()}+struct RouteCallbacks {+ context: ChannelRuntimeContext,+ cancellation: tokio_util::sync::CancellationToken,+}++#[tinybus::interface(name = "ai.tinyhumans.tinychannels.ChannelsHost")]+impl RouteCallbacks {+ async fn dispatch_controller_backend(&self, request: tinychannels_bus::ChannelBackendRequest) -> tinybus::Result<tinychannels_bus::ChannelBackendResult> {+ if self.cancellation.is_cancelled() {+ return Err(tinybus::Error::failed("channel session ended"));+ }+ match request {+ tinychannels_bus::ChannelBackendRequest::RemoteControl(request) => {+ super::host::remote_control::dispatch_callback(&self.context, request).await.map(tinychannels_bus::ChannelBackendResult::RemoteControl)+ }+ _ => Err(tinybus::Error::failed("channel callback unavailable")),+ }+ }+}+pub(crate) async fn handle_runtime_command_if_needed(ctx: &ChannelRuntimeContext,msg: &traits::ChannelMessage,target_channel: Option<&Arc<dyn Channel>>,+ sender_key: &str,) -> bool {- let Some(command) = parse_runtime_command(&msg.channel, &msg.content) else {+ // This is a host dispatch hint; the module alone parses and recognizes+ // commands. Ordinary messages avoid creating a private callback object.+ if !msg.content.trim_start().starts_with('/') {return false;- };-- let Some(channel) = target_channel else {- return true;- };-- let sender_key = conversation_history_key(msg);- let mut current = get_route_selection(ctx, &sender_key);-- let response = match command {- ChannelRuntimeCommand::Remote(remote) => {- let host = super::host::remote_control::RuntimeRemoteControl { ctx };- let remote_ctx = RemoteCommandContext {- channel: msg.channel.clone(),- reply_target: msg.reply_target.clone(),- sender_key: sender_key.clone(),- workspace_dir: ctx.workspace_dir.to_path_buf(),- };- execute_remote_command(&host, &remote_ctx, remote).await- }- ChannelRuntimeCommand::Portable(PortableCommand::ShowProviders) => {- build_providers_help_response(¤t, &provider_descriptors())- }- ChannelRuntimeCommand::Portable(PortableCommand::SetProvider(raw_provider)) => {- match resolve_provider_alias(&raw_provider) {- Some(provider_name) => {- tracing::debug!(- provider = %provider_name,- "[channels] validated crate-native provider route from catalog"- );- if provider_name != current.provider {- current.provider = provider_name.clone();- set_route_selection(ctx, &sender_key, current.clone());- clear_sender_history(ctx, &sender_key);- }- format!(- "Provider switched to `{provider_name}` for this sender session. Current model is `{}`.\nUse `/model <model-id>` to set a provider-compatible model.",- current.model- )- }- None => format!(- "Unknown provider `{raw_provider}`. Use `/models` to list valid providers."- ),- }- }- ChannelRuntimeCommand::Portable(PortableCommand::ShowModel) => {- build_models_help_response(¤t, ctx.workspace_dir.as_path())+ }+ let current = get_route_selection(ctx, sender_key);+ let history_len = ctx.conversation_histories.lock().unwrap_or_else(|e| e.into_inner()).get(sender_key).map(Vec::len).unwrap_or(0);+ let client = super::context::module_client(ctx).await;+ let operation = async {+ let lease = crate::modules::channel_runtime::ChannelRuntimeLease::open(client, RouteCallbacks {+ context: ctx.clone(),+ cancellation: super::runtime::session::capture_channel_cancellation(),+ }).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(),+ message: Box::new(msg.clone()),+ route: tinychannels_bus::module_remote::RemoteRoute { provider: current.provider, model: current.model },+ history_len,+ providers: provider_descriptors(),+ },)).await;+ let close = lease.close().await;+ let response = response?;+ close?;+ Ok::<_, crate::modules::client::ModuleCallError>(response)+ }.await;+ let (reply, next_route, clear_history) = match operation {+ Ok(ChannelControlResult::Route { reply, next_route, clear_history }) => (reply, next_route, clear_history),+ Ok(_) => {+ crate::modules::client::ModuleClient::report_malformed_reply("tinychannels");+ return true;}- ChannelRuntimeCommand::Portable(PortableCommand::SetModel(raw_model)) => {- let model = raw_model.trim().trim_matches('`').to_string();- if model.is_empty() {- "Model ID cannot be empty. Use `/model <model-id>`.".to_string()- } else {- current.model = model.clone();- set_route_selection(ctx, &sender_key, current.clone());- clear_sender_history(ctx, &sender_key);-- format!(- "Model switched to `{model}` for provider `{}` in this sender session.",- current.provider- )+ Err(_) => {+ if let Some(channel) = target_channel {+ let _ = channel.send_with_outbound_intent(&SendMessage::new("Channel module unavailable.", &msg.reply_target).in_thread(msg.thread_ts.clone())).await;}+ return true;}};-- if let Err(err) = channel- .send_with_outbound_intent(- &SendMessage::new(response, &msg.reply_target).in_thread(msg.thread_ts.clone()),- )- .await- {- tracing::warn!(- "Failed to send runtime command response on {}: {err}",- channel.name()- );+ if let Some(route) = next_route {+ set_route_selection(ctx, sender_key, ChannelRouteSelection { provider: route.provider, model: route.model });+ }+ if clear_history { clear_sender_history(ctx, sender_key); }+ let Some(reply) = reply else { return false; };+ if let Some(channel) = target_channel {+ if channel.send_with_outbound_intent(&SendMessage::new(reply, &msg.reply_target).in_thread(msg.thread_ts.clone())).await.is_err() {+ tracing::warn!("channel command response failed");+ }}-true}diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rsindex e0da3e2924..f13bca1104 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs@@ -107,7 +107,7 @@ pub(crate) async fn process_channel_runtime_message(});let target_channel = ctx.channels_by_name.get(&msg.channel).cloned();- if handle_runtime_command_if_needed(ctx.as_ref(), &msg, target_channel.as_ref()).await {+ if handle_runtime_command_if_needed(ctx.as_ref(), &msg, target_channel.as_ref(), &history_key).await {return;}