Skip to main content

agentmux_srv_core/backend/job_templates/
cloud.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a cloud job's manifest declares beyond a template's own fields
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §4.3): who owns it, which reporter's events count, the schedule
6//! it is expected on, how long a run may take, and how to start it.
7//!
8//! These fields belong to a template whose `kind` is `cloud`, and a job template may not carry them. AgentMux holds
9//! no cloud or CI credentials, so `runNow` only names a page to open or an instruction for the owner agent; it never
10//! starts anything itself.
11
12use std::sync::Arc;
13
14use serde::{Deserialize, Serialize};
15
16use super::manifest::{JobTemplateKind, JobTemplateManifest};
17use super::JobTemplates;
18use crate::backend::cron::schedule::JobSchedule;
19use crate::backend::jobs::cloud_events::{CloudJob, CloudJobs};
20use crate::backend::jobs::reporters::{self, ReporterState};
21
22/// The longest a run may take before it is `lost`: a week.
23const MAX_DURATION_MINUTES: u32 = 7 * 24 * 60;
24/// The longest grace after an expected slot: a day.
25const MAX_GRACE_MINUTES: u32 = 24 * 60;
26const MAX_TEXT_CHARS: usize = 500;
27
28/// The reporter whose events count for the job: its name in Settings and its public key. Approving the manifest pins
29/// the pair.
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
31#[serde(deny_unknown_fields)]
32#[ts(export, export_to = "../../../frontend/types/rpc/")]
33pub struct CloudReporter {
34    pub name: String,
35    /// An Ed25519 public key, base64.
36    pub key: String,
37}
38
39/// A manifest's reporter as the approval prompt shows it: the key by its fingerprint, and what approving does to the
40/// pins.
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
42#[ts(export, export_to = "../../../frontend/types/rpc/")]
43pub struct ReporterNote {
44    pub name: String,
45    pub fingerprint: String,
46    pub state: ReporterState,
47}
48
49/// A schedule the job is expected to run on.
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
51#[serde(rename_all = "camelCase", deny_unknown_fields)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53pub struct CloudSchedule {
54    pub cron: String,
55    pub tz: String,
56    /// Minutes after a slot before a missing report counts as missed.
57    pub grace_minutes: u32,
58}
59
60/// The one word `expect` takes when no schedule applies.
61#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
62#[ts(export, export_to = "../../../frontend/types/rpc/")]
63pub enum NoSchedule {
64    #[serde(rename = "none")]
65    None,
66}
67
68/// `expect`: a schedule, or `"none"` for a job that events start.
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
70#[serde(untagged)]
71#[ts(export, export_to = "../../../frontend/types/rpc/")]
72pub enum CloudExpect {
73    Never(NoSchedule),
74    Schedule(CloudSchedule),
75}
76
77/// `runNow`: one of a page that starts the job, or an instruction for the owner agent.
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
79#[serde(rename_all = "camelCase", deny_unknown_fields)]
80#[ts(export, export_to = "../../../frontend/types/rpc/")]
81pub struct CloudRunNow {
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub link: Option<String>,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub ask_owner: Option<String>,
86}
87
88/// Whether the manifest carries any cloud field.
89fn declares_cloud_fields(m: &JobTemplateManifest) -> bool {
90    m.owner.is_some() || m.reporter.is_some() || m.expect.is_some() || m.max_duration_minutes.is_some() || m.run_now.is_some() || m.aggregate
91}
92
93fn text_ok(s: &str) -> bool {
94    !s.trim().is_empty() && s.chars().count() <= MAX_TEXT_CHARS && !s.chars().any(char::is_control)
95}
96
97/// Check the cloud fields: present and well-formed on a cloud template, absent on a job template.
98pub fn validate(m: &JobTemplateManifest) -> Result<(), String> {
99    if m.kind != JobTemplateKind::Cloud {
100        return if declares_cloud_fields(m) {
101            Err("owner, reporter, expect, maxDurationMinutes, runNow and aggregate belong to a cloud template".to_string())
102        } else {
103            Ok(())
104        };
105    }
106    let owner = m.owner.as_deref().ok_or("a cloud template names its owner, an agent on this computer")?;
107    if owner.trim().is_empty() || owner.chars().count() > 64 || owner.chars().any(char::is_control) {
108        return Err("owner must be an agent's name or id, up to 64 characters".to_string());
109    }
110    let reporter = m.reporter.as_ref().ok_or("a cloud template names its reporter: {\"name\": …, \"key\": …}")?;
111    if !reporters::is_name(&reporter.name) {
112        return Err("reporter.name is lowercase letters, digits and -, up to 40".to_string());
113    }
114    if reporter.key != reporter.key.trim() || !reporters::is_public_key(&reporter.key) {
115        return Err("reporter.key isn't a 32-byte Ed25519 public key in base64".to_string());
116    }
117    match m.expect.as_ref().ok_or("a cloud template says what to expect: a schedule, or \"none\" for a job events start")? {
118        CloudExpect::Never(_) => {}
119        CloudExpect::Schedule(s) => {
120            JobSchedule::cron(&s.cron, &s.tz).map_err(|e| format!("expect: invalid cron {:?} in {:?}: {e}", s.cron, s.tz))?;
121            if s.grace_minutes > MAX_GRACE_MINUTES {
122                return Err(format!("expect.graceMinutes is at most {MAX_GRACE_MINUTES}"));
123            }
124        }
125    }
126    match m.max_duration_minutes {
127        Some(n) if (1..=MAX_DURATION_MINUTES).contains(&n) => {}
128        Some(_) => return Err(format!("maxDurationMinutes is 1 to {MAX_DURATION_MINUTES}")),
129        None => return Err("a cloud template says how long a run may take (maxDurationMinutes)".to_string()),
130    }
131    if let Some(run_now) = &m.run_now {
132        match (run_now.link.as_deref(), run_now.ask_owner.as_deref()) {
133            (Some(link), None) => {
134                let https = link.strip_prefix("https://").is_some_and(|rest| !rest.is_empty() && !rest.contains(char::is_whitespace));
135                if !https || !text_ok(link) {
136                    return Err("runNow.link is an https address".to_string());
137                }
138            }
139            (None, Some(ask)) if text_ok(ask) => {}
140            (None, Some(_)) => return Err(format!("runNow.askOwner is 1 to {MAX_TEXT_CHARS} characters of text")),
141            _ => return Err("runNow is one of link or askOwner".to_string()),
142        }
143    }
144    Ok(())
145}
146
147/// The cloud jobs the operator approved: a cloud template, approved and unchanged since, is the job its id names.
148/// Anything else is "unknown job".
149impl CloudJobs for Arc<JobTemplates> {
150    fn cloud_job(&self, job_id: &str) -> Option<CloudJob> {
151        let t = self.approved_cloud(job_id)?;
152        let reporter_key = t.manifest.reporter?.key;
153        Some(CloudJob { id: t.id, name: t.manifest.name, reporter_key })
154    }
155}