Skip to content

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

refactor(channels): consume shared dispatch helpers

Steven Enamakel526868a02aa3
diff --git a/crates/openhuman-core/src/channels/bus/thread_id.rs b/crates/openhuman-core/src/channels/bus/thread_id.rs
index 5ca84c8b03..8e0e7f58a2 100644
--- a/crates/openhuman-core/src/channels/bus/thread_id.rs
+++ b/crates/openhuman-core/src/channels/bus/thread_id.rs
@@ -1,84 +1,3 @@
-//! Per-sender thread and client id derivation for inbound channel messages.
+//! Compatibility re-exports for the TinyChannels inbound identity contract.
-/// Per-sender thread-id derivation for inbound channel messages.
-///
-/// Matches the shape `channels::context::conversation_history_key` builds
-/// for the canonical channel paths so the inbound bus handler does not
-/// re-introduce a session-collapse where distinct participants in a
-/// shared channel share a cached agent session.
-///
-/// Layout: `channel:<channel>[/<sender>][/<reply_target>][#thread:<ts>]`.
-/// Each optional segment is appended only when the publisher surfaced
-/// that field; legacy callers that pass only `channel` fall back to the
-/// historical `channel:<channel>` key so single-DM flows keep working.
-pub(crate) fn derive_inbound_thread_id(
- channel: &str,
- sender: Option<&str>,
- reply_target: Option<&str>,
- thread_ts: Option<&str>,
-) -> String {
- let mut key = format!("channel:{channel}");
- let clean = |s: &str| -> Option<String> {
- let t = s.trim();
- if t.is_empty() {
- None
- } else {
- Some(t.to_string())
- }
- };
- if let Some(s) = sender.and_then(clean) {
- key.push('/');
- key.push_str(&s);
- }
- if let Some(r) = reply_target.and_then(clean) {
- key.push('/');
- key.push_str(&r);
- }
- // Telegram threads its messages by `thread_ts` for transport routing
- // but should not split memory/history per message — match the
- // `conversation_history_key` carve-out and skip the thread suffix
- // there. The socket layer addresses Telegram with raw channel ids
- // like `tg:123` as well as the literal `telegram` slug, so the
- // carve-out keys off whichever provider prefix the channel string
- // exposes, not the full id.
- if !channel_is_telegram(channel) {
- if let Some(t) = thread_ts.and_then(clean) {
- key.push_str("#thread:");
- key.push_str(&t);
- }
- }
- key
-}
-
-/// Build the per-turn `client_id` for an inbound socket message. Inbound
-/// messages do not have a Socket.IO client id of their own — they arrive
-/// from the channel transport layer rather than from a connected web
-/// browser. Mint a stable label so downstream consumers that key on
-/// `client_id` (the agent-turn origin, approval-chat-context, wallet
-/// QuoteOwner pair, future audit-log keys) see distinct values for
-/// distinct senders sharing a single Discord / Slack channel.
-///
-/// `None` (legacy publisher that didn't fill `sender`) maps to the bare
-/// `"inbound"` literal that the path used historically, preserving
-/// behavior for single-DM flows where no co-channel attacker exists.
-pub(crate) fn derive_inbound_client_id(channel: &str, sender: Option<&str>) -> String {
- let trimmed_channel = channel.trim();
- let trimmed = sender.map(|s| s.trim()).filter(|s| !s.is_empty());
- match trimmed {
- Some(s) if !trimmed_channel.is_empty() => format!("inbound:{trimmed_channel}:{s}"),
- Some(s) => format!("inbound:{s}"),
- None => "inbound".to_string(),
- }
-}
-
-/// True for any inbound channel string that addresses Telegram, whether
-/// the publisher uses the canonical slug (`"telegram"`) or the raw
-/// provider-prefixed form the socket layer emits (`"tg:<chat_id>"`,
-/// `"telegram:<chat_id>"`).
-fn channel_is_telegram(channel: &str) -> bool {
- if channel == "telegram" || channel == "tg" {
- return true;
- }
- let provider = channel.split(':').next().unwrap_or("");
- matches!(provider, "telegram" | "tg")
-}
+pub(crate) use tinychannels::channel::{derive_inbound_client_id, derive_inbound_thread_id};
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs b/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs
index 9ca4b84323..5721527d4c 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/helpers.rs
@@ -1,46 +1,29 @@
-//! Small stateless helpers used by the channel runtime dispatch path.
-//!
-//! Contains:
-//! * [`build_channel_context_block`] — per-turn context injected for non-web
-//! channels.
-//! * [`select_acknowledgment_reaction`] — deterministic emoji picker.
-//! * [`log_worker_join_result`] / [`spawn_scoped_typing_task`] — worker
-//! lifecycle utilities.
-//! * Private [`contains_any`] / [`starts_with_any`] predicates.
+//! OpenHuman-specific dispatch prompt context plus TinyChannels helpers.
use crate::channels::context::CHANNEL_TYPING_REFRESH_INTERVAL_SECS;
use crate::channels::traits;
-use crate::channels::Channel;
-use std::sync::Arc;
use std::time::Duration;
-use tokio_util::sync::CancellationToken;
-/// Maximum characters shown in the debug reply println. Large enough to not truncate
-/// real responses while keeping terminal output readable.
+/// Maximum characters shown in the debug reply println.
pub(super) const REPLY_LOG_TRUNCATE_CHARS: usize = 200;
-/// Returns `true` if `s` contains any of the given substrings.
-#[inline]
-pub(super) fn contains_any(s: &str, words: &[&str]) -> bool {
- words.iter().any(|w| s.contains(w))
-}
+pub(super) use tinychannels::runtime::{log_worker_join_result, select_acknowledgment_reaction};
-/// Returns `true` if `s` starts with any of the given prefixes.
-#[inline]
-pub(super) fn starts_with_any(s: &str, prefixes: &[&str]) -> bool {
- prefixes.iter().any(|p| s.starts_with(p))
+/// Start the portable typing lifecycle with OpenHuman's configured interval.
+pub(super) fn spawn_scoped_typing_task(
+ channel: std::sync::Arc<dyn crate::channels::Channel>,
+ recipient: String,
+ cancellation_token: tokio_util::sync::CancellationToken,
+) -> tokio::task::JoinHandle<()> {
+ tinychannels::runtime::spawn_scoped_typing_task(
+ channel,
+ recipient,
+ cancellation_token,
+ Duration::from_secs(CHANNEL_TYPING_REFRESH_INTERVAL_SECS),
+ )
}
-/// Build the per-turn `[Channel context]` block prepended to the user
-/// message for non-web inbound channels (e.g. Telegram, Discord, Slack).
-///
-/// Surfaces the active channel and reply target so the model knows
-/// where it is talking and can route any tool side-effects (notably
-/// `cron_add`) back to the same chat instead of defaulting to the
-/// in-app web stream. See issue #928.
-///
-/// Returns an empty string for web/cli turns (the desktop UI is the
-/// default delivery surface, no hint needed).
+/// Build the OpenHuman `cron_add` delivery instruction for a channel turn.
pub(super) fn build_channel_context_block(msg: &traits::ChannelMessage) -> String {
let channel = msg.channel.trim();
if channel.is_empty()
@@ -49,12 +32,10 @@ pub(super) fn build_channel_context_block(msg: &traits::ChannelMessage) -> Strin
{
return String::new();
}
-
let reply_target = msg.reply_target.trim();
if reply_target.is_empty() {
return String::new();
}
-
format!(
"[Channel context]\n\
You are responding via the \"{channel}\" channel. Reply target: \"{reply_target}\".\n\
@@ -65,143 +46,3 @@ pub(super) fn build_channel_context_block(msg: &traits::ChannelMessage) -> Strin
in-app/desktop notification.\n\n"
)
}
-
-/// Pick a contextual acknowledgment emoji for an inbound message.
-///
-/// Intent categories are checked in priority order. Within each category two
-/// emoji options are defined; a cheap deterministic index (based on message
-/// length + first char value) selects between them so that similar messages
-/// don't always produce the identical reaction.
-///
-/// All emojis used here are in Telegram's standard (non-premium) reaction set.
-pub(super) fn select_acknowledgment_reaction(content: &str) -> &'static str {
- let l = content.to_lowercase();
-
- // Deterministic variant (0 or 1) — avoids true randomness while giving variety.
- let v = content
- .len()
- .wrapping_add(content.chars().next().map_or(0, |c| c as usize))
- & 1;
-
- let opts: &[&str] = if contains_any(&l, &["thank", "thx", "appreciate", "grateful", "cheers"]) {
- // Gratitude
- &["❤️", "🙏"]
- } else if contains_any(
- &l,
- &[
- "amazing",
- "awesome",
- "incredible",
- "love it",
- "congrat",
- "!!",
- ],
- ) {
- // Excitement / celebration
- &["🔥", "🎉"]
- } else if contains_any(
- &l,
- &[
- "price", "btc", "eth", "crypto", "trade", "pump", "dump", "market", "token", "wallet",
- "defi", "nft", "sol", "bnb",
- ],
- ) {
- // Crypto / finance
- &["💯", "⚡"]
- } else if contains_any(
- &l,
- &[
- "code",
- "function",
- "api",
- "deploy",
- "build",
- "debug",
- "script",
- "git",
- "rust",
- "python",
- "js",
- "typescript",
- ],
- ) {
- // Technical / dev
- &["👨‍💻", "🤓"]
- } else if starts_with_any(
- &l,
- &[
- "hi",
- "hello",
- "hey",
- "sup",
- "good morning",
- "good evening",
- "good afternoon",
- ],
- ) || l == "yo"
- || l.starts_with("yo ")
- {
- // Greeting
- &["🤗", "😁"]
- } else if l.contains('?')
- || starts_with_any(
- &l,
- &[
- "how",
- "what",
- "why",
- "when",
- "where",
- "who",
- "can you",
- "could you",
- "would you",
- "is ",
- "are ",
- "do you",
- "does",
- ],
- )
- {
- // Question / help request
- &["🤔", "✍️"]
- } else {
- // Default — "seen, on it"
- &["👀", "✍️"]
- };
-
- opts[v % opts.len()]
-}
-
-pub(super) fn log_worker_join_result(result: Result<(), tokio::task::JoinError>) {
- if let Err(error) = result {
- tracing::error!("Channel message worker crashed: {error}");
- }
-}
-
-pub(super) fn spawn_scoped_typing_task(
- channel: Arc<dyn Channel>,
- recipient: String,
- cancellation_token: CancellationToken,
-) -> tokio::task::JoinHandle<()> {
- let stop_signal = cancellation_token;
- let refresh_interval = Duration::from_secs(CHANNEL_TYPING_REFRESH_INTERVAL_SECS);
- let handle = tokio::spawn(async move {
- loop {
- tokio::select! {
- () = stop_signal.cancelled() => break,
- _ = tokio::time::sleep(refresh_interval) => {
- if let Err(e) = channel.start_typing(&recipient).await {
- tracing::debug!("Failed to start typing on {}: {e}", channel.name());
- }
- }
- }
- }
-
- if let Err(e) = channel.stop_typing(&recipient).await {
- tracing::debug!("Failed to stop typing on {}: {e}", channel.name());
- }
- });
-
- handle
-}
diff --git a/vendor/tinychannels b/vendor/tinychannels
index e211100fea..94000e3fd6 160000
--- a/vendor/tinychannels
+++ b/vendor/tinychannels
@@ -1 +1 @@
-Subproject commit e211100feafbe4ca5e7e0538038b919cd8cc87ec
+Subproject commit 94000e3fd60881b3a4754be9b5d766906bb15597