File size: 6,573 Bytes
afa0cbf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;
use ts_rs::TS;
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema, TS,
)]
#[serde(try_from = "String", into = "String")]
#[schemars(with = "String")]
#[ts(type = "string")]
pub struct AgentPath(String);
impl AgentPath {
pub const ROOT: &str = "/root";
pub const MORPHEUS: &str = "/morpheus";
const ROOT_SEGMENT: &str = "root";
pub fn root() -> Self {
Self(Self::ROOT.to_string())
}
pub fn morpheus() -> Self {
Self(Self::MORPHEUS.to_string())
}
pub fn from_string(path: String) -> Result<Self, String> {
validate_absolute_path(path.as_str())?;
Ok(Self(path))
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
pub fn is_root(&self) -> bool {
self.as_str() == Self::ROOT
}
pub fn name(&self) -> &str {
if self.is_root() {
return Self::ROOT_SEGMENT;
}
self.as_str()
.rsplit('/')
.next()
.filter(|segment| !segment.is_empty())
.unwrap_or(Self::ROOT_SEGMENT)
}
pub fn join(&self, agent_name: &str) -> Result<Self, String> {
validate_agent_name(agent_name)?;
Self::from_string(format!("{self}/{agent_name}"))
}
pub fn resolve(&self, reference: &str) -> Result<Self, String> {
if reference.is_empty() {
return Err("agent path must not be empty".to_string());
}
if reference == Self::ROOT {
return Ok(Self::root());
}
if reference.starts_with('/') {
return Self::try_from(reference);
}
validate_relative_reference(reference)?;
Self::from_string(format!("{self}/{reference}"))
}
}
impl TryFrom<String> for AgentPath {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_string(value)
}
}
impl TryFrom<&str> for AgentPath {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_string(value.to_string())
}
}
impl From<AgentPath> for String {
fn from(value: AgentPath) -> Self {
value.0
}
}
impl FromStr for AgentPath {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl AsRef<str> for AgentPath {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Deref for AgentPath {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl fmt::Display for AgentPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
fn validate_agent_name(agent_name: &str) -> Result<(), String> {
if agent_name.is_empty() {
return Err("agent_name must not be empty".to_string());
}
if agent_name == AgentPath::ROOT_SEGMENT {
return Err("agent_name `root` is reserved".to_string());
}
if agent_name == "." || agent_name == ".." {
return Err(format!("agent_name `{agent_name}` is reserved"));
}
if agent_name.contains('/') {
return Err("agent_name must not contain `/`".to_string());
}
if !agent_name
.chars()
.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
{
return Err(
"agent_name must use only lowercase letters, digits, and underscores".to_string(),
);
}
Ok(())
}
fn validate_absolute_path(path: &str) -> Result<(), String> {
if path == AgentPath::MORPHEUS {
return Ok(());
}
let Some(stripped) = path.strip_prefix('/') else {
return Err("absolute agent paths must start with `/root` or be `/morpheus`".to_string());
};
let mut segments = stripped.split('/');
let Some(root) = segments.next() else {
return Err("absolute agent path must not be empty".to_string());
};
if root != AgentPath::ROOT_SEGMENT {
return Err("absolute agent paths must start with `/root` or be `/morpheus`".to_string());
}
if stripped.ends_with('/') {
return Err("absolute agent path must not end with `/`".to_string());
}
for segment in segments {
validate_agent_name(segment)?;
}
Ok(())
}
fn validate_relative_reference(reference: &str) -> Result<(), String> {
if reference.ends_with('/') {
return Err("relative agent path must not end with `/`".to_string());
}
for segment in reference.split('/') {
validate_agent_name(segment)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::AgentPath;
use pretty_assertions::assert_eq;
#[test]
fn root_has_expected_name() {
let root = AgentPath::root();
assert_eq!(root.as_str(), AgentPath::ROOT);
assert_eq!(root.name(), "root");
assert!(root.is_root());
}
#[test]
fn morpheus_has_expected_name() {
let morpheus = AgentPath::morpheus();
assert_eq!(morpheus.as_str(), AgentPath::MORPHEUS);
assert_eq!(morpheus.name(), "morpheus");
assert!(!morpheus.is_root());
}
#[test]
fn join_builds_child_paths() {
let root = AgentPath::root();
let child = root.join("researcher").expect("child path");
assert_eq!(child.as_str(), "/root/researcher");
assert_eq!(child.name(), "researcher");
}
#[test]
fn resolve_supports_relative_and_absolute_references() {
let current = AgentPath::try_from("/root/researcher").expect("path");
assert_eq!(
current.resolve("worker").expect("relative path"),
AgentPath::try_from("/root/researcher/worker").expect("path")
);
assert_eq!(
current.resolve("/root/other").expect("absolute path"),
AgentPath::try_from("/root/other").expect("path")
);
}
#[test]
fn invalid_names_and_paths_are_rejected() {
assert_eq!(
AgentPath::root().join("BadName"),
Err("agent_name must use only lowercase letters, digits, and underscores".to_string())
);
assert_eq!(
AgentPath::try_from("/not-root"),
Err("absolute agent paths must start with `/root` or be `/morpheus`".to_string())
);
assert_eq!(
AgentPath::root().resolve("../sibling"),
Err("agent_name `..` is reserved".to_string())
);
}
}
|