Skip to content

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

Merge upstream/main into oh-embed-cron-resolver

Steven Enamakelfc4693a3e627
diff --cc crates/openhuman-core/src/core/runtime/context_turn_origin_tests.rs
index 9049da5c1b,94dd1ac7a8..13d389e4eb
--- a/crates/openhuman-core/src/core/runtime/context_turn_origin_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin_tests.rs
@@@ -53,6 -55,6 +55,7 @@@ async fn explicit_origin_scope_bridges_
sender: Some(format!("{channel}-sender")),
reply_target: format!("{channel}-room"),
message_id: format!("{channel}-message"),
++ history_key: None,
};
CoreContext::scope(context, async {
turn_origin::with_origin(origin, async {
diff --cc crates/openhuman-core/src/cron/README.md
index bec4fee824,1cf5847eb1..5a3ec1155b
--- a/crates/openhuman-core/src/cron/README.md
+++ b/crates/openhuman-core/src/cron/README.md
@@@ -8,11 -8,10 +8,12 @@@ Scheduled-job runtime. Owns cron-expres
- `pub fn add_once` / `pub fn add_once_at` / `pub fn parse_human_delay` / `pub fn pause_job` / `pub fn resume_job` / `pub fn update_cron_job`: `ops.rs` (also re-exported as `pub use ops as rpc`).
- `pub fn schedule_cron_expression` / `pub fn next_run_for_schedule` / `pub fn normalize_expression` / `pub fn validate_schedule` / `pub fn validate_agent_schedule` / `pub fn runs_closer_than` / `pub struct TooFrequent` / `pub const MIN_AGENT_JOB_INTERVAL`: `schedule.rs`.
- `pub fn add_job` / `pub fn add_agent_job` / `pub fn add_agent_job_with_definition` / `pub fn add_shell_job` / `pub fn add_flow_schedule_job` / `pub fn find_flow_schedule_job` / `pub fn due_jobs` / `pub fn get_job` / `pub fn list_jobs` / `pub fn list_runs` / `pub fn record_last_run` / `pub fn record_run` / `pub fn remove_job` / `pub fn reschedule_after_run` / `pub fn update_job`: `store.rs`, a thin `Config` -> `CronStoreOptions` wrapper over `tinyflows_sqlite::schedule` (schema, job CRUD and run history live upstream).
- - `pub mod scheduler` (`pub async fn run(config: Config)`, `pub async fn execute_job_now` for the `cron.run` "Run Now" path, `pub fn is_running` for the one-loop-per-process slot in `scheduler/slot.rs`; `scheduler/dispatch.rs` (`JobDispatcher`) and `scheduler/in_flight.rs` are described under [Dispatch](#dispatch)): `scheduler.rs`, split into submodules `scheduler/failure_classification.rs` (failure classifiers), `scheduler/retry.rs` (`execute_job_now`, `execute_job_with_retry`), `scheduler/agent_run.rs` (`run_agent_job`, `build_agent_for_cron_job`, `run_flow_schedule_job`), `scheduler/delivery.rs` (`deliver_if_configured`), `scheduler/shell_job.rs` (`run_job_command_with_timeout`), and `scheduler/run_record.rs`; the poll loop and `run` stay in `scheduler.rs` itself.
-- `pub mod scheduler` (`pub async fn run(config: Config)`, `pub async fn execute_job_now` for the `cron.run` "Run Now" path): `scheduler.rs`, split into submodules `scheduler/failure_classification.rs` (failure classifiers), `scheduler/retry.rs` (`execute_job_now`, `execute_job_with_retry`), `scheduler/agent_run.rs` (`run_agent_job`, `build_agent_for_cron_job`, `run_flow_schedule_job`), `scheduler/delivery.rs` (`deliver_run`, `deliver_job`), `scheduler/origin_context.rs` (the prompt of a `current` run), `scheduler/origin_delivery.rs` (`delivery.mode = "origin"`), `scheduler/shell_job.rs` (`run_job_command_with_timeout`), and `scheduler/run_record.rs`; the poll loop and `run` stay in `scheduler.rs` itself.
++- `pub mod scheduler` (`pub async fn run(config: Config)`, `pub async fn execute_job_now` for the `cron.run` "Run Now" path, `pub fn is_running` for the one-loop-per-process slot in `scheduler/slot.rs`; `scheduler/dispatch.rs` (`JobDispatcher`) is described under [Dispatch](#dispatch)): `scheduler.rs`, split into submodules `scheduler/failure_classification.rs` (failure classifiers), `scheduler/retry.rs` (`execute_job_now`, `execute_job_with_retry`), `scheduler/agent_run.rs` (`run_agent_job`, `build_agent_for_cron_job`, `run_flow_schedule_job`), `scheduler/delivery.rs` (`deliver_run`, `deliver_job`), `scheduler/origin_context.rs` (the prompt of a `current` run), `scheduler/origin_delivery.rs` (`delivery.mode = "origin"`), `scheduler/shell_job.rs` (`run_job_command_with_timeout`), and `scheduler/run_record.rs`; the poll loop and `run` stay in `scheduler.rs` itself.
+- `pub mod policy`: `policy.rs`: per-job `JobPolicy { retries, single_flight }` in a host-owned `cron_job_policies` table beside the store (`CronJob` itself belongs to `tinyflows-schedule`). No row is the default policy; `store::remove_job` / `clear_all_jobs` drop rows with their jobs.
+- `pub mod system_job_handlers`: `system_job_handlers.rs`: in-process handlers for system jobs (`register(name, handler) -> SystemJobRegistration`, `dispatch`). The embed facade's `Runtime::on_system_job` registers here.
- `pub mod scheduler_gate`: throttles *background* LLM work (memory digests, embeddings, summarisation) on host power / CPU signals via `current_policy()` / `wait_for_capacity()`. It lives here for historical reasons; the cron poll loop does not consult it, and its consumers are `modules/memory_host.rs` and `security/credentials/`. See its own [README](scheduler_gate/README.md).
- `pub mod seed`: `seed.rs`: `seed_proactive_agents` installs the built-in proactive jobs when onboarding flips to completed (`config/ops/ui.rs`); `prune_retired_jobs` removes rows for removed features on boot and workspace activation.
+ - `pub mod origin` / `pub mod job_builder` / `pub mod channel_bridge`: the conversation a job was created from. `origin.rs` captures a `JobOrigin` from the live `AgentTurnOrigin`, decides whether a creation call may skip the approval gate, and picks the turn origin a run executes under; `job_builder.rs` is the one path (`create_agent_job`) the `cron` and `schedule` tools both use to build agent jobs with origin-aware defaults and delivery validation; `channel_bridge.rs` is cron's handle on the channel runtime (per-chat history and live channels, registered by `start_channels`).
- `pub mod bus`: `bus.rs`: `CronDeliverySubscriber` (`cron::delivery`) consumes `CronDeliveryRequested` and sends through the named `tinychannels_bus::Channel`.
- `pub mod tools`: `tools.rs` + `tools/`: agent-facing tools: `CronAddTool`, `CronListTool`, `CronUpdateTool`, `CronRemoveTool`, `CronRunTool`, `CronRunsTool`, and the collapsed `CronTool` / `CRON_TOOL_NAME`. `tools/collapsed.rs` explains why the six stay registered as hidden schemas behind the one advertised tool; see also [tools/README.md](tools/README.md).
- RPC namespace `cron`: `add`, `list`, `update`, `remove`, `run`, `runs`: `schemas.rs` (aggregated as `all_cron_controller_schemas` / `all_cron_registered_controllers`).
@@@ -27,18 -26,7 +28,18 @@@
`run_agent_job` prefixes the prompt (`[cron:<id> <name>] <prompt>`), applies a per-job `model` override to a cloned `Config`, and, when `job.agent_id` names a definition in `AgentDefinitionRegistry`, resolves that definition's `ModelSpec` onto the cloned config (the iteration cap is left to the session builder, see #4868). `build_agent_for_cron_job` uses `Agent::from_config_for_agent` for a recognized `agent_id`, falling back to `Agent::from_config` when it cannot build a definition or no id was supplied.
-`execute_job_with_retry` wraps every job type with `config.reliability.scheduler_retries` attempts and exponential backoff. For agent jobs it classifies failures before retrying: backend session-expired, provider insufficient-credits (402), managed-backend budget-exhausted (400), API-key-unset, and local-LLM-unreachable all halt the loop immediately and suppress the retries-exhausted error report. The user-facing message is a canned string from `classify_agent_anyhow_for_user`; the raw error goes only to observability.
+When `job.agent_id` names an agent a host registered (`agent::host_agents::resolve`, installed by `openhuman-embed`'s `Runtime`), `build_agent_for_cron_job` builds the session from that `HostAgent` instead: its definition, its host tools and its config (provider model and route applied, the job's `model` on top), and the turn runs inside its `CoreContext`, still under `TrustedAutomation { Cron }`. The registry model overrides above are skipped for such agents.
+
+`execute_job_with_retry` wraps every job type with the job's retry budget (`policy::effective_retries`: the job's `retries` override, else `config.reliability.scheduler_retries`) attempts and exponential backoff. For agent jobs it classifies failures before retrying: backend session-expired, provider insufficient-credits (402), managed-backend budget-exhausted (400), API-key-unset, and local-LLM-unreachable all halt the loop immediately and suppress the retries-exhausted error report. The user-facing message is a canned string from `classify_agent_anyhow_for_user`; the raw error goes only to observability.
+
+## Dispatch
+
+The poll loop no longer awaits its batch. `JobDispatcher::dispatch` spawns each due job onto a task set (bounded by `scheduler.max_concurrent`) and returns, so one long agent turn cannot hold up the next poll. Two guards replace the implicit one the blocked loop gave:
+
- - `in_flight`: a job counts as running from dispatch until its run is persisted (a counter, so a "Run now" overlapping a scheduled run of a default job is tracked correctly); the scheduler never dispatches a running job.
++- Run claim: a job is claimed with `ops::try_acquire_run` (the claim Run Now and the `cron_run` tool also take) from dispatch until its run is persisted; the scheduler never dispatches a claimed job, and no two runs of one job overlap.
+- Claimed slot: a recurring job's `next_run` is advanced to its next occurrence at dispatch (`update_job` with the same schedule); the usual `reschedule_after_run` recomputes it from the finish time. A crash mid-run therefore does not re-run the job at startup.
+
- A slot that comes due while the job is still running is skipped silently by default. With `JobPolicy::single_flight` it is recorded as a `skipped` run and `ops::run_job_now` / `cron.run` refuse while the job runs. Dropping the dispatcher (the loop task aborted by `CoreRuntime::stop_services` or the runtime's drop) aborts its jobs. `ops::run_job_now` runs a job to completion with the same retry budget, run record and delivery; `cron.run` spawns the same `run_and_record`.
++A slot that comes due while the job is still running is skipped silently by default; with `JobPolicy::single_flight` it is recorded as a `skipped` run. `ops::run_job_now` / `cron.run` refuse while any run of the job is active. Dropping the dispatcher (the loop task aborted by `CoreRuntime::stop_services` or the runtime's drop) aborts its jobs. `ops::run_job_now` runs a job to completion with the same retry budget, run record and delivery; `cron.run` spawns the same `run_and_record`.
## Event bus
@@@ -104,6 -134,6 +147,6 @@@ that evidence on each run instead (#615
## Tests
- - Unit: `policy_tests.rs`, `system_job_handlers_tests.rs`, `scheduler/in_flight_tests.rs`, `ops_tests.rs`, `scheduler_tests.rs` (shared fixtures; `#[path]`-includes `scheduler_dispatch_tests.rs` (non-blocking dispatch, slot claim, single-flight skip, retry budgets, handler results), `scheduler_host_agent_tests.rs` (host-registered agents), `scheduler_profile_and_shell_tests.rs`, `scheduler_halt_and_persist_tests.rs`, `scheduler_classifier_and_delivery_tests.rs`, `scheduler_frequency_tests.rs`), `store_tests.rs` (Config-to-options mapping; the store itself is tested in `tinyflows-sqlite`), `schedule_tests.rs`, `types_tests.rs`, `seed_tests.rs`, `bus_tests.rs`.
-- Unit: `ops_tests.rs`, `scheduler_tests.rs` (shared fixtures; `#[path]`-includes `scheduler_profile_and_shell_tests.rs`, `scheduler_halt_and_persist_tests.rs`, `scheduler_classifier_and_delivery_tests.rs`, `scheduler_frequency_tests.rs`), `store_tests.rs` (Config-to-options mapping; the store itself is tested in `tinyflows-sqlite`), `schedule_tests.rs`, `types_tests.rs`, `seed_tests.rs`, `bus_tests.rs`.
++- Unit: `policy_tests.rs`, `system_job_handlers_tests.rs`, `ops_tests.rs`, `scheduler_tests.rs` (shared fixtures; `#[path]`-includes `scheduler_dispatch_tests.rs` (non-blocking dispatch, slot claim, single-flight skip, retry budgets, handler results), `scheduler_host_agent_tests.rs` (host-registered agents), `scheduler_profile_and_shell_tests.rs`, `scheduler_halt_and_persist_tests.rs`, `scheduler_classifier_and_delivery_tests.rs`, `scheduler_frequency_tests.rs`), `store_tests.rs` (Config-to-options mapping; the store itself is tested in `tinyflows-sqlite`), `schedule_tests.rs`, `types_tests.rs`, `seed_tests.rs`, `bus_tests.rs`.
- Schema/parsing coverage lives in `schemas_tests.rs`.
- Tool coverage: `tools/{add,list,remove,run,runs,update}_tests.rs` (announce-mode `allowed_users` checks live in `add_tests.rs`) and `tools/collapsed_tests.rs` (action enum, merged schema, per-action permission resolution).
diff --cc crates/openhuman-core/src/cron/mod.rs
index 636f4fbd96,572864689b..c89de2dead
--- a/crates/openhuman-core/src/cron/mod.rs
+++ b/crates/openhuman-core/src/cron/mod.rs
@@@ -10,9 -10,10 +10,12 @@@
pub mod scheduler_gate;
pub mod bus;
+ pub mod channel_bridge;
+ pub mod job_builder;
pub mod ops;
+ pub mod origin;
+/// Per-job run policy (retry budget, single-flight) kept beside the job store.
+pub mod policy;
mod schemas;
pub mod seed;
mod store;
diff --cc crates/openhuman-core/src/cron/ops.rs
index a8208edccb,9119843b0f..2d1cdb94b3
--- a/crates/openhuman-core/src/cron/ops.rs
+++ b/crates/openhuman-core/src/cron/ops.rs
@@@ -276,58 -317,6 +281,49 @@@ pub async fn cron_run(config: &Config,
))
}
+/// Run job `job_id` now and wait for it: the same execution, retry budget,
- /// run record and delivery as a scheduled run. Refused while a single-flight
- /// job ([`crate::cron::policy::JobPolicy::single_flight`]) is already running.
++/// 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> {
+ let job = cron::get_job(config, job_id.trim()).map_err(|e| e.to_string())?;
- refuse_if_single_flight_running(config, &job.id)?;
++ 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)
+}
+
- /// `Err` when `job_id` is single-flight and a run of it is in flight.
- fn refuse_if_single_flight_running(config: &Config, job_id: &str) -> Result<(), String> {
- if crate::cron::scheduler::in_flight::is_running(job_id)
- && crate::cron::policy::policy_or_default(config, job_id).single_flight
- {
- tracing::debug!(
- job_id,
- "[cron_run] single-flight job already running; refused"
- );
- return Err(format!("cron job '{job_id}' is already running"));
- }
- Ok(())
- }
-
- /// Execute `job` once (with its retry budget) and persist the run, its
- /// last-run state and its delivery, holding the job in flight meanwhile.
++/// 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) {
- let _in_flight = crate::cron::scheduler::in_flight::enter(&job.id);
++ 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).await;
++ let (success, output) = cron::scheduler::execute_job_now(config, job, &run_id).await;
+ let finished_at = chrono::Utc::now();
+ let duration_ms = (finished_at - started_at).num_milliseconds();
+ let status = if success { "ok" } else { "error" };
+ tracing::debug!(job_id = %job.id, status, duration_ms, "[cron_run] run finished");
+ // Remove a "queued" placeholder before inserting the real result so no
+ // orphaned rows are left in the run history.
+ let _ = cron::delete_queued_runs(config, &job.id);
- let _ = cron::record_run(
++ // 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 _ = cron::record_run_with_delivery(
+ config,
+ &job.id,
+ started_at,
+ finished_at,
+ status,
+ Some(&output),
+ duration_ms,
++ Some(delivery_status),
+ );
+ let _ = cron::record_last_run(config, &job.id, finished_at, success, &output);
- // Deliver via the same path as the scheduler loop so proactive messages
- // and alerts are sent on "Run Now" too.
- cron::scheduler::deliver_job(config, job, &output).await;
+ (success, output)
+}
+
pub async fn cron_runs(
config: &Config,
job_id: &str,
diff --cc crates/openhuman-core/src/cron/ops_tests.rs
index 5cfb32419f,a7ff5dce0a..332e267e11
--- a/crates/openhuman-core/src/cron/ops_tests.rs
+++ b/crates/openhuman-core/src/cron/ops_tests.rs
@@@ -545,69 -545,3 +545,69 @@@ async fn cron_run_rejects_duplicate_con
"expected 'already running', got: {err}"
);
}
+
+// ── run_job_now / single-flight ─────────────────────────────────
+
+fn single_flight_system_job(config: &Config, name: &str) -> CronJob {
+ let job = crate::cron::system_jobs::ensure_system_job(
+ config,
+ name,
+ Schedule::Every {
+ every_ms: 3_600_000,
+ },
+ )
+ .unwrap();
+ crate::cron::policy::set_policy(
+ config,
+ &job.id,
+ crate::cron::policy::JobPolicy {
+ retries: Some(0),
+ single_flight: true,
+ },
+ )
+ .unwrap();
+ job
+}
+
+#[tokio::test]
+async fn run_job_now_runs_and_records_the_handler_result() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let _handler = crate::cron::system_job_handlers::register(
+ "ops-run-now",
+ std::sync::Arc::new(|_ctx| Box::pin(async { Err("nope".to_string()) })),
+ );
+ let job = single_flight_system_job(&config, "ops-run-now");
+ let (success, output) = run_job_now(&config, &job.id).await.unwrap();
+ assert!(!success);
+ assert!(output.contains("nope"), "{output}");
+ let runs = cron::list_runs(&config, &job.id, 10).unwrap();
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].status, "error");
+ assert_eq!(
+ cron::get_job(&config, &job.id)
+ .unwrap()
+ .last_status
+ .as_deref(),
+ Some("error")
+ );
+}
+
+#[tokio::test]
- async fn run_job_now_refuses_a_single_flight_job_that_is_running() {
++async fn run_job_now_refuses_a_job_that_is_already_running() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let job = single_flight_system_job(&config, "ops-run-now-busy");
- let _running = crate::cron::scheduler::in_flight::enter(&job.id);
++ let _running = try_acquire_run(&job.id).expect("the job is free");
+ let err = run_job_now(&config, &job.id).await.unwrap_err();
+ assert!(err.contains("already running"), "{err}");
+ let err = cron_run(&config, &job.id).await.unwrap_err();
+ assert!(err.contains("already running"), "{err}");
+}
+
+#[tokio::test]
+async fn run_job_now_reports_an_unknown_job() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ assert!(run_job_now(&config, "no-such-job").await.is_err());
+}
diff --cc crates/openhuman-core/src/cron/scheduler.rs
index e84192cda3,8e87f3fa2f..fe1793ea4f
--- a/crates/openhuman-core/src/cron/scheduler.rs
+++ b/crates/openhuman-core/src/cron/scheduler.rs
@@@ -6,9 -5,9 +6,10 @@@
mod agent_run;
mod delivery;
+mod dispatch;
mod failure_classification;
- pub(crate) mod in_flight;
+ mod origin_context;
+ mod origin_delivery;
mod retry;
mod run_record;
mod shell_job;
diff --cc crates/openhuman-core/src/cron/scheduler/dispatch.rs
index ba0bb44020,0000000000..ba46851255
mode 100644,000000..100644
--- a/crates/openhuman-core/src/cron/scheduler/dispatch.rs
+++ b/crates/openhuman-core/src/cron/scheduler/dispatch.rs
@@@ -1,168 -1,0 +1,167 @@@
+//! Dispatching due jobs without holding the poll loop.
+//!
+//! The poll loop used to await its whole batch (`buffer_unordered`), so one
+//! long agent turn kept every other job — including ones that came due during
+//! it — waiting for the next poll that could only happen once it finished.
+//! Now each due job is spawned onto the [`JobDispatcher`]'s task set and the
+//! poll returns at once; a semaphore keeps at most `scheduler.max_concurrent`
+//! jobs executing. Dropping the dispatcher (the loop's task is aborted on
+//! shutdown) aborts the jobs it still owns.
+//!
+//! Because the loop no longer waits, two guards replace the old implicit one:
+//!
- //! - **In flight**: a job is marked running from dispatch until its run is
- //! persisted ([`super::in_flight`]), and a running job is never dispatched
- //! again.
++//! - **Run claim**: a job is claimed (`cron::ops::try_acquire_run`, the same
++//! claim Run Now and the run tool take) from dispatch until its run is
++//! persisted, and a claimed job is never dispatched again.
+//! - **Claimed slot**: a recurring job's `next_run` is advanced to its next
+//! occurrence at dispatch, so a running job is not "due" on every poll. When
+//! it finishes, the usual reschedule recomputes `next_run` from that moment,
+//! exactly as before. A job that comes due again while still running has
+//! genuinely missed a slot: a default job skips it silently (the historical
+//! behaviour, when such slots were swallowed by the blocked loop); a
+//! single-flight job ([`crate::cron::policy::JobPolicy::single_flight`])
+//! records it as a `skipped` run.
+
+use std::sync::Arc;
+
+use chrono::Utc;
+use tokio::sync::Semaphore;
+use tokio::task::JoinSet;
+
- use super::in_flight;
+use crate::config::Config;
+use crate::core::bus::BUS;
+use crate::core::events::DomainEvent;
+use crate::core::runtime::CoreContext;
+use crate::cron::policy::policy_or_default;
+use crate::cron::{next_run_for_schedule, record_run, update_job, CronJob, CronJobPatch, Schedule};
+use crate::security::SecurityPolicy;
+
+/// Output recorded for a single-flight slot missed while a run was in flight.
+pub(crate) const SKIPPED_OUTPUT: &str = "skipped: the previous run was still in flight";
+
+/// Owns the tasks of the jobs the poll loop dispatched.
+pub(crate) struct JobDispatcher {
+ tasks: JoinSet<()>,
+ permits: Arc<Semaphore>,
+}
+
+impl JobDispatcher {
+ /// A dispatcher running at most `max_concurrent` jobs at once.
+ pub(crate) fn new(max_concurrent: usize) -> Self {
+ Self {
+ tasks: JoinSet::new(),
+ permits: Arc::new(Semaphore::new(max_concurrent.max(1))),
+ }
+ }
+
+ /// Start every job in `jobs` that is not already running and return.
+ pub(crate) async fn dispatch(
+ &mut self,
+ config: &Config,
+ security: &Arc<SecurityPolicy>,
+ jobs: Vec<CronJob>,
+ ) {
+ self.reap();
+ for job in jobs {
- if in_flight::is_running(&job.id) {
++ // One run per job at a time, shared with Run Now and the run tool.
++ let Some(guard) = crate::cron::ops::try_acquire_run(&job.id) else {
+ skip_in_flight(config, &job);
+ continue;
- }
- let guard = in_flight::enter(&job.id);
++ };
+ claim_slot(config, &job);
+ let config = config.clone();
+ let security = Arc::clone(security);
+ let permits = Arc::clone(&self.permits);
+ tracing::debug!(job_id = %job.id, "[cron:dispatch] job dispatched");
+ self.tasks.spawn(CoreContext::propagate(async move {
+ let _guard = guard;
+ let Ok(_permit) = permits.acquire_owned().await else {
+ return;
+ };
+ let (job_id, success, failure_message) =
+ super::execute_and_persist_job(&config, security.as_ref(), &job).await;
+ BUS.publish(DomainEvent::HealthChanged {
+ component: "scheduler".to_string(),
+ healthy: success,
+ message: (!success)
+ .then(|| failure_message.unwrap_or_else(|| format!("job {job_id} failed"))),
+ });
+ }));
+ }
+ }
+
+ /// Wait for every dispatched job to finish.
+ pub(crate) async fn drain(&mut self) {
+ while let Some(result) = self.tasks.join_next().await {
+ log_join(result);
+ }
+ }
+
+ /// Collect the jobs that already finished, so the set does not grow.
+ fn reap(&mut self) {
+ while let Some(result) = self.tasks.try_join_next() {
+ log_join(result);
+ }
+ }
+}
+
+fn log_join(result: Result<(), tokio::task::JoinError>) {
+ if let Err(error) = result {
+ if error.is_panic() {
+ tracing::error!("[cron:dispatch] a dispatched job panicked: {error}");
+ }
+ }
+}
+
+/// Advance a recurring job's `next_run` past now, so it is not due again
+/// while it runs. Best effort: on failure the in-flight guard still keeps the
+/// job from being dispatched twice.
+fn claim_slot(config: &Config, job: &CronJob) {
+ if matches!(job.schedule, Schedule::At { .. }) {
+ return;
+ }
+ match update_job(
+ config,
+ &job.id,
+ CronJobPatch {
+ schedule: Some(job.schedule.clone()),
+ ..CronJobPatch::default()
+ },
+ ) {
+ Ok(claimed) => tracing::trace!(
+ job_id = %job.id,
+ next_run = %claimed.next_run,
+ "[cron:dispatch] slot claimed"
+ ),
+ Err(error) => tracing::debug!(
+ job_id = %job.id,
+ %error,
- "[cron:dispatch] could not claim the slot; relying on the in-flight guard"
++ "[cron:dispatch] could not claim the slot; relying on the run claim"
+ ),
+ }
+}
+
+/// A due job whose previous run is still going.
+fn skip_in_flight(config: &Config, job: &CronJob) {
+ let policy = policy_or_default(config, &job.id);
+ if !policy.single_flight || matches!(job.schedule, Schedule::At { .. }) {
+ tracing::trace!(job_id = %job.id, "[cron:dispatch] still running; not dispatched again");
+ return;
+ }
+ tracing::info!(job_id = %job.id, "[cron:dispatch] single-flight job still running; slot skipped");
+ let now = Utc::now();
+ if let Err(error) = record_run(
+ config,
+ &job.id,
+ now,
+ now,
+ "skipped",
+ Some(SKIPPED_OUTPUT),
+ 0,
+ ) {
+ tracing::warn!(job_id = %job.id, %error, "[cron:dispatch] recording the skipped run failed");
+ }
+ if next_run_for_schedule(&job.schedule, now).is_ok() {
+ claim_slot(config, job);
+ }
+}
diff --cc crates/openhuman-core/src/cron/scheduler/retry.rs
index dd8a42c378,bf3a650f5b..d26d53a607
--- a/crates/openhuman-core/src/cron/scheduler/retry.rs
+++ b/crates/openhuman-core/src/cron/scheduler/retry.rs
@@@ -51,9 -62,9 +66,9 @@@ pub(super) async fn execute_job_with_re
let (success, output) = run_job_command(config, security, job).await;
(success, output, None)
}
- JobType::Agent => run_agent_job(config, job).await,
+ JobType::Agent => run_agent_job_for_run(config, job, run_id).await,
JobType::Flow => {
- let (success, output) = run_flow_schedule_job(job);
+ let (success, output) = run_flow_schedule_job(job).await;
(success, output, None)
}
};
diff --cc crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
index c4fdcd7a31,0000000000..1152a036b7
mode 100644,000000..100644
--- a/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
@@@ -1,337 -1,0 +1,342 @@@
+//! Dispatch semantics: a long job does not hold the poll loop, a job is never
+//! dispatched twice, single-flight skips are recorded, per-job retry budgets
+//! are honoured and a system job's handler result is what gets recorded.
+
+use super::*;
+use crate::cron::policy::{set_policy, JobPolicy};
+use crate::cron::system_job_handlers::{register, SystemJobContext};
+use crate::cron::system_jobs::ensure_system_job;
+use crate::cron::Schedule;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::Duration;
+use tempfile::TempDir;
+
+fn security(config: &Config) -> Arc<SecurityPolicy> {
+ Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ))
+}
+
+/// A system job row named `name`, already due.
+fn due_system_job(config: &Config, name: &str) -> CronJob {
+ let mut job = ensure_system_job(
+ config,
+ name,
+ Schedule::Every {
+ every_ms: 3_600_000,
+ },
+ )
+ .unwrap();
+ // Due now, both in the row the next poll reads and in the value we pass.
+ crate::cron::update_job(
+ config,
+ &job.id,
+ crate::cron::CronJobPatch {
+ schedule: Some(Schedule::Every {
+ every_ms: 3_600_000,
+ }),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ force_due(config, &job.id);
+ job.next_run = Utc::now() - ChronoDuration::seconds(1);
+ job
+}
+
+fn force_due(config: &Config, job_id: &str) {
+ let conn = rusqlite::Connection::open(crate::cron::policy::db_path(config)).unwrap();
+ conn.execute(
+ "UPDATE cron_jobs SET next_run = ?1 WHERE id = ?2",
+ rusqlite::params![
+ (Utc::now() - ChronoDuration::seconds(1)).to_rfc3339(),
+ job_id
+ ],
+ )
+ .unwrap();
+}
+
+fn counting(
+ calls: Arc<AtomicUsize>,
+ result: Result<(), String>,
+) -> crate::cron::system_job_handlers::SystemJobHandler {
+ Arc::new(move |_ctx: SystemJobContext| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ let result = result.clone();
+ Box::pin(async move { result })
+ })
+}
+
++/// Whether a run of `job_id` holds the run claim.
++fn job_is_running(job_id: &str) -> bool {
++ crate::cron::ops::try_acquire_run(job_id).is_none()
++}
++
+async fn wait_for(mut check: impl FnMut() -> bool) -> bool {
+ for _ in 0..200 {
+ if check() {
+ return true;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ false
+}
+
+#[tokio::test]
+async fn a_long_job_does_not_hold_up_the_next_poll() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let security = security(&config);
+ let release = Arc::new(tokio::sync::Notify::new());
+ let gate = Arc::clone(&release);
+ let _slow = register(
+ "dispatch-slow",
+ Arc::new(move |_ctx| {
+ let gate = Arc::clone(&gate);
+ Box::pin(async move {
+ gate.notified().await;
+ Ok(())
+ })
+ }),
+ );
+ let fast_calls = Arc::new(AtomicUsize::new(0));
+ let _fast = register("dispatch-fast", counting(Arc::clone(&fast_calls), Ok(())));
+
+ let slow = due_system_job(&config, "dispatch-slow");
+ let mut dispatcher = JobDispatcher::new(4);
+ let mut health = None;
+ // First poll picks up only the slow job.
+ tick_once(&config, &security, &mut health, &mut dispatcher).await;
- assert!(in_flight::is_running(&slow.id), "the slow job is running");
++ assert!(job_is_running(&slow.id), "the slow job is running");
+
+ // The next poll must not wait for it.
+ let fast = due_system_job(&config, "dispatch-fast");
+ tokio::time::timeout(
+ Duration::from_secs(5),
+ tick_once(&config, &security, &mut health, &mut dispatcher),
+ )
+ .await
+ .expect("a poll returns while an earlier job is still running");
+ assert!(
+ wait_for(|| cron::get_job(&config, &fast.id)
+ .unwrap()
+ .last_status
+ .as_deref()
+ == Some("ok"))
+ .await,
+ "the fast job completed while the slow one was still running"
+ );
- assert!(in_flight::is_running(&slow.id));
++ assert!(job_is_running(&slow.id));
+ assert_eq!(fast_calls.load(Ordering::SeqCst), 1);
+
+ release.notify_one();
+ dispatcher.drain().await;
- assert!(!in_flight::is_running(&slow.id));
++ assert!(!job_is_running(&slow.id));
+ assert_eq!(
+ cron::get_job(&config, &slow.id)
+ .unwrap()
+ .last_status
+ .as_deref(),
+ Some("ok")
+ );
+}
+
+#[tokio::test]
+async fn dispatch_claims_the_slot_so_a_running_job_is_not_due_again() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let release = Arc::new(tokio::sync::Notify::new());
+ let gate = Arc::clone(&release);
+ let _handler = register(
+ "dispatch-claim",
+ Arc::new(move |_ctx| {
+ let gate = Arc::clone(&gate);
+ Box::pin(async move {
+ gate.notified().await;
+ Ok(())
+ })
+ }),
+ );
+ let job = due_system_job(&config, "dispatch-claim");
+ let mut dispatcher = JobDispatcher::new(4);
+ dispatcher
+ .dispatch(&config, &security(&config), vec![job.clone()])
+ .await;
+ let stored = cron::get_job(&config, &job.id).unwrap();
+ assert!(stored.next_run > Utc::now(), "the running slot is claimed");
+ assert!(cron::due_jobs(&config, Utc::now())
+ .unwrap()
+ .iter()
+ .all(|due| due.id != job.id));
+ release.notify_one();
+ dispatcher.drain().await;
+}
+
+#[tokio::test]
+async fn a_job_already_in_flight_is_not_dispatched_again() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let _handler = register("dispatch-dedupe", counting(Arc::clone(&calls), Ok(())));
+ let job = due_system_job(&config, "dispatch-dedupe");
- let running = in_flight::enter(&job.id);
++ let running = crate::cron::ops::try_acquire_run(&job.id).expect("the job is free");
+ let mut dispatcher = JobDispatcher::new(4);
+ dispatcher
+ .dispatch(&config, &security(&config), vec![job.clone()])
+ .await;
+ dispatcher.drain().await;
+ drop(running);
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ assert!(
+ cron::list_runs(&config, &job.id, 10).unwrap().is_empty(),
+ "a default job's overlap is silent"
+ );
+}
+
+#[tokio::test]
+async fn a_single_flight_job_records_the_missed_slot_as_skipped() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let _handler = register("dispatch-single", counting(Arc::clone(&calls), Ok(())));
+ let job = due_system_job(&config, "dispatch-single");
+ set_policy(
+ &config,
+ &job.id,
+ JobPolicy {
+ retries: None,
+ single_flight: true,
+ },
+ )
+ .unwrap();
- let running = in_flight::enter(&job.id);
++ let running = crate::cron::ops::try_acquire_run(&job.id).expect("the job is free");
+ let mut dispatcher = JobDispatcher::new(4);
+ dispatcher
+ .dispatch(&config, &security(&config), vec![job.clone()])
+ .await;
+ dispatcher.drain().await;
+ drop(running);
+
+ assert_eq!(
+ calls.load(Ordering::SeqCst),
+ 0,
+ "the overlapping run is skipped"
+ );
+ let runs = cron::list_runs(&config, &job.id, 10).unwrap();
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].status, "skipped");
+ assert!(
+ cron::get_job(&config, &job.id).unwrap().next_run > Utc::now(),
+ "the skipped slot is consumed so the next poll does not record it again"
+ );
+}
+
+#[tokio::test]
+async fn zero_retries_means_exactly_one_attempt() {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp).await;
+ config.reliability.scheduler_retries = 2;
+ config.reliability.provider_backoff_ms = 200;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let _handler = register(
+ "dispatch-once",
+ counting(Arc::clone(&calls), Err("boom".to_string())),
+ );
+ let job = due_system_job(&config, "dispatch-once");
+ set_policy(
+ &config,
+ &job.id,
+ JobPolicy {
+ retries: Some(0),
+ single_flight: false,
+ },
+ )
+ .unwrap();
+ let security =
+ SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
+ let (success, output) = execute_job_with_retry(&config, &security, &job).await;
+ assert!(!success);
+ assert!(output.contains("boom"), "{output}");
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn without_a_policy_the_configured_retry_budget_applies() {
+ let tmp = TempDir::new().unwrap();
+ let mut config = test_config(&tmp).await;
+ config.reliability.scheduler_retries = 1;
+ config.reliability.provider_backoff_ms = 200;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let _handler = register(
+ "dispatch-default-retries",
+ counting(Arc::clone(&calls), Err("again".to_string())),
+ );
+ let job = due_system_job(&config, "dispatch-default-retries");
+ let security =
+ SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
+ let (success, _) = execute_job_with_retry(&config, &security, &job).await;
+ assert!(!success);
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+}
+
+#[tokio::test]
+async fn a_system_job_handler_error_is_recorded_as_the_run_result() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let _handler = register(
+ "dispatch-recorded",
+ counting(
+ Arc::new(AtomicUsize::new(0)),
+ Err("handler failed".to_string()),
+ ),
+ );
+ let job = due_system_job(&config, "dispatch-recorded");
+ set_policy(
+ &config,
+ &job.id,
+ JobPolicy {
+ retries: Some(0),
+ single_flight: false,
+ },
+ )
+ .unwrap();
+ let mut dispatcher = JobDispatcher::new(4);
+ dispatcher
+ .dispatch(&config, &security(&config), vec![job.clone()])
+ .await;
+ dispatcher.drain().await;
+ let stored = cron::get_job(&config, &job.id).unwrap();
+ assert_eq!(stored.last_status.as_deref(), Some("error"));
+ assert!(stored
+ .last_output
+ .unwrap_or_default()
+ .contains("handler failed"));
+}
+
+#[tokio::test]
+async fn a_system_job_without_a_handler_is_still_ok_on_dispatch() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let job = due_system_job(&config, "dispatch-unclaimed");
+ let security =
+ SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
+ let (success, output) = execute_job_with_retry(&config, &security, &job).await;
+ assert!(success);
+ assert!(output.contains("dispatched"), "{output}");
+}
+
+#[test]
+fn only_one_scheduler_loop_holds_the_slot() {
+ let first = SchedulerSlot::acquire().expect("the slot is free");
+ assert!(is_running());
+ assert!(
+ SchedulerSlot::acquire().is_none(),
+ "a second loop is refused"
+ );
+ drop(first);
+ assert!(!is_running());
+ let again = SchedulerSlot::acquire();
+ assert!(again.is_some());
+}
diff --cc crates/openhuman-embed/src/cron.rs
index bd040bf22f,0000000000..fc686923d4
mode 100644,000000..100644
--- a/crates/openhuman-embed/src/cron.rs
+++ b/crates/openhuman-embed/src/cron.rs
@@@ -1,571 -1,0 +1,571 @@@
+//! Scheduling: OpenHuman's own cron, driven from the library.
+//!
+//! [`Runtime::cron`](crate::Runtime::cron) returns a [`Cron`] facade over the
+//! runtime's job store. A job is named, and [`Cron::upsert`] is idempotent by
+//! that name, so a host can declare its schedule on every start:
+//!
+//! ```no_run
+//! # async fn demo(runtime: &openhuman_embed::Runtime) -> Result<(), openhuman_embed::CronError> {
+//! use openhuman_embed::{JobSchedule, JobSpec};
+//!
+//! let cron = runtime.cron();
+//! // A turn of the runtime agent `teeny` every morning, with its host tools.
+//! cron.upsert(
+//! JobSpec::agent("morning", "teeny", "Plan the day.", JobSchedule::Cron {
+//! expr: "0 8 * * *".into(),
+//! tz: Some("Europe/Berlin".into()),
+//! })
+//! .retries(0)
+//! .single_flight(true),
+//! )?;
+//! // A job whose work is the host's own code.
+//! runtime.on_system_job("digest", |_ctx| async { Ok(()) })?;
+//! cron.upsert(JobSpec::system("digest", "digest", JobSchedule::Every { ms: 15 * 60_000 }))?;
+//! # Ok(()) }
+//! ```
+//!
+//! # Targets
+//!
+//! - [`JobTarget::Agent`] runs one turn of the agent with that id. When the id
+//! names an agent alive on this runtime ([`Runtime::agent`](crate::Runtime::agent)),
+//! the turn runs *as that agent*: its definition and system prompt, its
+//! [`AgentSpec::tools`](crate::AgentSpec::tools) and attached tools, its
+//! provider and its context. Otherwise the id resolves through the core's
+//! agent registries. Either way the turn's origin is
+//! `TrustedAutomation { Cron }`, not the agent's own access origin.
+//! - [`JobTarget::System`] runs the handler registered with
+//! [`Runtime::on_system_job`](crate::Runtime::on_system_job) and records
+//! its result. With no handler the run is announced on the bus
+//! (`CronSystemJobDue`) and recorded `ok`.
+//!
+//! # When jobs fire
+//!
+//! Only while the scheduler runs: build the runtime with
+//! `ServiceSet { cron: true, .. }` (or call
+//! [`Runtime::start_services`](crate::Runtime::start_services)). Without it
+//! jobs are stored and [`Cron::run_now`] still works, but nothing fires on
+//! its own.
+//!
+//! # Retries and overlap
+//!
+//! A failed run is retried `retries` times with backoff (`None` keeps the
+//! runtime's `reliability.scheduler_retries`, two by default; `Some(0)` is one
- //! attempt — choose it for a job whose turn has side effects). A job is never
- //! dispatched twice at once; with `single_flight` a slot that comes due while
- //! the previous run is still going is recorded as `skipped`, and
- //! [`Cron::run_now`] is refused meanwhile.
++//! attempt — choose it for a job whose turn has side effects). Two runs of one
++//! job never overlap: [`Cron::run_now`] is refused while one is active, and a
++//! slot that comes due mid-run is skipped — silently by default, recorded as
++//! a `skipped` run with `single_flight`.
+
+use std::future::Future;
+use std::time::SystemTime;
+
+use openhuman_core::config::Config;
+use openhuman_core::cron::policy::{self, JobPolicy};
+use openhuman_core::cron::system_jobs::SYSTEM_COMMAND_PREFIX;
+use openhuman_core::cron::{CronJob, CronJobPatch, JobType, Schedule};
+
+pub use openhuman_core::cron::system_job_handlers::SystemJobContext;
+
+/// When a job fires.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum JobSchedule {
+ /// A five-field cron expression, in `tz` (an IANA name) or UTC.
+ Cron {
+ /// The expression, e.g. `"0 8 * * *"`.
+ expr: String,
+ /// IANA time zone; `None` is UTC.
+ tz: Option<String>,
+ },
+ /// Every `ms` milliseconds. An agent job may not run more often than
+ /// every five minutes.
+ Every {
+ /// The interval in milliseconds.
+ ms: u64,
+ },
+ /// Once, at `at`. Disabled after it runs.
+ At {
+ /// The instant to run at; must be in the future.
+ at: SystemTime,
+ },
+}
+
+impl JobSchedule {
+ pub(crate) fn to_core(&self) -> Schedule {
+ match self {
+ Self::Cron { expr, tz } => Schedule::Cron {
+ expr: expr.clone(),
+ tz: tz.clone(),
+ active_hours: None,
+ },
+ Self::Every { ms } => Schedule::Every { every_ms: *ms },
+ Self::At { at } => Schedule::At {
+ at: chrono::DateTime::<chrono::Utc>::from(*at),
+ },
+ }
+ }
+
+ pub(crate) fn from_core(schedule: &Schedule) -> Self {
+ match schedule {
+ Schedule::Cron { expr, tz, .. } => Self::Cron {
+ expr: expr.clone(),
+ tz: tz.clone(),
+ },
+ Schedule::Every { every_ms } => Self::Every { ms: *every_ms },
+ Schedule::At { at } => Self::At {
+ at: SystemTime::from(*at),
+ },
+ }
+ }
+}
+
+/// What a job runs.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum JobTarget {
+ /// One turn of agent `agent_id` with `prompt`.
+ Agent {
+ /// A runtime agent's id, or a registry agent's.
+ agent_id: String,
+ /// The message the turn is driven by.
+ prompt: String,
+ },
+ /// The host's handler for system job `name`.
+ System {
+ /// The name handed to [`Runtime::on_system_job`](crate::Runtime::on_system_job).
+ name: String,
+ },
+}
+
+impl JobTarget {
+ /// The target of a stored job; `None` for shell jobs and workflow
+ /// schedule triggers, which this facade does not manage.
+ pub(crate) fn from_job(job: &CronJob) -> Option<Self> {
+ match job.job_type {
+ JobType::Agent => Some(Self::Agent {
+ agent_id: job
+ .agent_id
+ .clone()
+ .unwrap_or_else(|| "orchestrator".to_string()),
+ prompt: job.prompt.clone().unwrap_or_default(),
+ }),
+ JobType::Flow => {
+ openhuman_core::cron::system_jobs::system_job_name(job).map(|name| Self::System {
+ name: name.to_string(),
+ })
+ }
+ JobType::Shell => None,
+ }
+ }
+}
+
+/// A job as declared by the host. Upserted by `name`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct JobSpec {
+ /// The job's identity in the store.
+ pub name: String,
+ /// When it fires.
+ pub schedule: JobSchedule,
+ /// What it runs.
+ pub target: JobTarget,
+ /// Retries after a failed attempt; `None` keeps the runtime default.
+ pub retries: Option<u32>,
+ /// Skip, and record as `skipped`, a slot that comes due while the
+ /// previous run is still in flight.
+ pub single_flight: bool,
+ /// Whether the job fires at all.
+ pub enabled: bool,
+}
+
+impl JobSpec {
+ /// A turn of agent `agent_id` driven by `prompt`.
+ pub fn agent(
+ name: impl Into<String>,
+ agent_id: impl Into<String>,
+ prompt: impl Into<String>,
+ schedule: JobSchedule,
+ ) -> Self {
+ Self::new(
+ name,
+ schedule,
+ JobTarget::Agent {
+ agent_id: agent_id.into(),
+ prompt: prompt.into(),
+ },
+ )
+ }
+
+ /// The host's handler for system job `system_name`.
+ pub fn system(
+ name: impl Into<String>,
+ system_name: impl Into<String>,
+ schedule: JobSchedule,
+ ) -> Self {
+ Self::new(
+ name,
+ schedule,
+ JobTarget::System {
+ name: system_name.into(),
+ },
+ )
+ }
+
+ fn new(name: impl Into<String>, schedule: JobSchedule, target: JobTarget) -> Self {
+ Self {
+ name: name.into(),
+ schedule,
+ target,
+ retries: None,
+ single_flight: false,
+ enabled: true,
+ }
+ }
+
+ /// Retries after a failed attempt; `0` is exactly one attempt.
+ #[must_use]
+ pub fn retries(mut self, retries: u32) -> Self {
+ self.retries = Some(retries);
+ self
+ }
+
+ /// Skip slots that come due while a run is still in flight.
+ #[must_use]
+ pub fn single_flight(mut self, single_flight: bool) -> Self {
+ self.single_flight = single_flight;
+ self
+ }
+
+ /// Whether the job fires.
+ #[must_use]
+ pub fn enabled(mut self, enabled: bool) -> Self {
+ self.enabled = enabled;
+ self
+ }
+
+ pub(crate) fn validate(&self) -> Result<(), CronError> {
+ let blank = |value: &str, what: &str| {
+ if value.trim().is_empty() {
+ Err(CronError::Invalid(format!("{what} is blank")))
+ } else {
+ Ok(())
+ }
+ };
+ blank(&self.name, "the job name")?;
+ match &self.target {
+ JobTarget::Agent { agent_id, prompt } => {
+ blank(agent_id, "the agent id")?;
+ blank(prompt, "the prompt")
+ }
+ JobTarget::System { name } => {
+ blank(name, "the system job name")?;
+ if name.contains(':') {
+ return Err(CronError::Invalid(
+ "a system job name may not contain ':'".to_string(),
+ ));
+ }
+ Ok(())
+ }
+ }
+ }
+
+ fn policy(&self) -> JobPolicy {
+ JobPolicy {
+ retries: self.retries,
+ single_flight: self.single_flight,
+ }
+ }
+}
+
+/// A stored job, as [`Cron::list`] and [`Cron::upsert`] report it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ScheduledJob {
+ /// The store's id for the job.
+ pub id: String,
+ /// The job's name.
+ pub name: String,
+ /// When it fires.
+ pub schedule: JobSchedule,
+ /// What it runs.
+ pub target: JobTarget,
+ /// Retries after a failed attempt; `None` is the runtime default.
+ pub retries: Option<u32>,
+ /// Whether overlapping slots are skipped and recorded.
+ pub single_flight: bool,
+ /// Whether the job fires.
+ pub enabled: bool,
+ /// When it next fires.
+ pub next_run: SystemTime,
+ /// When it last ran.
+ pub last_run: Option<SystemTime>,
+ /// `ok` or `error` for the last run.
+ pub last_status: Option<String>,
+}
+
+/// One run's outcome from [`Cron::run_now`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct JobRun {
+ /// Whether the run (after its retries) succeeded.
+ pub success: bool,
+ /// The agent's reply, the handler's error, or a canned failure message.
+ pub output: String,
+}
+
+/// One entry of a job's run history.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct JobRunRecord {
+ /// `ok`, `error`, `skipped` or `queued`.
+ pub status: String,
+ /// What the run produced, truncated.
+ pub output: Option<String>,
+ /// When it started.
+ pub started_at: SystemTime,
+ /// When it finished.
+ pub finished_at: SystemTime,
+}
+
+/// Error from the [`Cron`] facade.
+#[derive(Debug, thiserror::Error)]
+pub enum CronError {
+ /// The runtime's config has `cron.enabled = false`.
+ #[error("cron is disabled by config (cron.enabled=false)")]
+ Disabled,
+ /// No job of that name is stored.
+ #[error("no scheduled job named {0:?}")]
+ NotFound(String),
+ /// The spec could not be honoured.
+ #[error("invalid job: {0}")]
+ Invalid(String),
+ /// The run was refused or could not start (a single-flight job that is
+ /// already running, for one).
+ #[error("{0}")]
+ Run(String),
+ /// The job store failed.
+ #[error("cron store: {0:#}")]
+ Store(#[from] anyhow::Error),
+}
+
+/// Typed access to the runtime's scheduled jobs. Obtain with
+/// [`Runtime::cron`](crate::Runtime::cron).
+pub struct Cron<'a> {
+ config: &'a Config,
+}
+
+impl<'a> Cron<'a> {
+ pub(crate) fn new(config: &'a Config) -> Self {
+ Self { config }
+ }
+
+ fn enabled(&self) -> Result<(), CronError> {
+ if self.config.cron.enabled {
+ Ok(())
+ } else {
+ Err(CronError::Disabled)
+ }
+ }
+
+ /// Create the job `spec.name`, or bring the stored one in line with
+ /// `spec`. Unchanged fields are left alone, so upserting the same spec
+ /// again does not move its next run.
+ pub fn upsert(&self, spec: JobSpec) -> Result<ScheduledJob, CronError> {
+ self.enabled()?;
+ spec.validate()?;
+ let config = self.config;
+ let schedule = spec.schedule.to_core();
+ let existing = self.find(&spec.name)?;
+ log::debug!(
+ "[embed][cron] upsert name={} exists={} target={:?}",
+ spec.name,
+ existing.is_some(),
+ spec.target
+ );
+ let job = match (&spec.target, existing) {
+ (JobTarget::Agent { agent_id, prompt }, Some(job))
+ if matches!(job.job_type, JobType::Agent) =>
+ {
+ let patch = CronJobPatch {
+ schedule: (job.schedule != schedule).then(|| schedule.clone()),
+ prompt: (job.prompt.as_deref() != Some(prompt.as_str()))
+ .then(|| prompt.clone()),
+ agent_id: (job.agent_id.as_deref() != Some(agent_id.as_str()))
+ .then(|| Some(agent_id.clone())),
+ enabled: (job.enabled != spec.enabled).then_some(spec.enabled),
+ ..CronJobPatch::default()
+ };
+ patch_if_needed(config, job, patch)?
+ }
+ (JobTarget::System { name }, Some(job))
+ if job.command == format!("{SYSTEM_COMMAND_PREFIX}{name}") =>
+ {
+ let patch = CronJobPatch {
+ schedule: (job.schedule != schedule).then(|| schedule.clone()),
+ enabled: (job.enabled != spec.enabled).then_some(spec.enabled),
+ ..CronJobPatch::default()
+ };
+ patch_if_needed(config, job, patch)?
+ }
+ (target, existing) => {
+ if let Some(job) = existing {
+ log::debug!("[embed][cron] target kind changed; replacing {}", job.id);
+ openhuman_core::cron::remove_job(config, &job.id)?;
+ }
+ create(config, &spec.name, target, schedule, spec.enabled)?
+ }
+ };
+ policy::set_policy(config, &job.id, spec.policy())?;
+ self.describe(job)?.ok_or_else(|| {
+ CronError::Invalid(format!("job {:?} is not an agent or system job", spec.name))
+ })
+ }
+
+ /// Every agent and system job in the store. Shell jobs and workflow
+ /// schedule triggers are not listed.
+ pub fn list(&self) -> Result<Vec<ScheduledJob>, CronError> {
+ self.enabled()?;
+ let mut jobs = Vec::new();
+ for job in openhuman_core::cron::list_jobs(self.config)? {
+ if let Some(described) = self.describe(job)? {
+ jobs.push(described);
+ }
+ }
+ Ok(jobs)
+ }
+
+ /// Remove job `name`. `false` when there was none.
+ pub fn remove(&self, name: &str) -> Result<bool, CronError> {
+ self.enabled()?;
+ match self.find(name)? {
+ Some(job) => {
+ log::debug!("[embed][cron] remove name={name} id={}", job.id);
+ openhuman_core::cron::remove_job(self.config, &job.id)?;
+ Ok(true)
+ }
+ None => Ok(false),
+ }
+ }
+
+ /// Run job `name` now and wait for it: the same execution, retry budget,
+ /// run record and delivery as a scheduled run.
+ pub async fn run_now(&self, name: &str) -> Result<JobRun, CronError> {
+ self.enabled()?;
+ let job = self
+ .find(name)?
+ .ok_or_else(|| CronError::NotFound(name.to_string()))?;
+ log::debug!("[embed][cron] run_now name={name} id={}", job.id);
+ let (success, output) = openhuman_core::cron::ops::run_job_now(self.config, &job.id)
+ .await
+ .map_err(CronError::Run)?;
+ Ok(JobRun { success, output })
+ }
+
+ /// The newest `limit` runs of job `name`, newest first.
+ pub fn runs(&self, name: &str, limit: usize) -> Result<Vec<JobRunRecord>, CronError> {
+ self.enabled()?;
+ let job = self
+ .find(name)?
+ .ok_or_else(|| CronError::NotFound(name.to_string()))?;
+ Ok(
+ openhuman_core::cron::list_runs(self.config, &job.id, limit.max(1))?
+ .into_iter()
+ .map(|run| JobRunRecord {
+ status: run.status,
+ output: run.output,
+ started_at: SystemTime::from(run.started_at),
+ finished_at: SystemTime::from(run.finished_at),
+ })
+ .collect(),
+ )
+ }
+
+ fn find(&self, name: &str) -> Result<Option<CronJob>, CronError> {
+ Ok(openhuman_core::cron::list_jobs(self.config)?
+ .into_iter()
+ .find(|job| job.name.as_deref() == Some(name) && JobTarget::from_job(job).is_some()))
+ }
+
+ fn describe(&self, job: CronJob) -> Result<Option<ScheduledJob>, CronError> {
+ let Some(target) = JobTarget::from_job(&job) else {
+ return Ok(None);
+ };
+ let policy = policy::get_policy(self.config, &job.id)?;
+ Ok(Some(ScheduledJob {
+ name: job.name.clone().unwrap_or_default(),
+ schedule: JobSchedule::from_core(&job.schedule),
+ target,
+ retries: policy.retries,
+ single_flight: policy.single_flight,
+ enabled: job.enabled,
+ next_run: SystemTime::from(job.next_run),
+ last_run: job.last_run.map(SystemTime::from),
+ last_status: job.last_status,
+ id: job.id,
+ }))
+ }
+}
+
+fn patch_if_needed(
+ config: &Config,
+ job: CronJob,
+ patch: CronJobPatch,
+) -> Result<CronJob, CronError> {
+ let unchanged = patch.schedule.is_none()
+ && patch.prompt.is_none()
+ && patch.agent_id.is_none()
+ && patch.enabled.is_none();
+ if unchanged {
+ return Ok(job);
+ }
+ Ok(openhuman_core::cron::update_job(config, &job.id, patch)?)
+}
+
+fn create(
+ config: &Config,
+ name: &str,
+ target: &JobTarget,
+ schedule: Schedule,
+ enabled: bool,
+) -> Result<CronJob, CronError> {
+ match target {
+ JobTarget::Agent { agent_id, prompt } => {
+ Ok(openhuman_core::cron::add_agent_job_with_definition(
+ config,
+ Some(name.to_string()),
+ schedule,
+ prompt,
+ openhuman_core::cron::SessionTarget::Isolated,
+ None,
+ None,
+ false,
+ Some(agent_id.clone()),
+ enabled,
+ )?)
+ }
+ JobTarget::System { name: system } => {
+ // One row per system job: the store keys it by its command.
+ let command = format!("{SYSTEM_COMMAND_PREFIX}{system}");
+ let job =
+ openhuman_core::cron::add_flow_schedule_job(config, &command, schedule.clone())?;
+ Ok(openhuman_core::cron::update_job(
+ config,
+ &job.id,
+ CronJobPatch {
+ name: Some(name.to_string()),
+ enabled: Some(enabled),
+ schedule: (job.schedule != schedule).then_some(schedule),
+ ..CronJobPatch::default()
+ },
+ )?)
+ }
+ }
+}
+
+/// Box a host's system-job handler into the core's handler type.
+pub(crate) fn boxed_handler<F, Fut>(
+ handler: F,
+) -> openhuman_core::cron::system_job_handlers::SystemJobHandler
+where
+ F: Fn(SystemJobContext) -> Fut + Send + Sync + 'static,
+ Fut: Future<Output = Result<(), String>> + Send + 'static,
+{
+ std::sync::Arc::new(move |ctx| Box::pin(handler(ctx)))
+}
+
+#[cfg(test)]
+#[path = "cron_tests.rs"]
+mod tests;
diff --cc crates/openhuman-embed/src/cron_tests.rs
index 6c9f98ad38,0000000000..d662ea6c7e
mode 100644,000000..100644
--- a/crates/openhuman-embed/src/cron_tests.rs
+++ b/crates/openhuman-embed/src/cron_tests.rs
@@@ -1,133 -1,0 +1,134 @@@
+use super::*;
+use std::time::{Duration, SystemTime};
+
+fn core_job(job_type: JobType, command: &str) -> CronJob {
+ let now = chrono::Utc::now();
+ CronJob {
+ id: "job-1".into(),
+ expression: String::new(),
+ schedule: Schedule::Every { every_ms: 60_000 },
+ command: command.into(),
+ prompt: Some("check in".into()),
+ name: Some("named".into()),
+ job_type,
+ session_target: openhuman_core::cron::SessionTarget::Isolated,
+ model: None,
+ agent_id: Some("teeny".into()),
+ enabled: true,
+ delivery: Default::default(),
+ delete_after_run: false,
+ created_at: now,
+ next_run: now,
+ last_run: None,
+ last_status: Some("ok".into()),
+ last_output: None,
++ origin: None,
+ }
+}
+
+#[test]
+fn schedules_convert_both_ways() {
+ let at = SystemTime::UNIX_EPOCH + Duration::from_secs(4_102_444_800);
+ for schedule in [
+ JobSchedule::Cron {
+ expr: "0 9 * * *".into(),
+ tz: Some("Europe/Berlin".into()),
+ },
+ JobSchedule::Every { ms: 600_000 },
+ JobSchedule::At { at },
+ ] {
+ assert_eq!(JobSchedule::from_core(&schedule.to_core()), schedule);
+ }
+}
+
+#[test]
+fn a_cron_schedule_drops_active_hours_it_cannot_express() {
+ let core = Schedule::Cron {
+ expr: "0 * * * *".into(),
+ tz: None,
+ active_hours: Some(openhuman_core::cron::ActiveHours {
+ start: "09:00".into(),
+ end: "17:00".into(),
+ }),
+ };
+ assert_eq!(
+ JobSchedule::from_core(&core),
+ JobSchedule::Cron {
+ expr: "0 * * * *".into(),
+ tz: None
+ }
+ );
+}
+
+#[test]
+fn targets_are_read_back_from_agent_and_system_rows_only() {
+ assert_eq!(
+ JobTarget::from_job(&core_job(JobType::Agent, "")),
+ Some(JobTarget::Agent {
+ agent_id: "teeny".into(),
+ prompt: "check in".into()
+ })
+ );
+ assert_eq!(
+ JobTarget::from_job(&core_job(JobType::Flow, "system:digest")),
+ Some(JobTarget::System {
+ name: "digest".into()
+ })
+ );
+ assert_eq!(
+ JobTarget::from_job(&core_job(JobType::Flow, "flow-123")),
+ None
+ );
+ assert_eq!(JobTarget::from_job(&core_job(JobType::Shell, "echo")), None);
+}
+
+#[test]
+fn specs_carry_their_defaults_and_overrides() {
+ let spec = JobSpec::agent(
+ "hourly",
+ "teeny",
+ "check in",
+ JobSchedule::Every { ms: 3_600_000 },
+ );
+ assert!(spec.enabled);
+ assert!(!spec.single_flight);
+ assert_eq!(spec.retries, None);
+ let spec = spec.retries(0).single_flight(true).enabled(false);
+ assert_eq!(spec.retries, Some(0));
+ assert!(spec.single_flight);
+ assert!(!spec.enabled);
+ let system = JobSpec::system("digest", "digest", JobSchedule::Every { ms: 60_000 });
+ assert_eq!(
+ system.target,
+ JobTarget::System {
+ name: "digest".into()
+ }
+ );
+}
+
+#[test]
+fn blank_names_and_targets_are_refused() {
+ let every = JobSchedule::Every { ms: 3_600_000 };
+ for spec in [
+ JobSpec::agent(" ", "teeny", "p", every.clone()),
+ JobSpec::agent("n", "", "p", every.clone()),
+ JobSpec::agent("n", "teeny", " ", every.clone()),
+ JobSpec::system("n", "", every.clone()),
+ JobSpec::system("n", "has:colon", every.clone()),
+ ] {
+ assert!(
+ matches!(spec.validate(), Err(CronError::Invalid(_))),
+ "{spec:?}"
+ );
+ }
+ assert!(JobSpec::agent("n", "teeny", "p", every).validate().is_ok());
+}
+
+#[test]
+fn errors_render_without_leaking_more_than_the_job_name() {
+ assert_eq!(
+ CronError::NotFound("nightly".into()).to_string(),
+ "no scheduled job named \"nightly\""
+ );
+ assert!(CronError::Disabled.to_string().contains("cron.enabled"));
+}
diff --cc gitbooks/developing/embedding.md
index 3c0b40ad84,da1dea4316..f789fe7bc9
--- a/gitbooks/developing/embedding.md
+++ b/gitbooks/developing/embedding.md
@@@ -272,61 -272,6 +272,61 @@@ that session held, and it is meant to b
is not sharing with turns that expect their history intact. `.meter(f)`
reports what a turn spent, including a turn that ran and then failed.
+## Scheduling
+
+OpenHuman's own cron can drive scheduled turns of a runtime's agents, with
+their host tools, and run host code on a schedule. `runtime.cron()` is a typed
+facade over the runtime's job store; jobs are named and `upsert` is idempotent
+by that name, so a host can declare its schedule on every start:
+
+```rust,no_run
+# async fn demo(runtime: &openhuman_embed::Runtime) -> Result<(), Box<dyn std::error::Error>> {
+use openhuman_embed::{JobSchedule, JobSpec};
+
+let cron = runtime.cron();
+// One turn of the runtime agent `teeny` every morning.
+cron.upsert(
+ JobSpec::agent("morning", "teeny", "Plan the day.", JobSchedule::Cron {
+ expr: "0 8 * * *".into(),
+ tz: Some("Europe/Berlin".into()),
+ })
+ .retries(0) // exactly one attempt: the turn has side effects
+ .single_flight(true) // skip (and record) a slot that comes due mid-run
+)?;
+// Host code on a schedule; its result is the run's recorded result.
+runtime.on_system_job("digest", |_ctx| async { Ok(()) })?;
+cron.upsert(JobSpec::system("digest", "digest", JobSchedule::Every { ms: 15 * 60_000 }))?;
+
+let run = cron.run_now("morning").await?; // same path as a scheduled run
+println!("{} {}", run.success, run.output);
+# Ok(()) }
+```
+
+- **Jobs fire only while the scheduler runs.** Build the runtime with
+ `.services(ServiceSet { cron: true, ..ServiceSet::none() })`; `build()` then
+ starts the selected services and dropping the runtime (and its agents) stops
+ them. `Runtime::start_services` / `stop_services` give explicit control.
+ Without the scheduler, jobs are stored and `run_now` still works.
+- **An agent job runs as the agent.** When `agent_id` names an agent alive on
+ the runtime, the turn uses its definition and system prompt, its
+ `AgentSpec::tools` and attached tools, its provider and its own context
+ (`agent::host_agents` resolves it for the core's cron and workflow drivers).
+ Any other id resolves through the core's agent registries. The turn's origin
+ is `TrustedAutomation { Cron }`, not the agent's own access origin. Agent jobs
+ may not run more often than every five minutes.
+- **A system job runs the host's handler.** `on_system_job(name, handler)`
+ registers an async `Fn(SystemJobContext) -> Result<(), String>`; when the job
+ comes due the scheduler still publishes `CronSystemJobDue` on the bus, then
+ awaits the handler and records `ok` or `error` with its message.
+- **Retries and overlap.** A failed run is retried `retries` times with
+ backoff; unset keeps `reliability.scheduler_retries` (2), and `0` is one
- attempt. A job is never run twice at once: each due job is dispatched on its
- own task, so a long job no longer holds up the others, and a slot that comes
- due while the job is still running is skipped. With `single_flight` that
- skip is recorded as a `skipped` run and `run_now` is refused meanwhile.
++ attempt. Two runs of one job never overlap: each due job is dispatched on
++ its own task, so a long job no longer holds up the others, `run_now` is
++ refused while a run is active, and a slot that comes due mid-run is skipped.
++ With `single_flight` that skip is recorded as a `skipped` run.
+- `cron.list()`, `cron.remove(name)` and `cron.runs(name, limit)` cover the
+ rest. Shell jobs and workflow schedule triggers are not managed here.
+
## Harness: the one-agent shorthand
`Harness` is a `Runtime` plus exactly one agent, built from one set of