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(cron): deliver scheduled run results to configured targets
Steven Enamakel04471f12228f
diff --git a/crates/openhuman-core/src/cron/scheduler/builtin.rs b/crates/openhuman-core/src/cron/scheduler/builtin.rsnew file mode 100644index 0000000000..34ae24a287--- /dev/null+++ b/crates/openhuman-core/src/cron/scheduler/builtin.rs@@ -0,0 +1,127 @@+//! The default job-kind handlers: shell, agent and flow.+//!+//! These are what [`crate::cron::handlers`] holds until a host registers its+//! own. Each is the thin adapter between a handler call and the code that+//! already did the work: the sandboxed shell runner ([`super::shell_job`]), a+//! full agent turn ([`super::agent_run`]) and the flow / system-job dispatch+//! below.++use std::sync::Arc;++use async_trait::async_trait;+use tinyflows_bus::schedule::types::{CronJob, JobType};++use super::agent_run::run_agent_job_for_run;+use super::shell_job::run_job_command;+use crate::core::bus::BUS;+use crate::core::events::DomainEvent;+use crate::cron::handlers::{JobKindHandler, JobOutcome, JobRunContext};++/// The built-in handler of every job kind.+pub(crate) fn defaults() -> Vec<(JobType, Arc<dyn JobKindHandler>)> {+ vec![+ (JobType::Shell, Arc::new(ShellHandler)),+ (JobType::Agent, Arc::new(AgentHandler)),+ (JobType::Flow, Arc::new(FlowHandler)),+ ]+}++/// `shell`: the command through the sandbox runner under the security policy.+struct ShellHandler;++#[async_trait]+impl JobKindHandler for ShellHandler {+ async fn run(&self, cx: &JobRunContext, job: &CronJob, _run_id: &str) -> JobOutcome {+ let (success, output) =+ run_job_command(&cx.dispatch_ctx(), &cx.config(), cx.security().as_ref(), job).await;+ JobOutcome {+ success,+ output,+ agent_error: None,+ permanent: false,+ }+ }+}++/// `agent`: a full agent turn; its own error text feeds failure classification.+struct AgentHandler;++#[async_trait]+impl JobKindHandler for AgentHandler {+ async fn run(&self, cx: &JobRunContext, job: &CronJob, run_id: &str) -> JobOutcome {+ let (success, output, agent_error) =+ run_agent_job_for_run(&cx.dispatch_ctx(), &cx.config(), job, run_id).await;+ JobOutcome {+ success,+ output,+ agent_error,+ permanent: false,+ }+ }+}++/// `flow`: a `system:<name>` job, or the schedule tick of the bound flow.+struct FlowHandler;++#[async_trait]+impl JobKindHandler for FlowHandler {+ async fn run(&self, cx: &JobRunContext, job: &CronJob, run_id: &str) -> JobOutcome {+ let flow_id = job.command.as_str();+ if let Some(name) = crate::cron::system_jobs::system_command_name(flow_id) {+ return run_system_job(&cx.dispatch_ctx(), &job.id, name, run_id).await;+ }+ // `[components] flows = false`: schedule-triggered flows stop while+ // agent, shell and system jobs keep running. The tick is answered, not+ // retried, so the row's recurrence moves on.+ if !cx.dispatch_ctx().components().flows {+ tracing::debug!(+ target: "flows",+ %flow_id,+ %run_id,+ "[cron] flow schedule trigger skipped: component 'flows' disabled"+ );+ return JobOutcome::ok(format!(+ "flow schedule tick skipped for flow {flow_id}: COMPONENT_DISABLED:flows"+ ));+ }+ tracing::info!(+ target: "flows",+ %flow_id,+ %run_id,+ "[cron] flow schedule trigger fired"+ );+ #[cfg(feature = "flows")]+ cx.binding()+ .flows()+ .dispatch_schedule_tick(&cx.dispatch_ctx(), flow_id)+ .await;+ #[cfg(not(feature = "flows"))]+ tracing::warn!(%flow_id, "[cron] built without `flows`; schedule trigger dropped");+ JobOutcome::ok(format!("flow schedule tick emitted for flow {flow_id}"))+ }+}++/// A host-owned system job (`system:<name>`): announced on the bus, then its+/// registered handler is awaited and its result is the run's result. Without a+/// handler the job is announce-only and `ok` on dispatch.+async fn run_system_job(+ ctx: &crate::core::runtime::DispatchCtx,+ job_id: &str,+ name: &str,+ run_id: &str,+) -> JobOutcome {+ tracing::info!(%job_id, job = %name, %run_id, "[cron] system job due — publishing CronSystemJobDue");+ BUS.publish(DomainEvent::CronSystemJobDue {+ job: name.to_string(),+ tenant: ctx.event_tenant(),+ });+ let ctx = crate::cron::system_job_handlers::SystemJobContext {+ job_id: job_id.to_string(),+ name: name.to_string(),+ };+ match crate::cron::system_job_handlers::dispatch(ctx).await {+ Some(Ok(())) => JobOutcome::ok(format!("system job {name} completed")),+ Some(Err(error)) => JobOutcome::failed(format!("system job {name} failed: {error}")),+ None => JobOutcome::ok(format!("system job {name} dispatched")),+ }+}diff --git a/crates/openhuman-core/src/cron/scheduler/run_delivery.rs b/crates/openhuman-core/src/cron/scheduler/run_delivery.rsindex c7cf104e5b..a6ce57bb8d 100644--- a/crates/openhuman-core/src/cron/scheduler/run_delivery.rs+++ b/crates/openhuman-core/src/cron/scheduler/run_delivery.rs@@ -1,177 +1,143 @@-//! The host's `RunDelivery` and `TriggerSink` ports for the schedule runtime.+//! The host's answers to the module's `Deliver` and `ScheduleTrigger`+//! callbacks.//!//! Delivery sends a finished run's output to its chat, channel or origin and//! raises the alert (`delivery.rs`), then announces the completion on the bus.-//! The trigger sink fires a `flow` row's schedule trigger directly in the-//! flows domain, or runs a host-owned system job, with no domain event in-//! between.+//! The trigger fires a `flow` row through the job-kind registry+//! ([`crate::cron::handlers`]): the default `flow` handler starts the flow's+//! schedule tick directly in the flows domain, or runs a host-owned system+//! job, with no domain event in between.use super::delivery::deliver_run;-use super::host::Binding;use crate::core::bus::BUS;use crate::core::events::DomainEvent;+use crate::cron::bus_host::{kind_refusal, Binding};+use crate::cron::handlers::{kind_handler, JobRunContext};use anyhow::Result;-use async_trait::async_trait;-use tinyflows_schedule::runtime::{Attempt, RunDelivery, TriggerSink};-use tinyflows_bus::schedule::types::{CronJob, DeliveryStatus};+use chrono::Utc;+use tinyflows_bus::schedule::types::{+ CronJob, DeliveryConfig, DeliveryStatus, JobPolicy, JobType, Schedule, SessionTarget,+};+use tinyflows_bus::schedule::{Attempt, StoreOperation};-pub(super) struct HostDelivery {- binding: Binding,+/// Deliver `attempt`'s output for `job` and publish the run's completion.+pub(crate) async fn deliver(+ binding: &Binding,+ job: &CronJob,+ run_id: &str,+ attempt: &Attempt,+) -> Result<DeliveryStatus> {+ binding+ .within(async {+ let config = binding.config();+ let ctx = binding.dispatch_ctx();+ let result =+ deliver_run(&ctx, &config, job, run_id, &attempt.output, attempt.success).await;+ // A failed required delivery fails the run, as the module+ // records it.+ let delivered = match &result {+ Ok(status) => *status != DeliveryStatus::Failed || job.delivery.best_effort,+ Err(_) => job.delivery.best_effort,+ };+ let success = attempt.success && delivered;+ // 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(&ctx, &job.id);+ BUS.publish(DomainEvent::CronJobCompleted {+ job_id: job.id.clone(),+ success,+ output: crate::util::truncate_with_ellipsis(&attempt.output, 512),+ });+ BUS.publish(DomainEvent::HealthChanged {+ component: "scheduler".to_string(),+ healthy: success,+ message: (!success).then(|| {+ if attempt.output.is_empty() {+ format!("job {} failed", job.id)+ } else {+ crate::util::truncate_with_ellipsis(&attempt.output, 256)+ }+ }),+ });+ result+ })+ .await}-impl HostDelivery {- pub(super) fn new(binding: Binding) -> Self {- Self { binding }+/// A `flow` row standing in for a trigger whose stored row cannot be read (it+/// was removed between the claim and the tick). The handler needs only the+/// bound flow id, which is the row's `command`.+fn stand_in(flow_id: &str) -> CronJob {+ let now = Utc::now();+ CronJob {+ claim_generation: 0,+ policy: JobPolicy::default(),+ id: flow_id.to_string(),+ expression: String::new(),+ schedule: Schedule::Every { every_ms: 60_000 },+ command: flow_id.to_string(),+ prompt: None,+ name: None,+ job_type: JobType::Flow,+ session_target: SessionTarget::default(),+ model: None,+ agent_id: None,+ enabled: true,+ delivery: DeliveryConfig::default(),+ delete_after_run: false,+ created_at: now,+ next_run: now,+ last_run: None,+ last_status: None,+ last_output: None,+ origin: None,}}-#[async_trait]-impl RunDelivery for HostDelivery {- async fn deliver(- &self,- job: &CronJob,- run_id: &str,- attempt: &Attempt,- ) -> Result<DeliveryStatus> {- self.binding- .within(async {- let config = self.binding.config();- let ctx = self.binding.dispatch_ctx();- let result =- 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 {- Ok(status) => *status != DeliveryStatus::Failed || job.delivery.best_effort,- Err(_) => job.delivery.best_effort,+/// Fire the `flow` row bound to `flow_id` through the registered `flow`+/// handler.+pub(crate) async fn trigger(binding: &Binding, flow_id: &str, run_id: &str) -> Attempt {+ binding+ .within(async {+ if let Some(refusal) = kind_refusal(binding, &JobType::Flow) {+ return Attempt {+ success: false,+ output: refusal,+ retryable: false,};- let success = attempt.success && delivered;- // 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(&ctx, &job.id);- BUS.publish(DomainEvent::CronJobCompleted {- job_id: job.id.clone(),- success,- output: crate::util::truncate_with_ellipsis(&attempt.output, 512),- });- BUS.publish(DomainEvent::HealthChanged {- component: "scheduler".to_string(),- healthy: success,- message: (!success).then(|| {- if attempt.output.is_empty() {- format!("job {} failed", job.id)- } else {- crate::util::truncate_with_ellipsis(&attempt.output, 256)- }- }),- });- result- })+ }+ let config = binding.config();+ let job = match crate::cron::client::store::<Option<CronJob>>(+ &config,+ StoreOperation::FindFlow {+ flow_id: flow_id.to_string(),+ },+ ).await- }-}--pub(super) struct HostTriggers {- binding: Binding,- /// Holds the per-flow in-flight dedupe across ticks.- #[cfg(feature = "flows")]- flows: std::sync::OnceLock<crate::flows::bus::FlowTriggerSubscriber>,-}--impl HostTriggers {- pub(super) fn new(binding: Binding) -> Self {- Self {- binding,- #[cfg(feature = "flows")]- flows: std::sync::OnceLock::new(),- }- }-}--#[async_trait]-impl TriggerSink for HostTriggers {- async fn schedule(&self, flow_id: &str, run_id: &str) -> Result<Attempt> {- self.binding- .within(async {- if let Some(name) = crate::cron::system_jobs::system_command_name(flow_id) {- let config = self.binding.config();- let job_id = match crate::cron::store::documents(&config) {- Ok(docs) => docs.find_flow_schedule_job(flow_id).await.ok().flatten(),- Err(_) => None,- }- .map_or_else(|| flow_id.to_string(), |job| job.id);- return Ok(run_system_job(&self.binding.dispatch_ctx(), &job_id, name, run_id).await);- }- // `[components] flows = false`: schedule-triggered flows stop- // while agent, shell and system jobs keep running. The tick is- // answered, not retried, so the row's recurrence moves on.- if !self.binding.dispatch_ctx().components().flows {- tracing::debug!(- target: "flows",- %flow_id,- %run_id,- "[cron] flow schedule trigger skipped: component 'flows' disabled"- );- return Ok(Attempt {- success: true,- output: format!("flow schedule tick skipped for flow {flow_id}: COMPONENT_DISABLED:flows"),- retryable: false,- });+ {+ Ok(Some(job)) => job,+ Ok(None) => stand_in(flow_id),+ Err(error) => {+ tracing::debug!(%flow_id, %error, "[cron:trigger] flow row unreadable; using a stand-in");+ stand_in(flow_id)}- tracing::info!(- target: "flows",- %flow_id,- %run_id,- "[cron] flow schedule trigger fired"- );- #[cfg(feature = "flows")]- self.flows- .get_or_init(|| {- crate::flows::bus::FlowTriggerSubscriber::new(std::sync::Arc::new(- self.binding.config(),- ))- })- .dispatch_schedule_tick(&self.binding.dispatch_ctx(), flow_id)- .await;- #[cfg(not(feature = "flows"))]- tracing::warn!(%flow_id, "[cron] built without `flows`; schedule trigger dropped");- Ok(Attempt {- success: true,- output: format!("flow schedule tick emitted for flow {flow_id}"),- retryable: true,- })- })- .await- }-}--/// A host-owned system job (`system:<name>`): announced on the bus, then its-/// registered handler is awaited and its result is the run's result. Without a-/// handler the job is announce-only and `ok` on dispatch.-async fn run_system_job(- ctx: &crate::core::runtime::DispatchCtx,- job_id: &str,- name: &str,- run_id: &str,-) -> Attempt {- tracing::info!(%job_id, job = %name, %run_id, "[cron] system job due — publishing CronSystemJobDue");- BUS.publish(DomainEvent::CronSystemJobDue {- job: name.to_string(),- tenant: ctx.event_tenant(),- });- let ctx = crate::cron::system_job_handlers::SystemJobContext {- job_id: job_id.to_string(),- name: name.to_string(),- };- let (success, output) = match crate::cron::system_job_handlers::dispatch(ctx).await {- Some(Ok(())) => (true, format!("system job {name} completed")),- Some(Err(error)) => (false, format!("system job {name} failed: {error}")),- None => (true, format!("system job {name} dispatched")),- };- Attempt {- success,- output,- retryable: true,- }+ };+ let Some(handler) = kind_handler(&JobType::Flow) else {+ return Attempt {+ success: false,+ output: "no handler is registered for flow jobs".to_string(),+ retryable: false,+ };+ };+ let outcome = handler+ .run(&JobRunContext::new(binding.clone()), &job, run_id)+ .await;+ Attempt {+ success: outcome.success,+ output: outcome.output,+ retryable: !outcome.permanent,+ }+ })+ .await}