Skip to content

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

fix(cron): give a reminder that answers NO_REPLY one corrective turn

oxoxDev62693ca1d0d7
diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run.rs b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
index 6b4a85cff9..c8c7b325b3 100644
--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
@@ -4,6 +4,7 @@
use super::delivery::is_morning_briefing_job;
use super::failure_classification::classify_agent_anyhow_for_user;
use super::origin_context::build_run_prompt;
+use super::origin_delivery::{fallback_reminder, is_no_reply, job_allows_no_reply};
use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
use {tinyflows_bus::schedule::types::CronJob, tinyflows_bus::schedule::types::SessionTarget};
@@ -171,30 +172,14 @@ pub(super) async fn run_agent_job_for_run(
MORNING_BRIEFING_TASK_RECENCY_SECS,
)));
}
- // Scope the run's origin around the turn. A job with no
- // channel origin runs as `TrustedAutomation { Cron }`: the
- // approval gate treats it as user-authorized automation
- // (the user created the job and authorized its prompt
- // together). A job created from a channel chat runs as
- // that channel's turn instead, so its external-effect
- // tools stay gated like its creator's were.
- let origin = crate::cron::origin::turn_origin_for_job_run(job, run_id);
- let turn = crate::security::turn_origin::with_origin(
- origin,
- agent.run_single(&prefixed_prompt),
- );
- // A host agent's turn runs in its own context, so every
- // ambient read (config, domains, tool groups, session
- // store) sees that agent rather than the process default.
- let turn: std::pin::Pin<
- Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send + '_>,
- > = match context {
- Some(context) => {
- Box::pin(crate::core::runtime::CoreContext::scope(context, turn))
- }
- None => Box::pin(turn),
- };
- turn.await
+ Box::pin(run_with_corrective_turn(
+ &mut agent,
+ context.as_ref(),
+ job,
+ run_id,
+ &prefixed_prompt,
+ ))
+ .await
}
Err(e) => Err(e),
}
@@ -229,6 +214,79 @@ pub(super) async fn run_agent_job_for_run(
}
}
+/// The line a corrective turn adds when a job that must deliver answered
+/// `NO_REPLY`.
+pub(super) const NO_REPLY_CORRECTION: &str =
+ "NO_REPLY is not allowed for this task; write the message to send now.";
+
+/// Run the scheduled turn. A job that must deliver and answers `NO_REPLY`
+/// (or nothing) gets one corrective turn; if that still yields no message the
+/// host's fallback reminder is the run's output.
+async fn run_with_corrective_turn(
+ agent: &mut OpenHumanSessionHost,
+ context: Option<&std::sync::Arc<crate::core::runtime::CoreContext>>,
+ job: &CronJob,
+ run_id: &str,
+ prompt: &str,
+) -> anyhow::Result<String> {
+ let response = Box::pin(run_cron_turn(agent, context, job, run_id, prompt)).await?;
+ if job_allows_no_reply(job) || !needs_correction(&response) {
+ return Ok(response);
+ }
+ tracing::info!(
+ job_id = %job.id,
+ run_id = %run_id,
+ "[cron] run answered NO_REPLY but the job must deliver; running a corrective turn"
+ );
+ let corrective = format!("{prompt}\n\n{NO_REPLY_CORRECTION}");
+ let response = Box::pin(run_cron_turn(agent, context, job, run_id, &corrective)).await?;
+ if !needs_correction(&response) {
+ return Ok(response);
+ }
+ tracing::info!(
+ job_id = %job.id,
+ run_id = %run_id,
+ "[cron] corrective turn still produced no message; delivering the fallback reminder"
+ );
+ Ok(fallback_reminder(job))
+}
+
+fn needs_correction(response: &str) -> bool {
+ response.trim().is_empty() || is_no_reply(response)
+}
+
+/// One scheduled turn under the run's origin, in the host agent's context
+/// when there is one.
+async fn run_cron_turn(
+ agent: &mut OpenHumanSessionHost,
+ context: Option<&std::sync::Arc<crate::core::runtime::CoreContext>>,
+ job: &CronJob,
+ run_id: &str,
+ prompt: &str,
+) -> anyhow::Result<String> {
+ // A job with no channel origin runs as `TrustedAutomation { Cron }`: the
+ // approval gate treats it as user-authorized automation (the user created
+ // the job and authorized its prompt together). A job created from a
+ // channel chat runs as that channel's turn instead, so its external-effect
+ // tools stay gated like its creator's were.
+ let origin = crate::cron::origin::turn_origin_for_job_run(job, run_id);
+ let turn =
+ crate::security::turn_origin::with_origin(origin, Box::pin(agent.run_single(prompt)));
+ // A host agent's turn runs in its own context, so every ambient read
+ // (config, domains, tool groups, session store) sees that agent rather
+ // than the process default.
+ let turn: std::pin::Pin<
+ Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send + '_>,
+ > = match context {
+ Some(context) => Box::pin(crate::core::runtime::CoreContext::scope(
+ context.clone(),
+ turn,
+ )),
+ None => Box::pin(turn),
+ };
+ turn.await
+}
+
/// Placeholder recorded in run history when an agent job succeeds but returns
/// no text. Never delivered to chat — used only for the run-history record.
pub(super) const EMPTY_AGENT_OUTPUT: &str = "agent job executed";
diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run_tests.rs b/crates/openhuman-core/src/cron/scheduler/agent_run_tests.rs
index 7b256bb827..d18b2103ef 100644
--- a/crates/openhuman-core/src/cron/scheduler/agent_run_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run_tests.rs
@@ -14,3 +14,195 @@ pub(crate) async fn run_agent_job(
)
.await
}
+
+mod corrective_turn {
+ use super::*;
+ use crate::agent::host_agents::{self, HostAgent, HostAgentResolver};
+ use crate::core::runtime::{CoreContext, DomainSet};
+ use std::sync::Arc;
+ use tinyflows_bus::schedule::types::{DeliveryConfig, JobType, Schedule};
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ const AGENT_ID: &str = "cron-no-reply-agent";
+
+ struct OneAgent(Config);
+
+ impl HostAgentResolver for OneAgent {
+ fn resolve(&self, agent_id: &str) -> Option<HostAgent> {
+ if agent_id != AGENT_ID {
+ return None;
+ }
+ let mut definition =
+ crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only()
+ .get("orchestrator")
+ .cloned()
+ .unwrap();
+ definition.id = agent_id.to_string();
+ definition.subagents.clear();
+ definition.system_prompt =
+ tinyagents_definition::PromptSource::Inline("CRON_NO_REPLY_AGENT".into());
+ definition.tools = tinyagents_definition::ToolScope::Named(Vec::new());
+ Some(HostAgent {
+ definition,
+ config: self.0.clone(),
+ host_tools: None,
+ hooks: Default::default(),
+ context: CoreContext::for_test_with_config(DomainSet::full(), self.0.clone()),
+ })
+ }
+ }
+
+ fn answer(text: &str) -> serde_json::Value {
+ serde_json::json!({
+ "id": "chatcmpl-1", "object": "chat.completion", "created": 1, "model": "fixture",
+ "choices": [{ "index": 0, "finish_reason": "stop",
+ "message": { "role": "assistant", "content": text } }],
+ "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }
+ })
+ }
+
+ async fn provider(first: &str, then: &str) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(answer(first)))
+ .up_to_n_times(1)
+ .with_priority(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(answer(then)))
+ .with_priority(2)
+ .mount(&server)
+ .await;
+ server
+ }
+
+ fn config(tmp: &tempfile::TempDir, server: &MockServer) -> Config {
+ let workspace = tmp.path().join("workspace");
+ std::fs::create_dir_all(&workspace).unwrap();
+ let mut config = Config {
+ workspace_dir: workspace.clone(),
+ action_dir: workspace,
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ config.local_ai.runtime_enabled = false;
+ config.memory.conversations.enabled = false;
+ config.agent.session_dual_write = false;
+ config.agent.session_shadow_reads = false;
+ config.default_model = Some("fixture".into());
+ let route = crate::config::schema::EphemeralRoute::from_params(
+ Some(format!("{}/v1", server.uri())),
+ Some("sk-fixture".into()),
+ )
+ .unwrap();
+ crate::config::schema::ephemeral_route::apply(&mut config, route);
+ config
+ }
+
+ fn reminder_job() -> CronJob {
+ CronJob {
+ claim_generation: 0,
+ policy: Default::default(),
+ id: format!("job-{}", uuid::Uuid::new_v4()),
+ expression: "*/5 * * * *".into(),
+ schedule: Schedule::Every { every_ms: 300_000 },
+ command: String::new(),
+ prompt: Some("Remind the user to drink water".into()),
+ name: Some("water".into()),
+ job_type: JobType::Agent,
+ session_target: SessionTarget::Isolated,
+ model: None,
+ agent_id: Some(AGENT_ID.into()),
+ enabled: true,
+ delivery: DeliveryConfig {
+ mode: "origin".into(),
+ channel: None,
+ to: None,
+ best_effort: true,
+ },
+ delete_after_run: false,
+ created_at: chrono::Utc::now(),
+ next_run: chrono::Utc::now(),
+ last_run: None,
+ last_status: None,
+ last_output: None,
+ origin: None,
+ }
+ }
+
+ async fn chat_bodies(server: &MockServer) -> Vec<String> {
+ server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .filter(|r| r.url.path().ends_with("/chat/completions"))
+ .map(|r| String::from_utf8_lossy(&r.body).to_string())
+ .collect()
+ }
+
+ async fn run(
+ job: CronJob,
+ first: &'static str,
+ then: &'static str,
+ ) -> ((bool, String), Vec<String>) {
+ let server = provider(first, then).await;
+ let tmp = tempfile::tempdir().unwrap();
+ crate::agent_registry::host_definition::AgentDefinitionRegistry::init_global_builtins()
+ .unwrap();
+ let config = config(&tmp, &server);
+ let resolver: Arc<dyn HostAgentResolver> = Arc::new(OneAgent(config.clone()));
+ host_agents::install(Arc::clone(&resolver));
+ let (success, output, error) = run_agent_job(&config, &job).await;
+ host_agents::clear_if(&resolver);
+ assert!(error.is_none(), "{error:?}");
+ ((success, output), chat_bodies(&server).await)
+ }
+
+ fn on_agent_runtime(test: impl std::future::Future<Output = ()> + Send + 'static) {
+ tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .thread_stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .build()
+ .unwrap()
+ .block_on(async { tokio::spawn(test).await.unwrap() });
+ }
+
+ #[test]
+ fn a_reminder_that_answers_no_reply_gets_one_corrective_turn() {
+ let _slot = host_agents::tests::lock();
+ on_agent_runtime(async {
+ let (outcome, chats) = run(reminder_job(), "NO_REPLY", "Time to drink water!").await;
+ assert_eq!(outcome, (true, "Time to drink water!".to_string()));
+ assert_eq!(chats.len(), 2, "{chats:#?}");
+ assert!(!chats[0].contains(NO_REPLY_CORRECTION));
+ assert!(chats[1].contains(NO_REPLY_CORRECTION), "{}", chats[1]);
+ });
+ }
+
+ #[test]
+ fn a_reminder_that_keeps_answering_no_reply_delivers_the_fallback() {
+ let _slot = host_agents::tests::lock();
+ on_agent_runtime(async {
+ let (outcome, chats) = run(reminder_job(), "NO_REPLY", "No_reply.").await;
+ assert_eq!(outcome, (true, "Reminder: water".to_string()));
+ assert_eq!(chats.len(), 2, "{chats:#?}");
+ });
+ }
+
+ #[test]
+ fn a_conditional_job_may_answer_no_reply_without_correction() {
+ let _slot = host_agents::tests::lock();
+ on_agent_runtime(async {
+ let mut job = reminder_job();
+ job.prompt = Some("Check the inbox; reply NO_REPLY if nothing changed".into());
+ let (outcome, chats) = run(job, "NO_REPLY", "unexpected").await;
+ assert_eq!(outcome, (true, "NO_REPLY".to_string()));
+ assert_eq!(chats.len(), 1, "{chats:#?}");
+ });
+ }
+}