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(embed): add channel-based embedding runtime
Steven Enamakel7a99c3ecebca
diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.tomlindex e2924b5c30..cd3db31d80 100644--- a/crates/openhuman-embed/Cargo.toml+++ b/crates/openhuman-embed/Cargo.toml@@ -9,7 +9,9 @@ readme = "README.md"publish = false[features]-default = ["openhuman-core/default"]+# `channels` is in core's default set already; enabling it here too compiles+# the `Runtime::channels` facade in a default build.+default = ["openhuman-core/default", "channels"]http-server = ["openhuman-core/http-server"]inference = ["openhuman-core/inference"]documents = ["openhuman-core/documents"]diff --git a/crates/openhuman-embed/src/channels.rs b/crates/openhuman-embed/src/channels.rsnew file mode 100644index 0000000000..6401f0d9b7--- /dev/null+++ b/crates/openhuman-embed/src/channels.rs@@ -0,0 +1,172 @@+//! Messaging channels answered by a runtime's own agents.+//!+//! ```no_run+//! # async fn demo(runtime: &openhuman_embed::Runtime) -> Result<(), openhuman_embed::ChannelError> {+//! use openhuman_embed::TelegramChannelSpec;+//!+//! let telegram = runtime.channels().telegram(+//! TelegramChannelSpec::new("123456:bot-token", "teeny-chat").allow_everyone(),+//! )?;+//! // ... later+//! telegram.stop();+//! # Ok(()) }+//! ```++use openhuman_core::config::Config;++pub use openhuman_core::config::schema::StreamMode;++use crate::Runtime;++/// A Telegram bot whose messages one runtime agent answers.+#[derive(Clone)]+pub struct TelegramChannelSpec {+ bot_token: String,+ agent_id: String,+ allowed_users: Vec<String>,+ mention_only: bool,+ stream_mode: StreamMode,+ chat_id: Option<String>,+}++impl TelegramChannelSpec {+ /// The bot `bot_token`, answered by the runtime agent `agent_id`.+ pub fn new(bot_token: impl Into<String>, agent_id: impl Into<String>) -> Self {+ Self {+ bot_token: bot_token.into(),+ agent_id: agent_id.into(),+ allowed_users: Vec::new(),+ mention_only: false,+ stream_mode: StreamMode::default(),+ chat_id: None,+ }+ }++ /// Accept messages from these Telegram usernames or numeric user ids.+ pub fn allowed_users<I, S>(mut self, users: I) -> Self+ where+ I: IntoIterator<Item = S>,+ S: Into<String>,+ {+ self.allowed_users = users.into_iter().map(Into::into).collect();+ self+ }++ /// Accept messages from anyone (`allowed_users = ["*"]`).+ pub fn allow_everyone(self) -> Self {+ self.allowed_users(["*"])+ }++ /// In groups, answer only messages that mention the bot.+ pub fn mention_only(mut self, mention_only: bool) -> Self {+ self.mention_only = mention_only;+ self+ }++ /// How replies stream into the chat.+ pub fn stream_mode(mut self, stream_mode: StreamMode) -> Self {+ self.stream_mode = stream_mode;+ self+ }++ /// The chat proactive sends (cron output) go to when they name none.+ pub fn chat_id(mut self, chat_id: impl Into<String>) -> Self {+ self.chat_id = Some(chat_id.into());+ self+ }++ /// The agent that answers this bot.+ pub fn agent_id(&self) -> &str {+ &self.agent_id+ }+}++impl std::fmt::Debug for TelegramChannelSpec {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("TelegramChannelSpec")+ .field("bot_token", &"<redacted>")+ .field("agent_id", &self.agent_id)+ .field("allowed_users", &self.allowed_users)+ .field("mention_only", &self.mention_only)+ .field("stream_mode", &self.stream_mode)+ .field("chat_id", &self.chat_id)+ .finish()+ }+}++/// Why a channel could not be started.+#[derive(Debug, thiserror::Error)]+pub enum ChannelError {+ /// The spec is missing something it needs.+ #[error("invalid channel spec: {0}")]+ Invalid(String),+ /// No agent with this id is alive on the runtime.+ #[error("no agent `{0}` on this runtime; create it before binding a channel to it")]+ UnknownAgent(String),+}++/// The runtime's channels. See the module docs.+pub struct Channels<'a> {+ runtime: &'a Runtime,+}++impl<'a> Channels<'a> {+ pub(crate) fn new(runtime: &'a Runtime) -> Self {+ Self { runtime }+ }++ /// Start a Telegram listener whose messages `spec`'s agent answers.+ pub fn telegram(&self, spec: TelegramChannelSpec) -> Result<ChannelListener, ChannelError> {+ let _ = (self.runtime, spec);+ Err(ChannelError::Invalid("not implemented".into()))+ }+}++/// A running channel listener. Stops when dropped.+pub struct ChannelListener {+ channel: &'static str,+ agent_id: String,+ task: tokio::task::AbortHandle,+}++impl ChannelListener {+ /// The channel this listener serves (`"telegram"`).+ pub fn channel(&self) -> &str {+ self.channel+ }++ /// The agent that answers it.+ pub fn agent_id(&self) -> &str {+ &self.agent_id+ }++ /// Whether the listener is still running.+ pub fn is_running(&self) -> bool {+ !self.task.is_finished()+ }++ /// Stop listening.+ pub fn stop(self) {}+}++impl Drop for ChannelListener {+ fn drop(&mut self) {+ self.task.abort();+ }+}++/// `base` serving only `spec`'s Telegram bot, bound to `spec`'s agent.+pub(crate) fn telegram_config(base: &Config, spec: &TelegramChannelSpec) -> Config {+ let _ = spec;+ base.clone()+}++/// Refuse a spec that names no bot or no agent.+pub(crate) fn validate(spec: &TelegramChannelSpec) -> Result<(), ChannelError> {+ let _ = spec;+ Ok(())+}++#[cfg(test)]+#[path = "channels_tests.rs"]+mod tests;diff --git a/crates/openhuman-embed/src/channels_tests.rs b/crates/openhuman-embed/src/channels_tests.rsnew file mode 100644index 0000000000..c3de0b3cb8--- /dev/null+++ b/crates/openhuman-embed/src/channels_tests.rs@@ -0,0 +1,64 @@+use super::*;++fn base() -> Config {+ let mut config = Config::default();+ config.channels_config.discord = Some(+ serde_json::from_value(serde_json::json!({ "bot_token": "d", "guild_id": null, "channel_id": null }))+ .unwrap(),+ );+ config+ .agent+ .channel_agents+ .insert("discord".into(), "someone-else".into());+ config+}++#[test]+fn the_config_serves_only_this_bot_and_binds_it_to_the_agent() {+ let spec = TelegramChannelSpec::new("123:abc", "teeny-chat")+ .allowed_users(["alice", "42"])+ .mention_only(true)+ .chat_id("-100");+ let config = telegram_config(&base(), &spec);++ let telegram = config.channels_config.telegram.expect("telegram configured");+ assert_eq!(telegram.bot_token, "123:abc");+ assert_eq!(telegram.allowed_users, vec!["alice", "42"]);+ assert!(telegram.mention_only);+ assert_eq!(telegram.chat_id.as_deref(), Some("-100"));+ assert!(+ config.channels_config.discord.is_none(),+ "only the bot asked for is started"+ );+ assert_eq!(+ config.agent.channel_agents,+ std::collections::HashMap::from([("telegram".to_string(), "teeny-chat".to_string())])+ );+}++#[test]+fn allow_everyone_is_the_wildcard() {+ let spec = TelegramChannelSpec::new("t", "a").allow_everyone();+ let config = telegram_config(&Config::default(), &spec);+ assert_eq!(config.channels_config.telegram.unwrap().allowed_users, vec!["*"]);+}++#[test]+fn a_spec_without_a_bot_or_an_agent_is_invalid() {+ assert!(matches!(+ validate(&TelegramChannelSpec::new(" ", "teeny-chat")),+ Err(ChannelError::Invalid(_))+ ));+ assert!(matches!(+ validate(&TelegramChannelSpec::new("123:abc", "")),+ Err(ChannelError::Invalid(_))+ ));+ assert!(validate(&TelegramChannelSpec::new("123:abc", "teeny-chat")).is_ok());+}++#[test]+fn debug_never_prints_the_token() {+ let rendered = format!("{:?}", TelegramChannelSpec::new("123:SECRET", "teeny-chat"));+ assert!(!rendered.contains("SECRET"), "{rendered}");+ assert!(rendered.contains("teeny-chat"), "{rendered}");+}diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex c01e854783..04fcb80246 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -88,6 +88,8 @@ pub mod agent_progress {mod agent;mod auth;mod call;+#[cfg(feature = "channels")]+pub mod channels;mod config;mod core_agent;pub mod cron;@@ -103,6 +105,10 @@ pub use agent::{ToolScopeSpec,};pub use auth::{Auth, AuthState, Session};+#[cfg(feature = "channels")]+pub use channels::{+ ChannelError, ChannelListener, Channels, StreamMode, TelegramChannelSpec,+};pub use config::{Config, RuntimeFlags};pub use core_agent::CoreAgent;pub use cron::{diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rsindex 7a436c22b0..1a5ddc465c 100644--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@ -274,6 +274,12 @@ impl Runtime {Ok(Agent::from_inner(inner))}+ /// The runtime's messaging channels. See [`crate::channels`].+ #[cfg(feature = "channels")]+ pub fn channels(&self) -> crate::channels::Channels<'_> {+ crate::channels::Channels::new(self)+ }+/// The runtime's scheduled jobs. See [`crate::cron`].pub fn cron(&self) -> crate::cron::Cron<'_> {crate::cron::Cron::new(&self.base_config)