Skip to main content

agent_attachment_protocol/
lib.rs

1use anyhow::{Result, bail};
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
5#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
6pub enum AttachmentReference {
7    Managed {
8        authority: String,
9        origin: String,
10        agent_id: String,
11    },
12    Native {
13        destination: Destination,
14        harness: String,
15        state_scope: String,
16        conversation_id: String,
17    },
18}
19
20#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
22pub enum Destination {
23    Local,
24    Ssh { target: String },
25}
26
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct CommandSpec {
30    pub program: String,
31    #[serde(default)]
32    pub args: Vec<String>,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub cwd: Option<String>,
35}
36
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
39pub enum AttachmentPlan {
40    LocalProcess {
41        program: String,
42        #[serde(default)]
43        args: Vec<String>,
44        #[serde(default, skip_serializing_if = "Option::is_none")]
45        cwd: Option<String>,
46    },
47}
48
49#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
51pub enum Observation {
52    Attachable { plan: AttachmentPlan },
53    ResumeRequired { reason: String },
54    Unreachable { reason: String },
55    OwnershipConflict { reason: String },
56    Uncertain { reason: String },
57    Deleted { reason: String },
58    Unsupported { reason: String },
59    Unavailable { reason: String },
60}
61
62#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct AttachmentResolution {
65    pub version: u32,
66    pub target: AttachmentReference,
67    pub observation: Observation,
68}
69
70pub fn validate_text(value: &str) -> Result<()> {
71    if value.contains(';') || value.chars().any(char::is_control) {
72        bail!("field contains a Terminal action separator or control character");
73    }
74    Ok(())
75}
76
77fn identity(value: &str) -> Result<()> {
78    validate_text(value)?;
79    if value.trim().is_empty() || value.chars().any(char::is_control) {
80        bail!("identity must be nonempty and contain no control characters");
81    }
82    Ok(())
83}
84
85impl AttachmentReference {
86    pub fn validate(&self) -> Result<()> {
87        match self {
88            Self::Managed {
89                authority,
90                origin,
91                agent_id,
92            } => {
93                identity(authority)?;
94                identity(agent_id)?;
95                validate_text(origin)?;
96                let url = url::Url::parse(origin)
97                    .map_err(|_| anyhow::anyhow!("invalid managed origin"))?;
98                if !matches!(url.scheme(), "http" | "https")
99                    || url.host_str().is_none()
100                    || !url.username().is_empty()
101                    || url.password().is_some()
102                    || url.query().is_some()
103                    || url.fragment().is_some()
104                {
105                    bail!("managed origin must be HTTP(S) without credentials, query, or fragment");
106                }
107            }
108            Self::Native {
109                destination,
110                harness,
111                state_scope,
112                conversation_id,
113            } => {
114                identity(harness)?;
115                identity(state_scope)?;
116                identity(conversation_id)?;
117                if let Destination::Ssh { target } = destination
118                    && (target.is_empty()
119                        || target.starts_with('-')
120                        || !target
121                            .chars()
122                            .all(|c| c.is_ascii_alphanumeric() || "._:@%+-[]".contains(c)))
123                {
124                    bail!("invalid SSH destination");
125                }
126            }
127        }
128        Ok(())
129    }
130}
131
132impl CommandSpec {
133    pub fn validate(&self) -> Result<()> {
134        if self.program.trim().is_empty() || self.program.starts_with('-') {
135            bail!("command needs an executable");
136        }
137        for value in std::iter::once(&self.program)
138            .chain(self.args.iter())
139            .chain(self.cwd.iter())
140        {
141            validate_text(value)?;
142        }
143        Ok(())
144    }
145}
146
147impl AttachmentPlan {
148    pub fn command(&self) -> CommandSpec {
149        match self {
150            Self::LocalProcess { program, args, cwd } => CommandSpec {
151                program: program.clone(),
152                args: args.clone(),
153                cwd: cwd.clone(),
154            },
155        }
156    }
157}
158
159impl Observation {
160    pub fn state(&self) -> &'static str {
161        match self {
162            Self::Attachable { .. } => "attachable",
163            Self::ResumeRequired { .. } => "resume_required",
164            Self::Unreachable { .. } => "unreachable",
165            Self::OwnershipConflict { .. } => "ownership_conflict",
166            Self::Uncertain { .. } => "uncertain",
167            Self::Deleted { .. } => "deleted",
168            Self::Unsupported { .. } => "unsupported",
169            Self::Unavailable { .. } => "unavailable",
170        }
171    }
172    pub fn reason(&self) -> Option<&str> {
173        match self {
174            Self::Attachable { .. } => None,
175            Self::ResumeRequired { reason }
176            | Self::Unreachable { reason }
177            | Self::OwnershipConflict { reason }
178            | Self::Uncertain { reason }
179            | Self::Deleted { reason }
180            | Self::Unsupported { reason }
181            | Self::Unavailable { reason } => Some(reason),
182        }
183    }
184}
185
186impl AttachmentResolution {
187    pub fn validate_for(&self, requested: &AttachmentReference) -> Result<()> {
188        if self.version != 1 {
189            bail!("unsupported attachment resolution version");
190        }
191        self.target.validate()?;
192        if &self.target != requested {
193            bail!("resolver returned a different target");
194        }
195        if let Observation::Attachable { plan } = &self.observation {
196            plan.command().validate()?;
197        }
198        Ok(())
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    #[test]
206    fn rejects_secret_origins_and_invalid_native_destinations() {
207        for origin in [
208            "https://user:password@host",
209            "https://host?tkn=secret",
210            "file:///tmp/agent",
211        ] {
212            assert!(
213                AttachmentReference::Managed {
214                    authority: "pulse-agents".into(),
215                    origin: origin.into(),
216                    agent_id: "a".into()
217                }
218                .validate()
219                .is_err()
220            );
221        }
222        assert!(
223            AttachmentReference::Native {
224                destination: Destination::Ssh {
225                    target: "-oProxyCommand=bad".into()
226                },
227                harness: "codex".into(),
228                state_scope: "home".into(),
229                conversation_id: "thread".into()
230            }
231            .validate()
232            .is_err()
233        );
234    }
235    #[test]
236    fn blocked_state_cannot_contain_a_plan() {
237        let value = serde_json::json!({"version":1,"target":{"kind":"managed","authority":"pulse-agents","origin":"https://host","agent_id":"a"},"observation":{"state":"deleted","reason":"gone","plan":{"kind":"local_process","program":"bad","args":[]}}});
238        assert!(serde_json::from_value::<AttachmentResolution>(value).is_err());
239    }
240}