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): add relay channel provider and cron bridge
Steven Enamakela0caa3c05cf6
diff --git a/Cargo.lock b/Cargo.lockindex d9016c4fa6..ff5fbe4f86 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8764,6 +8764,7 @@ dependencies = ["hmac 0.13.0","lettre","mail-parser",+ "mime","parking_lot","prost","rand 0.10.2",@@ -8798,14 +8799,11 @@ dependencies = [name = "tinychannels-bus"version = "0.1.34"dependencies = [- "anyhow",- "async-trait","base64 0.23.1","schemars","serde","serde_json","thiserror 2.0.20",- "tokio",][[package]]@@ -8815,6 +8813,7 @@ dependencies = ["anyhow","async-trait","base64 0.23.1",+ "futures-util","hex","log","serde",diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.tomlindex 9faf6e1148..1287e89f4f 100644--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@ -378,7 +378,7 @@ tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-sessiontinydocs-bus = { path = "../../vendor/tinydocs/crates/tinydocs-bus" }tinysearch-bus = { path = "../../vendor/tinysearch/crates/tinysearch-bus" }tinybus = { path = "../../vendor/tinybus/crates/tinybus", default-features = false, features = ["macros", "uds"] }-tinychannels = { version = "0.1", features = ["relay-websocket", "email"] }+tinychannels = { version = "0.1", features = ["email"] }tinyinference-core = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-core" }tinyinference-local = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local" }tinyinference-voice = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-voice" }diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex a4256f45f8..78511a1811 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -239,6 +239,8 @@ tinymcp-bus = { path = "../../vendor/tinymcp/crates/tinymcp-bus", features = ["s# types, so this vocabulary is always-on kernel surface. It costs serde/schemars and nothing# this build did not already have.tinychannels-bus = { version = "0.1", path = "../../vendor/tinychannels/crates/tinychannels-bus" }+# The web adapter (`adapters::web`) and the channel runtime traits live here.+tinychannels-runtime = { path = "../../vendor/tinychannels/crates/tinychannels-runtime" }# tinybus — the message bus. Owns what `crates/openhuman-core/src/core/event_bus/` used to: the typed# pub/sub surface (`EventBus`, `EventHandler`, `SubscriptionHandle`), the# in-process zero-serialization request registry (`NativeRegistry`), and peer@@ -509,8 +511,7 @@ tokio-tungstenite = { version = "0.29", default-features = false, features = ["c[dev-dependencies]# Legacy TinyChannels provider/runtime fixtures remain available to tests only;# production channel execution uses the TinyBus module contract above.-tinychannels = { path = "../../vendor/tinychannels", features = ["relay-websocket", "email", "lark", "whatsapp-web"] }-tinychannels-runtime = { path = "../../vendor/tinychannels/crates/tinychannels-runtime" }+tinychannels = { path = "../../vendor/tinychannels", features = ["email", "lark", "whatsapp-web"] }# The real TinyChannels module, linked into the test binary (never the product)# as the fixture behind `channels::module_fixture`.tinychannels-module = { path = "../../vendor/tinychannels/crates/tinychannels-module", features = ["static-link"] }diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rsindex 275752776b..fe2a1410db 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs@@ -8,7 +8,6 @@ use tinyagents_harness::steering::SteeringCommand;use tinyagents_tasks::DetachedTaskRegistryError;use tinyinference_llm::message::Message as TaMessage;-use super::cancel::now_ms;use super::registry::{control_admits, owner_key, registry};/// Why a steer could not be delivered.@@ -111,16 +110,12 @@ pub async fn steer(.run_queue.push(lane,- crate::agent::queued_turn::QueuedTurn {- id: uuid::Uuid::new_v4().to_string(),+ crate::agent::queued_turn::steer_message(+ uuid::Uuid::new_v4().to_string(),text,- client_id: "steer_subagent".to_string(),- thread_id: task_id.to_string(),- queued_at_ms: now_ms(),- model_override: None,- temperature: None,- locale: None,- },+ "steer_subagent",+ task_id,+ ),).await;log::info!(@@ -180,16 +175,12 @@ pub(crate) async fn steer_control(.run_queue.push(lane,- crate::agent::queued_turn::QueuedTurn {- id: uuid::Uuid::new_v4().to_string(),+ crate::agent::queued_turn::steer_message(+ uuid::Uuid::new_v4().to_string(),text,- client_id: "subagent_control_rpc".to_string(),- thread_id: task_id.to_string(),- queued_at_ms: now_ms(),- model_override: None,- temperature: None,- locale: None,- },+ "subagent_control_rpc",+ task_id,+ ),).await;log::info!(diff --git a/crates/openhuman-core/src/agent/queued_turn.rs b/crates/openhuman-core/src/agent/queued_turn.rsindex b3280184aa..d42a829427 100644--- a/crates/openhuman-core/src/agent/queued_turn.rs+++ b/crates/openhuman-core/src/agent/queued_turn.rs@@ -4,24 +4,101 @@//! selects how this payload is consumed. OpenHuman retains the web and//! orchestration metadata needed to dispatch a deferred follow-up turn.-/// A queued OpenHuman turn input.+use tinyagents_harness::turn_runner::{+ QueueDisposition, RequeuePayload, ScopeKey, TurnRequest,+};++/// The host metadata one OpenHuman turn carries through TinyAgents' turn+/// runner and its run queue: which client asked, the per-message model and+/// locale choices, and the context the turn runs under.///-/// The payload deliberately does not carry a lane: lane selection is made at-/// the host boundary when the item is pushed into TinyAgents' `RunQueue`.-#[derive(Debug, Clone)]-pub struct QueuedTurn {- /// Stable id for this queued item (minted once, at push time). Carried on- /// `RunQueue*` domain events (`item_id`) and the `queue_item_*` web-channel- /// events so the frontend can key a queued-message row and later target it- /// with `channel.web_queue_remove`.- pub id: String,- pub text: String,+/// This is the `P` of [`QueuedTurn`]. A turn the runner queues (steer,+/// follow-up, collect) keeps all of it, so a deferred turn dispatches exactly+/// as the user asked.+#[derive(Clone, Default)]+pub struct QueuedPayload {+ /// The context the turn runs under. `None` on a placeholder the harness+ /// rebuilt from a bare id and text; the runner fills it from the running+ /// turn ([`RequeuePayload::adopt`]).+ pub ctx: Option<crate::core::runtime::DispatchCtx>,pub client_id: String,- pub thread_id: String,- pub queued_at_ms: u64,pub model_override: Option<String>,pub temperature: Option<f64>,pub locale: Option<String>,+ pub metadata: tinychannels_bus::web::ChatRequestMetadata,+ pub queued_at_ms: u64,+}++impl std::fmt::Debug for QueuedPayload {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("QueuedPayload")+ .field("client_id", &self.client_id)+ .field("model_override", &self.model_override)+ .field("temperature", &self.temperature)+ .field("locale", &self.locale)+ .field("queued_at_ms", &self.queued_at_ms)+ .finish_non_exhaustive()+ }+}++impl RequeuePayload for QueuedPayload {+ fn requeued(_thread_label: &str, queued_at_ms: u64) -> Self {+ Self {+ queued_at_ms,+ ..Self::default()+ }+ }++ fn adopt(&mut self, running: &Self) {+ if self.ctx.is_none() {+ self.ctx.clone_from(&running.ctx);+ }+ if self.client_id.is_empty() {+ self.client_id.clone_from(&running.client_id);+ self.model_override.clone_from(&running.model_override);+ self.temperature = running.temperature;+ self.locale.clone_from(&running.locale);+ self.metadata.clone_from(&running.metadata);+ }+ }+}++/// A queued OpenHuman turn input: TinyAgents' [`TurnRequest`] carrying+/// OpenHuman's [`QueuedPayload`]. The request id doubles as the queued item's+/// id (what `channel.web_queue_remove` targets); the lane is chosen at the+/// host boundary when the item is pushed into the runner's `RunQueue`.+pub type QueuedTurn = TurnRequest<QueuedPayload>;++/// A steering message for a running sub-agent, attributed to `client_id`.+#[must_use]+pub fn steer_message(+ id: impl Into<String>,+ text: impl Into<String>,+ client_id: &str,+ thread_id: &str,+) -> QueuedTurn {+ let queued_at_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64;+ TurnRequest {+ scope: ScopeKey {+ agent_id: String::new(),+ profile_id: None,+ },+ thread_id: thread_id.to_owned(),+ request_id: id.into(),+ text: text.into(),+ payload: QueuedPayload {+ client_id: client_id.to_owned(),+ queued_at_ms,+ ..QueuedPayload::default()+ },+ host_authored: false,+ disposition: QueueDisposition::Steer,+ deadline: None,+ idle_timeout: None,+ }}/// Preview a queued message's caption or attachment names, without exposingdiff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rsindex c0d47e6681..7632ee6621 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs@@ -256,16 +256,12 @@ async fn run_queue_steer_lands_in_subagent_history() {run_queue.push(QueueLane::Steer,- crate::agent::queued_turn::QueuedTurn {- id: "queued-test".into(),- text: "switch focus to memory safety".into(),- client_id: "steer_subagent".into(),- thread_id: "t-steer".into(),- queued_at_ms: 0,- model_override: None,- temperature: None,- locale: None,- },+ crate::agent::queued_turn::steer_message(+ "queued-test",+ "switch focus to memory safety",+ "steer_subagent",+ "t-steer",+ ),).await;diff --git a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rsindex 5148bb761e..06b055fa28 100644--- a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs+++ b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs@@ -7,8 +7,6 @@//! the run never applied. The loop is upstream; this module supplies the host//! seams://!-//! - [`QueuedMessage`] for [`QueuedTurn`] (text/id accessors and how a recovered-//! steer is re-created),//! - [`queue_feed`], whose event sink publishes//! [`DomainEvent::RunQueueMessageDelivered`] ///! [`DomainEvent::RunQueueSteerRequeued`] on the event bus,@@ -18,7 +16,7 @@use std::sync::Arc;use tinyagents_harness::ids::TaskId;-use tinyagents_harness::run_queue::{ForwardEvent, ForwardEventSink, QueuedMessage, RunQueue};+use tinyagents_harness::run_queue::{ForwardEvent, ForwardEventSink, RunQueue};use tinyagents_harness::steering::SteeringHandle;use tinyagents_runtime::turn_driver::{RunQueueFeed, SteeringFeed, SteeringRegistrar};@@ -28,29 +26,6 @@ use crate::core::events::DomainEvent;use super::host::steering::shared_steering_registry;-impl QueuedMessage for QueuedTurn {- fn id(&self) -> &str {- &self.id- }-- fn text(&self) -> &str {- &self.text- }-- fn requeued(id: String, text: String, thread_label: &str, queued_at_ms: u64) -> Self {- QueuedTurn {- id,- text,- client_id: String::new(),- thread_id: thread_label.to_string(),- queued_at_ms,- model_override: None,- temperature: None,- locale: None,- }- }-}-/// Publish forwarder notifications as `RunQueue*` domain events.fn event_bus_sink() -> ForwardEventSink {Arc::new(|event| match event {diff --git a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rs b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rsindex 8fcd71fd32..de97ba43bd 100644--- a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rs@@ -1,4 +1,5 @@use super::*;+use tinyagents_harness::run_queue::QueuedMessage;use tinyagents_harness::run_queue::QueueLane;#[test]@@ -7,9 +8,13 @@ fn recovered_steer_becomes_a_queued_turn_on_the_forwarders_thread() {assert_eq!(turn.id(), "id-1");assert_eq!(turn.text(), "text");assert_eq!(turn.thread_id, "thread-9");- assert_eq!(turn.queued_at_ms, 42);- assert!(turn.client_id.is_empty());- assert!(turn.model_override.is_none() && turn.temperature.is_none() && turn.locale.is_none());+ assert_eq!(turn.payload.queued_at_ms, 42);+ assert!(turn.payload.client_id.is_empty());+ assert!(+ turn.payload.model_override.is_none()+ && turn.payload.temperature.is_none()+ && turn.payload.locale.is_none()+ );}#[tokio::test]diff --git a/crates/openhuman-core/src/channels/commands.rs b/crates/openhuman-core/src/channels/commands.rsindex 3ad9eb378d..1b3bbd7dff 100644--- a/crates/openhuman-core/src/channels/commands.rs+++ b/crates/openhuman-core/src/channels/commands.rs@@ -74,10 +74,6 @@ pub async fn doctor_channels(config: Config) -> Result<()> {println!("{}", report_line(&channel_label(&report.channel), state));}- if config.channels_config.webhook.is_some() {- println!(" ℹ️ Webhook ensure your webhook endpoint is reachable");- }-println!();println!("Summary: {healthy} healthy, {unhealthy} unhealthy, {timeout} timed out");Ok(())@@ -93,7 +89,6 @@ pub(crate) fn configured_providers(config: &Config) -> Vec<&'static str> {("slack", channels.slack.is_some()),("mattermost", channels.mattermost.is_some()),("imessage", channels.imessage.is_some()),- ("matrix", channels.matrix.is_some()),("signal", channels.signal.is_some()),("whatsapp", channels.whatsapp.is_some()),("linq", channels.linq.is_some()),diff --git a/crates/openhuman-core/src/channels/context.rs b/crates/openhuman-core/src/channels/context.rsindex acf84c9397..2e4802af89 100644--- a/crates/openhuman-core/src/channels/context.rs+++ b/crates/openhuman-core/src/channels/context.rs@@ -10,14 +10,15 @@ use std::path::PathBuf;use std::sync::{Arc, Mutex};use tinytools::Tool;-pub(crate) use tinychannels_bus::context::{- clear_sender_history, compact_sender_history, ChannelRouteSelection, ConversationHistoryMap,+pub(crate) use tinychannels_bus::context::ChannelRouteSelection;+pub(crate) use tinychannels_runtime::context::{+ clear_sender_history, compact_sender_history, ConversationHistoryMap,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_bus::context::{+pub(crate) use tinychannels_runtime::context::{CHANNEL_HISTORY_COMPACT_CONTENT_CHARS, CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES,};diff --git a/crates/openhuman-core/src/channels/context_tests.rs b/crates/openhuman-core/src/channels/context_tests.rsindex e7e91a7346..fdd9de075a 100644--- a/crates/openhuman-core/src/channels/context_tests.rs+++ b/crates/openhuman-core/src/channels/context_tests.rs@@ -92,9 +92,9 @@ 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(tinychannels_bus::context::ChatMessage::user("short"));+ history.push(tinychannels_runtime::context::ChatMessage::user("short"));history.extend(- (0..20).map(|idx| tinychannels_bus::context::ChatMessage::assistant("x".repeat(700 + idx))),+ (0..20).map(|idx| tinychannels_runtime::context::ChatMessage::assistant("x".repeat(700 + idx))),);ctx.conversation_histories.lock()diff --git a/crates/openhuman-core/src/channels/contract_reexport_tests.rs b/crates/openhuman-core/src/channels/contract_reexport_tests.rsindex b7440bbb23..80e96fd760 100644--- a/crates/openhuman-core/src/channels/contract_reexport_tests.rs+++ b/crates/openhuman-core/src/channels/contract_reexport_tests.rs@@ -8,7 +8,7 @@ struct Recorder {}#[async_trait::async_trait]-impl tinychannels_bus::Channel for Recorder {+impl tinychannels_runtime::Channel for Recorder {fn name(&self) -> &str {"recorder"}@@ -38,7 +38,7 @@ fn channel_vocabulary_is_the_contract_crates_own_types() {use std::any::TypeId;assert_eq!(TypeId::of::<dyn Channel>(),- TypeId::of::<dyn tinychannels_bus::Channel>()+ TypeId::of::<dyn tinychannels_runtime::Channel>());assert_eq!(TypeId::of::<SendMessage>(),diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rsindex 074b39fc8f..7bab1ffced 100644--- a/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rs+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/shared.rs@@ -12,7 +12,6 @@ pub(crate) async fn channel_config_connected(("slack", channels.slack.is_some()),("mattermost", channels.mattermost.is_some()),("imessage", channels.imessage.is_some()),- ("matrix", channels.matrix.is_some()),("signal", channels.signal.is_some()),("whatsapp", channels.whatsapp.is_some()),("linq", channels.linq.is_some()),diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/status.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/status.rsindex abad25c6f8..9b32b27be5 100644--- a/crates/openhuman-core/src/channels/controllers/ops/connect/status.rs+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/status.rs@@ -160,9 +160,6 @@ pub async fn connected_channel_slugs(config: &Config) -> Result<Vec<String>, Strif cc.signal.is_some() {slugs.insert("signal".to_string());}- if cc.matrix.is_some() {- slugs.insert("matrix".to_string());- }if cc.imessage.is_some() {slugs.insert("imessage".to_string());}diff --git a/crates/openhuman-core/src/channels/mod.rs b/crates/openhuman-core/src/channels/mod.rsindex ccba734c86..31dbd19928 100644--- a/crates/openhuman-core/src/channels/mod.rs+++ b/crates/openhuman-core/src/channels/mod.rs@@ -11,7 +11,8 @@ pub mod contract_schema;#[cfg(any(feature = "voice", feature = "channels"))]pub(crate) mod credentials;-pub use tinychannels_bus::{Channel, ChannelSendExt, SendMessage};+pub use tinychannels_bus::SendMessage;+pub use tinychannels_runtime::{Channel, ChannelSendExt};#[cfg(feature = "channels")]pub mod bus;diff --git a/crates/openhuman-core/src/channels/providers/relay/channel.rs b/crates/openhuman-core/src/channels/providers/relay/channel.rsindex d3426ddf8d..8aadcbae8a 100644--- a/crates/openhuman-core/src/channels/providers/relay/channel.rs+++ b/crates/openhuman-core/src/channels/providers/relay/channel.rs@@ -11,7 +11,8 @@ use async_trait::async_trait;use serde_json::json;use crate::web_chat::{publish_web_channel_event, WebChannelEvent};-use tinychannels_bus::{Channel, ChannelMessage, SendMessage};+use tinychannels_bus::{ChannelMessage, SendMessage};+use tinychannels_runtime::Channel;/// The event name a relayed reply is published under.pub const CHANNEL_OUTBOUND_EVENT: &str = "channel_outbound";diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rsindex 73869968f5..a1bbbf283b 100644--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs@@ -133,7 +133,7 @@ pub(crate) async fn run_relay_turn(tracing::warn!("relayed channel runtime limits unavailable: {error}");let reply ="⚠️ This chat's assistant is not available right now. Please try again later.";- let _ = tinychannels_bus::Channel::send(+ let _ = tinychannels_runtime::Channel::send(channel.as_ref(),&crate::channels::SendMessage::new(reply, ¶ms.chat_id),)@@ -170,7 +170,7 @@ pub(crate) async fn run_relay_turn();let reply ="⚠️ This chat's assistant is not available right now. Please try again later.";- let _ = tinychannels_bus::Channel::send(+ let _ = tinychannels_runtime::Channel::send(channel.as_ref(),&crate::channels::SendMessage::new(reply, ¶ms.chat_id),)diff --git a/crates/openhuman-core/src/channels/providers/relay/store.rs b/crates/openhuman-core/src/channels/providers/relay/store.rsindex 1dc0313803..504a12bbaf 100644--- a/crates/openhuman-core/src/channels/providers/relay/store.rs+++ b/crates/openhuman-core/src/channels/providers/relay/store.rs@@ -15,7 +15,7 @@ type ThreadLocks = Mutex<HashMap<(PathBuf, String), Arc<tokio::sync::Mutex<()>>>use chrono::Utc;use serde_json::json;-use tinychannels_bus::context::ChatMessage;+use tinychannels_runtime::context::ChatMessage;use super::params::RelayInboundParams;use crate::threads::store::blocking as conversations;diff --git a/crates/openhuman-core/src/channels/routes_tests.rs b/crates/openhuman-core/src/channels/routes_tests.rsindex d1c642f116..6faad77f51 100644--- a/crates/openhuman-core/src/channels/routes_tests.rs+++ b/crates/openhuman-core/src/channels/routes_tests.rs@@ -12,7 +12,7 @@ use std::sync::{Arc, Mutex};use std::task::{Context, Poll, Waker};use tinybus::EventHandler;use tinychannels::routes::resolve_provider_alias;-use tinychannels_bus::context::ChatMessage;+use tinychannels_runtime::context::ChatMessage;use tinychannels_bus::ChannelMessage;use tinytools::{Tool, ToolResult};diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs b/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rsindex 902f59a767..afdf76ef20 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs@@ -11,7 +11,7 @@ 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!("{}", traits::context::worker_crash_message(&error));+ tracing::warn!("{}", tinychannels_runtime::context::worker_crash_message(&error));}}diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rsindex 49e939da66..c83696402d 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs@@ -18,7 +18,7 @@ use std::sync::Arc;use std::time::{Duration, Instant};use tinyagents_session::transcript::TranscriptMessage;use tinychannels_bus as traits;-use tinychannels_bus::context::ChatMessage;+use tinychannels_runtime::context::ChatMessage;use tokio_util::sync::CancellationToken;use tokio_util::task::AbortOnDropHandle;diff --git a/crates/openhuman-core/src/channels/runtime/startup.rs b/crates/openhuman-core/src/channels/runtime/startup.rsindex 2ddb66581a..8092b220a9 100644--- a/crates/openhuman-core/src/channels/runtime/startup.rs+++ b/crates/openhuman-core/src/channels/runtime/startup.rs@@ -37,7 +37,7 @@ pub(crate) async fn prepare_runtime_limits(ChannelControlResult::RuntimeLimits {timeout_secs,max_in_flight,- } if timeout_secs >= tinychannels_bus::context::MIN_CHANNEL_MESSAGE_TIMEOUT_SECS+ } if timeout_secs >= tinychannels_runtime::context::MIN_CHANNEL_MESSAGE_TIMEOUT_SECS&& max_in_flight > 0 =>{Ok((timeout_secs, max_in_flight))diff --git a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rsindex 3f661745d1..f58095305b 100644--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs@@ -14,7 +14,8 @@ use tinychannels_bus::module_runtime::{ChannelIngressKind, ChannelMessagePreparation, ConfiguredChannelInfo,};use tinychannels_bus::module_supervision::ChannelSupervisionPolicy;-use tinychannels_bus::{Channel, ChannelMessage, SendMessage};+use tinychannels_bus::{ChannelMessage, SendMessage};+use tinychannels_runtime::Channel;use tinychannels_bus::{ChannelInteraction, ChannelInteractionResult};use tokio::sync::mpsc;diff --git a/crates/openhuman-core/src/channels/runtime/test_support.rs b/crates/openhuman-core/src/channels/runtime/test_support.rsindex 79edbb13ea..dc96145f3c 100644--- a/crates/openhuman-core/src/channels/runtime/test_support.rs+++ b/crates/openhuman-core/src/channels/runtime/test_support.rs@@ -21,7 +21,7 @@ use std::path::PathBuf;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;-use tinychannels_bus::context::ChatMessage;+use tinychannels_runtime::context::ChatMessage;use tinychannels_bus::{ChannelMessage, SendMessage};use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};use tinytools::{Tool, ToolResult};diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rsindex 3d79789cbb..c6c46d8116 100644--- a/crates/openhuman-core/src/config/mod.rs+++ b/crates/openhuman-core/src/config/mod.rs@@ -49,7 +49,7 @@ pub use schema::{DictationActivationMode, DictationConfig, DiscordConfig, DockerRuntimeConfig, EmailConfig,EmbeddingRouteConfig, GitbooksConfig, HttpHeader, HttpRequestConfig, IMessageConfig,IntegrationToggle, IntegrationsConfig, LarkConfig, LegacySearchInputs, LinqConfig,- LocalAiConfig, LocalJailConfig, MatrixConfig, McpAuthConfig, McpClientConfig,+ LocalAiConfig, LocalJailConfig, McpAuthConfig, McpClientConfig,McpClientIdentityConfig, McpServerConfig, McpToolExposure, MemoryConfig, MemoryLayoutMode,ModelRouteConfig, MultimodalConfig, MultimodalFileConfig, ObservabilityConfig,OrchestratorModelConfig, PresentationMode, PrivacyConfig, PrivacyMode, ProviderRoute,@@ -58,7 +58,7 @@ pub use schema::{SearchConfig, SearchEngineCredentials, SearchHostCredential, SearchProviderSettings,SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig, SlackConfig, StreamMode, SttEngine,TeamModelConfig, TelegramConfig, TokenjuiceConfig, UnknownKeyedSearchProvider, UpdateConfig,- UpdateRestartStrategy, VoiceActivationMode, VoiceServerConfig, WebSearchConfig, WebhookConfig,+ UpdateRestartStrategy, VoiceActivationMode, VoiceServerConfig, WebSearchConfig,YuanbaoConfig, DEFAULT_MODEL, LEGACY_TIER_MODELS, MANAGED_MULTIMODAL_MODELS,MANAGED_SEARCH_PROVIDERS, MODEL_IMAGE_GENERATION_AGENT, MODEL_MANAGED_DEFAULT,MODEL_MEDIA_UNDERSTANDING, MODEL_VIDEO_GENERATION_AGENT, SEARCH_ENGINE_BRAVE,diff --git a/crates/openhuman-core/src/config/schema/channels.rs b/crates/openhuman-core/src/config/schema/channels.rsindex ffd2d3f56f..ec28c4d13a 100644--- a/crates/openhuman-core/src/config/schema/channels.rs+++ b/crates/openhuman-core/src/config/schema/channels.rs@@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize};pub use tinychannels_bus::config::{ChannelsConfig, DingTalkConfig, DiscordConfig, EmailConfig, IMessageConfig, IrcConfig,- LarkConfig, LarkReceiveMode, LinqConfig, MatrixConfig, MattermostConfig, QQConfig,- SignalConfig, SlackConfig, StreamMode, TelegramConfig, WebhookConfig, WhatsAppConfig,+ LarkConfig, LarkReceiveMode, LinqConfig, MattermostConfig, QQConfig,+ SignalConfig, SlackConfig, StreamMode, TelegramConfig, WhatsAppConfig,YuanbaoConfig,};diff --git a/crates/openhuman-core/src/config/schema/load/secrets.rs b/crates/openhuman-core/src/config/schema/load/secrets.rsindex 35a76b8581..640d3c291d 100644--- a/crates/openhuman-core/src/config/schema/load/secrets.rs+++ b/crates/openhuman-core/src/config/schema/load/secrets.rs@@ -189,14 +189,6 @@ pub(super) fn decrypt_config_secrets(config: &mut Config, openhuman_dir: &Path)decrypt_optional_secret(&store, &mut tok, "mattermost.bot_token")?;m.bot_token = tok.unwrap_or_default();}- if let Some(ref mut w) = ch.webhook {- decrypt_optional_secret(&store, &mut w.secret, "webhook.secret")?;- }- if let Some(ref mut mx) = ch.matrix {- let mut tok = Some(mx.access_token.clone());- decrypt_optional_secret(&store, &mut tok, "matrix.access_token")?;- mx.access_token = tok.unwrap_or_default();- }if let Some(ref mut wa) = ch.whatsapp {decrypt_optional_secret(&store, &mut wa.access_token, "whatsapp.access_token")?;decrypt_optional_secret(&store, &mut wa.verify_token, "whatsapp.verify_token")?;@@ -306,14 +298,6 @@ pub(super) fn encrypt_config_secrets(config: &mut Config) -> Result<()> {encrypt_optional_secret(&store, &mut tok, "mattermost.bot_token")?;m.bot_token = tok.unwrap_or_default();}- if let Some(ref mut w) = ch.webhook {- encrypt_optional_secret(&store, &mut w.secret, "webhook.secret")?;- }- if let Some(ref mut mx) = ch.matrix {- let mut tok = Some(mx.access_token.clone());- encrypt_optional_secret(&store, &mut tok, "matrix.access_token")?;- mx.access_token = tok.unwrap_or_default();- }if let Some(ref mut wa) = ch.whatsapp {encrypt_optional_secret(&store, &mut wa.access_token, "whatsapp.access_token")?;encrypt_optional_secret(&store, &mut wa.verify_token, "whatsapp.verify_token")?;diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rsindex e7488dc1d9..fd26de1226 100644--- a/crates/openhuman-core/src/config/schema/mod.rs+++ b/crates/openhuman-core/src/config/schema/mod.rs@@ -84,9 +84,9 @@ pub use capability_providers::{CapabilityProviderConfig, CapabilityProviderTrustpub use channel_voice::{ChannelVoiceConfig, ChannelVoiceOverride, VoiceReplyMode};pub use channels::{AuditConfig, ChannelsConfig, DingTalkConfig, DiscordConfig, EmailConfig, IMessageConfig,- IrcConfig, LarkConfig, LarkReceiveMode, LinqConfig, MatrixConfig, MattermostConfig, QQConfig,+ IrcConfig, LarkConfig, LarkReceiveMode, LinqConfig, MattermostConfig, QQConfig,ResourceLimitsConfig, SandboxBackend, SandboxConfig, SecurityConfig, SignalConfig, SlackConfig,- StreamMode, TelegramConfig, WebhookConfig, WhatsAppConfig, YuanbaoConfig,+ StreamMode, TelegramConfig, WhatsAppConfig, YuanbaoConfig,};pub(crate) use cli_overrides::set_cli_inference_overrides;pub use context::{CompactionSettings, CompactionStrategy, ContextConfig};diff --git a/crates/openhuman-core/src/cron/bus.rs b/crates/openhuman-core/src/cron/bus.rsindex fe1a72afd7..4a95582319 100644--- a/crates/openhuman-core/src/cron/bus.rs+++ b/crates/openhuman-core/src/cron/bus.rs@@ -11,7 +11,8 @@ use async_trait::async_trait;use std::collections::HashMap;use std::sync::Arc;use tinybus::EventHandler;-use tinychannels_bus::{Channel, SendMessage};+use tinychannels_bus::SendMessage;+use tinychannels_runtime::Channel;/// Subscribes to `CronDeliveryRequested` events and dispatches/// the output to the named channel.diff --git a/crates/openhuman-core/src/cron/channel_bridge.rs b/crates/openhuman-core/src/cron/channel_bridge.rsindex db9614c05c..315428b21d 100644--- a/crates/openhuman-core/src/cron/channel_bridge.rs+++ b/crates/openhuman-core/src/cron/channel_bridge.rs@@ -10,8 +10,9 @@use std::collections::HashMap;use std::sync::{Arc, Mutex, RwLock};-use tinychannels_bus::context::ChatMessage;-use tinychannels_bus::{Channel, SendMessage};+use tinychannels_runtime::context::ChatMessage;+use tinychannels_bus::SendMessage;+use tinychannels_runtime::Channel;/// Same shape as `channels::context::ConversationHistoryMap`, spelled out so/// cron does not depend on the feature-gated `channels` module.diff --git a/crates/openhuman-core/src/cron/job_builder.rs b/crates/openhuman-core/src/cron/job_builder.rsindex 4818e06011..c198e83d14 100644--- a/crates/openhuman-core/src/cron/job_builder.rs+++ b/crates/openhuman-core/src/cron/job_builder.rs@@ -36,7 +36,6 @@ fn allowed_users_for_channel<'a>(config: &'a Config, channel: &str) -> Option<&'"discord" => cc.discord.as_ref().map(|c| c.allowed_users.as_slice()),"slack" => cc.slack.as_ref().map(|c| c.allowed_users.as_slice()),"mattermost" => cc.mattermost.as_ref().map(|c| c.allowed_users.as_slice()),- "matrix" => cc.matrix.as_ref().map(|c| c.allowed_users.as_slice()),"irc" => cc.irc.as_ref().map(|c| c.allowed_users.as_slice()),"lark" => cc.lark.as_ref().map(|c| c.allowed_users.as_slice()),"dingtalk" => cc.dingtalk.as_ref().map(|c| c.allowed_users.as_slice()),diff --git a/crates/openhuman-core/src/cron/mod.rs b/crates/openhuman-core/src/cron/mod.rsindex aa6656ca6e..e36a863384 100644--- a/crates/openhuman-core/src/cron/mod.rs+++ b/crates/openhuman-core/src/cron/mod.rs@@ -12,8 +12,10 @@// Host-condition policy (battery / AC / CPU) that throttles background LLM// work such as memory digests. The cron poll loop itself does not consult it.+#[allow(deprecated, reason = "v21 ChannelMessage/SendMessage shims stay until the native channel path moves to canonical v22 content")]pub mod bus;pub(crate) mod bus_host;+#[allow(deprecated, reason = "v21 ChannelMessage/SendMessage shims stay until the native channel path moves to canonical v22 content")]pub mod channel_bridge;pub(crate) mod client;pub mod completion_owner;diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rsindex 682d2b6a38..65b73a1b72 100644--- a/crates/openhuman-core/src/lib.rs+++ b/crates/openhuman-core/src/lib.rs@@ -54,6 +54,7 @@pub mod agent;pub mod backend;+#[allow(deprecated, reason = "v21 ChannelMessage/SendMessage shims stay until the native channel path moves to canonical v22 content")]pub mod channels;pub mod commands;pub mod config;diff --git a/crates/openhuman-core/src/platform/doctor/core/config_checks.rs b/crates/openhuman-core/src/platform/doctor/core/config_checks.rsindex 237be4d7d7..e92aedf1e9 100644--- a/crates/openhuman-core/src/platform/doctor/core/config_checks.rs+++ b/crates/openhuman-core/src/platform/doctor/core/config_checks.rs@@ -167,12 +167,10 @@ pub(super) fn check_config_semantics(config: &Config, items: &mut Vec<Diagnostic|| cc.discord.is_some()|| cc.slack.is_some()|| cc.imessage.is_some()- || cc.matrix.is_some()|| cc.whatsapp.is_some()|| cc.email.is_some()|| cc.irc.is_some()- || cc.lark.is_some()- || cc.webhook.is_some();+ || cc.lark.is_some();if has_channel {items.push(DiagnosticItem::ok(cat, "at least one channel configured"));diff --git a/crates/openhuman-core/src/threads/store/mod.rs b/crates/openhuman-core/src/threads/store/mod.rsindex f59c52671b..2f1978e58a 100644--- a/crates/openhuman-core/src/threads/store/mod.rs+++ b/crates/openhuman-core/src/threads/store/mod.rs@@ -31,6 +31,7 @@pub mod backend;pub mod blocking;+#[allow(deprecated, reason = "v21 ChannelMessage/SendMessage shims stay until the native channel path moves to canonical v22 content")]mod bus;mod legacy_import;#[cfg(test)]diff --git a/crates/openhuman-core/src/web_chat/channel_event.rs b/crates/openhuman-core/src/web_chat/channel_event.rsindex fae67f1607..9c4754af18 100644--- a/crates/openhuman-core/src/web_chat/channel_event.rs+++ b/crates/openhuman-core/src/web_chat/channel_event.rs@@ -1,10 +1,21 @@-//! Payload types for events the web channel publishes to connected clients.+//! The in-process form of the events the web channel publishes to connected+//! clients.//!-//! Domains build these and hand them to-//! [`publish_web_channel_event`](super::publish_web_channel_event); the-//! Socket.IO transport in `openhuman-rpc` forwards them to the browser.+//! The wire vocabulary is owned by `tinychannels-bus` ([`bus_web`]): a typed,+//! tagged enum plus the payload structs re-exported below. Domains still build+//! this flat struct and hand it to+//! [`publish_web_channel_event`](super::publish_web_channel_event) (the+//! Socket.IO transport in `openhuman-rpc`, the `/events` stream and the TUI all+//! read it), and the web adapter's typed events land here through the+//! `From<bus_web::WebChannelEvent>` conversion below.use serde::{Deserialize, Serialize};+use tinychannels_bus::web as bus_web;++pub use bus_web::{+ ChatSuggestion, GuardrailPayload, GuardrailReason, QueueItemPayload, SubagentProgressDetail,+ SubagentUsagePayload, TurnTimingPayload, TurnUsagePayload,+};/// Standard event payload for the web channel transport.///@@ -204,281 +215,29 @@ pub struct WebChannelEvent {/// original turn's request context).#[serde(skip_serializing_if = "Option::is_none")]pub turn_request_id: Option<String>,- /// Time-to-first-visible timing summary, carried on `chat_done`. See- /// `web_chat::turn_timing`.- #[serde(skip_serializing_if = "Option::is_none")]- pub timing: Option<TurnTimingPayload>,- /// Follow-up prompt suggestions offered to the user after a turn.- #[serde(skip_serializing_if = "Option::is_none")]- pub suggestions: Option<Vec<ChatSuggestion>>,- /// Guardrail verdict attached to a blocked/flagged turn.- #[serde(skip_serializing_if = "Option::is_none")]- pub guardrail: Option<GuardrailPayload>,- /// Run-queue item this event reports on (queued/delivered/removed).- #[serde(skip_serializing_if = "Option::is_none")]- pub queue_item: Option<QueueItemPayload>,- /// Session goal snapshot, carried on goal-lifecycle events. Left as a- /// raw `Value` because the goal shape is owned by `tinyagents-graph`,- /// not this crate.- #[serde(skip_serializing_if = "Option::is_none")]- pub goal: Option<serde_json::Value>,- /// Session todo-list snapshot, carried on todo-lifecycle events. Raw- /// `Value` for the same reason as `goal`.- #[serde(skip_serializing_if = "Option::is_none")]- pub todos: Option<serde_json::Value>,- /// Human-readable reason a turn/queue item was cancelled.- #[serde(skip_serializing_if = "Option::is_none")]- pub cancel_reason: Option<String>,- /// Id of the turn/request that superseded this one (e.g. a steer- /// requeue), when applicable.- #[serde(skip_serializing_if = "Option::is_none")]- pub superseded_by: Option<String>,- /// `Some(true)` on an `approval_request` whose park can outlive the chat- /// turn it is shown on (an async-delegated sub-agent). The client keeps- /// such a card across that turn's `chat_done` and clears it on- /// `approval_decided` instead. Absent for an ordinary in-turn park.- #[serde(skip_serializing_if = "Option::is_none")]- pub detached: Option<bool>,-}--impl WebChannelEvent {- /// Whether a SaaS user agent's stream may carry this event: only one- /// stamped with that agent. An unstamped event (published outside any- /// agent scope) is dropped rather than guessed at.- pub fn belongs_to(&self, agent: &str) -> bool {- self.agent.as_deref() == Some(agent)- }-- /// Whether a SaaS profile's stream may carry this event: only one stamped- /// with that profile. An unstamped event is dropped rather than guessed at.- pub fn belongs_to_profile(&self, profile: &str) -> bool {- self.profile.as_deref() == Some(profile)- }-- /// Stamp the tenant whose work produced this event where the publisher- /// left it unset. A SaaS task with no scope (`None`) stamps nothing, so- /// the event reaches no user's stream.- pub fn stamp_tenant(&mut self, tenant: Option<crate::core::runtime::Tenant>) {- let Some(tenant) = tenant else {- return;- };- if self.agent.is_none() {- self.agent = tenant.agent;+ impl From<bus_web::WebChannelEvent> for WebChannelEvent {+ /// The wire form of a typed event is, by construction, the flat struct's+ /// serialization, so the conversion goes through it. Two spellings the+ /// typed projection cannot omit are normalised to the deployed wire: a+ /// `null` argument payload and an unnamed tool on an argument delta are+ /// absent, not empty.+ fn from(event: bus_web::WebChannelEvent) -> Self {+ let mut flat = serde_json::to_value(&event)+ .and_then(serde_json::from_value::<WebChannelEvent>)+ .unwrap_or_else(|error| {+ log::warn!("[web-channel] typed event did not convert to the bus form: {error}");+ WebChannelEvent::default()+ });+ if flat.args.as_ref().is_some_and(serde_json::Value::is_null) {+ flat.args = None;}- if self.profile.is_none() {- self.profile = tenant.profile;+ if flat.tool_name.as_deref() == Some("") {+ flat.tool_name = None;}+ flat}}-/// Time-to-first-visible timing summary for a completed turn. See-/// `web_chat::turn_timing::TurnTiming`.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct TurnTimingPayload {- #[serde(skip_serializing_if = "Option::is_none")]- pub first_token_ms: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub first_tool_ms: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub total_ms: Option<u64>,- /// `usage.output_tokens / (total_ms / 1000)`, computed at delivery time- /// when both a timing snapshot and the turn's output-token count are- /// available. `None` when either input is missing (e.g. a budget-- /// exhausted synthetic result, or a turn that produced no completion- /// tokens). Added by C4 — not in the original wire-contract prep pass;- /// see wire-contract.md "Added by C4".- #[serde(skip_serializing_if = "Option::is_none")]- pub tokens_per_second: Option<f64>,-}--/// One follow-up prompt suggestion offered after a turn.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct ChatSuggestion {- pub prompt: String,- #[serde(skip_serializing_if = "Option::is_none")]- pub label: Option<String>,-}--/// One guardrail rejection reason code + message.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct GuardrailReason {- pub code: String,- pub message: String,-}--/// Guardrail verdict attached to a blocked/flagged turn (`chat_error` with-/// `error_type = "guardrail"`).-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct GuardrailPayload {- pub verdict: String,- pub score: f64,- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub reasons: Vec<GuardrailReason>,-}--/// A run-queue item summary (`queue_item_queued` / `queue_item_delivered` /-/// `queue_item_removed`).-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct QueueItemPayload {- pub id: String,- #[serde(skip_serializing_if = "Option::is_none")]- pub lane: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub text_preview: Option<String>,-}--/// Token/cost/context totals for one completed turn, attached to `chat_done`.-///-/// Every numeric is a turn total (parent agent **plus** any sub-agents spawned-/// during the turn); the `subagents` list breaks the same spend down per child-/// for the UI hover. `context_window` is `0` when the core couldn't resolve the-/// model's window (e.g. an unknown cloud model) — the UI falls back to a-/// default in that case.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct TurnUsagePayload {- pub input_tokens: u64,- pub output_tokens: u64,- pub cached_input_tokens: u64,- /// The turn's cost, or `null` when it is not known (some call had no- /// reported charge and no catalogued price). The UI shows no price then.- pub cost_usd: Option<f64>,- /// `charged` (every call billed by the provider), `estimated` (some call- /// priced from list rates) or `unknown`.- #[serde(default)]- pub cost_source: tinyagents_harness::cost::CostSource,- pub context_window: u64,- /// Tokens the parent's context held after the turn's final model call: the- /// context gauge's numerator. Unlike the totals above it is one request,- /// not a sum, and excludes sub-agents. `0` when the core did not record it;- /// the UI then falls back to its older estimate.- #[serde(default)]- pub context_tokens: u64,- /// Per-sub-agent spend, omitted from the wire when no sub-agents ran.- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub subagents: Vec<SubagentUsagePayload>,-}--/// One sub-agent's token/cost contribution within a turn (hover breakdown).-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct SubagentUsagePayload {- pub task_id: String,- pub agent_id: String,- pub input_tokens: u64,- pub output_tokens: u64,- /// `null` when the child's cost is not known.- pub cost_usd: Option<f64>,-}--/// Per-event subagent progress detail attached to `WebChannelEvent`.-///-/// Carries the fields the parent thread's UI needs to render a live-/// subagent block — child iteration counters, mode, child task/agent-/// ids when distinct from the flat `tool_name` (which already carries-/// the agent id on top-level subagent events but not on nested-/// `subagent_tool_*` events where `tool_name` is the *child's* tool),-/// and final-run statistics on `subagent_completed`.-///-/// Every field is optional and skipped from the JSON payload when-/// absent — this keeps the wire format compact for non-subagent events-/// (where the whole struct is `None`) and lets new fields land-/// non-breakingly behind older clients.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub struct SubagentProgressDetail {- /// Resolved spawn mode — `"typed"` or `"fork"`.- #[serde(skip_serializing_if = "Option::is_none")]- pub mode: Option<String>,- /// Whether the spawn requested a dedicated worker thread.- #[serde(skip_serializing_if = "Option::is_none")]- pub dedicated_thread: Option<bool>,- /// Character length of the delegation prompt (on `subagent_spawned`).- #[serde(skip_serializing_if = "Option::is_none")]- pub prompt_chars: Option<u64>,- /// Sub-agent's child iteration counter (on `subagent_iteration_start`,- /// `subagent_tool_call`, `subagent_tool_result`). 1-based.- #[serde(skip_serializing_if = "Option::is_none")]- pub child_iteration: Option<u32>,- /// Sub-agent's configured iteration cap.- #[serde(skip_serializing_if = "Option::is_none")]- pub child_max_iterations: Option<u32>,- /// Child agent id (on nested `subagent_tool_*` events where the flat- /// `tool_name` is the child's tool, not the agent).- #[serde(skip_serializing_if = "Option::is_none")]- pub agent_id: Option<String>,- /// Spawn task id (on nested `subagent_tool_*` events).- #[serde(skip_serializing_if = "Option::is_none")]- pub task_id: Option<String>,- /// Elapsed wall-clock for the call/run in milliseconds.- #[serde(skip_serializing_if = "Option::is_none")]- pub elapsed_ms: Option<u64>,- /// This child's own token + cost spend (on `subagent_completed`), and- /// **only when it is not already inside the parent turn's totals**.- ///- /// The consumer adds these unconditionally, so an emit site that leaves- /// them absent contributes nothing — the safe direction. Populating them- /// for a child whose usage DID reach `parent_subagent_usage` silently- /// doubles the user's reported tokens and money, because- /// `holistic_last_turn_usage` already folded both into `chat_done`. See- /// `AgentProgress::SubagentCompleted::usage`.- #[serde(skip_serializing_if = "Option::is_none")]- pub input_tokens: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub output_tokens: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub cached_input_tokens: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- pub cost_usd: Option<f64>,- /// Total iterations the sub-agent used (on `subagent_completed`).- #[serde(skip_serializing_if = "Option::is_none")]- pub iterations: Option<u32>,- /// Character length of the sub-agent's final assistant text- /// (on `subagent_completed`) or the tool result- /// (on `subagent_tool_result`).- #[serde(skip_serializing_if = "Option::is_none")]- pub output_chars: Option<u64>,- /// Persistent worker sub-thread id backing the delegation (on- /// `subagent_spawned`). The frontend stores it on the subagent row and- /// uses it to reopen the full parent↔subagent conversation from memory.- #[serde(skip_serializing_if = "Option::is_none")]- pub worker_thread_id: Option<String>,- /// Human-readable display name from the agent registry (e.g.- /// "Researcher", "Coding Agent"). The frontend uses this for- /// consistent agent labels across timeline, sub-mascots, and drawer.- #[serde(skip_serializing_if = "Option::is_none")]- pub display_name: Option<String>,- /// Absolute path to the worker's isolated `git worktree` checkout- /// (on `subagent_completed`, when the worker ran with- /// `isolation = "worktree"`). Drives the inline worktree row's- /// open/diff/remove actions. `None` for non-isolated workers (#3376).- #[serde(skip_serializing_if = "Option::is_none")]- pub worktree_path: Option<String>,- /// Files (relative to the worktree root) the worker changed, snapshot- /// after the run (on `subagent_completed`). Absent for non-isolated- /// workers and clean worktrees.- #[serde(skip_serializing_if = "Option::is_none")]- pub changed_files: Option<Vec<String>>,- /// Whether the worker's worktree had uncommitted changes after the run- /// (on `subagent_completed`). A dirty worktree must not be auto-removed —- /// the UI requires an explicit user decision. `None` for non-isolated.- #[serde(skip_serializing_if = "Option::is_none")]- pub dirty_status: Option<bool>,- /// The parent turn's tool-call id that this sub-agent spawn is- /// attributed to (on `subagent_spawned`), mirroring- /// `AgentProgress::SubagentSpawned::parent_call_id`. Lets the UI- /// attach a spawn to the exact `spawn_subagent`/dispatch tool call- /// that created it instead of inferring it from arrival order.- #[serde(skip_serializing_if = "Option::is_none")]- pub parent_call_id: Option<String>,- /// The sub-agent's final output text (on `subagent_completed`),- /// mirrored alongside the top-level `output` field so a consumer that- /// only reads `subagent.*` still gets the result text.- #[serde(skip_serializing_if = "Option::is_none")]- pub output: Option<String>,-}+#[cfg(test)]+#[path = "channel_event_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/web_chat/surface.rs b/crates/openhuman-core/src/web_chat/surface.rsnew file mode 100644index 0000000000..d77d25773a--- /dev/null+++ b/crates/openhuman-core/src/web_chat/surface.rs@@ -0,0 +1,132 @@+//! The host's side of the `tinychannels` web adapter: where a turn's typed+//! events go.+//!+//! The adapter projects canonical output events onto the deployed web wire and+//! hands each result to a [`WebEventSink`]. This host's sink is the+//! process-wide `WebChannelEvent` broadcast (`event_bus_channel`), which+//! Socket.IO, the JSON-RPC `/events` stream, the relay and the TUI already+//! consume, stamped with the tenant of the context the turn runs under.++use std::sync::atomic::{AtomicU32, Ordering};+use std::sync::Arc;++use async_trait::async_trait;+use tinychannels_bus::module_progressive::ChannelOutputEvent;+use tinychannels_bus::web as bus_web;+use tinychannels_runtime::adapters::web::{WebChannelAdapter, WebEventSink, WebScope};+use tinychannels_runtime::channel::ChannelSendError;++use super::event_bus_channel::publish_web_channel_event_in;+use super::WebChannelEvent;+use crate::core::runtime::DispatchCtx;++/// Addressing of one turn on the web wire.+#[derive(Clone, Debug)]+pub(crate) struct TurnIds {+ pub(crate) client_id: String,+ pub(crate) thread_id: String,+ pub(crate) request_id: String,+}++/// [`WebEventSink`] over the in-process broadcast.+struct SurfaceSink {+ ctx: DispatchCtx,+ /// The round of the narration the next `chat_interim` carries. The+ /// canonical `Clarification` output has no round, and the frontend keys one+ /// interim bubble per round, so the host supplies it here.+ interim_round: AtomicU32,+}++#[async_trait]+impl WebEventSink for SurfaceSink {+ async fn publish(+ &self,+ _scope: &WebScope,+ event: bus_web::WebChannelEvent,+ ) -> Result<(), ChannelSendError> {+ let mut flat = WebChannelEvent::from(event);+ if flat.event == "chat_interim" && flat.round.is_none() {+ flat.round = Some(self.interim_round.load(Ordering::Relaxed)).filter(|r| *r > 0);+ }+ publish_web_channel_event_in(&self.ctx, flat);+ Ok(())+ }+}++/// One turn's web adapter plus the sink it publishes through.+#[derive(Clone)]+pub(crate) struct Surface {+ adapter: Arc<WebChannelAdapter>,+ sink: Arc<SurfaceSink>,+ ids: TurnIds,+}++impl Surface {+ /// A surface for the turn `ids`, publishing under `ctx`. One adapter per+ /// turn: it carries that turn's `seq` counter, and dropping it with the+ /// turn is its cleanup.+ pub(crate) fn new(ctx: &DispatchCtx, ids: TurnIds) -> Self {+ let sink = Arc::new(SurfaceSink {+ ctx: ctx.clone(),+ interim_round: AtomicU32::new(0),+ });+ let adapter = Arc::new(WebChannelAdapter::new(+ None,+ WebScope::local(),+ sink.clone() as Arc<dyn WebEventSink>,+ ));+ Self { adapter, sink, ids }+ }++ /// Project one canonical output event onto the web wire, in `seq` order.+ pub(crate) async fn output(&self, event: ChannelOutputEvent) {+ let TurnIds {+ client_id,+ thread_id,+ request_id,+ } = &self.ids;+ if let Err(error) = self+ .adapter+ .publish_output(client_id, thread_id, request_id, event)+ .await+ {+ log::warn!(+ "[web-channel] output event not published request_id={request_id}: {}",+ error.message+ );+ }+ }++ /// The leading narration of `round`, flushed as an interim bubble.+ pub(crate) async fn interim(&self, round: u32, text: String) {+ self.sink.interim_round.store(round, Ordering::Relaxed);+ self.output(ChannelOutputEvent::Clarification { prompt: text })+ .await;+ }++ /// Publish a host-authored event unchanged: a terminal event, or one with+ /// no canonical output form.+ pub(crate) async fn event(&self, event: bus_web::WebChannelEvent) {+ if let Err(error) = self.adapter.publish_event(event).await {+ log::warn!(+ "[web-channel] event not published request_id={}: {}",+ self.ids.request_id,+ error.message+ );+ }+ }++ /// The addressing context for an event of this turn.+ pub(crate) fn context(&self) -> bus_web::WebEventContext {+ bus_web::WebEventContext {+ client_id: self.ids.client_id.clone(),+ thread_id: self.ids.thread_id.clone(),+ request_id: self.ids.request_id.clone(),+ ..Default::default()+ }+ }+}++#[cfg(test)]+#[path = "surface_tests.rs"]+mod tests;diff --git a/tests/in_process/config_auth_app_state_connectivity_e2e.rs b/tests/in_process/config_auth_app_state_connectivity_e2e.rsindex 6f2c5335db..72e4de9259 100644--- a/tests/in_process/config_auth_app_state_connectivity_e2e.rs+++ b/tests/in_process/config_auth_app_state_connectivity_e2e.rs@@ -22,9 +22,9 @@ use tempfile::{tempdir, TempDir};use openhuman_core::config::schema::{AuditConfig, CapabilityProviderConfig, CapabilityProviderTrustState, DashboardConfig,- DingTalkConfig, DiscordConfig, EventStreamConfig, IrcConfig, LarkConfig, MatrixConfig,+ DingTalkConfig, DiscordConfig, EventStreamConfig, IrcConfig, LarkConfig,MemoryConfig, ModelHealthConfig, ProxyConfig, ProxyScope, QQConfig, ResourceLimitsConfig,- SandboxConfig, SecurityConfig, SlackConfig, TelegramConfig, WebhookConfig, WhatsAppConfig,+ SandboxConfig, SecurityConfig, SlackConfig, TelegramConfig, WhatsAppConfig,};use openhuman_core::config::{clear_active_user, default_projects_dir, pre_login_user_dir, read_active_user_id,@@ -1342,14 +1342,6 @@ async fn config_save_and_load_encrypts_channel_secret_fields() {channel_id: Some("C123".into()),allowed_users: vec![],});- config.channels_config.matrix = Some(MatrixConfig {- homeserver: "https://matrix.example.test".into(),- access_token: "matrix-secret".into(),- user_id: Some("@worker:example.test".into()),- device_id: None,- room_id: "!room:example.test".into(),- allowed_users: vec![],- });config.channels_config.whatsapp = Some(WhatsAppConfig {access_token: Some("whatsapp-access-secret".into()),phone_number_id: Some("phone".into()),@@ -1360,10 +1352,6 @@ async fn config_save_and_load_encrypts_channel_secret_fields() {pair_code: None,allowed_numbers: vec![],});- config.channels_config.webhook = Some(WebhookConfig {- port: 0,- secret: Some("webhook-secret".into()),- });config.channels_config.irc = Some(IrcConfig {server: "irc.example.test".into(),port: 6697,@@ -1407,9 +1395,7 @@ async fn config_save_and_load_encrypts_channel_secret_fields() {"discord-secret","slack-bot-secret","slack-app-secret",- "matrix-secret","whatsapp-access-secret",- "webhook-secret","irc-server-secret","lark-app-secret","dingtalk-secret",