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
feat(channels): route channel messages through shared context
Steven Enamakeldad49a61972a
diff --git a/crates/openhuman-core/src/channels/context.rs b/crates/openhuman-core/src/channels/context.rsindex d2f8c62be7..c88e0394f7 100644--- a/crates/openhuman-core/src/channels/context.rs+++ b/crates/openhuman-core/src/channels/context.rs@@ -5,14 +5,13 @@//! turns are ingested from the `ConversationTurnCommitted` bus event.use crate::agent::tinyagents::TurnModelSource;-use crate::util::truncate_with_ellipsis;use std::collections::HashMap;use std::path::PathBuf;use std::sync::{Arc, Mutex};-use tinyagents_session::transcript::TranscriptMessage;use tinytools::Tool;pub(crate) use tinychannels_bus::context::{+ clear_sender_history, compact_sender_history, ConversationHistoryMap,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,@@ -24,9 +23,6 @@ pub(crate) use tinychannels::context::{effective_channel_message_timeout_secs, MIN_CHANNEL_MESSAGE_TIMEOUT_SECS,};-/// Per-sender conversation history for channel messages.-pub(crate) type ConversationHistoryMap = Arc<Mutex<HashMap<String, Vec<TranscriptMessage>>>>;-pub(crate) type TurnModelSourceCacheMap = Arc<Mutex<HashMap<String, TurnModelSource>>>;pub(crate) type RouteSelectionMap = Arc<Mutex<HashMap<String, ChannelRouteSelection>>>;@@ -80,43 +76,6 @@ pub(crate) fn conversation_history_key(msg: &tinychannels_bus::ChannelMessage) -tinychannels::context::conversation_history_key(msg)}-pub(crate) fn clear_sender_history(ctx: &ChannelRuntimeContext, sender_key: &str) {- ctx.conversation_histories- .lock()- .unwrap_or_else(|e| e.into_inner())- .remove(sender_key);-}--pub(crate) fn compact_sender_history(ctx: &ChannelRuntimeContext, sender_key: &str) -> bool {- let mut histories = ctx- .conversation_histories- .lock()- .unwrap_or_else(|e| e.into_inner());-- let Some(turns) = histories.get_mut(sender_key) else {- return false;- };-- if turns.is_empty() {- return false;- }-- let keep_from = turns- .len()- .saturating_sub(CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES);- let mut compacted = turns[keep_from..].to_vec();-- for turn in &mut compacted {- if turn.content.chars().count() > CHANNEL_HISTORY_COMPACT_CONTENT_CHARS {- turn.content =- truncate_with_ellipsis(&turn.content, CHANNEL_HISTORY_COMPACT_CONTENT_CHARS);- }- }-- *turns = compacted;- true-}-pub(crate) async fn is_context_window_overflow_error(ctx: &ChannelRuntimeContext,err: &anyhow::Error,diff --git a/crates/openhuman-core/src/channels/context_tests.rs b/crates/openhuman-core/src/channels/context_tests.rsindex 89e7b20ae3..dd555bf5e5 100644--- a/crates/openhuman-core/src/channels/context_tests.rs+++ b/crates/openhuman-core/src/channels/context_tests.rs@@ -89,11 +89,11 @@ fn clear_and_compact_sender_history_update_cached_messages() {let ctx = runtime_context();let sender = "discord_alice_reply_thread:thread-1";let mut history = Vec::new();- history.push(tinyagents_session::transcript::TranscriptMessage::user(+ history.push(tinyagents_session::transcript::ChatMessage::user("short",));history.extend((0..20).map(|idx| {- tinyagents_session::transcript::TranscriptMessage::assistant("x".repeat(700 + idx))+ tinyagents_session::transcript::ChatMessage::assistant("x".repeat(700 + idx))}));ctx.conversation_histories.lock()diff --git a/crates/openhuman-core/src/channels/host/remote_control.rs b/crates/openhuman-core/src/channels/host/remote_control.rsindex a81543a393..ff5ced51fa 100644--- a/crates/openhuman-core/src/channels/host/remote_control.rs+++ b/crates/openhuman-core/src/channels/host/remote_control.rs@@ -57,7 +57,7 @@ pub(crate) async fn dispatch_callback(if cancellation.is_cancelled() {return Err(tinybus::Error::failed("channel session ended"));}- clear_sender_history(ctx, &sender_key);+ clear_sender_history(&ctx.conversation_histories, &sender_key);Ok(Response::Completed)}Request::InvalidateThread { thread_id } => {diff --git a/crates/openhuman-core/src/channels/providers/relay/store.rs b/crates/openhuman-core/src/channels/providers/relay/store.rsindex 0cdc3378e3..bd1dc36213 100644--- a/crates/openhuman-core/src/channels/providers/relay/store.rs+++ b/crates/openhuman-core/src/channels/providers/relay/store.rs@@ -14,7 +14,7 @@ type ThreadLocks = Mutex<HashMap<(PathBuf, String), Arc<tokio::sync::Mutex<()>>>use chrono::Utc;use serde_json::json;-use tinyagents_session::transcript::TranscriptMessage;+use tinychannels_bus::context::ChatMessage;use super::params::RelayInboundParams;use crate::threads::store::blocking as conversations;@@ -145,7 +145,7 @@ pub async fn prior_turns(thread_id: &str,message_id: &str,limit: usize,-) -> Result<Vec<TranscriptMessage>, String> {+) -> Result<Vec<ChatMessage>, String> {let current = inbound_message_id(message_id);let messages =conversations::get_messages(workspace_dir.to_path_buf(), thread_id.to_string()).await?;@@ -155,13 +155,13 @@ pub async fn prior_turns(}/// `messages` up to (not including) the one with id `current`, as history.-fn to_history(messages: &[ConversationMessage], current: &str) -> Vec<TranscriptMessage> {+fn to_history(messages: &[ConversationMessage], current: &str) -> Vec<ChatMessage> {messages.iter().take_while(|message| message.id != current).filter_map(|message| match message.sender.as_str() {- "user" => Some(TranscriptMessage::user(&message.content)),- "assistant" => Some(TranscriptMessage::assistant(&message.content)),+ "user" => Some(ChatMessage::user(&message.content)),+ "assistant" => Some(ChatMessage::assistant(&message.content)),_ => None,}).collect()diff --git a/crates/openhuman-core/src/channels/routes.rs b/crates/openhuman-core/src/channels/routes.rsindex c1d2985ab3..17ea513760 100644--- a/crates/openhuman-core/src/channels/routes.rs+++ b/crates/openhuman-core/src/channels/routes.rs@@ -215,7 +215,7 @@ pub(crate) async fn handle_runtime_command_if_needed();}if clear_history {- clear_sender_history(ctx, sender_key);+ clear_sender_history(&ctx.conversation_histories, sender_key);}let Some(reply) = reply else {return false;diff --git a/crates/openhuman-core/src/channels/routes_tests.rs b/crates/openhuman-core/src/channels/routes_tests.rsindex 3a986e5962..c4dd09223c 100644--- a/crates/openhuman-core/src/channels/routes_tests.rs+++ b/crates/openhuman-core/src/channels/routes_tests.rs@@ -10,7 +10,7 @@ use std::future::Future;use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};use std::task::{Context, Poll, Wake, Waker};-use tinyagents_session::transcript::TranscriptMessage;+use tinychannels_bus::context::ChatMessage;use tinybus::EventHandler;use tinychannels::routes::resolve_provider_alias;use tinychannels_bus::ChannelMessage;@@ -345,7 +345,7 @@ async fn handle_runtime_command_set_model_clears_sender_history_and_persists_roulet key = "telegram_alice_room";ctx.conversation_histories.lock().unwrap().insert(key.to_string(),- vec![TranscriptMessage::user("old history")],+ vec![ChatMessage::user("old history")],);let channel_impl = Arc::new(RecordingChannel::default());let channel: Arc<dyn Channel> = channel_impl.clone();@@ -522,7 +522,7 @@ async fn handle_runtime_command_telegram_new_status_and_sessions_round_trip() {ctx.conversation_histories.lock().unwrap().insert(sender_key.to_string(),- vec![TranscriptMessage::user("old history")],+ vec![ChatMessage::user("old history")],);let new_msg = ChannelMessage {@@ -553,7 +553,7 @@ async fn handle_runtime_command_telegram_new_status_and_sessions_round_trip() {ctx.conversation_histories.lock().unwrap().insert(sender_key.to_string(),- vec![TranscriptMessage::user("after new")],+ vec![ChatMessage::user("after new")],);set_route_selection(&ctx,diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rsindex dc523dae2c..70bf0d9ba6 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs@@ -530,7 +530,7 @@ pub(crate) async fn process_channel_runtime_message(.await.unwrap_or(false){- let compacted = compact_sender_history(ctx.as_ref(), &history_key);+ let compacted = compact_sender_history(&ctx.conversation_histories, &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."} else {diff --git a/crates/openhuman-core/src/cron/channel_bridge.rs b/crates/openhuman-core/src/cron/channel_bridge.rsindex a2aa3ffd3b..db9614c05c 100644--- a/crates/openhuman-core/src/cron/channel_bridge.rs+++ b/crates/openhuman-core/src/cron/channel_bridge.rs@@ -10,12 +10,12 @@use std::collections::HashMap;use std::sync::{Arc, Mutex, RwLock};-use tinyagents_session::transcript::TranscriptMessage;+use tinychannels_bus::context::ChatMessage;use tinychannels_bus::{Channel, SendMessage};/// Same shape as `channels::context::ConversationHistoryMap`, spelled out so/// cron does not depend on the feature-gated `channels` module.-pub type ChannelHistories = Arc<Mutex<HashMap<String, Vec<TranscriptMessage>>>>;+pub type ChannelHistories = Arc<Mutex<HashMap<String, Vec<ChatMessage>>>>;/// How many messages a chat's history keeps; matches the channel processor's/// own trimming so a delivered reminder never grows it past that bound.@@ -86,7 +86,7 @@ pub fn append_assistant_message(history_key: &str, text: &str) -> bool {let max = MAX_HISTORY.load(std::sync::atomic::Ordering::Relaxed);let mut histories = bridge.histories.lock().unwrap_or_else(|e| e.into_inner());let turns = histories.entry(history_key.to_string()).or_default();- turns.push(TranscriptMessage::assistant(text));+ turns.push(ChatMessage::assistant(text));while turns.len() > max {turns.remove(0);}diff --git a/crates/openhuman-core/src/cron/channel_bridge_tests.rs b/crates/openhuman-core/src/cron/channel_bridge_tests.rsindex c697d29ce4..273a78796b 100644--- a/crates/openhuman-core/src/cron/channel_bridge_tests.rs+++ b/crates/openhuman-core/src/cron/channel_bridge_tests.rs@@ -35,8 +35,8 @@ async fn bridge_reads_appends_trims_and_sends() {histories.lock().unwrap().insert("k".into(),vec![- TranscriptMessage::user("remind me"),- TranscriptMessage::assistant("ok"),+ ChatMessage::user("remind me"),+ ChatMessage::assistant("ok"),],);let sends = Arc::new(AtomicUsize::new(0));