Skip to content

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

Merge remote-tracking branch 'upstream/main' into channels-provider-lease-bus

Steven Enamakel383b01e39c82
diff --cc Cargo.toml
index 65899e9766,65899e9766..134c0ef917
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -72,6 -72,6 +72,9 @@@ tinyinference-providers = { path = "ven
tinyinference-voice = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-voice" }
[patch.crates-io]
++tinybus = { path = "vendor/tinybus/crates/tinybus" }
++tinybus-macros = { path = "vendor/tinybus/crates/tinybus-macros" }
++tinybus-module = { path = "vendor/tinybus/crates/tinybus-module" }
tinyinference-core = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-core" }
tinyinference-embeddings = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-embeddings" }
tinyinference-llm = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }
diff --cc crates/openhuman-core/Cargo.toml
index bfebccd1e9,f305c980ea..e13299452b
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@@ -548,11 -541,7 +533,12 @@@ windows-sys = { version = "0.61", featu
tokio-tungstenite = { version = "0.29", default-features = false, features = ["connect", "handshake", "rustls-tls-webpki-roots"] }
[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-module = { path = "../../vendor/tinychannels/crates/tinychannels-module", features = ["static-link"] }
+ tinybox-core = { path = "../../vendor/tinybox/crates/tinybox-core" }
# The TinyMemory reference engine (an in-memory `MemoryEngine`) and the
# behavioural suite every engine must pass. Memory unit tests bind it as the
# engine instead of talking to CortexDB.
diff --cc crates/openhuman-core/src/channels/bus/delivery.rs
index 7dc367ccc3,8796148bc3..b468305014
--- a/crates/openhuman-core/src/channels/bus/delivery.rs
+++ b/crates/openhuman-core/src/channels/bus/delivery.rs
@@@ -1,29 -1,36 +1,29 @@@
-//! 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::modules::{
+ channel_runtime::ChannelRuntimeLease,
+ client::{ModuleCallError, ModuleClient},
+};
use crate::security::credentials::session_support::{
- BackendCredential, get_session_token, is_local_session_token,
+ get_session_token, is_local_session_token, BackendCredential,
};
-use async_trait::async_trait;
-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)
-}
++use serde_json::json;
+#[cfg(test)]
+use serde_json::Value;
- use serde_json::json;
+use tinychannels_bus::module_progressive::{
+ ProgressiveCommand, ProgressiveEvent, ProgressiveResult, ProgressiveTransportRequest,
+ ProgressiveTransportResult,
+};
- use tinychannels_bus::{ChannelBackendRequest, ChannelBackendResult, methods};
++use tinychannels_bus::{methods, ChannelBackendRequest, ChannelBackendResult};
-/// 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>() {
+/// 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 { .. }) => {
- ProgressiveSendError::EditUnsupported
+ ProgressiveTransportResult::EditUnsupported
}
- Some(BackendApiError::MessageNotFound { .. }) => ProgressiveSendError::MessageGone,
- _ => ProgressiveSendError::Other(err),
+ Some(BackendApiError::MessageNotFound { .. }) => ProgressiveTransportResult::MessageGone,
+ _ => ProgressiveTransportResult::Failed,
}
}
diff --cc crates/openhuman-core/src/channels/bus/delivery_tests.rs
index f2be5dc5e1,17f4efc7a6..263f33f03d
--- a/crates/openhuman-core/src/channels/bus/delivery_tests.rs
+++ b/crates/openhuman-core/src/channels/bus/delivery_tests.rs
@@@ -16,50 -16,22 +16,48 @@@ async fn transport_captures_no_local_or
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());
- assert!(
- ManagedTransport::capture(
- &crate::config::Config::default(),
- "telegram".into(),
- tokio_util::sync::CancellationToken::new()
- )
- .is_err()
- );
- let sender = BackendProgressiveSender;
++ assert!(ManagedTransport::capture(
++ &crate::config::Config::default(),
++ "telegram".into(),
++ tokio_util::sync::CancellationToken::new()
++ )
++ .is_err());
+}
- 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)
- ));
+#[test]
+fn every_transport_operation_carries_the_channel_scoped_by_the_host() {
+ for request in [
+ ProgressiveTransportRequest::Send {
+ channel: "discord:fixture".into(),
+ message: json!({"text":"hello"}),
+ },
+ ProgressiveTransportRequest::Edit {
+ channel: "discord:fixture".into(),
+ message_id: "message".into(),
+ text: "edited".into(),
+ },
+ ProgressiveTransportRequest::Delete {
+ channel: "discord:fixture".into(),
+ message_id: "message".into(),
+ },
+ ProgressiveTransportRequest::Typing {
+ channel: "discord:fixture".into(),
+ },
+ ] {
+ assert_eq!(request_channel(&request), "discord:fixture");
+ }
+}
+
+#[test]
+fn a_cancelled_identity_cannot_capture_a_replacement_credential() {
+ let session = tokio_util::sync::CancellationToken::new();
+ session.cancel();
+ let error = ManagedTransport::capture(
+ &crate::config::Config::default(),
+ "telegram".into(),
+ session,
+ )
+ .err()
+ .expect("closed identities must fail before credential reads");
+ assert_eq!(error.to_string(), "Channel session closed");
}
diff --cc crates/openhuman-core/src/channels/context.rs
index 4a9747d509,1e4c83b8ee..fee410b054
--- a/crates/openhuman-core/src/channels/context.rs
+++ b/crates/openhuman-core/src/channels/context.rs
@@@ -12,16 -12,15 +12,17 @@@ use std::sync::{Arc, Mutex}
use tinyagents_session::transcript::TranscriptMessage;
use tinytools::Tool;
-pub(crate) use tinychannels::context::{
- effective_channel_message_timeout_secs, ChannelRouteSelection,
- CHANNEL_HISTORY_COMPACT_CONTENT_CHARS, CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES,
- CHANNEL_MESSAGE_TIMEOUT_SECS, CHANNEL_TYPING_REFRESH_INTERVAL_SECS,
- DEFAULT_CHANNEL_INITIAL_BACKOFF_SECS, DEFAULT_CHANNEL_MAX_BACKOFF_SECS, MAX_CHANNEL_HISTORY,
+pub(crate) use tinychannels_bus::context::{
- CHANNEL_HISTORY_COMPACT_CONTENT_CHARS, CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES,
- CHANNEL_MESSAGE_TIMEOUT_SECS, CHANNEL_TYPING_REFRESH_INTERVAL_SECS, ChannelRouteSelection,
- DEFAULT_CHANNEL_INITIAL_BACKOFF_SECS, DEFAULT_CHANNEL_MAX_BACKOFF_SECS, MAX_CHANNEL_HISTORY,
++ ChannelRouteSelection, CHANNEL_HISTORY_COMPACT_CONTENT_CHARS,
++ CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES, CHANNEL_MESSAGE_TIMEOUT_SECS,
++ CHANNEL_TYPING_REFRESH_INTERVAL_SECS, DEFAULT_CHANNEL_INITIAL_BACKOFF_SECS,
++ DEFAULT_CHANNEL_MAX_BACKOFF_SECS, MAX_CHANNEL_HISTORY,
};
#[cfg(test)]
-pub(crate) use tinychannels::context::MIN_CHANNEL_MESSAGE_TIMEOUT_SECS;
+pub(crate) use tinychannels::context::{
- MIN_CHANNEL_MESSAGE_TIMEOUT_SECS, effective_channel_message_timeout_secs,
++ effective_channel_message_timeout_secs, MIN_CHANNEL_MESSAGE_TIMEOUT_SECS,
+};
/// Per-sender conversation history for channel messages.
pub(crate) type ConversationHistoryMap = Arc<Mutex<HashMap<String, Vec<TranscriptMessage>>>>;
diff --cc crates/openhuman-core/src/channels/context_tests.rs
index 15c11ea13c,4273a97214..9ee00b44b6
--- a/crates/openhuman-core/src/channels/context_tests.rs
+++ b/crates/openhuman-core/src/channels/context_tests.rs
@@@ -110,25 -110,19 +110,25 @@@ fn clear_and_compact_sender_history_upd
}
clear_sender_history(&ctx, sender);
- assert!(
- !ctx.conversation_histories
- .lock()
- .unwrap()
- .contains_key(sender)
- );
+ assert!(!ctx
+ .conversation_histories
+ .lock()
+ .unwrap()
+ .contains_key(sender));
}
-#[test]
-fn overflow_detection_covers_edge_cases() {
- assert!(is_context_window_overflow_error(&anyhow::anyhow!(
- "Maximum context length exceeded"
- )));
- assert!(!is_context_window_overflow_error(&anyhow::anyhow!(
- "network timeout"
- )));
+#[tokio::test]
+async fn overflow_detection_covers_edge_cases() {
+ let ctx = runtime_context();
- assert!(
- is_context_window_overflow_error(&ctx, &anyhow::anyhow!("Maximum context length exceeded"))
- .await
- .unwrap()
- );
++ assert!(is_context_window_overflow_error(
++ &ctx,
++ &anyhow::anyhow!("Maximum context length exceeded")
++ )
++ .await
++ .unwrap());
+ assert!(
+ !is_context_window_overflow_error(&ctx, &anyhow::anyhow!("network timeout"))
+ .await
+ .unwrap()
+ );
}
diff --cc crates/openhuman-core/src/channels/controllers/backend.rs
index 100ce72f4a,c7dc585288..04c8447a14
--- a/crates/openhuman-core/src/channels/controllers/backend.rs
+++ b/crates/openhuman-core/src/channels/controllers/backend.rs
@@@ -1,17 -1,21 +1,17 @@@
//! TinyChannels backend implementation for OpenHuman controller operations.
- use serde_json::{Value, json};
-use async_trait::async_trait;
-use serde::Serialize;
+ use serde_json::{json, Value};
use crate::config::{ChannelsConfig, Config};
use crate::core::Outcome;
use super::ops;
- #[cfg(test)]
- use tinychannels_bus::SendMessage;
-use tinychannels::{ChannelBackend, ChannelOutboundIntent, SendMessage};
use tinychannels_bus::controllers::{
- ChannelAuthMode, ChannelConnectionResult, ChannelDisconnectResult, ChannelReactionResult,
- ChannelSendMessageResult, ChannelStatusEntry, ChannelTestResult, ChannelThreadListResult,
- ChannelThreadResult, DiscordChannelEntry, DiscordChannelListResult, DiscordGuildEntry,
- DiscordGuildListResult, DiscordLinkCheckResult, DiscordLinkStartResult,
- DiscordPermissionCheckResult, TelegramLoginCheckResult, TelegramLoginStartResult,
+ ChannelAuthMode, ChannelDisconnectResult, ChannelReactionResult, ChannelSendMessageResult,
+ ChannelStatusEntry, ChannelThreadListResult, ChannelThreadResult,
};
++#[cfg(test)]
++use tinychannels_bus::SendMessage;
/// OpenHuman-owned implementation of the TinyChannels backend contract.
#[derive(Debug, Clone)]
diff --cc crates/openhuman-core/src/channels/host/channel_events.rs
index 2eb8e47449,8ac49351bf..67d0ef5c64
--- a/crates/openhuman-core/src/channels/host/channel_events.rs
+++ b/crates/openhuman-core/src/channels/host/channel_events.rs
@@@ -1,56 -1,48 +1,56 @@@
-//! 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 crate::channels::{Channel, ChannelSendExt, SendMessage};
+use crate::core::events::DomainEvent;
+use crate::modules::client::ModuleClient;
+use async_trait::async_trait;
use std::collections::HashMap;
use std::path::PathBuf;
-use std::sync::Arc;
-
-use async_trait::async_trait;
+use std::sync::{Arc, Mutex};
use tinybus::EventHandler;
- use tinychannels_bus::{ChannelMessage, capabilities_for};
-use tinychannels::approvals::{ApprovalPrompt, ApprovalSurface};
-use tinychannels::capabilities_for;
++use tinychannels_bus::{capabilities_for, ChannelMessage};
-use crate::channels::Channel;
-use crate::core::events::DomainEvent;
+#[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 {
+ pub fn with_config(
+ channels: Arc<HashMap<String, Arc<dyn Channel>>>,
+ config: Arc<crate::config::Config>,
+ ) -> Self {
Self {
- surface: ApprovalSurface::new(channels_by_name),
+ 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 {
diff --cc crates/openhuman-core/src/channels/host/mod.rs
index eb0ba8ae10,dfb48ef82d..d5746235fe
--- a/crates/openhuman-core/src/channels/host/mod.rs
+++ b/crates/openhuman-core/src/channels/host/mod.rs
@@@ -14,15 -24,11 +14,15 @@@ pub use adapters::
};
pub use channel_events::{ChannelApprovalSurfaceSubscriber, ChannelTurnStateSubscriber};
+#[cfg(test)]
use std::sync::Arc;
- #[cfg(test)]
- use tinychannels::ChannelHost;
+#[cfg(test)]
use tinychannels::host::ChannelHostBuilder;
++#[cfg(test)]
+ use tinychannels::ChannelHost;
+#[cfg(test)]
use crate::config::Config;
/// Assemble the full OpenHuman [`ChannelHost`] from a config snapshot.
diff --cc crates/openhuman-core/src/channels/host/remote_control.rs
index 21fa2e90eb,ea39374b57..c19121fbda
--- a/crates/openhuman-core/src/channels/host/remote_control.rs
+++ b/crates/openhuman-core/src/channels/host/remote_control.rs
@@@ -1,57 -1,90 +1,57 @@@
-//! OpenHuman's [`RemoteControlHost`]: the host state behind `/status`,
-//! `/sessions` and `/new` on every chat channel.
-//!
-//! Command parsing, rendering and the chat → thread bindings live in
-//! `tinychannels::remote`. This adapter answers from the channel runtime
-//! context (model routes, in-memory history), the conversation store and the
-//! web-chat session cache.
+//! Captured host conversation and session state supplied to the channel module.
- use crate::channels::context::{ChannelRuntimeContext, clear_sender_history};
-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,
+/// Serves product-owned conversation state to the captured module runtime.
+pub(crate) async fn dispatch_callback(
+ ctx: &ChannelRuntimeContext,
+ request: tinychannels_bus::module_remote::RemoteHostRequest,
+) -> tinybus::Result<tinychannels_bus::module_remote::RemoteHostResult> {
+ use tinychannels_bus::module_remote::{
+ RemoteHostRequest as Request, RemoteHostResult as Response,
+ };
+ match request {
+ Request::ListThreads => {
+ let threads = conversations::list_threads(ctx.workspace_dir.to_path_buf())
+ .map_err(|_| tinybus::Error::failed("conversation state unavailable"))?;
+ Ok(Response::Threads(
+ threads
+ .into_iter()
+ .map(
+ |thread| tinychannels_bus::module_remote::RemoteThreadSummary {
+ id: thread.id,
+ title: thread.title,
+ message_count: thread.message_count,
+ last_message_at: thread.last_message_at,
+ },
+ )
+ .collect(),
+ ))
+ }
+ Request::CreateThread(thread) => {
+ conversations::ensure_thread(
+ 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_err(|_| tinybus::Error::failed("conversation state unavailable"))?;
+ Ok(Response::Completed)
+ }
+ Request::ClearHistory { sender_key } => {
+ clear_sender_history(ctx, &sender_key);
+ Ok(Response::Completed)
+ }
+ Request::InvalidateThread { thread_id } => {
+ crate::web_chat::invalidate_thread_sessions(&thread_id).await;
+ Ok(Response::Completed)
}
- }
-
- 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;
}
}
diff --cc crates/openhuman-core/src/channels/module_fixture_tests.rs
index 2117c78411,0000000000..abb551f4bc
mode 100644,000000..100644
--- a/crates/openhuman-core/src/channels/module_fixture_tests.rs
+++ b/crates/openhuman-core/src/channels/module_fixture_tests.rs
@@@ -1,160 -1,0 +1,160 @@@
+//! A linked TinyChannels module fixture for host-side unit tests.
+//!
+//! These tests exercise the real owning module over TinyBus without downloading
+//! a release artifact or reaching a provider service. The fixture broker and
+//! module stay on a dedicated process-lifetime runtime because TinyBus module
+//! tasks must outlive the short Tokio runtimes used by individual tests.
+
+use super::*;
+use crate::modules::client::ModuleClient;
+use std::sync::{Mutex, OnceLock};
+use tinybus::Proxy;
+use tinychannels_bus::methods;
+
+static FIXTURE_PROXY: OnceLock<Proxy> = OnceLock::new();
+static FIXTURE_INIT: Mutex<()> = Mutex::new(());
+
+/// Return a client for the compiled, linked TinyChannels module fixture.
+pub(crate) async fn client() -> ModuleClient {
+ if let Some(proxy) = FIXTURE_PROXY.get() {
+ return ModuleClient::fixture(proxy.clone());
+ }
+
+ let _guard = FIXTURE_INIT
+ .lock()
+ .expect("the TinyChannels fixture initialization lock is not poisoned");
+ if let Some(proxy) = FIXTURE_PROXY.get() {
+ return ModuleClient::fixture(proxy.clone());
+ }
+
+ let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1);
+ std::thread::Builder::new()
+ .name("tinychannels-test-module".into())
+ .spawn(move || {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .thread_name("tinychannels-test-bus")
+ .build()
+ .expect("the TinyChannels test runtime should start");
+ runtime.block_on(async move {
+ let transport = tinybus::transport::memory::MemoryBus::new();
+ let broker = tinybus::broker::Broker::new();
+ broker.spawn(transport.clone());
+ let connection = tinybus::Connection::connect(
+ transport
+ .connect()
+ .await
+ .expect("the TinyChannels fixture broker should accept a connection"),
+ )
+ .await
+ .expect("the TinyChannels fixture host should connect to its broker");
+ let host = tinybus::module::ModuleHost::new(broker);
+ host.attach_linked_with_config(
+ tinychannels_module::linked_module()
+ .expect("the linked TinyChannels module should be available"),
+ serde_json::json!({}),
+ )
+ .expect("the linked TinyChannels module should be admitted");
+ let proxy = connection
+ .proxy(
+ tinychannels_module::BUS_NAME,
+ tinychannels_module::OBJECT_PATH,
+ tinychannels_module::BUS_NAME,
+ )
+ .expect("the linked TinyChannels proxy should be valid");
+ let _ = ready_tx.send(proxy);
+
+ // Keep the connection and module host alive with the broker
+ // until process exit. Aborting this task would fault the
+ // attached module and invalidate proxies held by other tests.
+ let (_connection, _host) = (connection, host);
+ std::future::pending::<()>().await;
+ });
+ })
+ .expect("the TinyChannels fixture thread should start");
+
+ let proxy = ready_rx
+ .recv()
+ .expect("the linked TinyChannels module should finish setup");
+ let _ = FIXTURE_PROXY.set(proxy.clone());
+ ModuleClient::fixture(FIXTURE_PROXY.get().unwrap().clone())
+}
+
+#[tokio::test]
+async fn linked_module_prepares_runtime_limits_over_confidential_bus_call() {
+ use tinychannels_bus::module_control::{ChannelControlRequest, ChannelControlResult};
+
+ let response: ChannelControlResult = client()
+ .await
+ .call_confidential(
+ "tinychannels",
+ methods::PREPARE_CHANNEL_CONTROL,
+ (ChannelControlRequest::RuntimeLimits {
+ timeout_secs: 1,
+ listener_count: 100,
+ },),
+ )
+ .await
+ .expect("the attached linked module should answer a confidential call");
+
+ assert_eq!(
+ response,
+ ChannelControlResult::RuntimeLimits {
+ timeout_secs: 30,
+ max_in_flight: 64,
+ }
+ );
+}
+
+#[tokio::test]
+async fn linked_module_prepares_legacy_inbound_facts_over_confidential_bus_call() {
- use tinychannels_bus::ChannelMessage;
+ use tinychannels_bus::module_inbound::{
+ ChannelInboundSource, PrepareChannelInboundRequest, PreparedChannelInbound,
+ };
++ use tinychannels_bus::ChannelMessage;
+
+ let message = ChannelMessage {
+ id: "message-1".into(),
+ channel: "discord".into(),
+ sender: "sender/a".into(),
+ reply_target: "room#b".into(),
+ content: "fixture content".into(),
+ timestamp: 42,
+ thread_ts: Some("thread/c".into()),
+ sender_name: Some("Display".into()),
+ };
+ let response: PreparedChannelInbound = client()
+ .await
+ .call_confidential(
+ "tinychannels",
+ methods::PREPARE_CHANNEL_INBOUND,
+ (PrepareChannelInboundRequest {
+ source: ChannelInboundSource::Legacy {
+ message,
+ envelope: None,
+ },
+ namespace: "openhuman".into(),
+ session_policy: Default::default(),
+ },),
+ )
+ .await
+ .expect("the attached linked module should prepare inbound facts");
+
+ assert_eq!(
+ response.thread_id,
+ "channel:discord/sender%2Fa/room%23b#thread:thread%2Fc"
+ );
+ assert_eq!(response.client_id, "inbound:discord:sender/a");
+ assert_eq!(
+ response.history_key,
+ "discord_sender/a_room#b_thread:thread/c"
+ );
+ assert_eq!(
+ response.session_key,
+ "openhuman:discord:default:unknown:room#b:thread/c"
+ );
+ assert_eq!(response.message.timestamp, 42);
+ assert_eq!(response.message.sender_name.as_deref(), Some("Display"));
+ assert_eq!(response.envelope.text, "fixture content");
+}
diff --cc crates/openhuman-core/src/channels/providers/relay/ops.rs
index 31047af8e4,43d5a83279..c8f74160b1
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@@ -8,10 -8,9 +8,10 @@@ use serde_json::{json, Value}
use super::channel::RelayChannel;
use super::params::RelayInboundParams;
use super::store::{self, Recorded};
-use crate::channels::context::{conversation_history_key, MAX_CHANNEL_HISTORY};
+use crate::channels::context::MAX_CHANNEL_HISTORY;
use crate::channels::runtime::{
- PromptToolDescs, build_channel_turn_parts, prepare_runtime_limits,
- process_channel_runtime_message, runtime_context,
- build_channel_turn_parts, process_channel_message, runtime_context, PromptToolDescs,
++ build_channel_turn_parts, prepare_runtime_limits, process_channel_runtime_message,
++ runtime_context, PromptToolDescs,
};
use crate::config::Config;
use crate::core::Outcome;
diff --cc crates/openhuman-core/src/channels/routes.rs
index 7e242f7ce5,fcd83626bf..ec0f19b3d9
--- a/crates/openhuman-core/src/channels/routes.rs
+++ b/crates/openhuman-core/src/channels/routes.rs
@@@ -1,23 -1,21 +1,23 @@@
//! Per-sender routing and runtime command handling.
- use super::context::{ChannelRouteSelection, ChannelRuntimeContext, clear_sender_history};
-use super::context::{
- clear_sender_history, conversation_history_key, ChannelRouteSelection, ChannelRuntimeContext,
-};
++use super::context::{clear_sender_history, ChannelRouteSelection, ChannelRuntimeContext};
use super::traits;
use super::{Channel, ChannelSendExt, SendMessage};
use crate::inference::provider;
use std::sync::Arc;
-use tinychannels::remote::RemoteCommandContext;
-use tinychannels::remote::{execute_remote_command, parse_remote_command, RemoteCommand};
+#[cfg(test)]
- use tinychannels::remote::{RemoteCommand, parse_remote_command};
++use tinychannels::remote::{parse_remote_command, RemoteCommand};
+#[cfg(test)]
use tinychannels::routes::{
- ChannelRuntimeCommand as PortableCommand,
- build_models_help_response, build_providers_help_response,
parse_runtime_command as parse_portable_runtime_command,
resolve_provider_alias as resolve_portable_provider_alias,
- ChannelRuntimeCommand as PortableCommand, ProviderDescriptor,
++ ChannelRuntimeCommand as PortableCommand,
+};
+use tinychannels_bus::module_control::{
+ ChannelControlRequest, ChannelControlResult, ProviderDescriptor,
};
+#[cfg(test)]
#[derive(Debug, Clone, PartialEq, Eq)]
enum ChannelRuntimeCommand {
Portable(PortableCommand),
diff --cc crates/openhuman-core/src/channels/routes_tests.rs
index 4da0df21d9,ee158ecc0d..88153cb220
--- a/crates/openhuman-core/src/channels/routes_tests.rs
+++ b/crates/openhuman-core/src/channels/routes_tests.rs
@@@ -1,7 -1,5 +1,7 @@@
use super::*;
-use crate::channels::context::{ChannelRuntimeContext, RouteSelectionMap, TurnModelSourceCacheMap};
+use crate::channels::context::{
- ChannelRuntimeContext, RouteSelectionMap, TurnModelSourceCacheMap, conversation_history_key,
++ conversation_history_key, ChannelRuntimeContext, RouteSelectionMap, TurnModelSourceCacheMap,
+};
use crate::channels::host::ChannelTurnStateSubscriber;
use crate::channels::traits::ChannelMessage;
use crate::core::events::DomainEvent;
@@@ -298,22 -288,15 +296,21 @@@ async fn handle_runtime_command_set_mod
sender_name: None,
};
- let handled = handle_runtime_command_if_needed(&ctx, &msg, Some(&channel)).await;
+ let handled = handle_runtime_command_if_needed(
+ &ctx,
+ &msg,
+ Some(&channel),
+ &conversation_history_key(&msg),
+ )
+ .await;
assert!(handled);
- assert!(
- ctx.conversation_histories
- .lock()
- .unwrap()
- .get(key)
- .is_none()
- );
+ assert!(ctx
+ .conversation_histories
+ .lock()
+ .unwrap()
+ .get(key)
+ .is_none());
assert_eq!(
get_route_selection(&ctx, key),
ChannelRouteSelection {
@@@ -474,22 -434,13 +467,21 @@@ async fn handle_runtime_command_telegra
thread_ts: Some("42".into()),
sender_name: None,
};
- assert!(handle_runtime_command_if_needed(&ctx, &new_msg, Some(&channel)).await);
+ assert!(
+ handle_runtime_command_if_needed(
+ &ctx,
+ &new_msg,
+ Some(&channel),
+ &conversation_history_key(&new_msg)
+ )
+ .await
+ );
- assert!(
- ctx.conversation_histories
- .lock()
- .unwrap()
- .get(sender_key)
- .is_none()
- );
+ assert!(ctx
+ .conversation_histories
+ .lock()
+ .unwrap()
+ .get(sender_key)
+ .is_none());
ctx.conversation_histories.lock().unwrap().insert(
sender_key.to_string(),
diff --cc crates/openhuman-core/src/channels/runtime/dispatch/helpers_tests.rs
index 556480a586,0000000000..2b25366c1f
mode 100644,000000..100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/helpers_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/helpers_tests.rs
@@@ -1,59 -1,0 +1,59 @@@
+use super::*;
+use std::sync::Arc;
- use tokio::sync::{Notify, oneshot};
++use tokio::sync::{oneshot, Notify};
+
+struct DeferredTyping {
+ started: Notify,
+ release: Notify,
+ stopped: std::sync::Mutex<Option<oneshot::Sender<String>>>,
+}
+#[async_trait::async_trait]
+impl crate::channels::Channel for DeferredTyping {
+ fn name(&self) -> &str {
+ "fixture"
+ }
+ async fn send(&self, _: &crate::channels::SendMessage) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn listen(
+ &self,
+ _: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn begin_typing_refresh(&self, _: &str, _: u64) -> anyhow::Result<Option<String>> {
+ self.started.notify_one();
+ self.release.notified().await;
+ Ok(Some("module-handle".into()))
+ }
+ async fn end_typing_refresh(&self, handle: &str) -> anyhow::Result<()> {
+ if let Some(sender) = self.stopped.lock().unwrap().take() {
+ let _ = sender.send(handle.into());
+ }
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn canceled_waiter_closes_handle_returned_by_in_flight_typing_start() {
+ let (sender, receiver) = oneshot::channel();
+ let channel = Arc::new(DeferredTyping {
+ started: Notify::new(),
+ release: Notify::new(),
+ stopped: std::sync::Mutex::new(Some(sender)),
+ });
+ let cancellation = tokio_util::sync::CancellationToken::new();
+ let waiter =
+ spawn_scoped_typing_task(channel.clone(), "recipient".into(), cancellation.clone());
+ channel.started.notified().await;
+ waiter.abort();
+ cancellation.cancel();
+ channel.release.notify_one();
+ assert_eq!(
+ tokio::time::timeout(std::time::Duration::from_secs(2), receiver)
+ .await
+ .unwrap()
+ .unwrap(),
+ "module-handle"
+ );
+}
diff --cc crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
index 3374999e44,7c7de72daa..433662df47
--- a/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
@@@ -28,12 -28,10 +28,12 @@@ use processor::channel_has_approval_sur
// Re-export internal helpers accessed by test_support (cfg(any(test,
// debug_assertions))) and the inline #[cfg(test)] modules via `super::*`.
#[cfg(any(test, debug_assertions))]
-use helpers::{build_channel_context_block, select_acknowledgment_reaction};
+use helpers::build_channel_context_block;
+#[cfg(test)]
+use helpers::select_acknowledgment_reaction;
#[cfg(test)]
- use routing::{AgentScoping, build_visible_tool_set};
+ use routing::{build_visible_tool_set, AgentScoping};
#[cfg(any(test, debug_assertions))]
use crate::channels::traits;
diff --cc crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
index a97e7318bc,f6ed313e68..f73d1cf366
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@@ -5,7 -5,8 +5,7 @@@
use crate::agent::bus::AgentTurnResponse;
use crate::agent::progress::AgentProgress;
use crate::channels::context::{
- ChannelRuntimeContext, compact_sender_history, is_context_window_overflow_error,
- compact_sender_history, conversation_history_key, is_context_window_overflow_error,
- ChannelRuntimeContext,
++ compact_sender_history, is_context_window_overflow_error, ChannelRuntimeContext,
};
use crate::channels::routes::{
get_or_create_turn_model_source, get_route_selection, handle_runtime_command_if_needed,
@@@ -22,13 -23,13 +22,13 @@@ use tokio_util::sync::CancellationToken
use tokio_util::task::AbortOnDropHandle;
use super::super::helpers::{
- REPLY_LOG_TRUNCATE_CHARS, build_channel_context_block, log_worker_join_result,
- spawn_scoped_typing_task,
- build_channel_context_block, log_worker_join_result, select_acknowledgment_reaction,
- spawn_scoped_typing_task, REPLY_LOG_TRUNCATE_CHARS,
++ build_channel_context_block, log_worker_join_result, spawn_scoped_typing_task,
++ REPLY_LOG_TRUNCATE_CHARS,
};
- use super::super::host_agent::{self, HostChannelTurn, HostRoute, run_host_agent_turn, seed_rows};
- use super::RuntimeChannelMessage;
+ use super::super::host_agent::{self, run_host_agent_turn, seed_rows, HostChannelTurn, HostRoute};
use super::approval::{channel_has_approval_surface, try_route_approval_reply};
use super::bus_turn::dispatch_bus_turn;
+ use super::RuntimeChannelMessage;
pub(crate) async fn process_channel_message(
ctx: Arc<ChannelRuntimeContext>,
diff --cc crates/openhuman-core/src/channels/runtime/startup/delivery_store.rs
index 82f3408db0,0000000000..711b92ad61
mode 100644,000000..100644
--- a/crates/openhuman-core/src/channels/runtime/startup/delivery_store.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/delivery_store.rs
@@@ -1,271 -1,0 +1,271 @@@
+//! Durable host-owned storage for TinyChannels delivery callbacks.
+
+use std::collections::{BTreeMap, HashMap};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex as StdMutex, OnceLock};
+use tinychannels_bus::module_delivery::{
- DELIVERY_PENDING_CAPACITY, DELIVERY_RECORD_BYTES, DELIVERY_RESULT_CAPACITY,
- DELIVERY_RESULT_TTL_SECONDS, DeliveryQueueEntry, DeliveryTerminalResult,
++ DeliveryQueueEntry, DeliveryTerminalResult, DELIVERY_PENDING_CAPACITY, DELIVERY_RECORD_BYTES,
++ DELIVERY_RESULT_CAPACITY, DELIVERY_RESULT_TTL_SECONDS,
+};
+use tokio::sync::Mutex;
+
+const FILE_NAME: &str = "channel-delivery.json";
+const MAX_STORE_BYTES: u64 = (DELIVERY_PENDING_CAPACITY * DELIVERY_RECORD_BYTES * 2) as u64
+ + (DELIVERY_RESULT_CAPACITY * DELIVERY_RECORD_BYTES) as u64;
+
+type Locks = HashMap<PathBuf, Arc<Mutex<()>>>;
+static WORKSPACE_LOCKS: OnceLock<StdMutex<Locks>> = OnceLock::new();
+
+#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
+#[serde(default)]
+struct DeliveryState {
+ pending: BTreeMap<String, DeliveryQueueEntry>,
+ failed: BTreeMap<String, DeliveryQueueEntry>,
+ results: BTreeMap<String, DeliveryTerminalResult>,
+}
+
+/// Shared store keyed by the captured workspace, so concurrent channel
+/// sessions serialize updates to the same durable queue.
+#[derive(Clone)]
+pub(super) struct ChannelDeliveryStore {
+ path: PathBuf,
+ gate: Arc<Mutex<()>>,
+}
+
+impl ChannelDeliveryStore {
+ pub(super) fn for_workspace(workspace: &Path) -> Self {
+ let path = workspace.join("channels").join(FILE_NAME);
+ let locks = WORKSPACE_LOCKS.get_or_init(|| StdMutex::new(HashMap::new()));
+ let gate = locks
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .entry(path.clone())
+ .or_insert_with(|| Arc::new(Mutex::new(())))
+ .clone();
+ Self { path, gate }
+ }
+
+ async fn locked_state(
+ &self,
+ ) -> anyhow::Result<(tokio::sync::OwnedMutexGuard<()>, DeliveryState)> {
+ let guard = Arc::clone(&self.gate).lock_owned().await;
+ let state = self.read_state().await?;
+ Ok((guard, state))
+ }
+
+ async fn read_state(&self) -> anyhow::Result<DeliveryState> {
+ let bytes = match tokio::fs::read(&self.path).await {
+ Ok(bytes) => bytes,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ return Ok(DeliveryState::default());
+ }
+ Err(error) => return Err(error.into()),
+ };
+ anyhow::ensure!(
+ bytes.len() as u64 <= MAX_STORE_BYTES,
+ "channel delivery store is oversized"
+ );
+ let state: DeliveryState = serde_json::from_slice(&bytes)?;
+ validate_state(&state)?;
+ Ok(state)
+ }
+
+ async fn write_state(&self, state: DeliveryState) -> anyhow::Result<()> {
+ validate_state(&state)?;
+ let bytes = serde_json::to_vec(&state)?;
+ anyhow::ensure!(
+ bytes.len() as u64 <= MAX_STORE_BYTES,
+ "channel delivery store is oversized"
+ );
+ let path = self.path.clone();
+ tokio::task::spawn_blocking(move || {
+ crate::security::secret_storage::file_store::write_atomic(&path, &bytes)
+ .map_err(anyhow::Error::from)
+ })
+ .await??;
+ Ok(())
+ }
+
+ pub(super) async fn save_pending(&self, entry: DeliveryQueueEntry) -> anyhow::Result<()> {
+ validate_entry(&entry)?;
+ let (_guard, mut state) = self.locked_state().await?;
+ if let Some(existing) = state.pending.get(&entry.id) {
+ anyhow::ensure!(
+ existing == &entry,
+ "delivery id conflicts with pending entry"
+ );
+ return Ok(());
+ }
+ anyhow::ensure!(
+ !state.failed.contains_key(&entry.id) && !state.results.contains_key(&entry.id),
+ "delivery id already has a terminal result"
+ );
+ anyhow::ensure!(
+ state.pending.len() < DELIVERY_PENDING_CAPACITY,
+ "delivery queue is full"
+ );
+ state.pending.insert(entry.id.clone(), entry);
+ self.write_state(state).await
+ }
+
+ pub(super) async fn load_pending(
+ &self,
+ id: String,
+ ) -> anyhow::Result<Option<DeliveryQueueEntry>> {
+ validate_id(&id)?;
+ let (_guard, state) = self.locked_state().await?;
+ Ok(state.pending.get(&id).cloned())
+ }
+
+ pub(super) async fn load_pending_all(&self) -> anyhow::Result<Vec<DeliveryQueueEntry>> {
+ let (_guard, state) = self.locked_state().await?;
+ let mut entries: Vec<_> = state.pending.into_values().collect();
+ entries.sort_by(|left, right| {
+ left.enqueued_at_unix_ms
+ .cmp(&right.enqueued_at_unix_ms)
+ .then_with(|| left.id.cmp(&right.id))
+ });
+ Ok(entries)
+ }
+
+ pub(super) async fn remove_pending(&self, id: String) -> anyhow::Result<()> {
+ validate_id(&id)?;
+ let (_guard, mut state) = self.locked_state().await?;
+ if state.pending.remove(&id).is_some() {
+ self.write_state(state).await?;
+ }
+ Ok(())
+ }
+
+ pub(super) async fn save_failed(&self, entry: DeliveryQueueEntry) -> anyhow::Result<()> {
+ validate_entry(&entry)?;
+ let (_guard, mut state) = self.locked_state().await?;
+ if let Some(existing) = state.failed.get(&entry.id) {
+ anyhow::ensure!(
+ existing == &entry,
+ "delivery id conflicts with failed entry"
+ );
+ return Ok(());
+ }
+ anyhow::ensure!(
+ state.failed.len() < DELIVERY_PENDING_CAPACITY,
+ "failed delivery store is full"
+ );
+ state.failed.insert(entry.id.clone(), entry);
+ self.write_state(state).await
+ }
+
+ pub(super) async fn load_failed(
+ &self,
+ id: String,
+ ) -> anyhow::Result<Option<DeliveryQueueEntry>> {
+ validate_id(&id)?;
+ let (_guard, state) = self.locked_state().await?;
+ Ok(state.failed.get(&id).cloned())
+ }
+
+ pub(super) async fn save_result(&self, result: DeliveryTerminalResult) -> anyhow::Result<()> {
+ validate_id(&result.id)?;
+ anyhow::ensure!(
+ !result.intent_fingerprint.is_empty() && result.intent_fingerprint.len() <= 128,
+ "delivery fingerprint is invalid"
+ );
+ anyhow::ensure!(
+ serde_json::to_vec(&result).map_or(false, |bytes| bytes.len() <= DELIVERY_RECORD_BYTES),
+ "delivery result exceeds its record limit"
+ );
+ let (_guard, mut state) = self.locked_state().await?;
+ prune_results(&mut state, now_unix_ms());
+ if let Some(existing) = state.results.get(&result.id) {
+ anyhow::ensure!(
+ existing == &result,
+ "delivery id conflicts with terminal result"
+ );
+ return Ok(());
+ }
+ anyhow::ensure!(
+ state.results.len() < DELIVERY_RESULT_CAPACITY,
+ "delivery result replay store is full"
+ );
+ state.results.insert(result.id.clone(), result);
+ self.write_state(state).await
+ }
+
+ pub(super) async fn load_result(
+ &self,
+ id: String,
+ ) -> anyhow::Result<Option<DeliveryTerminalResult>> {
+ validate_id(&id)?;
+ let (_guard, mut state) = self.locked_state().await?;
+ prune_results(&mut state, now_unix_ms());
+ let result = state.results.get(&id).cloned();
+ if result.is_none() {
+ self.write_state(state).await?;
+ }
+ Ok(result)
+ }
+}
+
+fn validate_state(state: &DeliveryState) -> anyhow::Result<()> {
+ anyhow::ensure!(
+ state.pending.len() <= DELIVERY_PENDING_CAPACITY,
+ "pending delivery store exceeds capacity"
+ );
+ anyhow::ensure!(
+ state.failed.len() <= DELIVERY_PENDING_CAPACITY,
+ "failed delivery store exceeds capacity"
+ );
+ anyhow::ensure!(
+ state.results.len() <= DELIVERY_RESULT_CAPACITY,
+ "delivery result store exceeds capacity"
+ );
+ for (id, entry) in state.pending.iter().chain(state.failed.iter()) {
+ anyhow::ensure!(id == &entry.id, "delivery store key does not match record");
+ validate_entry(entry)?;
+ }
+ for (id, result) in &state.results {
+ validate_id(id)?;
+ anyhow::ensure!(
+ id == &result.id,
+ "delivery result key does not match record"
+ );
+ }
+ Ok(())
+}
+
+fn validate_entry(entry: &DeliveryQueueEntry) -> anyhow::Result<()> {
+ validate_id(&entry.id)?;
+ anyhow::ensure!(
+ entry.intent.idempotency_key == entry.id,
+ "delivery id does not match intent key"
+ );
+ anyhow::ensure!(
+ serde_json::to_vec(entry).map_or(false, |bytes| bytes.len() <= DELIVERY_RECORD_BYTES),
+ "delivery record exceeds its limit"
+ );
+ Ok(())
+}
+
+fn validate_id(id: &str) -> anyhow::Result<()> {
+ anyhow::ensure!(!id.is_empty() && id.len() <= 256, "delivery id is invalid");
+ Ok(())
+}
+
+fn prune_results(state: &mut DeliveryState, now_ms: u64) {
+ let ttl_ms = DELIVERY_RESULT_TTL_SECONDS.saturating_mul(1000);
+ state
+ .results
+ .retain(|_, result| result.completed_at_unix_ms.saturating_add(ttl_ms) > now_ms);
+}
+
+fn now_unix_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis()
+ .min(u64::MAX as u128) as u64
+}
+
+#[cfg(test)]
+#[path = "delivery_store_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/channels/runtime/startup/delivery_store_tests.rs
index 931d50f8a2,0000000000..7882e83d76
mode 100644,000000..100644
--- a/crates/openhuman-core/src/channels/runtime/startup/delivery_store_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/delivery_store_tests.rs
@@@ -1,116 -1,0 +1,114 @@@
+use super::*;
+use tinychannels_bus::{ChannelOutboundIntent, DeliveryDurability, OutboundPayload};
+
+fn entry(id: &str, at: u64) -> DeliveryQueueEntry {
+ DeliveryQueueEntry::new(
+ id,
+ ChannelOutboundIntent {
+ idempotency_key: id.to_owned(),
+ channel_id: "telegram".into(),
+ conversation_id: "chat-1".into(),
+ reply_to_id: None,
+ thread_id: None,
+ durability: DeliveryDurability::Required,
+ payload: OutboundPayload::Text {
+ text: "hello".into(),
+ },
+ },
+ at,
+ )
+}
+
+fn store(path: &Path) -> ChannelDeliveryStore {
+ ChannelDeliveryStore {
+ path: path.to_path_buf(),
+ gate: Arc::new(Mutex::new(())),
+ }
+}
+
+#[tokio::test]
+async fn pending_delivery_is_durable_ordered_and_idempotent() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("delivery.json");
+ let first = store(&path);
+ first.save_pending(entry("later", 20)).await.unwrap();
+ first.save_pending(entry("earlier", 10)).await.unwrap();
+ first.save_pending(entry("earlier", 10)).await.unwrap();
+
+ let reopened = store(&path);
+ assert_eq!(
+ reopened.load_pending("earlier".into()).await.unwrap(),
+ Some(entry("earlier", 10))
+ );
+ assert_eq!(
+ reopened
+ .load_pending_all()
+ .await
+ .unwrap()
+ .iter()
+ .map(|item| item.id.as_str())
+ .collect::<Vec<_>>(),
+ vec!["earlier", "later"]
+ );
+}
+
+#[tokio::test]
+async fn changed_intent_cannot_reuse_a_pending_delivery_id() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = store(&dir.path().join("delivery.json"));
+ store.save_pending(entry("same", 1)).await.unwrap();
+ let mut changed = entry("same", 1);
+ changed.intent.conversation_id = "other-chat".into();
+ assert!(store.save_pending(changed).await.is_err());
+ assert_eq!(
+ store.load_pending_all().await.unwrap(),
+ vec![entry("same", 1)]
+ );
+}
+
+#[tokio::test]
+async fn terminal_result_is_replayed_and_conflicts_are_rejected() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = store(&dir.path().join("delivery.json"));
+ let result = DeliveryTerminalResult {
+ id: "done".into(),
+ intent_fingerprint: "abc123".into(),
+ completed_at_unix_ms: now_unix_ms(),
+ };
+ store.save_result(result.clone()).await.unwrap();
+ store.save_result(result.clone()).await.unwrap();
+ assert_eq!(
+ store.load_result("done".into()).await.unwrap(),
+ Some(result.clone())
+ );
+
+ let conflict = DeliveryTerminalResult {
+ intent_fingerprint: "different".into(),
+ ..result
+ };
+ assert!(store.save_result(conflict).await.is_err());
+}
+
+#[tokio::test]
+async fn removal_and_failed_delivery_are_idempotent_and_durable() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("delivery.json");
+ let store = store(&path);
+ let failed = entry("failed", 1);
+ store.save_failed(failed.clone()).await.unwrap();
+ store.save_failed(failed.clone()).await.unwrap();
+ store.save_pending(entry("pending", 2)).await.unwrap();
+ store.remove_pending("pending".into()).await.unwrap();
+ store.remove_pending("pending".into()).await.unwrap();
+
+ let reopened = store(&path);
+ assert_eq!(
+ reopened.load_failed("failed".into()).await.unwrap(),
+ Some(failed)
+ );
- assert!(
- reopened
- .load_pending("pending".into())
- .await
- .unwrap()
- .is_none()
- );
++ assert!(reopened
++ .load_pending("pending".into())
++ .await
++ .unwrap()
++ .is_none());
+}
diff --cc crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
index 9d4ee7527d,0beabbca64..a1761e48fb
--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
@@@ -1,9 -1,15 +1,9 @@@
//! The channel runtime's entry point: wiring subscribers, providers, the
//! system prompt, and the message dispatch loop.
-use super::super::dispatch::{run_message_dispatch_loop, RuntimeChannelMessage};
-use super::super::supervision::spawn_supervised_listener;
-use super::credentials::{hydrate_channel_credentials, RuntimeProxyClients};
-use super::relay::start_relay_runtime;
+use super::super::dispatch::run_message_dispatch_loop;
+use super::module_providers::ModuleChannelRuntime;
- use super::turn_parts::{PromptToolDescs, build_channel_turn_parts, runtime_context};
+ use super::turn_parts::{build_channel_turn_parts, runtime_context, PromptToolDescs};
-use crate::channels::context::{
- DEFAULT_CHANNEL_INITIAL_BACKOFF_SECS, DEFAULT_CHANNEL_MAX_BACKOFF_SECS,
-};
-use crate::channels::traits;
use crate::config::Config;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
diff --cc crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
index 792f6be474,ea3452e1c2..d10e3dd8ca
--- a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
@@@ -6,10 -6,10 +6,10 @@@
//! the caller's own config and policy, so a relayed turn never runs with the
//! operator's tools or workspace.
- use super::chat_workload::{ChatWorkloadResolution, resolve_chat_workload};
+ use super::chat_workload::{resolve_chat_workload, ChatWorkloadResolution};
use super::prompt::format_access_context;
use crate::agent::host_runtime;
-use crate::channels::context::{effective_channel_message_timeout_secs, ChannelRuntimeContext};
+use crate::channels::context::ChannelRuntimeContext;
use crate::channels::system_prompt::{ChannelPromptInputs, ChannelSystemPrompt};
use crate::config::Config;
use crate::inference::provider;
diff --cc crates/openhuman-core/src/channels/runtime/test_support.rs
index 1726a3042c,be2248058c..ee577adbb4
--- a/crates/openhuman-core/src/channels/runtime/test_support.rs
+++ b/crates/openhuman-core/src/channels/runtime/test_support.rs
@@@ -1,16 -1,18 +1,16 @@@
//! Debug-build harnesses for raw integration coverage of the channel runtime.
-pub use super::dispatch::test_support::{
- build_channel_context_block_for_test, select_acknowledgment_reaction_for_test,
-};
+pub use super::dispatch::test_support::build_channel_context_block_for_test;
use super::dispatch::{
- RuntimeChannelMessage, process_channel_message, process_channel_runtime_message,
+ process_channel_message, process_channel_runtime_message, RuntimeChannelMessage,
};
pub use super::startup::test_support::resolve_yuanbao_app_secret_for_test;
- use crate::agent::bus::{AGENT_RUN_TURN_METHOD, AgentTurnRequest, AgentTurnResponse};
+ use crate::agent::bus::{AgentTurnRequest, AgentTurnResponse, AGENT_RUN_TURN_METHOD};
use crate::agent::progress::AgentProgress;
+ use crate::channels::context::{ChannelRuntimeContext, CHANNEL_MESSAGE_TIMEOUT_SECS};
+ use crate::channels::traits::{ChannelMessage, SendMessage};
use crate::channels::Channel;
use crate::channels::ChannelSystemPrompt;
- use crate::channels::context::{CHANNEL_MESSAGE_TIMEOUT_SECS, ChannelRuntimeContext};
- use crate::channels::traits::{ChannelMessage, SendMessage};
use crate::config::{MultimodalConfig, MultimodalFileConfig, ReliabilityConfig};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
diff --cc scripts/ci/module-boundaries.json
index da59e10018,abebe7f75a..9306ceba13
--- a/scripts/ci/module-boundaries.json
+++ b/scripts/ci/module-boundaries.json
@@@ -106,21 -106,16 +106,6 @@@
"package": "tinymcp",
"reason": "Protocol servers and supervisor operations still call the implementation."
},
- {
- "scope": "hosts",
- "package": "tinybox-core",
- "reason": "Sandbox execution, shell analysis and pre-core gateways need a bus contract."
- },
-- {
-- "scope": "hosts",
- "package": "tinybox-jail",
- "reason": "Sandbox execution, shell analysis and pre-core gateways need a bus contract."
- "package": "tinychannels",
- "reason": "Providers, relay, pairing and delivery lifecycles still call the implementation."
-- },
-- {
-- "scope": "hosts",
- "package": "tinybox-docker",
- "reason": "Sandbox execution, shell analysis and pre-core gateways need a bus contract."
- "package": "tinychannels-runtime",
- "reason": "Providers, relay, pairing and delivery lifecycles still call the implementation."
-- },
{
"scope": "hosts",
"package": "tinywallet-crypto",