Skip to content

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

feat(channels): add delivery and messaging channel modules

Steven Enamakel5e5dee9814ee
diff --git a/crates/openhuman-tinyhumans/src/channels/delivery.rs b/crates/openhuman-tinyhumans/src/channels/delivery.rs
new file mode 100644
index 0000000000..027d22c704
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/channels/delivery.rs
@@ -0,0 +1,121 @@
+//! Progressive delivery (send, edit, delete, typing) on the hosted client's
+//! channel routes.
+//!
+//! Transport refusals are typed facts mapped by [`map_backend_error`];
+//! recovery and retry budgets belong to the channel module.
+
+#![cfg(feature = "channels")]
+
+use openhuman_embed::__host::channel_callback::ChannelCallbackCtx;
+use openhuman_embed::__host::security::credentials::session_support::{
+ get_session_token, is_local_session_token, BackendCredential,
+};
+use serde_json::json;
+use tinychannels_bus::module_progressive::{
+ ProgressiveTransportRequest, ProgressiveTransportResult,
+};
+
+use crate::client::{BackendClient, HostedApiError};
+
+/// Maps a client error onto the module's transport facts.
+pub(super) fn map_backend_error(error: anyhow::Error) -> ProgressiveTransportResult {
+ match error.downcast_ref::<HostedApiError>() {
+ Some(HostedApiError::ChannelEditUnsupported { .. }) => {
+ ProgressiveTransportResult::EditUnsupported
+ }
+ Some(HostedApiError::MessageNotFound { .. }) => ProgressiveTransportResult::MessageGone,
+ _ => ProgressiveTransportResult::Failed,
+ }
+}
+
+fn request_channel(request: &ProgressiveTransportRequest) -> &str {
+ match request {
+ ProgressiveTransportRequest::Send { channel, .. }
+ | ProgressiveTransportRequest::Edit { channel, .. }
+ | ProgressiveTransportRequest::Delete { channel, .. }
+ | ProgressiveTransportRequest::Typing { channel } => channel,
+ }
+}
+
+/// The hosted session credential, never the offline local token.
+fn hosted_credential(
+ config: &openhuman_embed::__host::config::Config,
+) -> Option<BackendCredential> {
+ match get_session_token(config) {
+ Ok(Some(token)) if !is_local_session_token(&token) => Some(BackendCredential::Session(token)),
+ _ => None,
+ }
+}
+
+/// Runs one progressive transport request for the session `ctx` describes.
+pub(super) async fn execute(
+ ctx: &ChannelCallbackCtx,
+ request: ProgressiveTransportRequest,
+) -> ProgressiveTransportResult {
+ if ctx.session.is_cancelled() {
+ log::debug!("[tinyhumans][channels] session closed before the transport call");
+ return ProgressiveTransportResult::Unavailable;
+ }
+ if let Some(channel) = &ctx.channel {
+ if request_channel(&request) != channel {
+ log::debug!("[tinyhumans][channels] request names a different channel; refused");
+ return ProgressiveTransportResult::Failed;
+ }
+ }
+ let Some(credential) = hosted_credential(&ctx.config) else {
+ log::debug!("[tinyhumans][channels] hosted channel credential unavailable");
+ return ProgressiveTransportResult::Unavailable;
+ };
+ let client = match BackendClient::from_config(&ctx.config) {
+ Ok(client) => client,
+ Err(error) => {
+ log::debug!("[tinyhumans][channels] backend client unavailable: {error:#}");
+ return ProgressiveTransportResult::Failed;
+ }
+ };
+ tokio::select! {
+ biased;
+ _ = ctx.session.cancelled() => ProgressiveTransportResult::Unavailable,
+ result = send(&client, &credential, request) => result,
+ }
+}
+
+async fn send(
+ client: &BackendClient,
+ credential: &BackendCredential,
+ request: ProgressiveTransportRequest,
+) -> ProgressiveTransportResult {
+ let result = match request {
+ ProgressiveTransportRequest::Send { channel, message } => {
+ client
+ .send_channel_message(&channel, credential.clone(), message)
+ .await
+ }
+ ProgressiveTransportRequest::Edit {
+ channel,
+ message_id,
+ text,
+ } => {
+ client
+ .send_channel_edit(&channel, &message_id, credential.clone(), json!({"text": text}))
+ .await
+ }
+ ProgressiveTransportRequest::Delete {
+ channel,
+ message_id,
+ } => {
+ client
+ .send_channel_delete(&channel, &message_id, credential.clone())
+ .await
+ }
+ ProgressiveTransportRequest::Typing { channel } => {
+ client
+ .send_channel_typing(&channel, credential.clone())
+ .await
+ }
+ };
+ match result {
+ Ok(value) => ProgressiveTransportResult::Success(value),
+ Err(error) => map_backend_error(error),
+ }
+}
diff --git a/crates/openhuman-tinyhumans/src/channels/messaging.rs b/crates/openhuman-tinyhumans/src/channels/messaging.rs
new file mode 100644
index 0000000000..a9bc1e9e1f
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/channels/messaging.rs
@@ -0,0 +1,135 @@
+//! Channel reactions and threads on the hosted client's channel routes.
+//!
+//! Results are the vendor contract's typed results; the backend payload rides
+//! in `raw` (and is parsed into the typed fields when its shape matches), so
+//! the RPC response shapes are unchanged.
+
+#![cfg(feature = "channels")]
+
+use openhuman_embed::__host::config::Config;
+use openhuman_embed::__host::security::credentials::session_support::{
+ resolve_backend_credential, BackendCredential,
+};
+use serde_json::Value;
+use tinychannels_bus::controllers::{
+ ChannelReactionResult, ChannelSendMessageResult, ChannelThreadListResult, ChannelThreadResult,
+};
+
+use crate::client::{flatten_authed_error, BackendClient};
+
+/// A result type that keeps the backend payload when its shape is unknown.
+pub(super) trait RawFallback {
+ fn with_raw(value: Value) -> Self;
+ fn with_raw_if_absent(self, value: Value) -> Self;
+}
+
+macro_rules! raw_fallback {
+ ($ty:ty, $($default:tt)*) => {
+ impl RawFallback for $ty {
+ fn with_raw(value: Value) -> Self {
+ Self {
+ raw: Some(value),
+ $($default)*
+ ..Default::default()
+ }
+ }
+
+ fn with_raw_if_absent(mut self, value: Value) -> Self {
+ if self.raw.is_none() {
+ self.raw = Some(value);
+ }
+ self
+ }
+ }
+ };
+}
+
+raw_fallback!(ChannelSendMessageResult,);
+raw_fallback!(ChannelReactionResult, success: true,);
+raw_fallback!(ChannelThreadResult,);
+raw_fallback!(ChannelThreadListResult,);
+
+/// Parses `value` into `T`, or wraps it as `raw` when the shape is unknown.
+pub(super) fn parse_or_raw<T>(value: Value) -> T
+where
+ T: Default + serde::de::DeserializeOwned + RawFallback,
+{
+ serde_json::from_value::<T>(value.clone())
+ .map(|parsed| parsed.with_raw_if_absent(value.clone()))
+ .unwrap_or_else(|_| T::with_raw(value))
+}
+
+/// The client and credential for `config`, or the sentinel-bearing error the
+/// RPC error channel classifies.
+fn prepare(config: &Config) -> anyhow::Result<(BackendClient, BackendCredential)> {
+ let credential = resolve_backend_credential(config).map_err(anyhow::Error::msg)?;
+ let client = BackendClient::from_config(config)?;
+ Ok((client, credential))
+}
+
+pub(super) async fn send_reaction(
+ config: &Config,
+ channel: &str,
+ reaction: Value,
+) -> anyhow::Result<ChannelReactionResult> {
+ let (client, credential) = prepare(config)?;
+ log::debug!("[tinyhumans][channels] sending reaction to channel '{channel}'");
+ let value = client
+ .send_channel_reaction(channel, credential, reaction)
+ .await
+ .map_err(|e| {
+ anyhow::anyhow!("failed to send channel reaction: {}", flatten_authed_error(e))
+ })?;
+ Ok(parse_or_raw(value))
+}
+
+pub(super) async fn create_thread(
+ config: &Config,
+ channel: &str,
+ title: &str,
+) -> anyhow::Result<ChannelThreadResult> {
+ let (client, credential) = prepare(config)?;
+ log::debug!("[tinyhumans][channels] creating thread in channel '{channel}'");
+ let value = client
+ .create_channel_thread(channel, credential, title)
+ .await
+ .map_err(|e| {
+ anyhow::anyhow!("failed to create channel thread: {}", flatten_authed_error(e))
+ })?;
+ Ok(parse_or_raw(value))
+}
+
+pub(super) async fn update_thread(
+ config: &Config,
+ channel: &str,
+ thread_id: &str,
+ action: &str,
+) -> anyhow::Result<ChannelThreadResult> {
+ let (client, credential) = prepare(config)?;
+ log::debug!(
+ "[tinyhumans][channels] updating thread '{thread_id}' in channel '{channel}' action='{action}'"
+ );
+ let value = client
+ .update_channel_thread(channel, credential, thread_id, action)
+ .await
+ .map_err(|e| {
+ anyhow::anyhow!("failed to update channel thread: {}", flatten_authed_error(e))
+ })?;
+ Ok(parse_or_raw(value))
+}
+
+pub(super) async fn list_threads(
+ config: &Config,
+ channel: &str,
+ active: Option<bool>,
+) -> anyhow::Result<ChannelThreadListResult> {
+ let (client, credential) = prepare(config)?;
+ log::debug!("[tinyhumans][channels] listing threads in channel '{channel}' active={active:?}");
+ let value = client
+ .list_channel_threads(channel, credential, active)
+ .await
+ .map_err(|e| {
+ anyhow::anyhow!("failed to list channel threads: {}", flatten_authed_error(e))
+ })?;
+ Ok(parse_or_raw(value))
+}
diff --git a/crates/openhuman-tinyhumans/src/channels/mod.rs b/crates/openhuman-tinyhumans/src/channels/mod.rs
index 3146f5a87a..9c1167fc1f 100644
--- a/crates/openhuman-tinyhumans/src/channels/mod.rs
+++ b/crates/openhuman-tinyhumans/src/channels/mod.rs
@@ -1,14 +1,86 @@
//! Hosted channel delivery and messaging.
//!
-//! Empty for now: the code for this area moves here from `openhuman-core`'s
-//! `backend/` and its consumers, and plugs back into the core through the
-//! generic registries on `openhuman_embed::__host` (`channel_callback`). [`register`] is the
-//! one place it does so; `crate::register::register_all` calls it from
-//! `install()`.
+//! The managed channel callback: one closure over the vendor contract
+//! (`tinychannels_bus::ChannelBackendRequest -> ChannelBackendResult`) that
+//! [`register`] hands to the core's channel callback slot
+//! (`openhuman_embed::__host::channel_callback`). It serves
+//!
+//! - progressive delivery (send, edit, delete, typing) through
+//! [`delivery`], on the hosted client's `channels/{c}/...` routes, and
+//! - reactions and threads through [`messaging`].
+//!
+//! The core keeps only the generic slot dispatch; with this callback
+//! unregistered, those calls answer the `BACKEND_UNAVAILABLE:` sentinel.
+
+mod delivery;
+mod messaging;
+
+#[cfg(feature = "channels")]
+use openhuman_embed::__host::channel_callback::{
+ register_channel_callback, CallbackFuture, ChannelCallbackCtx,
+};
+#[cfg(feature = "channels")]
+use tinychannels_bus::{ChannelBackendRequest, ChannelBackendResult};
use crate::install::InstallOptions;
+/// The id the callback registers under.
+pub const CALLBACK_ID: &str = "tinyhumans";
+
+/// Serves one callback request.
+#[cfg(feature = "channels")]
+pub(crate) async fn serve(
+ ctx: ChannelCallbackCtx,
+ request: ChannelBackendRequest,
+) -> anyhow::Result<ChannelBackendResult> {
+ use ChannelBackendRequest as Request;
+ use ChannelBackendResult as Result;
+ match request {
+ Request::ProgressiveTransport(request) => Ok(Result::ProgressiveTransport(
+ delivery::execute(&ctx, request).await,
+ )),
+ Request::SendReaction { channel, reaction } => {
+ messaging::send_reaction(&ctx.config, &channel, reaction)
+ .await
+ .map(Result::SendReaction)
+ }
+ Request::CreateThread { channel, title } => {
+ messaging::create_thread(&ctx.config, &channel, &title)
+ .await
+ .map(Result::Thread)
+ }
+ Request::UpdateThread {
+ channel,
+ thread_id,
+ action,
+ } => messaging::update_thread(&ctx.config, &channel, &thread_id, &action)
+ .await
+ .map(Result::Thread),
+ Request::ListThreads { channel, active } => {
+ messaging::list_threads(&ctx.config, &channel, active)
+ .await
+ .map(Result::Threads)
+ }
+ _ => {
+ log::debug!("[tinyhumans] channels: request not served by the managed callback");
+ anyhow::bail!("request is not served by the managed channel callback")
+ }
+ }
+}
+
/// Registers this area's hooks with the core. Idempotent.
pub(crate) fn register(_options: &InstallOptions) {
- log::trace!("[tinyhumans] channels: nothing to register yet");
+ #[cfg(feature = "channels")]
+ {
+ register_channel_callback(CALLBACK_ID, |ctx, request| -> CallbackFuture<_> {
+ Box::pin(serve(ctx, request))
+ });
+ log::debug!("[tinyhumans] channels: managed channel callback registered");
+ }
+ #[cfg(not(feature = "channels"))]
+ log::trace!("[tinyhumans] channels: feature off, nothing to register");
}
+
+#[cfg(all(test, feature = "channels"))]
+#[path = "mod_tests.rs"]
+mod tests;