strands_agents/
identifier.rs

1//! Strands identifier utilities.
2
3use std::path::Path;
4
5/// Strands identifier types.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Identifier {
8    Agent,
9    Session,
10}
11
12impl Identifier {
13    /// Returns the string value of the identifier type.
14    pub fn value(&self) -> &'static str {
15        match self {
16            Identifier::Agent => "agent",
17            Identifier::Session => "session",
18        }
19    }
20}
21
22impl std::fmt::Display for Identifier {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "{}", self.value())
25    }
26}
27
28/// Validate strands id.
29///
30/// # Arguments
31///
32/// * `id` - Id to validate.
33/// * `type_` - Type of the identifier (e.g., session id, agent id, etc.)
34///
35/// # Returns
36///
37/// Validated id.
38///
39/// # Errors
40///
41/// Returns an error if the id contains path separators.
42pub fn validate(id: &str, type_: Identifier) -> Result<&str, String> {
43
44    let filename = Path::new(id)
45        .file_name()
46        .and_then(|f| f.to_str())
47        .unwrap_or("");
48
49    if filename != id {
50        return Err(format!(
51            "{}_id={} | id cannot contain path separators",
52            type_.value(),
53            id
54        ));
55    }
56
57    Ok(id)
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_validate_valid_id() {
66        assert_eq!(validate("my-agent", Identifier::Agent).unwrap(), "my-agent");
67        assert_eq!(validate("session123", Identifier::Session).unwrap(), "session123");
68    }
69
70    #[test]
71    fn test_validate_invalid_id_with_path_separator() {
72        assert!(validate("a/b", Identifier::Agent).is_err());
73        assert!(validate("path/to/session", Identifier::Session).is_err());
74    }
75
76    #[test]
77    fn test_identifier_display() {
78        assert_eq!(Identifier::Agent.to_string(), "agent");
79        assert_eq!(Identifier::Session.to_string(), "session");
80    }
81}
82