Skip to main content

acl_core/
registry.rs

1//! Local agent registry (spec roadmap): discovery for same-machine agents
2//! without a directory service. File-backed JSON at a caller-chosen path.
3
4use crate::AgentCard;
5use serde::{Deserialize, Serialize};
6use std::path::{Path, PathBuf};
7
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
9pub struct RegistryEntry {
10    pub name: String,
11    pub aid: String,
12    /// hex-encoded Ed25519 public key (32 bytes = 64 hex chars)
13    pub public_key: String,
14    pub capabilities: Vec<String>,
15    pub registered_at_ms: i64,
16}
17
18#[derive(Debug, Default, Serialize, Deserialize)]
19struct RegistryFile {
20    agents: Vec<RegistryEntry>,
21}
22
23#[derive(Debug)]
24pub struct Registry {
25    path: PathBuf,
26}
27
28impl Registry {
29    pub fn open(path: impl AsRef<Path>) -> Self {
30        Registry { path: path.as_ref().to_path_buf() }
31    }
32
33    fn load(&self) -> RegistryFile {
34        std::fs::read(&self.path)
35            .ok()
36            .and_then(|b| serde_json::from_slice(&b).ok())
37            .unwrap_or_default()
38    }
39
40    fn save(&self, f: &RegistryFile) -> Result<(), String> {
41        if let Some(parent) = self.path.parent() {
42            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
43        }
44        let json = serde_json::to_vec_pretty(f).map_err(|e| e.to_string())?;
45        std::fs::write(&self.path, json).map_err(|e| e.to_string())
46    }
47
48    pub fn register(&self, entry: RegistryEntry) -> Result<(), String> {
49        let mut f = self.load();
50        f.agents.retain(|a| a.name != entry.name);
51        f.agents.push(entry);
52        self.save(&f)
53    }
54
55    pub fn lookup(&self, name: &str) -> Option<RegistryEntry> {
56        self.load().agents.into_iter().find(|a| a.name == name)
57    }
58
59    pub fn by_capability(&self, cap: &str) -> Vec<RegistryEntry> {
60        self.load()
61            .agents
62            .into_iter()
63            .filter(|a| a.capabilities.iter().any(|c| c == cap))
64            .collect()
65    }
66
67    pub fn list(&self) -> Vec<RegistryEntry> {
68        self.load().agents
69    }
70
71    pub fn unregister(&self, name: &str) -> Result<bool, String> {
72        let mut f = self.load();
73        let before = f.agents.len();
74        f.agents.retain(|a| a.name != name);
75        let removed = f.agents.len() < before;
76        if removed {
77            self.save(&f)?;
78        }
79        Ok(removed)
80    }
81
82    // ------------------------------------------------ AgentCard integration
83
84    /// Build a registry entry from a signed AgentCard (§7). The card is the
85    /// source of truth: name, endpoint (as aid), capabilities, public key.
86    pub fn entry_from_card(card: &AgentCard) -> RegistryEntry {
87        RegistryEntry {
88            name: card.name.clone(),
89            aid: card.endpoint.0.clone(),
90            public_key: card
91                .public_key
92                .as_ref()
93                .map(|pk| pk.iter().map(|b| format!("{b:02x}")).collect::<String>())
94                .unwrap_or_default(),
95            capabilities: card.capabilities.iter().map(|c| c.name.clone()).collect(),
96            registered_at_ms: 0,
97        }
98    }
99
100    /// Register an agent directly from its AgentCard (replaces by name).
101    pub fn register_card(&self, card: &AgentCard) -> Result<(), String> {
102        self.register(Self::entry_from_card(card))
103    }
104
105    /// Discovery: agents with a capability, returned as best-effort
106    /// AgentCards reconstructed from the registry (public key restored
107    /// when present; signature NOT carried — verify at contact time).
108    pub fn discover_cards(&self, cap: &str) -> Vec<AgentCard> {
109        self.by_capability(cap)
110            .into_iter()
111            .map(|e| {
112                let pk = (0..e.public_key.len())
113                    .step_by(2)
114                    .filter_map(|i| e.public_key.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()))
115                    .collect::<Vec<u8>>();
116                AgentCard {
117                    name: e.name.clone(),
118                    version: "1".into(),
119                    description: format!("discovered via registry ({})", e.aid),
120                    endpoint: crate::Aid(e.aid.clone()),
121                    capabilities: e
122                        .capabilities
123                        .iter()
124                        .map(|c| crate::Capability {
125                            name: c.clone(),
126                            input_schema: None,
127                            output_schema: None,
128                            examples: None,
129                        })
130                        .collect(),
131                    auth_scheme: "ed25519".into(),
132                    key_id: None,
133                    public_key: if pk.len() == 32 { Some(pk) } else { None },
134                    rate_hint: None,
135                    valid_until: None,
136                    sig: None,
137                }
138            })
139            .collect()
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    fn tmp(name: &str) -> PathBuf {
148        let mut p = std::env::temp_dir();
149        p.push(format!("acl-registry-test-{}-{name}", std::process::id()));
150        let _ = std::fs::remove_file(&p);
151        p
152    }
153
154    fn entry(name: &str, caps: &[&str]) -> RegistryEntry {
155        RegistryEntry {
156            name: name.into(),
157            aid: format!("local:1:{name}"),
158            public_key: "ab".repeat(32),
159            capabilities: caps.iter().map(|s| s.to_string()).collect(),
160            registered_at_ms: 0,
161        }
162    }
163
164    #[test]
165    fn register_lookup_list_unregister() {
166        let path = tmp("a");
167        let r = Registry::open(&path);
168        r.register(entry("argus", &["log.watch"])).unwrap();
169        r.register(entry("kenji", &["code"])).unwrap();
170        assert_eq!(r.lookup("argus").unwrap().aid, "local:1:argus");
171        assert!(r.lookup("nope").is_none());
172        assert_eq!(r.list().len(), 2);
173        assert_eq!(r.by_capability("code").len(), 1);
174        assert!(r.unregister("argus").unwrap());
175        assert_eq!(r.list().len(), 1);
176        let _ = std::fs::remove_file(&path);
177    }
178
179    #[test]
180    fn re_register_replaces() {
181        let path = tmp("b");
182        let r = Registry::open(&path);
183        r.register(entry("kenji", &["code"])).unwrap();
184        let mut e2 = entry("kenji", &["code", "review"]);
185        e2.aid = "local:2:kenji".into();
186        r.register(e2).unwrap();
187        assert_eq!(r.list().len(), 1);
188        assert_eq!(r.lookup("kenji").unwrap().aid, "local:2:kenji");
189        let _ = std::fs::remove_file(&path);
190    }
191
192    #[test]
193    fn register_card_and_discover() {
194        use crate::Capability;
195        let path = tmp("d");
196        let r = Registry::open(&path);
197        let card = AgentCard {
198            name: "argus".into(),
199            version: "1.0".into(),
200            description: "watcher".into(),
201            endpoint: crate::Aid::new("http://127.0.0.1:9200"),
202            capabilities: vec![Capability {
203                name: "log.watch".into(),
204                input_schema: Some(serde_json::json!({"type": "object"})),
205                output_schema: None,
206                examples: None,
207            }],
208            auth_scheme: "ed25519".into(),
209            key_id: None,
210            public_key: Some((0u8..32).collect()),
211            rate_hint: None,
212            valid_until: None,
213            sig: None,
214        };
215        r.register_card(&card).unwrap();
216        assert_eq!(r.lookup("argus").unwrap().capabilities, vec!["log.watch"]);
217        // discovery by capability returns reconstructed cards
218        let found = r.discover_cards("log.watch");
219        assert_eq!(found.len(), 1);
220        assert_eq!(found[0].name, "argus");
221        assert_eq!(found[0].capabilities[0].name, "log.watch");
222        assert!(found[0].public_key.is_some());
223        // no capability match -> empty
224        assert!(r.discover_cards("nope").is_empty());
225        let _ = std::fs::remove_file(&path);
226    }
227
228    #[test]
229    fn persists_across_instances() {
230        let path = tmp("c");
231        Registry::open(&path).register(entry("balboa", &["run"])).unwrap();
232        let r2 = Registry::open(&path);
233        assert!(r2.lookup("balboa").is_some());
234        let _ = std::fs::remove_file(&path);
235    }
236}