Skip to main content

agent_hub_runtime/core/automation/
package.rs

1//! Independent task packages. Portable intent and local runtime evidence
2//! live in separate files; a damaged package cannot hide another package.
3pub mod catalog;
4#[cfg(test)]
5mod copy_tests;
6mod creation;
7mod dependencies;
8mod exchange;
9mod hermes_bridge;
10mod layout;
11mod lifecycle;
12mod migration;
13mod privileged;
14mod registration;
15mod relocation;
16mod storage;
17#[cfg(test)]
18mod tests;
19mod update;
20
21pub(super) use exchange::normalize;
22pub use exchange::{
23    export_package, import_definition, import_package, preview_package, AutomationPackage,
24};
25#[cfg(any(feature = "cloud-sync", test))]
26pub(crate) use exchange::{read_backup_directory, write_backup_directory};
27pub(crate) use layout::{manifest_directory, manifest_path};
28pub(super) use lifecycle::{prepare_at, remove};
29pub use migration::migrate;
30pub(super) use storage::fingerprint as storage_fingerprint;
31pub(super) use storage::{discover, read, regular_directory, write_receipt};
32pub(super) use update::save;
33
34/// Read an editable task draft using the same JSON budget as package imports.
35pub fn read_definition(path: &std::path::Path) -> Result<AutomationDraft, String> {
36    storage::json(path)
37}
38
39use super::{definition::valid_id, store, AutomationDraft, ManagedAutomation};
40use serde::{Deserialize, Serialize};
41use std::path::{Path, PathBuf};
42
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
44#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
45pub enum Dependency {
46    Command { name: String },
47    Library { name: String },
48    Python { packages: Vec<String> },
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
52#[serde(deny_unknown_fields)]
53pub struct HermesScripts {
54    pub script: Option<String>,
55    pub monitor_script: Option<String>,
56    #[serde(default)]
57    pub no_agent: bool,
58}
59
60/// Release version and install requirements travel with GUI/CLI drafts and backups.
61/// On disk they have a single home in the package manifest.
62#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
63#[serde(deny_unknown_fields)]
64pub struct PackageOptions {
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub version: Option<String>,
67    #[serde(default)]
68    pub dependencies: Vec<Dependency>,
69    pub hermes: Option<HermesScripts>,
70}
71
72pub(super) fn validate_options(options: &PackageOptions) -> Result<(), String> {
73    validate_version(options.version.as_deref())?;
74    dependencies::validate(&options.dependencies)
75}
76
77pub(super) fn validate_version(version: Option<&str>) -> Result<(), String> {
78    if let Some(version) = version {
79        if version.len() > 128
80            || version.trim() != version
81            || semver::Version::parse(version).is_err()
82        {
83            return Err("Task version must be a SemVer value such as 1.0.0".into());
84        }
85    }
86    Ok(())
87}
88
89#[derive(Clone, Serialize, Deserialize)]
90#[serde(deny_unknown_fields)]
91pub(super) struct Manifest {
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    version: Option<String>,
94    schema_version: u32,
95    #[serde(default)]
96    instance_id: String,
97    shell: String,
98    draft: AutomationDraft,
99    files: Vec<String>,
100    #[serde(default)]
101    dependencies: Vec<Dependency>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    hermes: Option<HermesScripts>,
104}
105
106#[derive(Clone, Serialize, Deserialize)]
107pub(super) struct Receipt {
108    pub revision: u64,
109    pub source: String,
110    pub identifier: String,
111    pub location: String,
112    #[serde(deserialize_with = "read_runtime_state")]
113    pub state: String,
114    pub error: Option<String>,
115    pub fingerprint: String,
116    pub pending_backup: bool,
117    #[serde(default)]
118    pub removal_pending: bool,
119    #[serde(default)]
120    pub archived: bool,
121}
122
123#[derive(Clone, Serialize, Deserialize)]
124pub(super) struct Binding {
125    pub workdir: Option<String>,
126}
127
128#[derive(Clone, Serialize, Deserialize)]
129pub(super) struct UpdateSnapshot {
130    pub record: ManagedAutomation,
131    pub receipt: Receipt,
132    pub manifest: Manifest,
133}
134
135/// No user-chosen directories are adopted as packages: only the managed root
136/// is searched, one level deep. Explicit old directories remain legacy tasks.
137pub(super) fn root(state: &Path) -> PathBuf {
138    #[cfg(test)]
139    {
140        state.join("workspaces")
141    }
142    #[cfg(not(test))]
143    {
144        if state == store::root() {
145            super::workspace::workspace_root()
146        } else {
147            state.join("workspaces")
148        }
149    }
150}
151
152pub(super) fn directory(record: &ManagedAutomation) -> Option<PathBuf> {
153    let path = PathBuf::from(record.draft.script_dir.as_ref()?);
154    let identity = layout::read_manifest(&path)
155        .map(|m| m.instance_id)
156        .or_else(|_| {
157            storage::json::<UpdateSnapshot>(&path.join(".local/operation.json"))
158                .map(|s| s.record.id)
159        })
160        .ok()?;
161    (valid_id(&record.id) && identity == record.id).then_some(path)
162}
163
164pub(super) fn checked(state: &Path, record: &ManagedAutomation) -> Result<PathBuf, String> {
165    let path = directory(record).ok_or("Missing or invalid task package")?;
166    let root = root(state);
167    if path.parent() != Some(root.as_path()) {
168        return Err("Task package is outside its managed root".into());
169    }
170    crate::core::path_guard::ensure_dir_within_root(&path, &root).map_err(|e| e.to_string())?;
171    storage::regular_directory(&path)?;
172    storage::regular_directory(&path.join(".local"))?;
173    super::managed::verify(state, record)?;
174    Ok(path)
175}
176
177pub(super) fn receipt(record: &ManagedAutomation) -> Result<Receipt, String> {
178    storage::json(
179        &directory(record)
180            .ok_or("Missing task package")?
181            .join(".local/receipt.json"),
182    )
183}
184
185pub(super) fn lock(state: &Path, id: &str) -> Result<store::Lock, String> {
186    if !valid_id(id) {
187        return Err("Invalid task instance ID".into());
188    }
189    store::Lock::acquire(
190        &state
191            .join("operations")
192            .join(id.trim_start_matches("agent_hub:")),
193    )
194}
195
196pub(super) fn find(state: &Path, id: &str) -> Result<ManagedAutomation, String> {
197    discover(state)
198        .0
199        .into_iter()
200        .find(|record| record.id == id)
201        .ok_or_else(|| "Task package not found or damaged; inspect the automation list".into())
202}
203
204pub(super) fn json_write(path: &Path, value: &impl Serialize) -> Result<(), String> {
205    store::write(
206        path,
207        &serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?,
208    )
209}
210
211pub(super) fn state(record: &ManagedAutomation) -> Option<String> {
212    directory(record)?;
213    Some(
214        receipt(record)
215            .map(|r| r.state)
216            .unwrap_or_else(|_| "prepare_failed".into()),
217    )
218}
219
220#[cfg(any(feature = "cloud-sync", test))]
221pub(super) fn is_package_draft(draft: &AutomationDraft) -> bool {
222    draft
223        .script_dir
224        .as_ref()
225        .is_some_and(|path| manifest_path(Path::new(path)).is_file())
226}
227
228// Read receipts from the former installation lifecycle without rewriting data on list.
229fn read_runtime_state<'de, D: serde::Deserializer<'de>>(
230    deserializer: D,
231) -> Result<String, D::Error> {
232    let state = String::deserialize(deserializer)?;
233    Ok(match state.as_str() {
234        "installed" => "ready".into(),
235        "uninstalled" => "legacy_uninstalled".into(),
236        "installing" => "preparing".into(),
237        "install_failed" => "prepare_failed".into(),
238        "uninstalling" => "removing".into(),
239        "uninstall_failed" => "remove_failed".into(),
240        _ => state,
241    })
242}