agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
pub(super) mod prompt_variants;
use serde::{Deserialize, Serialize};

pub(super) const MAX_TASK_BYTES: usize = 1024 * 1024;
pub(super) const MAX_TASK_JSON_BYTES: usize = 8 * MAX_TASK_BYTES;
pub(super) const MAX_TASK_FILES: usize = 64;
pub(super) const MAX_PROMPT_BYTES: usize = 65536;
const MAX_DESCRIPTION_BYTES: usize = 1000;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Schedule {
    Manual,
    Custom {
        expression: String,
    },
    Interval {
        minutes: u32,
    },
    Hourly {
        minute: u8,
    },
    Daily {
        hour: u8,
        minute: u8,
        weekdays: bool,
    },
}

impl Schedule {
    pub(super) fn validate(&self) -> Result<(), String> {
        match self {
            Self::Custom { expression }
                if expression.trim().is_empty()
                    || expression.len() > 200
                    || expression.contains(['\0', '\n', '\r']) =>
            {
                Err("Invalid Hermes schedule".into())
            }
            Self::Interval { minutes } if !(1..=525600).contains(minutes) => {
                Err("Interval must be between 1 and 525600 minutes".into())
            }
            Self::Hourly { minute } if *minute > 59 => Err("Invalid minute of hour".into()),
            Self::Daily { hour, minute, .. } if *hour > 23 || *minute > 59 => {
                Err("Invalid local time".into())
            }
            _ => Ok(()),
        }
    }
    pub(super) fn display(&self) -> String {
        match self {
            Self::Manual => "manual".into(),
            Self::Custom { expression } => expression.clone(),
            Self::Interval { minutes } => format!("every {minutes}m"),
            Self::Hourly { minute } => format!("{minute} * * * *"),
            Self::Daily {
                hour,
                minute,
                weekdays,
            } => format!(
                "{minute} {hour} * * {}",
                if *weekdays { "1-5" } else { "*" }
            ),
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Provider {
    System,
    Hermes,
}

/// The same input contract is accepted by IPC and CLI; commands are executed
/// only by an explicit run or the selected scheduler, never while saving.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct AutomationScriptFile {
    pub path: String,
    pub content: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct AutomationDraft {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub package_options: Option<super::package::PackageOptions>,
    pub name: String,
    /// Optional summary of what the task does, shown in the task list.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub provider: Provider,
    pub content: String,
    pub workdir: Option<String>,
    /// Script storage is independent of the directory in which the task runs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_dir: Option<String>,
    pub schedule: Schedule,
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub files: Vec<AutomationScriptFile>,
}

pub(super) fn runtime_prompt_file(draft: &AutomationDraft) -> Option<&AutomationScriptFile> {
    draft
        .files
        .iter()
        .find(|file| file.path == "prompts/prompt.md")
        .or_else(|| {
            draft
                .files
                .iter()
                .find(|file| file.path == "prompt.md" || file.path.ends_with("/prompt.md"))
        })
}

impl AutomationDraft {
    pub(super) fn scripts_dir(&self) -> Option<&str> {
        self.script_dir.as_deref().or(self.workdir.as_deref())
    }

    pub(super) fn validate(&mut self) -> Result<(), String> {
        if let Some(options) = &self.package_options {
            super::package::validate_options(options)?;
        }
        let mut paths = std::collections::HashSet::new();
        let mut total = if super::native::shell_entry::entry(self).is_some() {
            0
        } else {
            self.content.len()
        };
        for file in &self.files {
            super::super::path_guard::ensure_safe_skill_relative_path(&file.path)
                .map_err(|e| e.to_string())?;
            if file.path.contains(['\\', ':'])
                || ![".py", ".sh", ".ps1", ".json", ".md"]
                    .iter()
                    .any(|extension| file.path.ends_with(extension))
                || !paths.insert(&file.path)
                || file.content.trim().is_empty()
                || file.content.contains('\0')
                || (file.path != "config/prompt-variants.json"
                    && file.content.len() > MAX_PROMPT_BYTES)
            {
                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());
            }
            total = total.saturating_add(file.content.len());
        }
        if self.files.len() > MAX_TASK_FILES || total > MAX_TASK_BYTES {
            return Err("Task files must total at most 1 MiB across 64 files".into());
        }
        prompt_variants::validate(self)?;
        super::actions::read(self)?;
        self.name = self.name.trim().into();
        if self.name.is_empty() || self.name.len() > 200 || self.name.chars().any(char::is_control)
        {
            return Err("Name must contain 1–200 bytes without control characters".into());
        }
        self.description = self
            .description
            .as_deref()
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .map(Into::into);
        if self.description.as_ref().is_some_and(|text| {
            text.len() > MAX_DESCRIPTION_BYTES || text.chars().any(|c| c.is_control() && c != '\n')
        }) {
            return Err(
                "Description must contain at most 1000 bytes without control characters".into(),
            );
        }
        if self.content.trim().is_empty()
            || self.content.len() > 65536
            || self.content.contains('\0')
        {
            return Err("Command or prompt must contain 1–65536 bytes without NUL".into());
        }
        self.schedule.validate()?;
        if self.provider == Provider::System && matches!(self.schedule, Schedule::Custom { .. }) {
            return Err("Custom expressions are supported by Hermes only".into());
        }
        if self.provider == Provider::Hermes && matches!(self.schedule, Schedule::Manual) {
            return Err(
                "Hermes requires a recurring schedule; use pause and Run now for manual use".into(),
            );
        }
        for directory in [&mut self.workdir, &mut self.script_dir] {
            if let Some(dir) = directory.as_ref() {
                if dir.is_empty() {
                    *directory = None;
                    continue;
                }
                let path = if dir == "~" || dir.starts_with("~/") {
                    dirs::home_dir()
                        .ok_or("Cannot resolve home")?
                        .join(dir.strip_prefix("~/").unwrap_or(""))
                } else {
                    dir.into()
                };
                if !path.is_absolute() || !path.is_dir() {
                    return Err("Working directory must be an existing absolute directory".into());
                }
                *directory = Some(path.to_string_lossy().into_owned());
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManagedAutomation {
    pub id: String,
    pub revision: u64,
    pub draft: AutomationDraft,
    pub source: String,
    pub identifier: String,
    pub location: String,
}

pub(super) fn valid_id(id: &str) -> bool {
    id.strip_prefix("agent_hub:")
        .is_some_and(|suffix| uuid::Uuid::parse_str(suffix).is_ok())
}

#[cfg(test)]
mod tests;