Skip to main content

agent_hub_core/
agent_launch.rs

1//! Portable Agent launch scheme validation and command resolution.
2use anyhow::{ensure, Context, Result};
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5use std::collections::BTreeMap;
6
7mod defaults;
8mod schemes;
9
10pub use defaults::{instructions as default_instructions, key_for_kind, kind_for_key};
11pub use schemes::{normalize, AgentSchemes, LaunchScheme};
12
13#[cfg(test)]
14mod tests;
15
16#[derive(Clone, Debug, Serialize, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct Document {
19    pub schema_version: u32,
20    pub default_agent: String,
21    /// Legacy input only; normalize consumes it before persistence or resolution.
22    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
23    pub instructions: BTreeMap<String, String>,
24    #[serde(default)]
25    pub schemes: BTreeMap<String, AgentSchemes>,
26}
27impl Default for Document {
28    fn default() -> Self {
29        Self {
30            schema_version: 2,
31            default_agent: "codex".into(),
32            instructions: BTreeMap::new(),
33            schemes: BTreeMap::new(),
34        }
35    }
36}
37#[derive(Clone, Debug, Serialize)]
38pub struct Launch {
39    pub key: String,
40    pub kind: Option<String>,
41    pub program: String,
42    pub arguments: Vec<String>,
43}
44
45fn valid_key(key: &str) -> bool {
46    !key.is_empty()
47        && key.len() <= 128
48        && key
49            .bytes()
50            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
51}
52/// A command is argv, not a shell program. Quote paths/arguments containing spaces.
53/// Parsing never expands environment variables, command substitutions or pipelines.
54pub fn parse(instruction: &str) -> Result<(String, Vec<String>)> {
55    ensure!(
56        !instruction.is_empty()
57            && instruction.len() <= 8192
58            && !instruction.chars().any(char::is_control),
59        "Enter a single launch instruction up to 8 KiB"
60    );
61    let mut words = shell_words::split(instruction)
62        .context("Launch instruction has unclosed quotes")?
63        .into_iter();
64    let program = words
65        .next()
66        .filter(|s| !s.is_empty() && !s.starts_with('-'))
67        .context("Enter an Agent executable")?;
68    Ok((program, words.collect()))
69}
70/// Resolve and validate an Agent identifier using the configured default when requested.
71pub fn agent_key<'a>(document: &'a Document, agent: &'a str) -> Result<&'a str> {
72    let key = key_for_kind(if agent == "default" {
73        &document.default_agent
74    } else {
75        agent
76    });
77    ensure!(valid_key(key), "Invalid Agent key");
78    Ok(key)
79}
80
81/// Resolve a normalized launch configuration to an executable and its arguments.
82/// Use [normalize] before resolving a configuration read from external input.
83pub fn resolve_document(
84    document: &Document,
85    agent: &str,
86    scheme_id: Option<&str>,
87) -> Result<Launch> {
88    ensure!(
89        document.schema_version == 2 && document.instructions.is_empty(),
90        "Normalize the Agent launch configuration before resolving a scheme"
91    );
92    let key = agent_key(document, agent)?;
93    let requested = scheme_id.filter(|id| !id.is_empty());
94    let defaults = defaults::instructions();
95    let instruction = if let Some(schemes) = document.schemes.get(key) {
96        let selected = requested.unwrap_or(&schemes.default_id);
97        &schemes
98            .items
99            .iter()
100            .find(|scheme| scheme.id == selected)
101            .context("Selected Agent launch scheme is no longer available; choose another scheme")?
102            .instruction
103    } else {
104        ensure!(
105            requested.map_or(true, |id| id == "default"),
106            "Selected Agent launch scheme is no longer available; choose another scheme"
107        );
108        defaults.get(key).map(String::as_str).unwrap_or(key)
109    };
110    let (mut program, arguments) = parse(instruction)?;
111    if let Some(suffix) = program.strip_prefix("~/") {
112        program = dirs::home_dir()
113            .context("Cannot resolve home directory")?
114            .join(suffix)
115            .to_string_lossy()
116            .into();
117    }
118    Ok(Launch {
119        key: key.into(),
120        kind: kind_for_key(key).map(str::to_string),
121        program,
122        arguments,
123    })
124}
125
126/// Detect changes between a managed runner's resolve and start calls.
127pub fn plan_fingerprint(launch: &Launch) -> Result<String> {
128    Ok(hex::encode(Sha256::digest(serde_json::to_vec(launch)?)))
129}
130
131pub fn verify_plan(launch: &Launch, expected: Option<&str>) -> Result<()> {
132    if let Some(expected) = expected {
133        ensure!(
134            plan_fingerprint(launch)? == expected,
135            "Agent launch scheme changed before startup; retry with the current settings"
136        );
137    }
138    Ok(())
139}