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): move progressive delivery into the module
Steven Enamakel00b413b7e2ef
diff --git a/crates/openhuman-core/src/channels/bus/delivery.rs b/crates/openhuman-core/src/channels/bus/delivery.rsindex 8796148bc3..3ad86c68fd 100644--- a/crates/openhuman-core/src/channels/bus/delivery.rs+++ b/crates/openhuman-core/src/channels/bus/delivery.rs@@ -1,123 +1,91 @@-//! OpenHuman's [`ProgressiveSender`]: progressive channel replies over the-//! backend REST relay.-//!-//! The streaming choreography (draft, thinking and filler bubbles, failure-//! latches, finalize invariants) lives in `tinychannels::delivery::progressive`.-//! This adapter supplies the transport: it resolves the hosted session,-//! attaches idempotency keys, and maps [`BackendApiError`] onto-//! [`ProgressiveSendError`].-+//! Captured managed transport for module-owned progressive replies.use crate::backend::{BackendApiError, BackendClient};-use crate::security::credentials::session_support::{- get_session_token, is_local_session_token, BackendCredential,-};-use async_trait::async_trait;+use crate::security::credentials::session_support::{get_session_token, is_local_session_token, BackendCredential};+use crate::modules::{channel_runtime::ChannelRuntimeLease, client::{ModuleClient, ModuleCallError}};+use tinychannels_bus::{ChannelBackendRequest, ChannelBackendResult, methods};+use tinychannels_bus::module_progressive::{ProgressiveCommand, ProgressiveEvent, ProgressiveResult, ProgressiveTransportRequest, ProgressiveTransportResult};use serde_json::{json, Value};-use tinychannels::delivery::progressive::{ProgressiveSendError, ProgressiveSender};-/// Attach a deterministic idempotency key to an outbound channel message-/// body, derived from the channel and message content.-pub(super) fn channel_message_body_with_idempotency(channel: &str, body: Value) -> Value {- let intent = tinychannels::outbound_intent_from_legacy_message(channel, body);- tinychannels::legacy_message_value_from_outbound_intent(&intent)+/// Transport refusals are typed facts; recovery and retry budgets belong to the module.+pub(super) fn map_backend_error(error: anyhow::Error) -> ProgressiveTransportResult {+ match error.downcast_ref::<BackendApiError>() {+ Some(BackendApiError::ChannelEditUnsupported { .. }) => ProgressiveTransportResult::EditUnsupported,+ Some(BackendApiError::MessageNotFound { .. }) => ProgressiveTransportResult::MessageGone,+ _ => ProgressiveTransportResult::Failed,+ }}-/// Map a backend failure onto the recovery the progressive driver needs.-/// Typed, never by message text, so recoveries cannot drift with wording.-pub(super) fn map_backend_error(err: anyhow::Error) -> ProgressiveSendError {- match err.downcast_ref::<BackendApiError>() {- Some(BackendApiError::ChannelEditUnsupported { .. }) => {- ProgressiveSendError::EditUnsupported- }- Some(BackendApiError::MessageNotFound { .. }) => ProgressiveSendError::MessageGone,- _ => ProgressiveSendError::Other(err),- }+#[derive(Clone)]+struct ManagedTransport {+ client: BackendClient,+ credential: BackendCredential,}-/// Construct the REST client plus the hosted session credential. Returns-/// `None` (and logs why) when either is unavailable.-async fn build_channel_client() -> Option<(BackendClient, BackendCredential)> {- let config = match crate::config::rpc::load_config_with_timeout().await {- Ok(c) => c,- Err(e) => {- tracing::error!("[channel-inbound] failed to load config: {}", e);- return None;- }- };- let credential = match get_session_token(&config) {- Ok(Some(token)) if !is_local_session_token(&token) => BackendCredential::Session(token),- Ok(_) => {- tracing::error!("[channel-inbound] no hosted user session — cannot send");- return None;- }- Err(e) => {- tracing::error!(- "[channel-inbound] no backend credential — cannot send: {}",- e- );- return None;- }- };- match BackendClient::from_config(&config) {- Ok(client) => Some((client, credential)),- Err(e) => {- tracing::error!("[channel-inbound] failed to create API client: {}", e);- None- }+impl ManagedTransport {+ fn capture(config: &crate::config::Config) -> anyhow::Result<Self> {+ let credential = match get_session_token(config)? {+ Some(token) if !is_local_session_token(&token) => BackendCredential::Session(token),+ _ => anyhow::bail!("Hosted channel credential unavailable"),+ };+ Ok(Self { client: BackendClient::from_config(config)?, credential })+ }++ async fn execute(&self, request: ProgressiveTransportRequest) -> ProgressiveTransportResult {+ let result = match request {+ ProgressiveTransportRequest::Send { channel, message } => self.client.send_channel_message(&channel, &self.credential, message).await,+ ProgressiveTransportRequest::Edit { channel, message_id, text } => self.client.send_channel_edit(&channel, &message_id, &self.credential, json!({"text":text})).await,+ ProgressiveTransportRequest::Delete { channel, message_id } => self.client.send_channel_delete(&channel, &message_id, &self.credential).await,+ ProgressiveTransportRequest::Typing { channel } => self.client.send_channel_typing(&channel, &self.credential).await,+ };+ match result { Ok(value) => ProgressiveTransportResult::Success(value), Err(error) => map_backend_error(error) }}}-async fn client() -> Result<(BackendClient, BackendCredential), ProgressiveSendError> {- build_channel_client()- .await- .ok_or(ProgressiveSendError::Unavailable)+#[tinybus::interface(name = "ai.tinyhumans.tinychannels.ChannelsHost")]+impl ManagedTransport {+ async fn dispatch_controller_backend(&self, request: ChannelBackendRequest) -> tinybus::Result<ChannelBackendResult> {+ let ChannelBackendRequest::ProgressiveTransport(request) = request else {+ return Err(tinybus::Error::failed("callback capability unavailable"));+ };+ Ok(ChannelBackendResult::ProgressiveTransport(self.execute(request).await))+ }}-/// Progressive replies through `BackendClient::send_channel_*`.-pub(super) struct BackendProgressiveSender;+/// The host projects ordered turn facts; the module owns timers and delivery state.+pub(super) struct ModuleProgressiveReply {+ runtime: ChannelRuntimeLease,+ handle: String,+}-#[async_trait]-impl ProgressiveSender for BackendProgressiveSender {- async fn send(&self, channel: &str, text: &str) -> Result<Value, ProgressiveSendError> {- let (client, credential) = client().await?;- let body = channel_message_body_with_idempotency(channel, json!({ "text": text }));- client- .send_channel_message(channel, &credential, body)- .await- .map_err(map_backend_error)+impl ModuleProgressiveReply {+ pub(super) async fn open(config: crate::config::Config, channel: String) -> anyhow::Result<Self> {+ let callback = ManagedTransport::capture(&config)?;+ let runtime = ChannelRuntimeLease::open(ModuleClient::new(config), callback).await?;+ let result: ProgressiveResult = runtime.object().call_confidential(methods::EXECUTE_PROGRESSIVE, (ProgressiveCommand::Open { channel },)).await?;+ match result {+ ProgressiveResult::Opened { handle } if !handle.is_empty() && handle.len() <= 128 => Ok(Self { runtime, handle }),+ _ => { ModuleClient::report_malformed_reply("tinychannels"); Err(ModuleCallError::ModuleFault.into()) }+ }}- async fn edit(- &self,- channel: &str,- message_id: &str,- text: &str,- ) -> Result<(), ProgressiveSendError> {- let (client, credential) = client().await?;- client- .send_channel_edit(channel, message_id, &credential, json!({ "text": text }))- .await- .map(drop)- .map_err(map_backend_error)+ pub(super) async fn feed(&self, events: Vec<ProgressiveEvent>) -> Result<(), ModuleCallError> {+ let result: ProgressiveResult = self.runtime.object().call_confidential(methods::EXECUTE_PROGRESSIVE, (ProgressiveCommand::Feed { handle: self.handle.clone(), events },)).await?;+ if result != ProgressiveResult::Updated { ModuleClient::report_malformed_reply("tinychannels"); return Err(ModuleCallError::ModuleFault); }+ Ok(())}- async fn delete(&self, channel: &str, message_id: &str) -> Result<(), ProgressiveSendError> {- let (client, credential) = client().await?;- client- .send_channel_delete(channel, message_id, &credential)- .await- .map(drop)- .map_err(map_backend_error)+ pub(super) async fn finalize(&self, text: &str) -> Result<(), ModuleCallError> {+ let result: ProgressiveResult = self.runtime.object().call_confidential(methods::EXECUTE_PROGRESSIVE, (ProgressiveCommand::Finish { handle: self.handle.clone(), text: text.into() },)).await?;+ if result != ProgressiveResult::Closed { ModuleClient::report_malformed_reply("tinychannels"); return Err(ModuleCallError::ModuleFault); }+ self.runtime.close().await}+}- async fn typing(&self, channel: &str) -> Result<(), ProgressiveSendError> {- let (client, credential) = client().await?;- client- .send_channel_typing(channel, &credential)- .await- .map(drop)- .map_err(map_backend_error)- }+// Compatibility fixtures exercise the owning library only in test builds.+#[cfg(test)]+pub(super) fn channel_message_body_with_idempotency(channel: &str, body: Value) -> Value {+ let intent = tinychannels::outbound_intent_from_legacy_message(channel, body);+ tinychannels::legacy_message_value_from_outbound_intent(&intent)}#[cfg(test)]diff --git a/crates/openhuman-core/src/channels/bus/delivery_tests.rs b/crates/openhuman-core/src/channels/bus/delivery_tests.rsindex 17f4efc7a6..088cab6f17 100644--- a/crates/openhuman-core/src/channels/bus/delivery_tests.rs+++ b/crates/openhuman-core/src/channels/bus/delivery_tests.rs@@ -12,26 +12,9 @@ fn outbound_body_has_stable_idempotency_key() {}#[tokio::test]-async fn sender_methods_report_unavailable_without_a_hosted_session() {+async fn transport_captures_no_local_or_missing_hosted_credential() {let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;let workspace = tempfile::tempdir().expect("temporary workspace");let _workspace_env = EnvVarGuard::workspace_unlocked(workspace.path());- let sender = BackendProgressiveSender;-- assert!(matches!(- sender.send("telegram", "hello").await,- Err(ProgressiveSendError::Unavailable)- ));- assert!(matches!(- sender.edit("telegram", "message", "hello").await,- Err(ProgressiveSendError::Unavailable)- ));- assert!(matches!(- sender.delete("telegram", "message").await,- Err(ProgressiveSendError::Unavailable)- ));- assert!(matches!(- sender.typing("telegram").await,- Err(ProgressiveSendError::Unavailable)- ));+ assert!(ManagedTransport::capture(&crate::config::Config::default()).is_err());}diff --git a/crates/openhuman-core/src/channels/bus/subscriber.rs b/crates/openhuman-core/src/channels/bus/subscriber.rsindex e3564e6afe..ead0fd3057 100644--- a/crates/openhuman-core/src/channels/bus/subscriber.rs+++ b/crates/openhuman-core/src/channels/bus/subscriber.rs@@ -1,19 +1,9 @@-//! The `ChannelInboundSubscriber` event handler: runs the agent loop for an-//! inbound channel message and streams the reply back through the REST API.-//!-//! The web-chat event loop is host-owned; the progressive delivery it drives-//! (draft, thinking and filler bubbles, finalize) is-//! `tinychannels::delivery::progressive::ProgressiveReply` over-//! [`BackendProgressiveSender`].--use super::delivery::BackendProgressiveSender;+//! Host-owned agent turn orchestration with module-owned progressive delivery.+use super::delivery::ModuleProgressiveReply;use crate::core::events::DomainEvent;use async_trait::async_trait;-use std::sync::Arc;use tinybus::EventHandler;-use tinychannels::delivery::progressive::{- ProgressiveReply, EDIT_FLUSH_INTERVAL, FILLER_INTERVAL, TYPING_REFRESH_INTERVAL,-};+use tinychannels_bus::module_progressive::ProgressiveEvent;/// Subscribes to `ChannelInboundMessage` events and runs the agent loop,/// sending replies back to the originating channel via the backend REST API.@@ -82,7 +72,7 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {}};let identity = match crate::modules::channel_controller::prepare_identity(- &crate::modules::client::ModuleClient::new(config),+ &crate::modules::client::ModuleClient::new(config.clone()),tinychannels_bus::module_inbound::PrepareChannelIdentityRequest {channel: channel.clone(),sender: sender.clone(),@@ -102,7 +92,13 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {let client_id = identity.client_id;let mut event_rx = crate::web_chat::subscribe_web_channel_events();- let mut reply = ProgressiveReply::new(Arc::new(BackendProgressiveSender), channel.clone());+ let reply = match ModuleProgressiveReply::open(config, channel.clone()).await {+ Ok(reply) => reply,+ Err(error) => {+ tracing::error!("[channel-inbound] progressive runtime unavailable: {error}");+ return;+ }+ };let request_id = match crate::web_chat::start_chat(&client_id,@@ -131,9 +127,7 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {}Err(err) => {tracing::error!("[channel-inbound] start_chat failed: {}", err);- reply- .send_reply(&format!("Sorry, I couldn't process your message: {err}"))- .await;+ let _ = reply.finalize(&format!("Sorry, I couldn't process your message: {err}")).await;return;}};@@ -141,37 +135,6 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {let timeout = tokio::time::Duration::from_secs(180);let deadline = tokio::time::Instant::now() + timeout;- // ── Progressive-edit timer ────────────────────────────────────- // Buffered text/thinking deltas flush as edits on this timer. The- // driver latches into atomic-final delivery on channels or backends- // that cannot edit.- let mut edit_timer = tokio::time::interval(EDIT_FLUSH_INTERVAL);- edit_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);- // Don't fire immediately; wait for the first tick.- edit_timer.tick().await;-- // ── Typing indicator ──────────────────────────────────────────- // Telegram's `sendChatAction` keeps the "typing…" UI alive for- // ~5s, so re-send every 4s while the turn is in flight. The first- // call fires immediately.- let mut typing_timer = tokio::time::interval(TYPING_REFRESH_INTERVAL);- typing_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);- // Fire immediately on first tick so the indicator shows up as- // soon as the inbound message is received.- reply.typing_tick().await;- typing_timer.tick().await; // consume the immediate tick-- // ── Filler messages ──────────────────────────────────────────- // Once progressive edits + thinking streams go quiet (backend- // doesn't support PATCH, reasoning has finished, etc.) the user- // can wait 30–90 s seeing no fresh activity. Post a short filler- // every FILLER_INTERVAL so the chat keeps moving. All filler ids- // are tracked in `StreamingState.filler_message_ids` and deleted- // by `ProgressiveReply::finalize` once the real response is on screen.- let mut filler_timer = tokio::time::interval(FILLER_INTERVAL);- filler_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);- filler_timer.tick().await; // consume the immediate tick — first filler fires after FILLER_INTERVAL-loop {tokio::select! {event = event_rx.recv() => {@@ -180,22 +143,22 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {match ev.event.as_str() {"text_delta" => {if let Some(delta) = ev.delta.as_ref() {- reply.on_text_delta(delta);+ if let Err(error) = reply.feed(vec![ProgressiveEvent::TextDelta(delta.clone())]).await { tracing::error!("[channel-inbound] delivery failed: {error}"); return; }}}"tool_call" => {if let Some(ref name) = ev.tool_name {- reply.on_tool_call(name);+ if let Err(error) = reply.feed(vec![ProgressiveEvent::ToolCall(name.clone())]).await { tracing::error!("[channel-inbound] delivery failed: {error}"); return; }}}"tool_result" => {if let Some(ref name) = ev.tool_name {- reply.on_tool_result(name, ev.success.unwrap_or(true));+ if let Err(error) = reply.feed(vec![ProgressiveEvent::ToolResult { tool_name: name.clone(), success: ev.success.unwrap_or(true) }]).await { tracing::error!("[channel-inbound] delivery failed: {error}"); return; }}}"thinking_delta" => {if let Some(delta) = ev.delta.as_ref() {- reply.on_thinking_delta(delta);+ if let Err(error) = reply.feed(vec![ProgressiveEvent::ThinkingDelta(delta.clone())]).await { tracing::error!("[channel-inbound] delivery failed: {error}"); return; }}}"chat_done" | "chat:done" => {@@ -214,23 +177,20 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {full_response.as_str()};tracing::info!(- "[channel-inbound] agent done, replying to channel='{}' len={} streamed_msg_id={:?}",+ "[channel-inbound] agent done, replying to channel='{}' len={}",channel,reply_text.len(),- reply.state().message_id,);// If we've been streaming progressive edits, replace// the outbound message with the final canonical text.// Otherwise send a fresh message atomically.- reply.finalize(reply_text).await;+ if let Err(error) = reply.finalize(reply_text).await { tracing::error!("[channel-inbound] final delivery failed: {error}"); }return;}"chat_error" | "chat:error" => {let err_msg = ev.message.unwrap_or_else(|| "unknown error".to_string());tracing::error!("[channel-inbound] agent error: {}", err_msg);- reply- .finalize(&format!("Sorry, I encountered an error: {err_msg}"))- .await;+ let _ = reply.finalize(&format!("Sorry, I encountered an error: {err_msg}")).await;return;}// New terminal event (see web_chat::ops::channel_ops /@@ -249,7 +209,7 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {"[channel-inbound] turn cancelled reason={:?}",ev.cancel_reason);- reply.finalize("Cancelled.").await;+ let _ = reply.finalize("Cancelled.").await;return;}_ => {}@@ -265,15 +225,9 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {}}}- // Draft/thinking/filler bubbles need edit+delete support; the- // driver skips them on channels without it (Discord) so they- // never leave un-cleanable placeholder messages.- _ = edit_timer.tick() => reply.edit_tick().await,- _ = typing_timer.tick() => reply.typing_tick().await,- _ = filler_timer.tick() => reply.filler_tick().await,_ = tokio::time::sleep_until(deadline) => {tracing::error!("[channel-inbound] agent timed out after {}s", timeout.as_secs());- reply.finalize("Sorry, the request timed out.").await;+ let _ = reply.finalize("Sorry, the request timed out.").await;return;}}diff --git a/crates/openhuman-core/src/channels/bus_tests.rs b/crates/openhuman-core/src/channels/bus_tests.rsindex 85848ffd7d..0db0054a63 100644--- a/crates/openhuman-core/src/channels/bus_tests.rs+++ b/crates/openhuman-core/src/channels/bus_tests.rs@@ -4,7 +4,7 @@ use crate::core::events::DomainEvent;use tinybus::EventHandler;use crate::channels::bus::delivery::map_backend_error;-use tinychannels::delivery::progressive::ProgressiveSendError;+use tinychannels_bus::module_progressive::ProgressiveTransportResult;#[test]fn subscriber_metadata_is_stable() {let subscriber = ChannelInboundSubscriber::new();@@ -35,7 +35,7 @@ fn backend_errors_map_to_distinct_progressive_recoveries() {});assert!(matches!(map_backend_error(route_absent),- ProgressiveSendError::EditUnsupported+ ProgressiveTransportResult::EditUnsupported));let message_absent = anyhow::Error::new(BackendApiError::MessageNotFound {@@ -44,13 +44,13 @@ fn backend_errors_map_to_distinct_progressive_recoveries() {});assert!(matches!(map_backend_error(message_absent),- ProgressiveSendError::MessageGone+ ProgressiveTransportResult::MessageGone));// Anything untyped (5xx, transport, rate limit) keeps the retry budget.assert!(matches!(map_backend_error(anyhow::anyhow!("502 Bad Gateway")),- ProgressiveSendError::Other(_)+ ProgressiveTransportResult::Failed));// A different typed variant must not be mistaken for either edit case.@@ -60,6 +60,6 @@ fn backend_errors_map_to_distinct_progressive_recoveries() {});assert!(matches!(map_backend_error(unauthorized),- ProgressiveSendError::Other(_)+ ProgressiveTransportResult::Failed));}