Skip to main content

agent_hub_runtime/core/automation/
output.rs

1//! Bounded provider output reads shared by latest output and local history.
2use super::{hermes_manage, managed, native, store, Provider};
3use crate::core::path_guard::is_path_safe;
4use serde::Serialize;
5use std::{
6    fs,
7    io::{Read, Seek, SeekFrom},
8    path::{Path, PathBuf},
9};
10const OUTPUT_LIMIT: u64 = 256 * 1024;
11#[derive(Debug, Serialize)]
12pub struct AutomationRunOutput {
13    pub content: String,
14    pub truncated: bool,
15    /// No provider output exists yet; this is distinct from a failed read.
16    pub available: bool,
17    pub kind: String,
18}
19pub(super) fn checked(root: &Path, path: &Path) -> Result<(), String> {
20    if !is_path_safe(root, path)
21        || fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink())
22    {
23        return Err("Execution output is outside the task directory or is a symbolic link".into());
24    }
25    Ok(())
26}
27pub(super) fn hermes_outputs(root: &Path, id: &str) -> Result<Vec<PathBuf>, String> {
28    if id.is_empty() || id == "." || id == ".." || id.contains(['/', '\\', ':']) {
29        return Err("Invalid Hermes job ID".into());
30    }
31    let dir = root.join("cron/output").join(id);
32    checked(root, &dir)?;
33    let entries = match fs::read_dir(&dir) {
34        Ok(entries) => entries,
35        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
36        Err(e) => return Err(e.to_string()),
37    };
38    let mut outputs = Vec::new();
39    for (count, entry) in entries.enumerate() {
40        if count >= 10000 {
41            return Err("Too many Hermes output files".into());
42        }
43        let path = entry.map_err(|e| e.to_string())?.path();
44        let valid = path
45            .file_name()
46            .and_then(|n| n.to_str())
47            .and_then(|n| n.strip_suffix(".md"))
48            .is_some_and(|n| chrono::NaiveDateTime::parse_from_str(n, "%Y-%m-%d_%H-%M-%S").is_ok());
49        if !valid {
50            continue;
51        }
52        checked(root, &path)?;
53        if path.is_file() {
54            outputs.push(path);
55        }
56    }
57    outputs.sort_by(|a, b| b.cmp(a));
58    Ok(outputs)
59}
60fn latest_hermes(root: &Path, id: &str) -> Result<Option<PathBuf>, String> {
61    Ok(hermes_outputs(root, id)?.into_iter().next())
62}
63/// Read local ownership without enumerating schedulers or unrelated providers.
64pub(super) fn native_task_at(
65    root: &Path,
66    id: &str,
67) -> Result<Option<(super::ManagedAutomation, PathBuf)>, String> {
68    if !super::definition::valid_id(id) {
69        return Ok(None);
70    }
71    let record = store::load(root)?
72        .into_iter()
73        .find(|r| r.id == id && r.draft.provider == Provider::System);
74    let Some(record) = record else {
75        return Ok(None);
76    };
77    managed::verify(root, &record)?;
78    let dir = native::directory(root, &record);
79    if super::package::directory(&record).is_some() {
80        super::package::checked(root, &record)?;
81    } else {
82        checked(root, &dir)?;
83    }
84    Ok(Some((record, dir)))
85}
86pub(super) fn native_directory(task: &super::AutomationTask) -> Result<Option<PathBuf>, String> {
87    Ok(native_task_at(&store::root(), &task.id)?.map(|(_, dir)| dir))
88}
89/// Resolve exact task ownership and scope; callers cannot supply a log path.
90pub fn output(id: &str) -> Result<AutomationRunOutput, String> {
91    if let Some((_, dir)) = native_task_at(&store::root(), id)? {
92        return latest_native(&dir);
93    }
94    let task = managed::find(id)?;
95    let (root, path, kind) = if task.source == "hermes" {
96        let root = hermes_manage::root_for(&task)?;
97        let path = latest_hermes(
98            &root,
99            task.identifier.as_deref().ok_or("Missing Hermes job ID")?,
100        )?;
101        (root, path, "hermes")
102    } else {
103        if let Some(dir) = native_directory(&task)? {
104            return latest_native(&dir);
105        } else {
106            (store::root(), None, "unsupported")
107        }
108    };
109    let path = match path {
110        Some(path) => match fs::metadata(&path) {
111            Ok(_) => Some(path),
112            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
113            Err(e) => return Err(e.to_string()),
114        },
115        None => None,
116    };
117    match path {
118        Some(path) => {
119            let mut result = read_output(&root, &path)?;
120            result.kind = kind.into();
121            Ok(result)
122        }
123        _ => Ok(AutomationRunOutput {
124            content: String::new(),
125            truncated: false,
126            available: false,
127            kind: kind.into(),
128        }),
129    }
130}
131fn latest_native(dir: &Path) -> Result<AutomationRunOutput, String> {
132    let path = dir.join("output.log");
133    checked(dir, &path)?;
134    if !path.try_exists().map_err(|e| e.to_string())? {
135        return Ok(AutomationRunOutput {
136            content: String::new(),
137            truncated: false,
138            available: false,
139            kind: "system".into(),
140        });
141    }
142    let mut result = read_output(dir, &path)?;
143    result.kind = "system".into();
144    Ok(result)
145}
146pub(super) fn read_output(root: &Path, path: &Path) -> Result<AutomationRunOutput, String> {
147    checked(root, path)?;
148    if !fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
149        return Err("Execution output is not a regular file".into());
150    }
151    let mut file = fs::File::open(path).map_err(|e| e.to_string())?;
152    let meta = file.metadata().map_err(|e| e.to_string())?;
153    if !meta.is_file() {
154        return Err("Execution output is not a regular file".into());
155    }
156    let mut bom = [0; 2];
157    let read = file.read(&mut bom).map_err(|e| e.to_string())?;
158    let utf16 = read == 2 && (bom == [0xff, 0xfe] || bom == [0xfe, 0xff]);
159    let offset = meta.len().saturating_sub(OUTPUT_LIMIT);
160    let offset = if utf16 { offset + offset % 2 } else { offset };
161    file.seek(SeekFrom::Start(offset))
162        .map_err(|e| e.to_string())?;
163    let mut bytes = vec![];
164    file.take(OUTPUT_LIMIT)
165        .read_to_end(&mut bytes)
166        .map_err(|e| e.to_string())?;
167    let content = if utf16 {
168        let units: Vec<_> = bytes
169            .chunks_exact(2)
170            .map(|p| {
171                if bom == [0xff, 0xfe] {
172                    u16::from_le_bytes([p[0], p[1]])
173                } else {
174                    u16::from_be_bytes([p[0], p[1]])
175                }
176            })
177            .collect();
178        String::from_utf16_lossy(&units)
179    } else {
180        String::from_utf8_lossy(&bytes).into_owned()
181    };
182    Ok(AutomationRunOutput {
183        content: content.trim_start_matches('\u{feff}').into(),
184        truncated: offset > 0,
185        available: true,
186        kind: String::new(),
187    })
188}
189
190#[cfg(test)]
191mod tests;