Skip to content

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

feat(cron): route embedded agents' scheduled replies to the host

Steven Enamakel5422d8fa4a20
diff --git a/crates/openhuman-core/src/cron/host_delivery.rs b/crates/openhuman-core/src/cron/host_delivery.rs
index c5c5992043..37a461b955 100644
--- a/crates/openhuman-core/src/cron/host_delivery.rs
+++ b/crates/openhuman-core/src/cron/host_delivery.rs
@@ -1,12 +1,15 @@
-//! Host-routed delivery of a hosted profile's scheduled output.
+//! Host-routed delivery of scheduled output.
//!
-//! A host that embeds profiles (`profiles::ProfileHost`) owns the conversations
-//! its users talk in, so it can route a scheduled reply better than the core
-//! can. With a [`CronDelivery`] installed, an `origin`-mode run of a profile's
-//! job hands its output to the host instead of writing into a local thread or
-//! channel: the host is told which profile, which conversation the job was
-//! created in, and the job's recorded origin. A run with nothing to say (blank
-//! or `NO_REPLY`) never reaches it.
+//! A host that embeds profiles (`profiles::ProfileHost`) or library agents
+//! (`openhuman_embed::Runtime`) owns the conversations its users talk in, so it
+//! can route a scheduled reply better than the core can. With a
+//! [`CronDelivery`] installed, an `origin`-mode run of a profile's or an
+//! embedded agent's job hands its output to the host instead of writing into a
+//! local thread or channel: the host is told whose job it was (the profile, the
+//! agent, or both), which conversation the job was created in, and the job's
+//! recorded origin. A run with nothing to say (blank or `NO_REPLY`) never
+//! reaches it. A run with neither a profile nor an agent (the desktop's own
+//! orchestrator) keeps the core's delivery.
use std::sync::{Arc, RwLock};
@@ -17,8 +20,12 @@ use crate::cron::JobOrigin;
/// One scheduled reply for the host to route.
#[derive(Debug, Clone, PartialEq)]
pub struct CronReply {
- /// The profile whose job produced the reply.
- pub profile_id: String,
+ /// The profile whose job produced the reply; `None` for an embedded
+ /// agent outside any profile.
+ pub profile_id: Option<String>,
+ /// The agent whose job produced the reply; `None` for a profile's
+ /// default agent.
+ pub agent_id: Option<String>,
/// The job that ran.
pub job_id: String,
/// This run; stable across redelivery of the same reply.
diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
index f2f1b95065..3f9d54a2ab 100644
--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
@@ -152,19 +152,25 @@ pub(crate) async fn deliver_to_origin(
};
let text = output.trim();
- // A hosted profile's host routes the reply itself.
- if let (Some(sink), Some(profile_id)) = (
- crate::cron::host_delivery::installed(),
- crate::core::runtime::current_tenant()
- .ok()
- .and_then(|tenant| tenant.profile),
- ) {
+ // A hosted profile's or an embedded agent's host routes the reply itself.
+ let owner = crate::core::runtime::current_tenant()
+ .ok()
+ .filter(|tenant| tenant.profile.is_some() || tenant.agent.is_some());
+ if let (Some(sink), Some(owner)) = (crate::cron::host_delivery::installed(), owner) {
let thread_id = match origin {
JobOrigin::Web { thread_id, .. } => Some(thread_id.clone()),
JobOrigin::Channel { thread_id, .. } => thread_id.clone(),
};
+ tracing::debug!(
+ job_id = %job.id,
+ run_id = %run_id,
+ profile = owner.profile.is_some(),
+ agent = owner.agent.is_some(),
+ "[cron] origin delivery handed to the host"
+ );
sink.deliver(crate::cron::host_delivery::CronReply {
- profile_id,
+ profile_id: owner.profile,
+ agent_id: owner.agent,
job_id: job.id.clone(),
run_id: run_id.to_string(),
thread_id,
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index 78d333a34f..2d2e312e5b 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -187,9 +187,13 @@ pub use harness::{
};
#[cfg(feature = "mcp")]
pub use harness::{HttpHeader, McpAuthConfig, McpServer};
+/// Host-routed delivery of scheduled replies, for [`RuntimeBuilder::cron_delivery`]
+/// and the profile runtime alike.
+pub use openhuman_core::cron::host_delivery::{CronDelivery, CronReply};
+pub use openhuman_core::cron::JobOrigin;
#[cfg(feature = "profiles")]
pub use profiles::{
- ChatReply, CronDelivery, CronReply, CronSweepReport, DirectProfileProvider, JobOrigin,
+ ChatReply, CronSweepReport, DirectProfileProvider,
OpenError, ProfileError, ProfileEvents, ProfileHandle, ProfileId, ProfileIdMode,
ProfileRuntime, ProfileRuntimeBuilder, ProfileSummary, Provisioned, SaasConfig,
};
diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rs
index 04fdf56252..ce598b84ad 100644
--- a/crates/openhuman-embed/src/runtime/build.rs
+++ b/crates/openhuman-embed/src/runtime/build.rs
@@ -218,6 +218,10 @@ impl RuntimeBuilder {
if let Some(engine) = self.memory_engine.clone() {
openhuman_core::memory::engine::install_host_engine(engine);
}
+ if let Some(delivery) = self.cron_delivery.clone() {
+ log::debug!("[embed][runtime] host cron delivery installed");
+ openhuman_core::cron::host_delivery::install(delivery);
+ }
// Install only after all fallible workspace/config resolution has
// completed; core boot performs recovery against this provider.
diff --git a/crates/openhuman-embed/src/runtime/builder.rs b/crates/openhuman-embed/src/runtime/builder.rs
index f78f60be0c..aaec18d055 100644
--- a/crates/openhuman-embed/src/runtime/builder.rs
+++ b/crates/openhuman-embed/src/runtime/builder.rs
@@ -99,6 +99,7 @@ pub struct RuntimeBuilder {
pub(super) backend_transport: Option<Arc<dyn BackendTransport>>,
pub(super) memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,
pub(super) session_store: Option<Arc<dyn SessionStoreProvider>>,
+ pub(super) cron_delivery: Option<Arc<dyn openhuman_core::cron::host_delivery::CronDelivery>>,
pub(super) seams: HostSeams,
pub(super) max_agents: usize,
pub(super) agent_defaults: super::AgentDefaults,
@@ -144,6 +145,7 @@ impl RuntimeBuilder {
backend_transport: None,
memory_engine: None,
session_store: None,
+ cron_delivery: None,
seams: HostSeams::default(),
max_agents: DEFAULT_MAX_AGENTS,
agent_defaults: super::AgentDefaults::default(),
@@ -261,6 +263,24 @@ impl RuntimeBuilder {
self
}
+ /// Route the replies of the agents' scheduled jobs yourself.
+ ///
+ /// An `origin`-mode run of an agent's cron job hands its output to
+ /// [`CronDelivery::deliver`](crate::CronDelivery::deliver) with the agent
+ /// id, the thread the job was created in and its
+ /// [`JobOrigin`](crate::JobOrigin), instead of writing into a local thread
+ /// or channel; a run that answers `NO_REPLY`, or fails, is never delivered.
+ /// Jobs still run only while their agent is live (the scheduler service
+ /// must be on). It is process-wide, as the runtime is, and the core has no
+ /// uninstall for it: it stays installed for the life of the process.
+ pub fn cron_delivery(
+ mut self,
+ delivery: Arc<dyn openhuman_core::cron::host_delivery::CronDelivery>,
+ ) -> Self {
+ self.cron_delivery = Some(delivery);
+ self
+ }
+
/// The most agents this runtime hosts at once; [`crate::Runtime::agent`]
/// returns [`AgentError::AgentLimit`](crate::AgentError::AgentLimit)
/// beyond it. Removed and dropped agents do not count. Defaults to
diff --git a/crates/openhuman-embed/tests/cron_host_delivery.rs b/crates/openhuman-embed/tests/cron_host_delivery.rs
new file mode 100644
index 0000000000..b6da4c722d
--- /dev/null
+++ b/crates/openhuman-embed/tests/cron_host_delivery.rs
@@ -0,0 +1,119 @@
+//! A library agent's scheduled reply reaches the host's `CronDelivery`.
+//!
+//! The agent makes a one-shot job through the `cron` tool in a chat turn on a
+//! stateless runtime. When the scheduler runs it, the reply is handed to the
+//! host with the agent's id and the thread the job was made in, not written
+//! into a local thread.
+//!
+//! One runtime per process, so one test in this binary.
+
+mod common;
+
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use common::{offline_config, runtime, scripted_provider, stub_backend, tool_call_completion};
+use openhuman_embed::{
+ AgentDefinitionSpec, AgentSpec, CronDelivery, CronReply, HostTurnTools, InMemorySessionStores,
+ JobOrigin, Runtime, ServiceSet, ToolScopeSpec, Workspace,
+};
+
+#[derive(Default)]
+struct Recorder(Mutex<Vec<CronReply>>);
+
+#[async_trait::async_trait]
+impl CronDelivery for Recorder {
+ async fn deliver(&self, reply: CronReply) -> Result<(), String> {
+ self.0.lock().unwrap().push(reply);
+ Ok(())
+ }
+}
+
+/// A `cron add` call for a one-shot agent job a few seconds from now.
+fn add_job(name: &str, prompt: &str) -> serde_json::Value {
+ let at = chrono::Utc::now() + chrono::Duration::seconds(2);
+ let arguments = serde_json::json!({
+ "action": "add", "job_type": "agent", "name": name, "prompt": prompt,
+ "delivery": {"mode": "origin"},
+ "schedule": {"kind": "at", "at": at.to_rfc3339()},
+ });
+ tool_call_completion("cron", &arguments.to_string())
+}
+
+#[test]
+fn a_library_agents_scheduled_reply_is_handed_to_the_host() {
+ runtime().block_on(async {
+ tokio::spawn(async {
+ let backend = stub_backend().await;
+ // The chat turn schedules the job and acknowledges it; the job's
+ // own run answers from the fallback.
+ let provider = scripted_provider(
+ vec![
+ add_job("stretch", "stretch reminder"),
+ common::chat_completion("Scheduled."),
+ ],
+ "Time to stretch!",
+ )
+ .await;
+ let recorder = Arc::new(Recorder::default());
+ let mut config = offline_config();
+ config.reliability.scheduler_poll_secs = 5;
+ let runtime = Runtime::builder()
+ .config(config)
+ .workspace(Workspace::Stateless)
+ .session_store(Arc::new(InMemorySessionStores::new()))
+ .backend_url(backend.uri())
+ .cron_delivery(recorder.clone())
+ .services(ServiceSet {
+ cron: true,
+ ..ServiceSet::none()
+ })
+ .build()
+ .await
+ .expect("runtime builds");
+ let agent = runtime
+ .agent(
+ AgentSpec::new("teeny")
+ .provider(common::route(&provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .system_prompt("TEENY")
+ .tools(ToolScopeSpec::Named(vec!["cron".into()])),
+ )
+ .tools(|_| HostTurnTools::advertised(Vec::new())),
+ )
+ .expect("agent instantiates");
+
+ agent
+ .turn("remind me to stretch")
+ .session("t-stretch")
+ .send()
+ .await
+ .expect("the stretch turn runs");
+
+ let mut delivered = Vec::new();
+ for _ in 0..120 {
+ delivered = recorder.0.lock().unwrap().clone();
+ if !delivered.is_empty() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ assert_eq!(delivered.len(), 1, "{delivered:?}");
+ let reply = &delivered[0];
+ assert_eq!(reply.agent_id.as_deref(), Some("teeny"));
+ assert_eq!(reply.profile_id, None, "a library agent has no profile");
+ assert_eq!(reply.thread_id.as_deref(), Some("t-stretch"));
+ assert_eq!(reply.text, "Time to stretch!");
+ assert!(
+ matches!(&reply.origin, Some(JobOrigin::Web { thread_id, .. }) if thread_id == "t-stretch"),
+ "{:?}",
+ reply.origin
+ );
+ drop(agent);
+ drop(runtime);
+ })
+ .await
+ .expect("library host task did not panic");
+ });
+}
diff --git a/crates/openhuman-embed/tests/profile_cron_sweep.rs b/crates/openhuman-embed/tests/profile_cron_sweep.rs
index e071ec957b..c6d8ac4430 100644
--- a/crates/openhuman-embed/tests/profile_cron_sweep.rs
+++ b/crates/openhuman-embed/tests/profile_cron_sweep.rs
@@ -138,6 +138,10 @@ async fn scenario() {
})
.collect();
delivered.sort_by(|x, y| x.0.cmp(&y.0));
+ assert!(
+ recorder.0.lock().unwrap().iter().all(|r| r.agent_id.is_none()),
+ "a profile's default agent is not named"
+ );
let web = |user: &str| {
Some(JobOrigin::Web {
thread_id: format!("t-{user}"),
@@ -148,13 +152,13 @@ async fn scenario() {
delivered,
[
(
- "alice".into(),
+ Some("alice".into()),
Some("t-alice".into()),
"ran: alice".into(),
web("alice")
),
(
- "bob".into(),
+ Some("bob".into()),
Some("t-bob".into()),
"ran: bob".into(),
web("bob")