Skip to main content

agent_models/registry/
registry.rs

1use crate::{
2    client::ConversationClient,
3    error::ModelError,
4    models::ModelCapability,
5    providers::{GeminiClient, OpenAICompatibleClient},
6};
7use agent_config::{ConfigError, read_toml_dir};
8use std::{collections::BTreeMap, path::Path, sync::Arc};
9
10use super::provider_config::ProviderConfig;
11
12/// Credential-free metadata for a configured provider and its models.
13#[derive(Debug, Clone, serde::Serialize)]
14pub struct ProviderInfo {
15    pub name: String,
16    pub client: String,
17    pub models: Vec<ProviderModelInfo>,
18}
19
20#[derive(Debug, Clone, serde::Serialize)]
21pub struct ProviderModelInfo {
22    pub name: String,
23    pub capabilities: Vec<ModelCapability>,
24}
25
26pub struct Registry {
27    providers: BTreeMap<String, ProviderConfig>,
28}
29
30impl Registry {
31    pub fn load(data_dir: impl AsRef<Path>) -> Result<Self, ConfigError> {
32        let providers_dir = data_dir.as_ref().join("providers");
33        let loaded = read_toml_dir::<ProviderConfig>(&providers_dir)?;
34
35        if loaded.is_empty() {
36            return Err(ConfigError::no_files("provider", providers_dir));
37        }
38
39        let mut providers = BTreeMap::new();
40
41        for (path, config) in loaded {
42            config.validate(&path)?;
43            let name = config.name.clone();
44
45            if providers.insert(name.clone(), config).is_some() {
46                return Err(ConfigError::duplicate("provider", name, Some(path)));
47            }
48        }
49
50        Ok(Self { providers })
51    }
52
53    /// Returns the validated provider/model metadata without exposing credentials.
54    pub fn catalog(&self) -> Vec<ProviderInfo> {
55        self.providers
56            .values()
57            .map(|provider| ProviderInfo {
58                name: provider.name.clone(),
59                client: provider.client.clone(),
60                models: provider
61                    .models
62                    .iter()
63                    .map(|model| ProviderModelInfo {
64                        name: model.name.clone(),
65                        capabilities: model.capabilities.clone(),
66                    })
67                    .collect(),
68            })
69            .collect()
70    }
71
72    /// Returns whether a provider/model pair is declared in the loaded configuration.
73    ///
74    /// This check does not read credentials or construct a provider client.
75    pub fn contains_model(&self, model_name: &str) -> bool {
76        let Some((provider_name, model_name)) = model_name.split_once('/') else {
77            return false;
78        };
79
80        if provider_name.is_empty() || model_name.is_empty() {
81            return false;
82        }
83
84        self.providers
85            .get(provider_name)
86            .is_some_and(|provider| provider.models.iter().any(|model| model.name == model_name))
87    }
88
89    /// Returns whether one configured model provides every requested capability.
90    ///
91    /// Provider names are traversed in `BTreeMap` order and models in their TOML
92    /// declaration order, so the first compatible model is deterministic. This
93    /// metadata-only query does not read credentials or contact providers.
94    pub fn contains_compatible_model(&self, required: &[ModelCapability]) -> bool {
95        self.first_compatible_model(required).is_some()
96    }
97
98    /// Returns every configured model that provides all requested capabilities.
99    ///
100    /// Provider names are traversed in `BTreeMap` order and models in their TOML
101    /// declaration order. The result is therefore deterministic and provider-qualified.
102    /// This metadata-only query does not read credentials or contact providers.
103    pub fn compatible_models(&self, required: &[ModelCapability]) -> Vec<String> {
104        if required.is_empty() {
105            return Vec::new();
106        }
107
108        self.providers
109            .iter()
110            .flat_map(|(provider_name, provider)| {
111                provider
112                    .models
113                    .iter()
114                    .filter(move |model| {
115                        required
116                            .iter()
117                            .all(|capability| model.capabilities.contains(capability))
118                    })
119                    .map(move |model| format!("{provider_name}/{}", model.name))
120            })
121            .collect()
122    }
123
124    /// Finds the first configured model that provides every requested capability.
125    ///
126    /// This is a convenience wrapper around deterministic candidate enumeration.
127    pub fn first_compatible_model(&self, required: &[ModelCapability]) -> Option<String> {
128        self.compatible_models(required).into_iter().next()
129    }
130
131    pub fn resolve_model(
132        &self,
133        model_name: &str,
134    ) -> Result<Arc<dyn ConversationClient>, ModelError> {
135        let (provider_name, model) = model_name
136            .split_once('/')
137            .ok_or_else(|| ModelError::InvalidModelName(model_name.to_string()))?;
138
139        let provider = self
140            .providers
141            .get(provider_name)
142            .ok_or_else(|| ModelError::UnsupportedProvider(provider_name.to_string()))?;
143
144        if !provider.models.iter().any(|m| m.name == model) {
145            return Err(ModelError::UnsupportedModel(format!(
146                "{provider_name}/{model}"
147            )));
148        }
149
150        let key = std::env::var(&provider.api_key_env)
151            .map_err(|_| ModelError::MissingApiKey(provider.api_key_env.clone()))?;
152
153        match provider.client.as_str() {
154            "gemini" => Ok(Arc::new(GeminiClient::new(key, model))),
155            "openai-compatible" => {
156                let base_url = match (&provider.account_id_env, &provider.base_url) {
157                    (Some(account_id_env), Some(url)) => {
158                        let account_id = std::env::var(account_id_env)
159                            .map_err(|_| ModelError::MissingApiKey(account_id_env.clone()))?;
160                        url.replace("{account_id}", &account_id)
161                    }
162                    (None, Some(url)) => url.clone(),
163                    _ => return Err(ModelError::UnsupportedProvider(provider.name.clone())),
164                };
165
166                Ok(Arc::new(OpenAICompatibleClient::new(&base_url, key, model)))
167            }
168            _ => Err(ModelError::UnsupportedProvider(provider.client.clone())),
169        }
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use std::{
176        fs,
177        path::{Path, PathBuf},
178        sync::atomic::{AtomicUsize, Ordering},
179    };
180
181    use super::Registry;
182    use crate::{error::ModelError, models::ModelCapability};
183    use agent_config::ConfigError;
184
185    struct TestDirectory(PathBuf);
186
187    impl TestDirectory {
188        fn new() -> Self {
189            static NEXT: AtomicUsize = AtomicUsize::new(0);
190            let path = std::env::temp_dir().join(format!(
191                "provider-registry-test-{}-{}",
192                std::process::id(),
193                NEXT.fetch_add(1, Ordering::Relaxed)
194            ));
195            fs::create_dir_all(&path).unwrap();
196            Self(path)
197        }
198
199        fn case(&self, name: &str) -> PathBuf {
200            let path = self.0.join(name);
201            fs::create_dir_all(path.join("providers")).unwrap();
202            path
203        }
204    }
205
206    impl Drop for TestDirectory {
207        fn drop(&mut self) {
208            let _ = fs::remove_dir_all(&self.0);
209        }
210    }
211
212    fn write_provider(root: &Path, file: &str, name: &str, client: &str) {
213        fs::write(
214            root.join("providers").join(file),
215            format!(
216                r#"
217name = "{name}"
218client = "{client}"
219api_key_env = "TEST_API_KEY"
220
221[[models]]
222name = "test-model"
223capabilities = ["chat"]
224"#
225            ),
226        )
227        .unwrap();
228    }
229
230    #[test]
231    fn loads_valid_providers_and_rejects_invalid_registry_configuration() {
232        let directory = TestDirectory::new();
233
234        // Valid provider configuration: model lookup must not require credentials.
235        let valid = directory.case("valid");
236        write_provider(&valid, "provider.toml", "test", "gemini");
237        let registry = Registry::load(&valid).unwrap();
238        assert!(registry.contains_model("test/test-model"));
239        assert!(!registry.contains_model("test/missing-model"));
240        assert!(registry.contains_compatible_model(&[ModelCapability::Chat]));
241        assert_eq!(
242            registry.compatible_models(&[ModelCapability::Chat]),
243            vec!["test/test-model"]
244        );
245        assert_eq!(
246            registry
247                .first_compatible_model(&[ModelCapability::Chat])
248                .as_deref(),
249            Some("test/test-model")
250        );
251        assert!(!registry.contains_compatible_model(&[ModelCapability::Reasoning]));
252        assert_eq!(registry.first_compatible_model(&[]), None);
253
254        // Candidate ordering is stable across provider files and independent
255        // of the order in which those files are discovered.
256        let ordered = directory.case("ordered");
257        write_provider(&ordered, "z.toml", "zeta", "gemini");
258        write_provider(&ordered, "a.toml", "alpha", "gemini");
259        let ordered_registry = Registry::load(&ordered).unwrap();
260        assert_eq!(
261            ordered_registry.compatible_models(&[ModelCapability::Chat]),
262            vec!["alpha/test-model", "zeta/test-model"]
263        );
264
265        // Duplicate provider identifiers are rejected across files.
266        let duplicate = directory.case("duplicate");
267        write_provider(&duplicate, "a.toml", "same", "gemini");
268        write_provider(&duplicate, "b.toml", "same", "gemini");
269        assert!(matches!(
270            Registry::load(&duplicate),
271            Err(ConfigError::Duplicate { .. })
272        ));
273
274        // Unsupported provider clients are invalid definitions.
275        let invalid = directory.case("invalid");
276        write_provider(&invalid, "provider.toml", "test", "unsupported");
277        assert!(matches!(
278            Registry::load(&invalid),
279            Err(ConfigError::Invalid { .. })
280        ));
281
282        // A missing providers directory is reported as a filesystem error.
283        assert!(matches!(
284            Registry::load(directory.0.join("missing")),
285            Err(ConfigError::Io { .. })
286        ));
287
288        // Resolving a declared model still distinguishes missing credentials.
289        assert!(matches!(
290            registry.resolve_model("test/test-model"),
291            Err(ModelError::MissingApiKey(_))
292        ));
293    }
294}