Skip to main content

agent_hub_runtime/core/
agent_launch_config.rs

1//! Host persistence for shared Agent launch preferences.
2use super::{cloud_sync, repo_lock::RepoLock, user_config};
3use agent_hub_core::agent_launch::{default_instructions, normalize, resolve_document};
4use anyhow::{bail, ensure, Context, Result};
5use serde::Serialize;
6use sha2::{Digest, Sha256};
7use std::{
8    collections::BTreeMap,
9    fs,
10    io::{Read, Write},
11    path::Path,
12};
13
14mod edit;
15pub use agent_hub_core::agent_launch::{
16    key_for_kind, kind_for_key, parse, plan_fingerprint, verify_plan, AgentSchemes, Document,
17    Launch, LaunchScheme,
18};
19pub use edit::{edit_schemes, effective_schemes, set_default_agent, SchemeEdit};
20
21#[cfg(test)]
22mod scheme_tests;
23#[cfg(test)]
24mod tests;
25
26const FILE: &str = "agent-launch.json";
27
28/// Return the single user-editable file backing shared Agent launch settings.
29pub fn file_path() -> Result<String> {
30    user_config::ready().map_err(anyhow::Error::msg)?;
31    let root = user_config::root();
32    let path = root.join(FILE);
33    user_config::checked(&path).map_err(anyhow::Error::msg)?;
34    Ok(path.to_string_lossy().into_owned())
35}
36
37#[derive(Serialize)]
38pub struct Snapshot {
39    pub document: Document,
40    pub revision: String,
41    pub defaults: BTreeMap<String, String>,
42}
43
44fn read(root: &Path) -> Result<(Document, String)> {
45    let path = root.join(FILE);
46    let mut bytes = Vec::new();
47    let mut exists = true;
48    match fs::File::open(path) {
49        Ok(file) => {
50            file.take(1024 * 1024 + 1).read_to_end(&mut bytes)?;
51        }
52        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
53            exists = false;
54        }
55        Err(e) => return Err(e.into()),
56    }
57    ensure!(
58        bytes.len() <= 1024 * 1024,
59        "Agent launch configuration is too large"
60    );
61    let document = if !exists {
62        Document::default()
63    } else {
64        serde_json::from_slice(&bytes).context("Invalid Agent launch configuration")?
65    };
66    let document = normalize(document)?;
67    Ok((document, hex::encode(Sha256::digest(&bytes))))
68}
69/// Validate restored configuration before the backup transaction publishes any files.
70/// Caller validates the containing tree's symlink and size boundaries first.
71#[cfg(feature = "cloud-sync")]
72pub(crate) fn validate_at(root: &Path) -> Result<()> {
73    read(root).map(|_| ())
74}
75fn load_unlocked() -> Result<Snapshot> {
76    super::cloud_sync::recover_for_user_config()?;
77    read_snapshot()
78}
79fn read_snapshot() -> Result<Snapshot> {
80    let root = user_config::root();
81    user_config::checked(&root.join(FILE)).map_err(anyhow::Error::msg)?;
82    let (document, revision) = read(&root)?;
83    Ok(Snapshot {
84        document,
85        revision,
86        defaults: default_instructions(),
87    })
88}
89pub fn load() -> Result<Snapshot> {
90    // Saves replace this small file atomically. Ordinary reads need not queue
91    // behind unrelated skill scans or Git network operations holding RepoLock.
92    // A restore moves the whole directory under a publication journal: check
93    // it around both reads so a transient missing file cannot become defaults
94    // if a complete publication happens between two checks.
95    let optimistic = || -> Result<Snapshot> {
96        user_config::ready().map_err(anyhow::Error::msg)?;
97        let before = read_snapshot()?;
98        user_config::ready().map_err(anyhow::Error::msg)?;
99        let after = read_snapshot()?;
100        user_config::ready().map_err(anyhow::Error::msg)?;
101        ensure!(
102            before.revision == after.revision,
103            "Agent launch settings changed while reading"
104        );
105        Ok(after)
106    };
107    if let Ok(snapshot) = optimistic() {
108        return Ok(snapshot);
109    }
110    // Contended publication, invalid data and recovery retain the existing
111    // serialized path and its errors. Writes always retain revision protection.
112    let _lock = RepoLock::acquire_foreground("read Agent launch settings")?;
113    load_unlocked()
114}
115/// Compare-and-replace; drafts from another window or a prior restore cannot overwrite edits.
116pub fn save(document: Document, expected_revision: &str) -> Result<Snapshot> {
117    let document = normalize(document)?;
118    let _lock = RepoLock::acquire_foreground("save Agent launch settings")?;
119    let current = load_unlocked()?;
120    ensure!(
121        current.revision == expected_revision,
122        "Agent launch settings changed; reload before saving. Your draft is preserved."
123    );
124    let root = user_config::ensure_root().map_err(anyhow::Error::msg)?;
125    let path = root.join(FILE);
126    let bytes = serde_json::to_vec_pretty(&document)?;
127    ensure!(
128        bytes.len() <= 1024 * 1024,
129        "Agent launch configuration is too large"
130    );
131    user_config::check_file(&path, bytes.len()).map_err(anyhow::Error::msg)?;
132    let mut staged = tempfile::NamedTempFile::new_in(&root)?;
133    staged.write_all(&bytes)?;
134    staged.as_file().sync_all()?;
135    user_config::checked(&path).map_err(anyhow::Error::msg)?;
136    if read(&root)?.1 != expected_revision {
137        bail!("Agent launch settings changed while saving; draft preserved")
138    }
139    staged.persist(&path).map_err(|e| e.error)?;
140    cloud_sync::notify_central_change();
141    load_unlocked()
142}
143pub fn resolve(agent: &str) -> Result<Launch> {
144    resolve_scheme(agent, None)
145}
146
147/// Resolve an optional stable scheme reference without changing global defaults.
148pub fn resolve_scheme(agent: &str, scheme_id: Option<&str>) -> Result<Launch> {
149    resolve_document(&load()?.document, agent, scheme_id)
150}