Skip to content

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

fix(cron): deliver scheduled run results to the originating session

Steven Enamakelf170ffd8b839
diff --git a/crates/openhuman-core/src/cron/completion_owner.rs b/crates/openhuman-core/src/cron/completion_owner.rs
index e2e3d390d8..e835354724 100644
--- a/crates/openhuman-core/src/cron/completion_owner.rs
+++ b/crates/openhuman-core/src/cron/completion_owner.rs
@@ -21,8 +21,9 @@ static OWNERS: LazyLock<Mutex<HashMap<String, String>>> = LazyLock::new(Default:
/// Notes that `job_id` just completed as the current context's agent, when
/// it ran as one. Call just before publishing `CronJobCompleted`.
-pub fn note(job_id: &str) {
- let Some(agent) = crate::core::runtime::current_tenant()
+pub fn note(ctx: &crate::core::runtime::DispatchCtx, job_id: &str) {
+ let Some(agent) = ctx
+ .tenant()
.ok()
.and_then(|tenant| tenant.agent)
else {
diff --git a/crates/openhuman-core/src/cron/ops.rs b/crates/openhuman-core/src/cron/ops.rs
index 7a9ac5297c..6606d19013 100644
--- a/crates/openhuman-core/src/cron/ops.rs
+++ b/crates/openhuman-core/src/cron/ops.rs
@@ -182,7 +182,11 @@ pub async fn cron_remove(
))
}
-pub async fn cron_run(config: &Config, job_id: &str) -> Result<Outcome<serde_json::Value>, String> {
+pub async fn cron_run(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ job_id: &str,
+) -> Result<Outcome<serde_json::Value>, String> {
let job_id = job_id.trim();
if job_id.is_empty() {
return Err("Missing 'job_id' parameter".to_string());
@@ -213,6 +217,7 @@ pub async fn cron_run(config: &Config, job_id: &str) -> Result<Outcome<serde_jso
let _ = cron::record_run(config, &job.id, queued_at, queued_at, "queued", None, 0);
let config_owned = config.clone();
+ let ctx_owned = ctx.clone();
let job_id_owned = job_id.to_string();
tracing::debug!(job_id, "[cron_run] enqueuing background execution");
@@ -224,7 +229,7 @@ pub async fn cron_run(config: &Config, job_id: &str) -> Result<Outcome<serde_jso
let _guard = run_guard;
tracing::debug!(job_id = %job_id_owned, "[cron_run] background task started");
- run_and_record(&config_owned, &job).await;
+ run_and_record(&ctx_owned, &config_owned, &job).await;
});
Ok(Outcome::new(
@@ -239,19 +244,23 @@ pub async fn cron_run(config: &Config, job_id: &str) -> Result<Outcome<serde_jso
/// Run job `job_id` now and wait for it: the same execution, retry budget,
/// delivery and run record as a scheduled run. Refused while a run of the job
/// (scheduled or another Run Now) is already active.
-pub async fn run_job_now(config: &Config, job_id: &str) -> Result<(bool, String), String> {
+pub async fn run_job_now(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &Config,
+ job_id: &str,
+) -> Result<(bool, String), String> {
let job = load_job_for_run(config, job_id.trim()).map_err(|e| e.to_string())?;
cron::limits::check_run(config, &job).map_err(|e| e.to_string())?;
let Some(_guard) = try_acquire_run(&job.id) else {
tracing::debug!(job_id = %job.id, "[cron_run] job already running; refused");
return Err(format!("cron job '{}' is already running", job.id));
};
- Ok(run_and_record(config, &job).await)
+ Ok(run_and_record(ctx, config, &job).await)
}
/// Execute `job` once (with its retry budget), deliver its output and persist
/// the run and its last-run state. The caller holds the job's run claim.
-async fn run_and_record(config: &Config, job: &CronJob) -> (bool, String) {
+async fn run_and_record(ctx: &crate::core::runtime::DispatchCtx, config: &Config, job: &CronJob) -> (bool, String) {
let run_id = uuid::Uuid::new_v4().to_string();
let started_at = chrono::Utc::now();
let (success, output) = cron::scheduler::execute_job_now(config, job, &run_id).await;
@@ -265,7 +274,7 @@ async fn run_and_record(config: &Config, job: &CronJob) -> (bool, String) {
// Deliver via the same path as the scheduler loop so proactive messages,
// origin replies and alerts are sent on "Run Now" too, then record the run
// with how the delivery went.
- let delivery_status = cron::scheduler::deliver_job(config, job, &run_id, &output).await;
+ let delivery_status = cron::scheduler::deliver_job(ctx, config, job, &run_id, &output).await;
let _ = cron::record_run_with_delivery(
config,
&job.id,
diff --git a/crates/openhuman-core/src/cron/scheduler/delivery.rs b/crates/openhuman-core/src/cron/scheduler/delivery.rs
index 1c8eaae9d0..b41952cb2f 100644
--- a/crates/openhuman-core/src/cron/scheduler/delivery.rs
+++ b/crates/openhuman-core/src/cron/scheduler/delivery.rs
@@ -73,12 +73,13 @@ pub(super) fn cron_alert_body(job: &CronJob, output: &str) -> String {
/// explicitly triggered (empty output is still skipped). Returns how the
/// delivery went, for the run record.
pub async fn deliver_job(
+ ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
job: &CronJob,
run_id: &str,
output: &str,
) -> DeliveryStatus {
- match deliver_run(config, job, run_id, output, true).await {
+ match deliver_run(ctx, config, job, run_id, output, true).await {
Ok(status) => status,
Err(e) => {
if job.delivery.best_effort {
@@ -114,18 +115,20 @@ pub(super) fn cron_result_should_alert(success: bool, output: &str) -> bool {
/// [`deliver_run`] under a fresh run id, discarding the status.
#[cfg(test)]
pub(super) async fn deliver_if_configured(
+ ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
job: &CronJob,
output: &str,
success: bool,
) -> Result<()> {
let run_id = uuid::Uuid::new_v4().to_string();
- deliver_run(config, job, &run_id, output, success)
+ deliver_run(ctx, config, job, &run_id, output, success)
.await
.map(|_| ())
}
pub(super) async fn deliver_run(
+ ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
job: &CronJob,
run_id: &str,
@@ -187,7 +190,7 @@ pub(super) async fn deliver_run(
// created the job and send it there once.
delivery_mode::ORIGIN => {
if deliver_to_chat {
- status = deliver_to_origin(config, job, run_id, output).await?;
+ status = deliver_to_origin(ctx, config, job, run_id, output).await?;
}
}
diff --git a/crates/openhuman-core/src/cron/scheduler/host.rs b/crates/openhuman-core/src/cron/scheduler/host.rs
index 70be14fea1..bf2c2a6945 100644
--- a/crates/openhuman-core/src/cron/scheduler/host.rs
+++ b/crates/openhuman-core/src/cron/scheduler/host.rs
@@ -64,6 +64,12 @@ impl Binding {
.unwrap_or_else(std::sync::PoisonError::into_inner) = config.clone();
}
+ /// The dispatch context the bound context stands for: the bound one, or
+ /// (when it has since been dropped, or none was bound) the calling task's.
+ pub(crate) fn dispatch_ctx(&self) -> crate::core::runtime::DispatchCtx {
+ crate::core::runtime::DispatchCtx::from_weak(self.context.as_ref())
+ }
+
/// Runs `fut` under the bound context. A context that has since been
/// dropped (its agent is no longer live) runs `fut` as the caller is.
pub(crate) async fn within<F: Future>(&self, fut: F) -> F::Output {
diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
index 534d17b0d4..da36a747a0 100644
--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
@@ -66,6 +66,7 @@ const TRANSCRIPT_APPEND_TIMEOUT: std::time::Duration = std::time::Duration::from
/// thread that never had an agent turn has no transcript (`NoSession`) and is
/// skipped. Must never be called from inside a turn of the same session.
pub(crate) async fn append_to_origin_transcript(
+ ctx: &crate::core::runtime::DispatchCtx,
workspace_dir: &Path,
append: &TranscriptAppend<'_>,
) -> Result<(), String> {
@@ -74,13 +75,13 @@ pub(crate) async fn append_to_origin_transcript(
FileTranscriptLocator, SessionRef, TranscriptMessage,
};
let session = SessionRef::scoped(append.thread_id.to_string(), append.agent_id.to_string());
- if let Some(agent) = crate::agent::session_store::current_embedded_agent() {
+ if let Some(agent) = crate::agent::session_store::current_embedded_agent(ctx) {
use tinyagents_session::transcript::TranscriptLocator;
tinyagents_session::transcript::AgentTranscriptFiles::new(workspace_dir, &agent)
.session_exists(&session);
}
let locator =
- FileTranscriptLocator::new(crate::agent::session_store::transcript_root(workspace_dir));
+ FileTranscriptLocator::new(crate::agent::session_store::transcript_root(ctx, workspace_dir));
let options = BackgroundAppend::new(
append.idempotency_key,
serde_json::json!({
@@ -133,6 +134,7 @@ pub(crate) async fn append_to_origin_transcript(
/// `Ok(Suppressed)` for an intentional empty/`NO_REPLY` output; `Ok(Delivered)`
/// when the reply was committed and sent; `Err` when it could not be.
pub(crate) async fn deliver_to_origin(
+ ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
job: &CronJob,
run_id: &str,
@@ -154,7 +156,8 @@ pub(crate) async fn deliver_to_origin(
let text = output.trim();
// A hosted profile's or an embedded agent's host routes the reply itself.
- let owner = crate::core::runtime::current_tenant()
+ let owner = ctx
+ .tenant()
.ok()
.filter(|tenant| tenant.profile.is_some() || tenant.agent.is_some());
if let (Some(sink), Some(owner)) = (crate::cron::host_delivery::installed(), owner) {
@@ -187,7 +190,7 @@ pub(crate) async fn deliver_to_origin(
JobOrigin::Web {
thread_id,
agent_id,
- } => deliver_to_web_thread(config, job, run_id, thread_id, agent_id.as_deref(), text).await,
+ } => deliver_to_web_thread(ctx, config, job, run_id, thread_id, agent_id.as_deref(), text).await,
JobOrigin::Channel {
channel,
reply_target,
@@ -218,6 +221,7 @@ pub(crate) async fn deliver_to_origin(
}
async fn deliver_to_web_thread(
+ ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
job: &CronJob,
run_id: &str,
@@ -266,6 +270,7 @@ async fn deliver_to_web_thread(
// After the announcement: waiting out a live turn of this session must not
// delay the user seeing the reply (the thread row is already stored).
if let Err(e) = append_to_origin_transcript(
+ ctx,
&config.workspace_dir,
&TranscriptAppend {
thread_id,
diff --git a/crates/openhuman-core/src/cron/scheduler/run_delivery.rs b/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
index e3f4283f9d..3f8fc79773 100644
--- a/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
+++ b/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
@@ -36,8 +36,9 @@ impl RunDelivery for HostDelivery {
self.binding
.within(async {
let config = self.binding.config();
+ let ctx = self.binding.dispatch_ctx();
let result =
- deliver_run(&config, job, run_id, &attempt.output, attempt.success).await;
+ deliver_run(&ctx, &config, job, run_id, &attempt.output, attempt.success).await;
// A failed required delivery fails the run, as the runtime
// records it.
let delivered = match &result {
@@ -48,7 +49,7 @@ impl RunDelivery for HostDelivery {
// The job ran as its agent (when it had one); a one-shot job
// is deleted once the run completes, so subscribers learn the
// owner here, not from the store.
- crate::cron::completion_owner::note(&job.id);
+ crate::cron::completion_owner::note(&ctx, &job.id);
BUS.publish(DomainEvent::CronJobCompleted {
job_id: job.id.clone(),
success,
diff --git a/crates/openhuman-core/src/cron/schemas.rs b/crates/openhuman-core/src/cron/schemas.rs
index 43263405ff..b742ac4a89 100644
--- a/crates/openhuman-core/src/cron/schemas.rs
+++ b/crates/openhuman-core/src/cron/schemas.rs
@@ -431,7 +431,7 @@ fn handle_run(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture
Box::pin(async move {
let config = ctx.load_config().await?;
let job_id = read_required::<String>(&params, "job_id")?;
- to_json(crate::cron::rpc::cron_run(&config, job_id.trim()).await?)
+ to_json(crate::cron::rpc::cron_run(&ctx, &config, job_id.trim()).await?)
})
}