Skip to content

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

refactor(channels): route approvals and turn state through the module

Steven Enamakel00a4c067a288
diff --git a/crates/openhuman-core/src/channels/host/channel_events.rs b/crates/openhuman-core/src/channels/host/channel_events.rs
index 8ac49351bf..f48b93bb24 100644
--- a/crates/openhuman-core/src/channels/host/channel_events.rs
+++ b/crates/openhuman-core/src/channels/host/channel_events.rs
@@ -1,171 +1,116 @@
-//! Event-bus subscribers that give every capable channel in-chat approvals
-//! and remote-control turn state.
-//!
-//! Both used to exist for Telegram only. The behaviour now lives in
-//! `tinychannels` (`approvals::ApprovalSurface`, `remote::mark_turn`), gated
-//! per provider by `ChannelCapabilities`; these subscribers only translate
-//! OpenHuman's [`DomainEvent`]s into it.
-
+//! Host-owned approval routing and turn events over the channel module.
use std::collections::HashMap;
use std::path::PathBuf;
-use std::sync::Arc;
-
+use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use tinybus::EventHandler;
-use tinychannels::approvals::{ApprovalPrompt, ApprovalSurface};
-use tinychannels::capabilities_for;
-
-use crate::channels::Channel;
+use tinychannels_bus::{capabilities_for, ChannelMessage};
+use crate::channels::{Channel, ChannelSendExt, SendMessage};
use crate::core::events::DomainEvent;
+use crate::modules::client::ModuleClient;
+
+#[derive(Clone)]
+struct ReplyContext { reply_target: String, thread_ts: Option<String> }
-/// Turns `ApprovalRequested` events into prompts in the chat the turn came
-/// from, for every channel with the `chat_approvals` capability.
-///
-/// The dispatch loop scopes those channels' turns in an
-/// `ApprovalChatContext` whose `thread_id` is the conversation history key and
-/// whose `client_id` is the channel name; this subscriber records each inbound
-/// message's reply target under the same key, so a later approval can find its
-/// way back. The user's `yes`/`no` reply is intercepted by the dispatch loop.
+/// Captures the account configuration and reply addresses used by approvals.
pub struct ChannelApprovalSurfaceSubscriber {
- surface: ApprovalSurface,
+ channels: Arc<HashMap<String, Arc<dyn Channel>>>,
+ replies: Mutex<HashMap<String, ReplyContext>>,
+ config: Option<Arc<crate::config::Config>>,
+ cancellation: tokio_util::sync::CancellationToken,
}
-
impl ChannelApprovalSurfaceSubscriber {
- pub fn new(channels_by_name: Arc<HashMap<String, Arc<dyn Channel>>>) -> Self {
- Self {
- surface: ApprovalSurface::new(channels_by_name),
- }
+ pub fn with_config(channels: Arc<HashMap<String, Arc<dyn Channel>>>, config: Arc<crate::config::Config>) -> Self {
+ Self { channels, replies: Mutex::new(HashMap::new()), config: Some(config), cancellation: super::super::runtime::session::channel_session() }
}
-
#[cfg(test)]
- pub(crate) fn surface(&self) -> &ApprovalSurface {
- &self.surface
+ pub fn new(channels: Arc<HashMap<String, Arc<dyn Channel>>>) -> Self {
+ Self { channels, replies: Mutex::new(HashMap::new()), config: None, cancellation: tokio_util::sync::CancellationToken::new() }
+ }
+ async fn client(&self) -> ModuleClient {
+ #[cfg(test)]
+ if self.config.is_none() { return crate::channels::module_fixture::client().await; }
+ ModuleClient::new(self.config.as_deref().cloned().unwrap_or_default())
}
}
-
#[async_trait]
impl EventHandler<DomainEvent> for ChannelApprovalSurfaceSubscriber {
- fn name(&self) -> &str {
- "channels::approval_surface"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["channel", "approval"])
- }
-
+ fn name(&self) -> &str { "channels::approval_surface" }
+ fn domains(&self) -> Option<&[&str]> { Some(&["channel", "approval"]) }
async fn handle(&self, event: &DomainEvent) {
+ if self.cancellation.is_cancelled() { return; }
match event {
- DomainEvent::ChannelMessageReceived {
- channel,
- sender,
- reply_target,
- thread_ts,
- ..
- } => {
- self.surface
- .record_inbound(channel, sender, reply_target, thread_ts.as_deref());
+ DomainEvent::ChannelMessageReceived { channel, message_id, sender, reply_target, content, thread_ts, inbound_envelope, workspace_dir } => {
+ if !capabilities_for(channel).chat_approvals { return; }
+ if self.config.as_ref().is_some_and(|config| config.workspace_dir != *workspace_dir) { return; }
+ let prepared = crate::modules::channel_controller::prepare_inbound(&self.client().await,
+ 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 },
+ envelope: inbound_envelope.clone(),
+ },
+ }).await;
+ if let Ok(prepared) = prepared {
+ self.replies.lock().unwrap_or_else(|e| e.into_inner()).insert(prepared.history_key, ReplyContext { reply_target: reply_target.clone(), thread_ts: thread_ts.clone() });
+ }
}
- DomainEvent::ApprovalRequested {
- request_id,
- tool_name,
- action_summary,
- thread_id,
- client_id,
- ..
- } => {
- // Web and other non-channel approvals carry their own client
- // ids; only channels that surface approvals in chat apply.
- let Some(channel) = client_id.as_deref() else {
- return;
- };
- if !capabilities_for(channel).chat_approvals {
- return;
+ DomainEvent::ApprovalRequested { tool_name, action_summary, thread_id: Some(thread_id), client_id: Some(channel_name), .. } => {
+ if !capabilities_for(channel_name).chat_approvals { return; }
+ let reply = self.replies.lock().unwrap_or_else(|e| e.into_inner()).get(thread_id).cloned();
+ let (Some(reply), Some(channel)) = (reply, self.channels.get(channel_name)) else { return; };
+ use tinychannels_bus::module_control::{ChannelControlRequest, ChannelControlResult};
+ let response = self.client().await.call_confidential::<ChannelControlResult>("tinychannels", tinychannels_bus::methods::PREPARE_CHANNEL_CONTROL, (ChannelControlRequest::Approval { tool_name: tool_name.clone(), action_summary: action_summary.clone() },)).await;
+ match response {
+ Ok(ChannelControlResult::Approval(body)) => {
+ if self.cancellation.is_cancelled() { return; }
+ let _ = channel.send_with_outbound_intent(&SendMessage::new(body, &reply.reply_target).in_thread(reply.thread_ts)).await;
+ }
+ Ok(_) => { ModuleClient::report_malformed_reply("tinychannels"); }
+ Err(_) => {}
}
- let Some(thread_id) = thread_id.as_deref() else {
- tracing::warn!(
- "[channel-approval] approval request_id={request_id} tool={tool_name} \
- has client_id={channel} but no thread_id — cannot route"
- );
- return;
- };
- let outcome = self
- .surface
- .surface(&ApprovalPrompt {
- request_id: request_id.clone(),
- tool_name: tool_name.clone(),
- action_summary: action_summary.clone(),
- thread_id: thread_id.to_string(),
- channel: channel.to_string(),
- })
- .await;
- tracing::debug!(
- "[channel-approval] request_id={request_id} channel={channel} outcome={outcome:?}"
- );
}
_ => {}
}
}
}
-/// Records per-chat turn state (busy while a turn runs) for `/status`, on
-/// every channel with the `remote_control` capability.
+/// Projects host turn lifecycle facts into module-owned remote status storage.
pub struct ChannelTurnStateSubscriber {
workspace_dir: PathBuf,
+ config: Option<Arc<crate::config::Config>>,
+ cancellation: tokio_util::sync::CancellationToken,
}
-
impl ChannelTurnStateSubscriber {
+ pub fn with_config(config: Arc<crate::config::Config>) -> Self {
+ Self { workspace_dir: config.workspace_dir.clone(), config: Some(config), cancellation: super::super::runtime::session::channel_session() }
+ }
+ #[cfg(test)]
pub fn new(workspace_dir: PathBuf) -> Self {
- Self { workspace_dir }
+ Self { workspace_dir, config: None, cancellation: tokio_util::sync::CancellationToken::new() }
}
-
async fn mark(&self, channel: &str, reply_target: &str, event_ws: &PathBuf, busy: bool) {
- if !capabilities_for(channel).remote_control {
- return;
- }
- if *event_ws != self.workspace_dir {
- tracing::debug!(
- "[channel-remote] dropping stale-workspace turn event busy={busy} event_ws={} self_ws={}",
- event_ws.display(),
- self.workspace_dir.display()
- );
- return;
- }
- tracing::debug!(
- "[channel-remote] turn busy={busy} channel={channel} reply_target={reply_target}"
- );
- tinychannels::remote::mark_turn(&self.workspace_dir, channel, reply_target, busy).await;
+ if self.cancellation.is_cancelled() || !capabilities_for(channel).remote_control || *event_ws != self.workspace_dir { return; }
+ #[cfg(test)]
+ let client = if self.config.is_none() { crate::channels::module_fixture::client().await } else { ModuleClient::new(self.config.as_deref().cloned().unwrap_or_default()) };
+ #[cfg(not(test))]
+ let client = ModuleClient::new(self.config.as_deref().cloned().unwrap_or_default());
+ let result: Result<tinychannels_bus::module_remote::RemoteOperationResult, _> = client.call_confidential("tinychannels", tinychannels_bus::methods::EXECUTE_REMOTE, (tinychannels_bus::module_remote::RemoteOperation::MarkTurn { workspace_dir: self.workspace_dir.to_string_lossy().into_owned(), channel: channel.into(), reply_target: reply_target.into(), busy },)).await;
+ if result.is_err() { tracing::debug!("channel turn status unavailable"); }
}
}
-
#[async_trait]
impl EventHandler<DomainEvent> for ChannelTurnStateSubscriber {
- fn name(&self) -> &str {
- "channels::turn_state"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["channel"])
- }
-
+ fn name(&self) -> &str { "channels::turn_state" }
+ fn domains(&self) -> Option<&[&str]> { Some(&["channel"]) }
async fn handle(&self, event: &DomainEvent) {
match event {
- DomainEvent::ChannelMessageReceived {
- channel,
- reply_target,
- workspace_dir,
- ..
- } => self.mark(channel, reply_target, workspace_dir, true).await,
- DomainEvent::ChannelMessageProcessed {
- channel,
- reply_target,
- workspace_dir,
- ..
- } => self.mark(channel, reply_target, workspace_dir, false).await,
+ DomainEvent::ChannelMessageReceived { channel, reply_target, workspace_dir, .. } => self.mark(channel, reply_target, workspace_dir, true).await,
+ DomainEvent::ChannelMessageProcessed { channel, reply_target, workspace_dir, .. } => self.mark(channel, reply_target, workspace_dir, false).await,
_ => {}
}
}
}
-
#[cfg(test)]
#[path = "channel_events_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/channels/host/channel_events_tests.rs b/crates/openhuman-core/src/channels/host/channel_events_tests.rs
index f2f5ec1079..cbd2cde58c 100644
--- a/crates/openhuman-core/src/channels/host/channel_events_tests.rs
+++ b/crates/openhuman-core/src/channels/host/channel_events_tests.rs
@@ -99,7 +99,7 @@ async fn approval_prompts_reach_every_chat_channel() {
assert_eq!(sub.domains(), Some(&["channel", "approval"][..]));
sub.handle(&received(channel, "chat-1", thread_ts, &ws))
.await;
- assert!(sub.surface().reply_context(key).is_some(), "{channel}");
+ assert!(sub.replies.lock().unwrap().contains_key(key), "{channel}");
sub.handle(&approval(Some(key), Some(channel))).await;
let sent = ch.sent.lock().unwrap().clone();
assert_eq!(sent.len(), 1, "{channel}");
diff --git a/crates/openhuman-core/src/channels/host/remote_control.rs b/crates/openhuman-core/src/channels/host/remote_control.rs
index d8ecbe2e9e..abd00fcc67 100644
--- a/crates/openhuman-core/src/channels/host/remote_control.rs
+++ b/crates/openhuman-core/src/channels/host/remote_control.rs
@@ -6,89 +6,9 @@
//! context (model routes, in-memory history), the conversation store and the
//! web-chat session cache.
-use async_trait::async_trait;
-use tinychannels::remote::{NewRemoteThread, RemoteControlHost, RemoteRoute, RemoteThreadSummary};
-
-use crate::channels::context::{
- clear_sender_history, ChannelRouteSelection, ChannelRuntimeContext,
-};
+use crate::channels::context::{clear_sender_history, ChannelRuntimeContext};
use crate::threads::store::{self as conversations, CreateConversationThread};
-/// Remote-control host state for one command, borrowed from the runtime.
-pub(crate) struct RuntimeRemoteControl<'a> {
- pub(crate) ctx: &'a ChannelRuntimeContext,
-}
-
-#[async_trait]
-impl RemoteControlHost for RuntimeRemoteControl<'_> {
- fn route(&self, sender_key: &str) -> RemoteRoute {
- let selection = self
- .ctx
- .route_overrides
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .get(sender_key)
- .cloned()
- .unwrap_or_else(|| ChannelRouteSelection {
- provider: self.ctx.default_provider.as_str().to_string(),
- model: self.ctx.model.as_str().to_string(),
- });
- RemoteRoute {
- provider: selection.provider,
- model: selection.model,
- }
- }
-
- fn history_len(&self, sender_key: &str) -> usize {
- self.ctx
- .conversation_histories
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .get(sender_key)
- .map(Vec::len)
- .unwrap_or(0)
- }
-
- fn clear_history(&self, sender_key: &str) {
- clear_sender_history(self.ctx, sender_key);
- }
-
- async fn list_threads(&self) -> anyhow::Result<Vec<RemoteThreadSummary>> {
- let threads = conversations::list_threads(self.ctx.workspace_dir.to_path_buf())
- .map_err(anyhow::Error::msg)?;
- Ok(threads
- .into_iter()
- .map(|thread| RemoteThreadSummary {
- id: thread.id,
- title: thread.title,
- message_count: thread.message_count,
- last_message_at: thread.last_message_at,
- })
- .collect())
- }
-
- async fn create_thread(&self, thread: NewRemoteThread) -> anyhow::Result<()> {
- conversations::ensure_thread(
- self.ctx.workspace_dir.to_path_buf(),
- CreateConversationThread {
- id: thread.id,
- title: thread.title,
- created_at: thread.created_at,
- parent_thread_id: None,
- labels: Some(thread.labels),
- personality_id: None,
- working_dir: None,
- },
- )
- .map(drop)
- .map_err(anyhow::Error::msg)
- }
-
- async fn invalidate_thread(&self, thread_id: &str) {
- crate::web_chat::invalidate_thread_sessions(thread_id).await;
- }
-}
-
/// Serves product-owned conversation state to the captured module runtime.
pub(crate) async fn dispatch_callback(
ctx: &ChannelRuntimeContext,
diff --git a/crates/openhuman-core/src/channels/runtime/mod.rs b/crates/openhuman-core/src/channels/runtime/mod.rs
index 0121b5ce5d..205035a9e0 100644
--- a/crates/openhuman-core/src/channels/runtime/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/mod.rs
@@ -6,6 +6,7 @@ mod startup;
mod supervision;
pub(crate) use startup::hydrate_channel_credentials;
+pub(crate) use startup::prepare_runtime_limits;
pub use startup::start_channels;
pub(crate) use startup::start_channels_with_session;
// The hosted-channel relay (`channels::providers::relay`) runs one message
diff --git a/crates/openhuman-core/src/channels/runtime/startup.rs b/crates/openhuman-core/src/channels/runtime/startup.rs
index 07d34c3ea8..977899937c 100644
--- a/crates/openhuman-core/src/channels/runtime/startup.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup.rs
@@ -10,6 +10,45 @@ mod relay;
mod start_channels;
mod turn_parts;
+use crate::modules::client::{ModuleCallError, ModuleClient};
+use anyhow::{Context, Result};
+
+/// Ask the owning module to prepare effective execution limits for this host
+/// runtime. A malformed response fails closed and reports only the module ID.
+pub(crate) async fn prepare_runtime_limits(
+ client: &ModuleClient,
+ timeout_secs: u64,
+ listener_count: usize,
+) -> Result<(u64, usize)> {
+ use tinychannels_bus::module_control::{ChannelControlRequest, ChannelControlResult};
+
+ let result: ChannelControlResult = client
+ .call_confidential(
+ "tinychannels",
+ 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 >= tinychannels_bus::context::MIN_CHANNEL_MESSAGE_TIMEOUT_SECS
+ && 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(crate) use credentials::hydrate_channel_credentials;
pub use start_channels::start_channels;
pub(crate) use start_channels::start_channels_with_session;
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 53c0568564..05b7bf1529 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -136,34 +136,7 @@ impl ModuleChannelRuntime {
timeout_secs: u64,
listener_count: usize,
) -> Result<(u64, usize)> {
- use tinychannels_bus::module_control::{ChannelControlRequest, ChannelControlResult};
-
- let result: ChannelControlResult = self
- .client
- .call_confidential(
- "tinychannels",
- 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 >= tinychannels_bus::context::MIN_CHANNEL_MESSAGE_TIMEOUT_SECS
- && 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"))
- }
- }
+ super::prepare_runtime_limits(&self.client, timeout_secs, listener_count).await
}
pub(super) async fn start(&mut self, config: &Config) -> Result<()> {