1use axum::extract::{Path, Query, State};
24use axum::http::StatusCode;
25use axum::response::Json;
26use chrono::Utc;
27use serde::{Deserialize, Serialize};
28use serde_json::{json, Map, Value};
29use uuid::Uuid;
30
31use crate::backend::cron::schedule::JobSchedule;
32use crate::backend::cron::FireOutcome;
33use crate::backend::jobs;
34use crate::backend::jobs::definition::{Action, Check, JobDefinition, LATER};
35use super::job_caps::{self, Origin};
36use crate::backend::storage::cron::CronJob;
37use crate::backend::storage::job_runs::{JobRun, OUTCOMES};
38use crate::backend::storage::store::Store;
39use std::sync::Arc;
40use super::caller::Caller;
41use super::AppState;
42
43#[derive(Debug, Deserialize)]
44pub struct CronCreateRequest {
45 pub name: String,
46 pub expression: String,
48 pub prompt: String,
49 pub target: String,
51 #[serde(default)]
55 pub target_uid: String,
56 #[serde(default)]
57 pub created_by: String,
58 pub max_fires: Option<i64>,
59 #[serde(default)]
64 pub max_age_secs: Option<i64>,
65 #[serde(default)]
68 pub catch_up: Option<String>,
69 #[serde(default)]
71 pub tz: Option<String>,
72 #[serde(default)]
74 pub policy: Option<Value>,
75 #[serde(default)]
77 pub template: Option<Value>,
78 #[serde(default)]
79 pub params: Option<Value>,
80}
81
82#[derive(Debug, Serialize)]
83pub struct CronJobView {
84 pub id: String,
85 pub name: String,
86 pub expression: String,
87 pub tz: String,
89 pub trigger_kind: String,
90 pub action_kind: String,
91 pub prompt: String,
92 pub target: String,
93 pub enabled: bool,
94 pub last_fired: Option<i64>,
95 pub fire_count: i64,
96 pub max_fires: Option<i64>,
97 pub created_at: i64,
98 pub max_age_secs: Option<i64>,
99 pub expires_in_secs: Option<i64>,
106 pub next_fire: Option<String>,
109 pub catch_up: String,
110 pub last_run: Option<JobRun>,
112 pub missed_count: i64,
115 pub last_missed_at: Option<i64>,
116 pub last_miss_reason: String,
117 #[serde(skip_serializing_if = "Option::is_none")]
120 pub over_cap: Option<String>,
121 pub definition: JobDefinition,
123}
124
125fn to_view(job: &CronJob) -> CronJobView {
126 let expires_in_secs = job.max_age_secs.map(|max_age| {
127 let elapsed = Utc::now().timestamp() - job.created_at;
128 (max_age - elapsed).max(0)
129 });
130 let definition = JobDefinition::from_job(job);
131 CronJobView {
132 id: job.id.clone(),
133 name: job.name.clone(),
134 expression: job.expression.clone(),
135 tz: if job.tz.is_empty() { "UTC".to_string() } else { job.tz.clone() },
136 trigger_kind: definition.trigger.kind().to_string(),
137 action_kind: definition.action.kind().to_string(),
138 prompt: job.prompt.clone(),
139 target: job.target.clone(),
140 enabled: job.enabled,
141 last_fired: job.last_fired,
142 fire_count: job.fire_count,
143 max_fires: job.max_fires,
144 created_at: job.created_at,
145 expires_in_secs,
146 max_age_secs: job.max_age_secs,
147 next_fire: next_fire(job),
148 catch_up: job.catch_up.clone(),
149 last_run: None,
150 missed_count: job.missed_count,
151 last_missed_at: job.last_missed_at,
152 last_miss_reason: job.last_miss_reason.clone(),
153 over_cap: None,
154 definition,
155 }
156}
157
158fn next_fire(job: &CronJob) -> Option<String> {
162 if !job.enabled {
163 return None;
164 }
165 let next = JobSchedule::of(job).ok()?.next_after(agentmux_common::time::now_ms())?;
166 Some(chrono::DateTime::from_timestamp_millis(next)?.to_rfc3339())
167}
168
169#[derive(Debug, Serialize)]
174pub struct CronSummary {
175 pub id: String,
176 pub block_id: String,
177 pub name: String,
178 pub expression: String,
179 pub target: String,
180 pub created_by: String,
181 pub enabled: bool,
182 pub last_fired: Option<i64>,
183 pub fire_count: i64,
184 pub max_fires: Option<i64>,
185 pub next_fire: Option<String>,
187 pub missed_count: i64,
189 pub last_miss_reason: String,
190}
191
192pub(crate) fn to_summary(job: &CronJob, block_id: String) -> CronSummary {
193 CronSummary {
194 id: job.id.clone(),
195 block_id,
196 name: job.name.clone(),
197 expression: job.expression.clone(),
198 target: job.target.clone(),
199 created_by: job.created_by.clone(),
200 enabled: job.enabled,
201 last_fired: job.last_fired,
202 fire_count: job.fire_count,
203 max_fires: job.max_fires,
204 next_fire: next_fire(job),
205 missed_count: job.missed_count,
206 last_miss_reason: job.last_miss_reason.clone(),
207 }
208}
209
210pub(crate) fn jobs_store(state: &AppState) -> Option<Arc<Store>> {
215 state.cron_store.clone()
216}
217
218pub(crate) fn ledger_store(state: &AppState) -> Arc<Store> {
226 state.work_store.clone()
227}
228
229#[cfg(test)]
232pub(crate) fn use_test_store_for_jobs(state: &mut AppState) {
233 state.cron_store = Some(state.mstore.clone());
234}
235
236pub(crate) fn work_store(state: &AppState) -> Arc<Store> {
239 state.work_store.clone()
240}
241
242fn jobs_store_or_503(state: &AppState) -> Result<Arc<Store>, Answer> {
244 jobs_store(state).ok_or_else(|| (StatusCode::SERVICE_UNAVAILABLE, Json(json!({"error": "shared store unavailable"}))))
245}
246
247fn publish_cron_changed(state: &AppState) {
248 state.broker.publish_event::<crate::backend::mps_events::CronChanged>(&(), vec![], 0);
249}
250
251#[derive(Debug, Clone, PartialEq, Eq)]
254pub(crate) enum Who {
255 Operator,
256 Agent { uid: String, slug: String, container: bool },
257}
258
259fn writer_of(from_host: bool, caller: Option<&Caller>) -> String {
263 if from_host {
264 return crate::backend::storage::cron::WRITER_OPERATOR.to_string();
265 }
266 match caller.and_then(Caller::uid) {
267 Some(uid) => uid.to_string(),
268 None => crate::backend::storage::cron::WRITER_UNKNOWN.to_string(),
269 }
270}
271
272fn who(state: &AppState, caller: Option<&Caller>) -> Who {
273 match caller.and_then(Caller::uid) {
274 None => Who::Operator,
275 Some(uid) => {
276 let def = state.mstore.agent_def_get(uid).ok().flatten();
277 Who::Agent {
278 uid: uid.to_string(),
279 slug: def.as_ref().map(|d| d.slug.clone()).unwrap_or_default(),
280 container: def.is_some_and(|d| d.runtime().is_container()),
281 }
282 }
283 }
284}
285
286const CONTAINER_HOST_JOB: &str = "a container agent can't schedule a job that starts workers or runs a Drone, because its runs start things on the host: schedule a message or task job instead, or ask your leader to create this one";
290
291fn forbidden(why: impl Into<String>) -> Answer {
292 (StatusCode::FORBIDDEN, Json(json!({"error": why.into()})))
293}
294
295fn bad_request(why: impl Into<String>) -> Answer {
296 (StatusCode::BAD_REQUEST, Json(json!({"error": why.into()})))
297}
298
299fn starts_on_the_host(action_kind: &str) -> bool {
302 matches!(action_kind, "spawn" | "drone")
303}
304
305pub(crate) fn may_define(who: &Who, def: &JobDefinition, current_owner: Option<&str>) -> Result<(), String> {
313 let Who::Agent { uid, container, .. } = who else { return Ok(()) };
314 if *container && matches!(def.action, Action::Spawn { .. } | Action::Drone { .. }) {
315 return Err(CONTAINER_HOST_JOB.to_string());
316 }
317 if let Action::Spawn { leader, .. } = &def.action {
318 if leader != uid {
319 return Err("an agent can create a spawn job only with itself as the leader".to_string());
320 }
321 return Err(
322 "a spawn job an agent creates needs the operator's approval once, which isn't available yet: ask the operator to create it"
323 .to_string(),
324 );
325 }
326 let owner = def.owner.trim();
327 let allowed = owner.is_empty() || owner == uid || current_owner == Some(owner);
328 if !allowed {
329 return Err("an agent's job is owned by that agent: leave owner out, or name yourself".to_string());
330 }
331 Ok(())
332}
333
334pub(crate) fn runnable_yet(def: &JobDefinition) -> Result<(), String> {
338 match def.policy.max_turns {
339 Some(_) => Err(format!("policy.max_turns is {LATER}")),
340 None => Ok(()),
341 }
342}
343
344const SPAWN_FROM_THE_APP: &str =
347 "a spawn job starts workers that spend until stopped: only the operator's own host creates and runs it, not this route";
348
349fn target_of(state: &AppState, to: &str) -> (String, String) {
353 match state.mstore.agent_def_get(to) {
354 Ok(Some(def)) if !to.is_empty() => (def.slug, to.to_string()),
355 _ => {
356 if !to.is_empty() {
357 crate::backend::agent_resolve::record_uid_fallback("jobs_create.uid_not_carried");
358 }
359 (to.to_string(), String::new())
360 }
361 }
362}
363
364fn legacy_definition(req: &CronCreateRequest, check: Check) -> Result<JobDefinition, String> {
367 let mut policy = match &req.policy {
368 None | Some(Value::Null) => Map::new(),
369 Some(Value::Object(p)) => p.clone(),
370 Some(_) => return Err("policy is an object".to_string()),
371 };
372 if let Some(catch_up) = &req.catch_up {
373 if catch_up != jobs::CATCH_UP_SKIP && catch_up != jobs::CATCH_UP_LATEST {
374 return Err(format!("invalid catch_up '{catch_up}' (use 'skip' or 'latest')"));
375 }
376 policy.insert("catch_up".into(), json!(catch_up));
377 }
378 let to = if req.target_uid.trim().is_empty() { req.target.trim() } else { req.target_uid.trim() };
379 let mut def = json!({
380 "jobVersion": jobs::definition::JOB_VERSION,
381 "name": req.name,
382 "trigger": { "kind": "cron", "cron": req.expression, "tz": req.tz.as_deref().unwrap_or("UTC") },
383 "action": { "kind": "message", "to": to, "brief": req.prompt },
384 "policy": policy,
385 });
386 for (key, value) in [("template", &req.template), ("params", &req.params)] {
387 if let Some(v) = value.as_ref().filter(|v| !v.is_null()) {
388 def[key] = v.clone();
389 }
390 }
391 jobs::from_template::apply(&mut def, None)?;
392 JobDefinition::parse(&def, check)
393}
394
395pub(super) async fn handle_cron_create(
396 State(state): State<AppState>,
397 caller: Option<axum::Extension<super::caller::Caller>>,
398 Json(body): Json<Value>,
399) -> (StatusCode, Json<Value>) {
400 create_job(&state, caller.as_deref(), body, Origin::default())
401}
402
403pub(crate) fn create_job(state: &AppState, caller: Option<&Caller>, body: Value, origin: Origin) -> (StatusCode, Json<Value>) {
410 let from_host = origin.from_host;
411 let check = Check { fresh: true, now_ms: agentmux_common::time::now_ms() };
412 let who = if from_host { Who::Operator } else { who(state, caller) };
413 let legacy = match body.get("jobVersion") {
416 Some(_) => None,
417 None => match serde_json::from_value::<CronCreateRequest>(body.clone()) {
418 Ok(req) => Some(req),
419 Err(e) => return bad_request(format!("invalid job: {e}")),
420 },
421 };
422 let parsed = match &legacy {
423 Some(req) => {
424 super::actor::check_actor(state, caller, super::actor::ActorSite::CronCreate, Some(&req.created_by));
425 legacy_definition(req, check)
426 }
427 None => {
428 let mut body = body.clone();
429 jobs::from_template::apply(&mut body, None).and_then(|()| JobDefinition::parse(&body, check))
430 }
431 };
432 let mut def = match parsed {
433 Ok(def) => def,
434 Err(e) => return bad_request(e),
435 };
436 if let Err(e) = may_define(&who, &def, None) {
437 return forbidden(e);
438 }
439 if matches!(def.action, Action::Spawn { .. }) && !from_host {
440 return forbidden(SPAWN_FROM_THE_APP);
441 }
442 if let Err(e) = runnable_yet(&def) {
443 return bad_request(e);
444 }
445 if let Err(stop) = super::drone_turn_on::allowed(state, &def, origin, true) {
446 return stop.answer();
447 }
448 let notes = match job_caps::apply_rules(state, &mut def, None, origin) {
449 Ok(notes) => notes,
450 Err(refused) => return refused,
451 };
452
453 let (created_by, owner) = match &who {
454 Who::Operator => (jobs::BY_OPERATOR.to_string(), def.owner.trim().to_string()),
455 Who::Agent { uid, slug, .. } => (if slug.is_empty() { uid.clone() } else { slug.clone() }, uid.clone()),
456 };
457 let mut job = CronJob {
458 id: Uuid::new_v4().to_string(),
459 created_by,
460 created_by_uid: super::caller::attributed_uid(caller),
463 last_written_by: writer_of(from_host, caller),
464 created_at: Utc::now().timestamp(),
465 ..Default::default()
466 };
467 match &legacy {
468 Some(req) => {
469 let target_uid = req.target_uid.trim().to_string();
474 if target_uid.is_empty() && !req.target.trim().is_empty() {
475 crate::backend::agent_resolve::record_uid_fallback("cron_create.uid_not_carried");
476 }
477 def.apply_to(&mut job, &|_| (req.target.clone(), target_uid.clone()));
478 job.created_by = req.created_by.clone();
479 (job.max_fires, job.max_age_secs) = (req.max_fires, req.max_age_secs);
480 }
481 None => def.apply_to(&mut job, &|to| target_of(state, to)),
482 }
483 job.owner = owner;
485
486 let store = match jobs_store_or_503(state) {
487 Ok(store) => store,
488 Err(e) => return e,
489 };
490 if let Err(e) = store.cron_create(&job) {
491 return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})));
492 }
493
494 if job.enabled {
496 state.cron_scheduler.schedule_job(&job);
497 }
498 publish_cron_changed(state);
499
500 (StatusCode::CREATED, Json(json!({"job": to_view(&job), "notes": notes})))
501}
502
503pub(super) async fn handle_cron_list(
504 State(state): State<AppState>,
505) -> (StatusCode, Json<Value>) {
506 let store = match jobs_store_or_503(&state) {
507 Ok(store) => store,
508 Err(e) => return e,
509 };
510 match store.cron_list() {
511 Ok(jobs) => {
512 let ledger = state.cron_scheduler.runs().cloned();
513 let (views, paused_all) = tokio::task::spawn_blocking(move || {
514 let views = jobs
515 .iter()
516 .map(|job| {
517 let mut view = to_view(job);
518 view.last_run = ledger.as_ref().and_then(|l| l.store().job_run_last(&job.id).ok().flatten());
519 view.over_cap = ledger.as_ref().and_then(|l| l.over_cap_today(job)).map(str::to_string);
520 view
521 })
522 .collect::<Vec<_>>();
523 (views, ledger.as_ref().and_then(|l| l.paused_all()))
525 })
526 .await
527 .unwrap_or_default();
528 (StatusCode::OK, Json(json!({"jobs": views, "paused_all": paused_all})))
529 }
530 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
531 }
532}
533
534fn may_act_on(state: &AppState, caller: Option<&Caller>, job: &CronJob) -> bool {
539 let Some(uid) = caller.and_then(Caller::uid) else {
540 return true;
541 };
542 if job.owner_uid() == uid {
543 return true;
544 }
545 if !job.created_by_uid.is_empty() {
546 return job.created_by_uid == uid;
547 }
548 match state.mstore.agent_def_get(uid) {
549 Ok(Some(def)) => {
551 !job.created_by.is_empty()
552 && !job.created_by.eq_ignore_ascii_case(jobs::BY_OPERATOR)
553 && def.slug.eq_ignore_ascii_case(&job.created_by)
554 }
555 _ => false,
556 }
557}
558
559#[derive(Debug, Deserialize)]
560pub struct CronRunsQuery {
561 #[serde(default)]
562 pub limit: Option<i64>,
563 #[serde(default)]
565 pub before: Option<i64>,
566}
567
568const RUNS_MAX: i64 = 200;
570
571type Answer = (StatusCode, Json<Value>);
572
573fn ledger_or_503(state: &AppState) -> Result<std::sync::Arc<jobs::RunLedger>, Answer> {
574 state
575 .cron_scheduler
576 .runs()
577 .cloned()
578 .ok_or_else(|| (StatusCode::SERVICE_UNAVAILABLE, Json(json!({"error": "run ledger unavailable"}))))
579}
580
581pub(super) async fn inject_here_following_runs(
585 state: &AppState,
586 req: &crate::backend::reactive::types::InjectionRequest,
587) -> crate::backend::reactive::types::InjectionResponse {
588 let delivery_started = agentmux_common::time::now_ms();
589 let resp = super::jekt_files::inject_here(state, req);
590 let run_id = req.request_id.clone().unwrap_or_default();
591 let block_id = resp.block_id.clone().unwrap_or_default();
592 if resp.success && req.forward_hops > 0 && !run_id.is_empty() && !block_id.is_empty() {
593 if let Some(ledger) = state.cron_scheduler.runs().cloned() {
594 let _ = tokio::task::spawn_blocking(move || ledger.follow_forwarded(&run_id, &block_id, delivery_started)).await;
595 }
596 }
597 resp
598}
599
600pub(super) async fn handle_cron_runs(
601 State(state): State<AppState>,
602 Path(id): Path<String>,
603 Query(q): Query<CronRunsQuery>,
604) -> Answer {
605 let ledger = match ledger_or_503(&state) {
606 Ok(l) => l,
607 Err(e) => return e,
608 };
609 let limit = q.limit.unwrap_or(20).clamp(1, RUNS_MAX);
610 match tokio::task::spawn_blocking(move || ledger.store().job_runs_for_job(&id, limit, q.before)).await {
611 Ok(Ok(runs)) => (StatusCode::OK, Json(json!({"runs": runs}))),
612 Ok(Err(e)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
613 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
614 }
615}
616
617pub(super) async fn handle_cron_run_now(
618 State(state): State<AppState>,
619 caller: Option<axum::Extension<Caller>>,
620 Path(id): Path<String>,
621) -> Answer {
622 let store = match jobs_store_or_503(&state) {
623 Ok(store) => store,
624 Err(e) => return e,
625 };
626 let job = match store.cron_get(&id) {
627 Ok(Some(job)) => job,
628 Ok(None) => return (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
629 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
630 };
631 if !may_act_on(&state, caller.as_deref(), &job) {
632 return (
633 StatusCode::FORBIDDEN,
634 Json(json!({"error": "only the agent that created this job, or the operator, can run it now"})),
635 );
636 }
637 if starts_on_the_host(&job.action_kind) && matches!(who(&state, caller.as_deref()), Who::Agent { container: true, .. }) {
638 return forbidden(CONTAINER_HOST_JOB);
639 }
640 if job.action_kind == "spawn" {
641 return forbidden(SPAWN_FROM_THE_APP);
642 }
643 let triggered_by =
644 caller.as_deref().and_then(Caller::uid).map(str::to_string).unwrap_or_else(|| jobs::BY_OPERATOR.to_string());
645 run_job_now(&state, &job, &triggered_by).await
646}
647
648async fn run_job_now(state: &AppState, job: &CronJob, triggered_by: &str) -> Answer {
650 let fired = state.cron_scheduler.run_now(job, triggered_by).await;
651 if let Some(why) = fired.waiting {
652 let body = json!({"run_id": fired.run_id, "outcome": "queued", "error": null, "waiting_for": why});
653 return (StatusCode::OK, Json(body));
654 }
655 let (outcome, error) = match &fired.outcome {
656 Some(FireOutcome::Delivered { .. }) => ("delivered", None),
657 Some(FireOutcome::Missed { .. }) => ("missed", Some(format!("agent {} is not running", job.target))),
658 Some(FireOutcome::Failed { error }) => ("failed", Some(error.clone())),
659 None => ("failed", Some("no way to deliver".to_string())),
660 };
661 (StatusCode::OK, Json(json!({"run_id": fired.run_id, "outcome": outcome, "error": error})))
662}
663
664pub(crate) async fn handle_host_jobs(
671 State(state): State<AppState>,
672 headers: axum::http::HeaderMap,
673 Json(body): Json<Value>,
674) -> axum::response::Response {
675 use axum::response::IntoResponse;
676 if !super::ui_handlers::from_host(&state, &headers).await {
677 return forbidden("only the AgentMux host can create, change or run a job that starts workers, or raise a spending cap").into_response();
678 }
679 let origin = Origin {
680 from_host: true,
681 confirm_no_cost: body.get("confirm_no_cost").and_then(Value::as_bool) == Some(true),
682 confirm_turn_on: body.get("confirm_turn_on").and_then(Value::as_bool) == Some(true),
683 };
684 match body.get("action").and_then(Value::as_str).unwrap_or("") {
685 "create" => create_job(&state, None, body.get("definition").cloned().unwrap_or(Value::Null), origin).into_response(),
686 "update" => {
687 let id = body.get("id").and_then(Value::as_str).unwrap_or("");
688 patch_job(&state, None, id, body.get("fields").cloned().unwrap_or(Value::Null), origin).into_response()
689 }
690 "run_now" => {
691 let id = body.get("id").and_then(Value::as_str).unwrap_or("");
692 let store = match jobs_store_or_503(&state) {
693 Ok(store) => store,
694 Err(e) => return e.into_response(),
695 };
696 match store.cron_get(id) {
697 Ok(Some(job)) => run_job_now(&state, &job, jobs::BY_OPERATOR).await.into_response(),
698 Ok(None) => (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))).into_response(),
699 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
700 }
701 }
702 other => bad_request(format!("unknown action {other:?} (use create, update or run_now)")).into_response(),
703 }
704}
705
706#[derive(Debug, Deserialize)]
707pub struct CronReportRequest {
708 pub outcome: String,
710 #[serde(default)]
711 pub summary: String,
712 #[serde(default)]
714 pub links: Option<Value>,
715}
716
717const REPORT_LINKS_MAX: usize = 5;
719const REPORT_URL_MAX: usize = 2048;
720const REPORT_LABEL_MAX: usize = 120;
721
722fn report_links(given: Option<Value>) -> Value {
726 let https = |u: &str| u.len() <= REPORT_URL_MAX && u.starts_with("https://") && u.len() > "https://".len();
727 let items = match given {
728 None | Some(Value::Null) => return Value::Null,
729 Some(Value::Array(items)) => items,
730 Some(other) => vec![other],
731 };
732 let kept: Vec<Value> = items
733 .into_iter()
734 .filter_map(|item| match item {
735 Value::String(u) if https(&u) => Some(Value::String(u)),
736 Value::Object(o) => {
737 let url = o.get("url").and_then(Value::as_str).filter(|u| https(u))?;
738 let label = o.get("label").and_then(Value::as_str).unwrap_or("");
739 (label.chars().count() <= REPORT_LABEL_MAX).then(|| json!({ "label": label, "url": url }))
740 }
741 _ => None,
742 })
743 .take(REPORT_LINKS_MAX)
744 .collect();
745 Value::Array(kept)
746}
747
748pub(super) async fn handle_cron_report(
749 State(state): State<AppState>,
750 caller: Option<axum::Extension<Caller>>,
751 Path(run_id): Path<String>,
752 Json(req): Json<CronReportRequest>,
753) -> Answer {
754 if req.outcome == "unknown" || !OUTCOMES.contains(&req.outcome.as_str()) {
755 return (
756 StatusCode::BAD_REQUEST,
757 Json(json!({"error": format!("invalid outcome '{}' (use ok, findings or failed)", req.outcome)})),
758 );
759 }
760 let links = report_links(req.links);
761 let ledger = match ledger_or_503(&state) {
762 Ok(l) => l,
763 Err(e) => return e,
764 };
765 let run = match ledger.store().job_run_get(&run_id) {
766 Ok(Some(run)) => run,
767 Ok(None) => return (StatusCode::NOT_FOUND, Json(json!({"error": "run not found"}))),
768 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
769 };
770 let allowed = match caller.as_deref().and_then(Caller::uid) {
774 None => true,
775 Some(uid) => {
776 let ran_it = if run.target_agent_uid.is_empty() {
777 !run.block_id.is_empty() && state.reactive_handler.block_for_uid(uid).as_deref() == Some(run.block_id.as_str())
778 } else {
779 run.target_agent_uid == uid
780 };
781 ran_it
782 || jobs_store(&state)
783 .and_then(|s| s.cron_get(&run.job_id).ok().flatten())
784 .is_some_and(|job| may_act_on(&state, caller.as_deref(), &job))
785 }
786 };
787 if !allowed {
788 return (StatusCode::FORBIDDEN, Json(json!({"error": "only the agent that ran this run can report it"})));
789 }
790 match ledger.store().job_run_report(&run_id, &req.outcome, &req.summary, &links) {
791 Ok(true) => {
792 ledger.changed(&run.job_id);
793 (StatusCode::OK, Json(json!({"ok": true, "run_id": run_id, "outcome": req.outcome})))
794 }
795 Ok(false) => (
796 StatusCode::CONFLICT,
797 Json(json!({"error": format!("run {run_id} never ran ({}): there is nothing to report", run.state)})),
798 ),
799 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
800 }
801}
802
803fn may_change_job(caller: Option<&super::caller::Caller>, job: &CronJob) -> bool {
812 let Some(uid) = caller.and_then(super::caller::Caller::uid) else {
813 return true;
814 };
815 job.created_by_uid.is_empty() || may_edit_job(caller, job) || job.target_uid == uid
816}
817
818fn may_edit_job(caller: Option<&super::caller::Caller>, job: &CronJob) -> bool {
823 let Some(uid) = caller.and_then(super::caller::Caller::uid) else {
824 return true;
825 };
826 !uid.is_empty() && (job.created_by_uid == uid || job.owner_uid() == uid)
827}
828
829fn job_for_change(
832 state: &AppState,
833 caller: Option<&super::caller::Caller>,
834 id: &str,
835) -> Result<(Arc<Store>, CronJob), Answer> {
836 let store = jobs_store_or_503(state)?;
837 match store.cron_get(id) {
838 Ok(Some(job)) if may_change_job(caller, &job) => Ok((store, job)),
839 Ok(Some(_)) => Err(forbidden("an agent can change only a scheduled job it created or one aimed at it")),
840 Ok(None) => Err((StatusCode::NOT_FOUND, Json(json!({"error": "job not found"})))),
841 Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))),
842 }
843}
844
845pub(super) async fn handle_cron_delete(
846 State(state): State<AppState>,
847 caller: Option<axum::Extension<super::caller::Caller>>,
848 Path(id): Path<String>,
849) -> (StatusCode, Json<Value>) {
850 let store = match job_for_change(&state, caller.as_deref(), &id) {
851 Ok((store, _)) => store,
852 Err(refused) => return refused,
853 };
854
855 state.cron_scheduler.cancel_job(&id);
857
858 match store.cron_delete(&id) {
859 Ok(true) => {
860 publish_cron_changed(&state);
861 (StatusCode::OK, Json(json!({"ok": true})))
862 }
863 Ok(false) => (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
864 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
865 }
866}
867
868const FIXED_FIELDS: [&str; 3] = ["id", "jobVersion", "created_by"];
870
871pub(super) async fn handle_cron_patch(
877 State(state): State<AppState>,
878 caller: Option<axum::Extension<super::caller::Caller>>,
879 Path(id): Path<String>,
880 Json(body): Json<Value>,
881) -> (StatusCode, Json<Value>) {
882 patch_job(&state, caller.as_deref(), &id, body, Origin::default())
883}
884
885pub(crate) fn patch_job(state: &AppState, caller: Option<&Caller>, id: &str, body: Value, origin: Origin) -> (StatusCode, Json<Value>) {
889 let (store, job) = match job_for_change(state, caller, id) {
890 Ok(found) => found,
891 Err(refused) => return refused,
892 };
893 if let Some(action) = body.get("action").and_then(Value::as_str) {
894 return set_enabled(state, &store, id, action, origin);
895 }
896 let Some(fields) = body.as_object() else { return bad_request("an edit is a JSON object of job fields") };
897 if job.action_kind == "spawn" && !origin.from_host {
898 return forbidden("a spawn job can be paused, resumed or deleted here; to change it, delete it and create it again from the Jobs tab");
899 }
900 if !may_edit_job(caller, &job) {
901 return forbidden("an agent can edit only a job it created or owns");
902 }
903 let before = JobDefinition::from_job(&job);
904 let mut merged = serde_json::to_value(&before).unwrap_or_default();
905 for (key, value) in fields {
906 if FIXED_FIELDS.contains(&key.as_str()) {
907 if merged.get(key) != Some(value) {
908 return bad_request(format!("{key} can't be changed"));
909 }
910 continue;
911 }
912 merged[key.as_str()] = value.clone();
913 }
914 if jobs::from_template::edit_needs_render(fields, &before) {
915 if let Err(e) = jobs::from_template::apply(&mut merged, before.template.as_ref()) {
916 return bad_request(e);
917 }
918 }
919 let fresh = fields.contains_key("trigger") || fields.contains_key("action");
920 let mut def = match JobDefinition::parse(&merged, Check { fresh, now_ms: agentmux_common::time::now_ms() }) {
921 Ok(def) => def,
922 Err(e) => return bad_request(e),
923 };
924 let editor = if origin.from_host { Who::Operator } else { who(state, caller) };
925 if let Err(e) = may_define(&editor, &def, Some(job.owner_uid())) {
926 return forbidden(e);
927 }
928 if matches!(def.action, Action::Spawn { .. }) && !(origin.from_host && job.action_kind == "spawn") {
929 return forbidden(SPAWN_FROM_THE_APP);
930 }
931 if let Err(e) = runnable_yet(&def) {
932 return bad_request(e);
933 }
934 let asks = !before.enabled || fields.contains_key("action") || fields.contains_key("trigger");
935 if let Err(stop) = super::drone_turn_on::allowed(state, &def, origin, asks) {
936 return stop.answer();
937 }
938 let notes = match job_caps::apply_rules(state, &mut def, Some(&before), origin) {
939 Ok(notes) => notes,
940 Err(refused) => return refused,
941 };
942 let mut edited = job.clone();
943 edited.last_written_by = writer_of(origin.from_host, caller);
945 if fields.contains_key("action") {
946 def.apply_to(&mut edited, &|to| target_of(state, to));
947 } else {
948 def.apply_to(&mut edited, &|_| (job.target.clone(), job.target_uid.clone()));
950 }
951 match store.cron_update_definition(&edited) {
952 Ok(true) => {}
953 Ok(false) => return (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
954 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
955 }
956 if edited.enabled {
957 state.cron_scheduler.schedule_job(&edited);
958 } else {
959 state.cron_scheduler.cancel_job(id);
960 }
961 publish_cron_changed(state);
962 (StatusCode::OK, Json(json!({"ok": true, "enabled": edited.enabled, "job": to_view(&edited), "notes": notes})))
963}
964
965fn set_enabled(state: &AppState, store: &Store, id: &str, action: &str, origin: Origin) -> Answer {
967 let enabled = match action {
968 "resume" => true,
969 "pause" => false,
970 other => return bad_request(format!("unknown action '{other}' (use 'pause' or 'resume')")),
971 };
972 if enabled {
973 if let Ok(Some(job)) = store.cron_get(id) {
974 let mut def = JobDefinition::from_job(&job);
975 def.enabled = true;
976 if let Err(stop) = super::drone_turn_on::allowed(state, &def, origin, true) {
977 return stop.answer();
978 }
979 }
980 }
981 match store.cron_set_enabled(id, enabled) {
982 Ok(true) => {}
983 Ok(false) => return (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
984 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
985 }
986
987 if enabled {
988 if let Ok(Some(job)) = store.cron_get(id) {
989 state.cron_scheduler.schedule_job(&job);
990 }
991 } else {
992 state.cron_scheduler.cancel_job(id);
993 }
994 publish_cron_changed(state);
995
996 (StatusCode::OK, Json(json!({"ok": true, "enabled": enabled})))
997}
998
999#[cfg(test)]
1000mod tests {
1001 use super::*;
1002
1003 fn mk_job(enabled: bool, max_fires: Option<i64>, fire_count: i64) -> CronJob {
1004 CronJob {
1005 id: "job-1".to_string(),
1006 name: "nightly build".to_string(),
1007 expression: "0 9 * * *".to_string(),
1008 prompt: "run the build".to_string(),
1009 target: "target-agent".to_string(),
1010 target_uid: String::new(),
1011 created_by: "creator-agent".to_string(),
1012 created_by_uid: String::new(),
1013 enabled,
1014 last_fired: Some(1_700_000_000),
1015 fire_count,
1016 max_fires,
1017 created_at: 1_699_000_000,
1018 max_age_secs: None,
1019 catch_up: "skip".to_string(),
1020 ..Default::default()
1021 }
1022 }
1023
1024 #[test]
1027 fn report_links_keep_only_bounded_https_urls() {
1028 let long_url = format!("https://example.com/{}", "a".repeat(REPORT_URL_MAX));
1029 let given = json!([
1030 "https://example.com/pr/1",
1031 "http://example.com/plain",
1032 "javascript:alert(1)",
1033 "https://",
1034 {"label": "Report", "url": "https://example.com/r"},
1035 {"label": "x".repeat(REPORT_LABEL_MAX + 1), "url": "https://example.com/too-long-label"},
1036 {"label": "bad", "url": "ftp://example.com"},
1037 {"url": "https://example.com/no-label"},
1038 long_url,
1039 42,
1040 {"label": "nested", "url": {"href": "https://example.com"}},
1041 ]);
1042 assert_eq!(
1043 report_links(Some(given)),
1044 json!([
1045 "https://example.com/pr/1",
1046 {"label": "Report", "url": "https://example.com/r"},
1047 {"label": "", "url": "https://example.com/no-label"},
1048 ])
1049 );
1050 let many: Vec<Value> = (0..9).map(|i| json!(format!("https://example.com/{i}"))).collect();
1051 assert_eq!(report_links(Some(Value::Array(many))).as_array().unwrap().len(), REPORT_LINKS_MAX);
1052 assert_eq!(report_links(Some(json!("https://example.com/one"))), json!(["https://example.com/one"]));
1053 assert_eq!(report_links(None), Value::Null);
1054 }
1055
1056 #[test]
1057 fn a_definition_is_written_by_whoever_the_request_proves() {
1058 use super::super::caller::Caller;
1059 use crate::backend::storage::cron::{WRITER_OPERATOR, WRITER_UNKNOWN};
1060 let agent = Caller::Agent { uid: "uid-a".to_string() };
1061 assert_eq!(writer_of(true, None), WRITER_OPERATOR);
1063 assert_eq!(writer_of(true, Some(&Caller::Unattributed)), WRITER_OPERATOR);
1064 assert_eq!(writer_of(false, Some(&agent)), "uid-a");
1066 assert_eq!(writer_of(false, Some(&Caller::Unattributed)), WRITER_UNKNOWN);
1068 assert_eq!(writer_of(false, None), WRITER_UNKNOWN);
1069 }
1070
1071 #[test]
1072 fn an_agent_changes_only_its_own_jobs_or_ones_aimed_at_it() {
1073 use super::super::caller::Caller;
1074 let mut job = mk_job(true, None, 0);
1075 job.created_by_uid = "uid-creator".to_string();
1076 job.target_uid = "uid-target".to_string();
1077 let agent = |uid: &str| Caller::Agent { uid: uid.to_string() };
1078 assert!(may_change_job(Some(&agent("uid-creator")), &job));
1079 assert!(may_change_job(Some(&agent("uid-target")), &job), "the agent it pings may pause it");
1080 assert!(!may_change_job(Some(&agent("uid-other")), &job));
1081 assert!(may_change_job(Some(&Caller::Unattributed), &job));
1083 assert!(may_change_job(None, &job));
1084 job.created_by_uid.clear();
1086 assert!(may_change_job(Some(&agent("uid-other")), &job));
1087 }
1088
1089 #[tokio::test]
1090 async fn an_agent_called_operator_cannot_act_on_a_job_the_person_made() {
1091 use super::super::caller::Caller;
1092 let state = crate::server::tests::test_state();
1093 let seed = |id: &str, slug: &str| {
1095 let mut def = crate::backend::storage::agents::test_agent_def(id, slug, "claude", "agent", 1, "");
1096 def.slug = slug.to_string();
1097 state.mstore.agent_def_insert(&mut def).unwrap();
1098 Caller::Agent { uid: id.to_string() }
1099 };
1100 let reserved = seed("uid-reserved", "operator");
1101 let nickname = seed("uid-nick", "creator-agent");
1102 let mut job = mk_job(true, None, 0);
1103 job.created_by = "operator".to_string();
1105 assert!(!may_act_on(&state, Some(&reserved), &job), "an agent that is called operator is not the person");
1106 job.created_by = "creator-agent".to_string();
1108 assert!(may_act_on(&state, Some(&nickname), &job));
1109 assert!(!may_act_on(&state, Some(&reserved), &job));
1110 let legacy = seed("uid-legacy", "swarm");
1112 job.created_by = "swarm".to_string();
1113 assert!(may_act_on(&state, Some(&legacy), &job));
1114 }
1115
1116 #[test]
1117 fn views_carry_the_miss_record() {
1118 let mut job = mk_job(true, None, 2);
1119 job.missed_count = 3;
1120 job.last_missed_at = Some(1_700_000_100);
1121 job.last_miss_reason = "target_stopped".to_string();
1122 let view = to_view(&job);
1123 assert_eq!((view.missed_count, view.last_missed_at), (3, Some(1_700_000_100)));
1124 assert_eq!(view.last_miss_reason, "target_stopped");
1125 let summary = to_summary(&job, "block-1".to_string());
1126 assert_eq!((summary.missed_count, summary.last_miss_reason.as_str()), (3, "target_stopped"));
1127 }
1128
1129 #[test]
1130 fn to_summary_carries_the_resolved_block_id() {
1131 let job = mk_job(true, None, 3);
1132 let summary = to_summary(&job, "block-42".to_string());
1133 assert_eq!(summary.id, "job-1");
1134 assert_eq!(summary.block_id, "block-42");
1135 assert_eq!(summary.created_by, "creator-agent");
1136 assert_eq!(summary.fire_count, 3);
1137 assert_eq!(summary.max_fires, None);
1138 }
1139
1140 #[test]
1141 fn to_summary_omits_next_fire_when_disabled() {
1142 let job = mk_job(false, Some(5), 5);
1143 let summary = to_summary(&job, "block-1".to_string());
1144 assert!(!summary.enabled);
1145 assert_eq!(summary.next_fire, None);
1146 }
1147
1148 #[test]
1149 fn to_summary_computes_next_fire_when_enabled() {
1150 let job = mk_job(true, None, 0);
1151 let summary = to_summary(&job, "block-1".to_string());
1152 assert!(summary.enabled);
1153 assert!(summary.next_fire.is_some());
1154 }
1155}
1156
1157#[cfg(test)]
1158#[path = "cron_tests.rs"]
1159mod route_tests;