use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum AttachmentReference {
Managed {
authority: String,
origin: String,
agent_id: String,
},
Native {
destination: Destination,
harness: String,
state_scope: String,
conversation_id: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Destination {
Local,
Ssh { target: String },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CommandSpec {
pub program: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum AttachmentPlan {
LocalProcess {
program: String,
#[serde(default)]
args: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cwd: Option<String>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
pub enum Observation {
Attachable { plan: AttachmentPlan },
ResumeRequired { reason: String },
Unreachable { reason: String },
OwnershipConflict { reason: String },
Uncertain { reason: String },
Deleted { reason: String },
Unsupported { reason: String },
Unavailable { reason: String },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AttachmentResolution {
pub version: u32,
pub target: AttachmentReference,
pub observation: Observation,
}
pub fn validate_text(value: &str) -> Result<()> {
if value.contains(';') || value.chars().any(char::is_control) {
bail!("field contains a Terminal action separator or control character");
}
Ok(())
}
fn identity(value: &str) -> Result<()> {
validate_text(value)?;
if value.trim().is_empty() || value.chars().any(char::is_control) {
bail!("identity must be nonempty and contain no control characters");
}
Ok(())
}
impl AttachmentReference {
pub fn validate(&self) -> Result<()> {
match self {
Self::Managed {
authority,
origin,
agent_id,
} => {
identity(authority)?;
identity(agent_id)?;
validate_text(origin)?;
let url = url::Url::parse(origin)
.map_err(|_| anyhow::anyhow!("invalid managed origin"))?;
if !matches!(url.scheme(), "http" | "https")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
bail!("managed origin must be HTTP(S) without credentials, query, or fragment");
}
}
Self::Native {
destination,
harness,
state_scope,
conversation_id,
} => {
identity(harness)?;
identity(state_scope)?;
identity(conversation_id)?;
if let Destination::Ssh { target } = destination
&& (target.is_empty()
|| target.starts_with('-')
|| !target
.chars()
.all(|c| c.is_ascii_alphanumeric() || "._:@%+-[]".contains(c)))
{
bail!("invalid SSH destination");
}
}
}
Ok(())
}
}
impl CommandSpec {
pub fn validate(&self) -> Result<()> {
if self.program.trim().is_empty() || self.program.starts_with('-') {
bail!("command needs an executable");
}
for value in std::iter::once(&self.program)
.chain(self.args.iter())
.chain(self.cwd.iter())
{
validate_text(value)?;
}
Ok(())
}
}
impl AttachmentPlan {
pub fn command(&self) -> CommandSpec {
match self {
Self::LocalProcess { program, args, cwd } => CommandSpec {
program: program.clone(),
args: args.clone(),
cwd: cwd.clone(),
},
}
}
}
impl Observation {
pub fn state(&self) -> &'static str {
match self {
Self::Attachable { .. } => "attachable",
Self::ResumeRequired { .. } => "resume_required",
Self::Unreachable { .. } => "unreachable",
Self::OwnershipConflict { .. } => "ownership_conflict",
Self::Uncertain { .. } => "uncertain",
Self::Deleted { .. } => "deleted",
Self::Unsupported { .. } => "unsupported",
Self::Unavailable { .. } => "unavailable",
}
}
pub fn reason(&self) -> Option<&str> {
match self {
Self::Attachable { .. } => None,
Self::ResumeRequired { reason }
| Self::Unreachable { reason }
| Self::OwnershipConflict { reason }
| Self::Uncertain { reason }
| Self::Deleted { reason }
| Self::Unsupported { reason }
| Self::Unavailable { reason } => Some(reason),
}
}
}
impl AttachmentResolution {
pub fn validate_for(&self, requested: &AttachmentReference) -> Result<()> {
if self.version != 1 {
bail!("unsupported attachment resolution version");
}
self.target.validate()?;
if &self.target != requested {
bail!("resolver returned a different target");
}
if let Observation::Attachable { plan } = &self.observation {
plan.command().validate()?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_secret_origins_and_invalid_native_destinations() {
for origin in [
"https://user:password@host",
"https://host?tkn=secret",
"file:///tmp/agent",
] {
assert!(
AttachmentReference::Managed {
authority: "pulse-agents".into(),
origin: origin.into(),
agent_id: "a".into()
}
.validate()
.is_err()
);
}
assert!(
AttachmentReference::Native {
destination: Destination::Ssh {
target: "-oProxyCommand=bad".into()
},
harness: "codex".into(),
state_scope: "home".into(),
conversation_id: "thread".into()
}
.validate()
.is_err()
);
}
#[test]
fn blocked_state_cannot_contain_a_plan() {
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":[]}}});
assert!(serde_json::from_value::<AttachmentResolution>(value).is_err());
}
}