Skip to main content

agent_hub_runtime/core/automation/
definition.rs

1pub(super) mod prompt_variants;
2use serde::{Deserialize, Serialize};
3
4pub(super) const MAX_TASK_BYTES: usize = 1024 * 1024;
5pub(super) const MAX_TASK_JSON_BYTES: usize = 8 * MAX_TASK_BYTES;
6pub(super) const MAX_TASK_FILES: usize = 64;
7pub(super) const MAX_PROMPT_BYTES: usize = 65536;
8const MAX_DESCRIPTION_BYTES: usize = 1000;
9
10#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
11#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
12pub enum Schedule {
13    Manual,
14    Custom {
15        expression: String,
16    },
17    Interval {
18        minutes: u32,
19    },
20    Hourly {
21        minute: u8,
22    },
23    Daily {
24        hour: u8,
25        minute: u8,
26        weekdays: bool,
27    },
28}
29
30impl Schedule {
31    pub(super) fn validate(&self) -> Result<(), String> {
32        match self {
33            Self::Custom { expression }
34                if expression.trim().is_empty()
35                    || expression.len() > 200
36                    || expression.contains(['\0', '\n', '\r']) =>
37            {
38                Err("Invalid Hermes schedule".into())
39            }
40            Self::Interval { minutes } if !(1..=525600).contains(minutes) => {
41                Err("Interval must be between 1 and 525600 minutes".into())
42            }
43            Self::Hourly { minute } if *minute > 59 => Err("Invalid minute of hour".into()),
44            Self::Daily { hour, minute, .. } if *hour > 23 || *minute > 59 => {
45                Err("Invalid local time".into())
46            }
47            _ => Ok(()),
48        }
49    }
50    pub(super) fn display(&self) -> String {
51        match self {
52            Self::Manual => "manual".into(),
53            Self::Custom { expression } => expression.clone(),
54            Self::Interval { minutes } => format!("every {minutes}m"),
55            Self::Hourly { minute } => format!("{minute} * * * *"),
56            Self::Daily {
57                hour,
58                minute,
59                weekdays,
60            } => format!(
61                "{minute} {hour} * * {}",
62                if *weekdays { "1-5" } else { "*" }
63            ),
64        }
65    }
66}
67
68#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
69#[serde(rename_all = "snake_case")]
70pub enum Provider {
71    System,
72    Hermes,
73}
74
75/// The same input contract is accepted by IPC and CLI; commands are executed
76/// only by an explicit run or the selected scheduler, never while saving.
77#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
78#[serde(deny_unknown_fields)]
79pub struct AutomationScriptFile {
80    pub path: String,
81    pub content: String,
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
85#[serde(deny_unknown_fields)]
86pub struct AutomationDraft {
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub package_options: Option<super::package::PackageOptions>,
89    pub name: String,
90    /// Optional summary of what the task does, shown in the task list.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub description: Option<String>,
93    pub provider: Provider,
94    pub content: String,
95    pub workdir: Option<String>,
96    /// Script storage is independent of the directory in which the task runs.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub script_dir: Option<String>,
99    pub schedule: Schedule,
100    pub enabled: bool,
101    #[serde(default, skip_serializing_if = "Vec::is_empty")]
102    pub files: Vec<AutomationScriptFile>,
103}
104
105pub(super) fn runtime_prompt_file(draft: &AutomationDraft) -> Option<&AutomationScriptFile> {
106    draft
107        .files
108        .iter()
109        .find(|file| file.path == "prompts/prompt.md")
110        .or_else(|| {
111            draft
112                .files
113                .iter()
114                .find(|file| file.path == "prompt.md" || file.path.ends_with("/prompt.md"))
115        })
116}
117
118impl AutomationDraft {
119    pub(super) fn scripts_dir(&self) -> Option<&str> {
120        self.script_dir.as_deref().or(self.workdir.as_deref())
121    }
122
123    pub(super) fn validate(&mut self) -> Result<(), String> {
124        if let Some(options) = &self.package_options {
125            super::package::validate_options(options)?;
126        }
127        let mut paths = std::collections::HashSet::new();
128        let mut total = if super::native::shell_entry::entry(self).is_some() {
129            0
130        } else {
131            self.content.len()
132        };
133        for file in &self.files {
134            super::super::path_guard::ensure_safe_skill_relative_path(&file.path)
135                .map_err(|e| e.to_string())?;
136            if file.path.contains(['\\', ':'])
137                || ![".py", ".sh", ".ps1", ".json", ".md"]
138                    .iter()
139                    .any(|extension| file.path.ends_with(extension))
140                || !paths.insert(&file.path)
141                || file.content.trim().is_empty()
142                || file.content.contains('\0')
143                || (file.path != "config/prompt-variants.json"
144                    && file.content.len() > MAX_PROMPT_BYTES)
145            {
146                return Err("Task files require unique relative .py, .sh, .ps1, .json or .md paths and nonempty UTF-8 contents up to 64 KiB each".into());
147            }
148            total = total.saturating_add(file.content.len());
149        }
150        if self.files.len() > MAX_TASK_FILES || total > MAX_TASK_BYTES {
151            return Err("Task files must total at most 1 MiB across 64 files".into());
152        }
153        prompt_variants::validate(self)?;
154        super::actions::read(self)?;
155        self.name = self.name.trim().into();
156        if self.name.is_empty() || self.name.len() > 200 || self.name.chars().any(char::is_control)
157        {
158            return Err("Name must contain 1–200 bytes without control characters".into());
159        }
160        self.description = self
161            .description
162            .as_deref()
163            .map(str::trim)
164            .filter(|text| !text.is_empty())
165            .map(Into::into);
166        if self.description.as_ref().is_some_and(|text| {
167            text.len() > MAX_DESCRIPTION_BYTES || text.chars().any(|c| c.is_control() && c != '\n')
168        }) {
169            return Err(
170                "Description must contain at most 1000 bytes without control characters".into(),
171            );
172        }
173        if self.content.trim().is_empty()
174            || self.content.len() > 65536
175            || self.content.contains('\0')
176        {
177            return Err("Command or prompt must contain 1–65536 bytes without NUL".into());
178        }
179        self.schedule.validate()?;
180        if self.provider == Provider::System && matches!(self.schedule, Schedule::Custom { .. }) {
181            return Err("Custom expressions are supported by Hermes only".into());
182        }
183        if self.provider == Provider::Hermes && matches!(self.schedule, Schedule::Manual) {
184            return Err(
185                "Hermes requires a recurring schedule; use pause and Run now for manual use".into(),
186            );
187        }
188        for directory in [&mut self.workdir, &mut self.script_dir] {
189            if let Some(dir) = directory.as_ref() {
190                if dir.is_empty() {
191                    *directory = None;
192                    continue;
193                }
194                let path = if dir == "~" || dir.starts_with("~/") {
195                    dirs::home_dir()
196                        .ok_or("Cannot resolve home")?
197                        .join(dir.strip_prefix("~/").unwrap_or(""))
198                } else {
199                    dir.into()
200                };
201                if !path.is_absolute() || !path.is_dir() {
202                    return Err("Working directory must be an existing absolute directory".into());
203                }
204                *directory = Some(path.to_string_lossy().into_owned());
205            }
206        }
207        Ok(())
208    }
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct ManagedAutomation {
213    pub id: String,
214    pub revision: u64,
215    pub draft: AutomationDraft,
216    pub source: String,
217    pub identifier: String,
218    pub location: String,
219}
220
221pub(super) fn valid_id(id: &str) -> bool {
222    id.strip_prefix("agent_hub:")
223        .is_some_and(|suffix| uuid::Uuid::parse_str(suffix).is_ok())
224}
225
226#[cfg(test)]
227mod tests;