Skip to main content

artifactize_core/llm/
models.rs

1use std::{path::Path, time::Duration};
2
3use rig_core::providers::{anthropic, gemini, openai};
4use serde::Serialize;
5
6use super::Api;
7use crate::config::Backend;
8
9/// Model discovery is interactive metadata, not a review; stop a stalled listing
10/// after thirty seconds for both API-key backends and the Codex account endpoint.
11pub(super) const LIST_TIMEOUT: Duration = Duration::from_secs(30);
12
13#[derive(Serialize)]
14pub struct ListedModel {
15    pub slug: crate::config::ModelId,
16    pub display_name: String,
17    pub efforts: Vec<String>,
18    pub default_effort: Option<String>,
19}
20
21impl ListedModel {
22    pub(super) fn new(slug: crate::config::ModelId, display_name: String) -> Self {
23        Self {
24            slug,
25            display_name,
26            efforts: Vec::new(),
27            default_effort: None,
28        }
29    }
30
31    pub(super) fn with_efforts(
32        mut self,
33        efforts: impl IntoIterator<Item = String>,
34        default: Option<String>,
35    ) -> Self {
36        for effort in efforts {
37            if !effort.is_empty() && !self.efforts.contains(&effort) {
38                self.efforts.push(effort);
39            }
40        }
41        // The picker and new sessions share one order: a provider's declared default
42        // first, otherwise the first advertised level is the starting choice.
43        if let Some(index) =
44            default.and_then(|default| self.efforts.iter().position(|effort| *effort == default))
45        {
46            let default = self.efforts.remove(index);
47            self.efforts.insert(0, default);
48        }
49        self.default_effort = self.efforts.first().cloned();
50        self
51    }
52}
53
54#[derive(Serialize)]
55pub struct Listing {
56    pub backend: Backend,
57    pub models: Vec<ListedModel>,
58}
59
60/// The result a model menu renders. Absence of setup is not a failed listing.
61pub enum Availability {
62    Models(Vec<ListedModel>),
63    NotSetUp {
64        reason: String,
65    },
66    Failed {
67        error: String,
68    },
69    CliMissing {
70        reason: String,
71    },
72    CliTooOld {
73        version: semver::Version,
74        required_version: semver::Version,
75        error: String,
76    },
77}
78
79impl Availability {
80    fn listed(listing: Result<Vec<ListedModel>, String>) -> Self {
81        match listing {
82            Ok(models) => Self::Models(models),
83            Err(error) => Self::Failed { error },
84        }
85    }
86}
87
88/// Discover models and classify setup failures at the native provider boundary.
89pub async fn availability(
90    backend: Backend,
91    state: Option<&Path>,
92    repo: Option<&Path>,
93) -> Availability {
94    use super::Route;
95    use crate::auth::{antigravity, claude_agent, codex};
96    use Availability::*;
97    let route = match super::route(&backend, state, repo, "to list models") {
98        Ok(route) => route,
99        Err(failure) if failure.code == crate::agent::error::Code::Authentication => {
100            return NotSetUp {
101                reason: failure.message,
102            };
103        }
104        Err(failure) => {
105            return Failed {
106                error: failure.message,
107            };
108        }
109    };
110    match route {
111        Route::Antigravity => {
112            use super::antigravity::{MINIMUM, Problem};
113            match antigravity::models_checked().await {
114                Ok(models) => Models(models),
115                Err(Problem::Missing) => CliMissing {
116                    reason: "Install the Antigravity CLI (agy).".into(),
117                },
118                Err(Problem::SignedOut) => NotSetUp {
119                    reason: "Sign in to Antigravity with Google.".into(),
120                },
121                Err(Problem::TooOld { version }) => CliTooOld {
122                    error: format!("Update Antigravity to {MINIMUM} or newer."),
123                    version,
124                    required_version: MINIMUM,
125                },
126                Err(problem) => Failed {
127                    error: crate::agent::error::Failure::from(problem).message,
128                },
129            }
130        }
131        Route::ClaudeAgent => {
132            let minimum = super::claude_agent::MINIMUM_VERSION;
133            match claude_agent::cli_version().await {
134                Ok(None) => {
135                    return CliMissing {
136                        reason: "Install Claude Code (claude).".into(),
137                    };
138                }
139                Ok(Some(version)) if version < minimum => {
140                    return CliTooOld {
141                        error: format!("Update Claude Code to {minimum} or newer."),
142                        version,
143                        required_version: minimum,
144                    };
145                }
146                Err(error) => return Failed { error },
147                Ok(Some(_)) => {}
148            }
149            match claude_agent::status().await {
150                claude_agent::Status::Missing => CliMissing {
151                    reason: "Install Claude Code (claude).".into(),
152                },
153                claude_agent::Status::SignedOut => NotSetUp {
154                    reason: "Sign in to Claude Code.".into(),
155                },
156                claude_agent::Status::Failed { error } => Failed { error },
157                claude_agent::Status::SignedIn { .. } => {
158                    Availability::listed(super::claude_agent::models().await)
159                }
160            }
161        }
162        Route::Http(super::HttpRoute {
163            api: Api::Codex,
164            base,
165            ..
166        }) => match codex::status(state, repo) {
167            Ok(codex::Status::Absent) => NotSetUp {
168                reason: "Sign in to Codex.".into(),
169            },
170            Ok(codex::Status::Refused { reason }) => Failed { error: reason },
171            Err(error) => Failed { error },
172            Ok(_) => Availability::listed(super::codex::models(&base, state, repo).await),
173        },
174        Route::Http(super::HttpRoute { api, base, key }) => {
175            let key = key.as_ref().map_or("", |key| key.expose());
176            Availability::listed(list_at(api, key, super::adapter_base(&base)).await)
177        }
178    }
179}
180
181/// `state` holds saved keys, custom providers and Codex credentials; `repo` keeps them
182/// outside the reviewed repository.
183pub async fn list(
184    backend: Backend,
185    state: Option<&Path>,
186    repo: Option<&Path>,
187) -> Result<Listing, String> {
188    let route =
189        super::route(&backend, state, repo, "to list models").map_err(|failure| failure.message)?;
190    let models = match route {
191        super::Route::Antigravity => crate::auth::antigravity::models().await?,
192        super::Route::ClaudeAgent => super::claude_agent::models().await?,
193        super::Route::Http(super::HttpRoute {
194            api: Api::Codex,
195            base,
196            ..
197        }) => super::codex::models(&base, state, repo).await?,
198        super::Route::Http(super::HttpRoute { api, base, key }) => {
199            let key = key.as_ref().map_or("", |key| key.expose());
200            list_at(api, key, super::adapter_base(&base)).await?
201        }
202    };
203    Ok(Listing { backend, models })
204}
205
206async fn list_at(api: Api, key: &str, base: &str) -> Result<Vec<ListedModel>, String> {
207    let http = rig_reqwest::ReqwestClient::from(super::http_client()?);
208    let request = async {
209        match api {
210            Api::OpenaiResponses | Api::OpenaiChat => {
211                openai::OpenAIConfig::new(key.to_owned())
212                    .with_base_url(base)
213                    .connect(http)
214                    .list_models()
215                    .await
216            }
217            Api::Anthropic => {
218                anthropic::AnthropicConfig::new(key.to_owned())
219                    .with_base_url(base)
220                    .connect(http)
221                    .list_models()
222                    .await
223            }
224            Api::Gemini => {
225                gemini::GeminiConfig::new(key.to_owned())
226                    .with_base_url(base)
227                    .connect(http)
228                    .list_models()
229                    .await
230            }
231            Api::Codex | Api::ClaudeAgent | Api::Antigravity => {
232                unreachable!("they list their own models")
233            }
234        }
235    };
236    let models = tokio::time::timeout(LIST_TIMEOUT, request)
237        .await
238        .map_err(|_| "Model listing timed out.".to_owned())?
239        .map_err(|error| {
240            let sent: Vec<&str> = Some(key)
241                .filter(|key| !key.is_empty())
242                .into_iter()
243                .collect();
244            let text = super::diagnostic_hiding(&error, &sent);
245            if text == crate::secret::WITHHELD {
246                format!("Model listing failed: {text}")
247            } else {
248                text
249            }
250        })?;
251    // A listed model without a usable id cannot be selected, so it is left out.
252    Ok(models
253        .into_iter()
254        .filter_map(|model| {
255            let slug = model.id.parse().ok()?;
256            let (efforts, default) = super::api::model_efforts(api, &model.id);
257            Some(
258                ListedModel::new(slug, model.name.unwrap_or(model.id)).with_efforts(
259                    efforts.iter().map(|effort| (*effort).to_owned()),
260                    default.map(str::to_owned),
261                ),
262            )
263        })
264        .collect())
265}
266
267#[cfg(test)]
268mod tests {
269    use rig_core::test_utils::MockHttpResponse;
270    use serde_json::json;
271
272    use super::*;
273    use crate::llm::tests::Server;
274
275    #[tokio::test]
276    async fn api_key_models_use_provider_headers_and_follow_anthropic_pages() {
277        Server::run(
278            vec![MockHttpResponse::success(
279                json!({"data":[
280                    {"id":"z-model"}, {"id":"a-model", "name":"A model"}
281                ]})
282                .to_string(),
283            )],
284            async |openai| {
285                let models = list_at(Api::OpenaiResponses, "openai-key", &openai.base)
286                    .await
287                    .unwrap();
288                assert_eq!(
289                    serde_json::to_value(models).unwrap(),
290                    json!([
291                        {"slug":"z-model","display_name":"z-model","efforts":[],"default_effort":null},
292                        {"slug":"a-model","display_name":"A model","efforts":[],"default_effort":null}
293                    ])
294                );
295                let requests = openai.requests();
296                assert_eq!(requests[0].line, "GET /v1/models HTTP/1.1");
297                assert_eq!(requests[0].headers["authorization"], "Bearer openai-key");
298                assert!(!requests[0].headers.contains_key("x-api-key"));
299                assert!(requests[0].body.is_null());
300            },
301        )
302        .await;
303
304        Server::run(
305            vec![
306                MockHttpResponse::success(
307                    json!({
308                        "data":[{"id":"first", "display_name":"First","efforts":[],"default_effort":null}],
309                        "has_more":true,
310                        "last_id":"first",
311                    })
312                    .to_string(),
313                ),
314                MockHttpResponse::success(
315                    json!({"data":[{"id":"second", "display_name":"Second","efforts":[],"default_effort":null}],"has_more":false})
316                        .to_string(),
317                ),
318            ],
319            async |anthropic| {
320                let models = list_at(Api::Anthropic, "anthropic-key", &anthropic.base)
321                    .await
322                    .unwrap();
323                assert_eq!(
324                    serde_json::to_value(models).unwrap(),
325                    json!([
326                        {"slug":"first","display_name":"First","efforts":[],"default_effort":null},
327                        {"slug":"second","display_name":"Second","efforts":[],"default_effort":null}
328                    ])
329                );
330                let requests = anthropic.requests();
331                assert_eq!(requests[0].line, "GET /v1/models HTTP/1.1");
332                assert_eq!(requests[1].line, "GET /v1/models?after_id=first HTTP/1.1");
333                assert_eq!(requests[0].headers["x-api-key"], "anthropic-key");
334                assert!(requests[0].headers.contains_key("anthropic-version"));
335                assert!(!requests[0].headers.contains_key("authorization"));
336            },
337        )
338        .await;
339    }
340
341    #[tokio::test]
342    async fn model_listing_errors_do_not_expose_api_keys() {
343        for backend in [Api::OpenaiResponses, Api::Anthropic] {
344            Server::run(
345                vec![MockHttpResponse::error(
346                rig_core::http_client::StatusCode::UNAUTHORIZED,
347                json!({"error":{"message":"Invalid secret-key", "type":"authentication_error"}})
348                    .to_string(),
349            )],
350                async |server| {
351                    let error = list_at(backend, "secret-key", &server.base)
352                        .await
353                        .err()
354                        .unwrap();
355                    // The provider's text held the key: withheld whole, as every server text is.
356                    assert_eq!(
357                        error,
358                        format!("Model listing failed: {}", crate::secret::WITHHELD)
359                    );
360                },
361            )
362            .await;
363        }
364        // Text without the key still explains the failure.
365        Server::run(
366            vec![MockHttpResponse::error(
367                rig_core::http_client::StatusCode::UNAUTHORIZED,
368                json!({"error":{"message":"Invalid API key\n", "type":"authentication_error"}})
369                    .to_string(),
370            )],
371            async |server| {
372                let error = list_at(Api::OpenaiResponses, "secret-key-value", &server.base)
373                    .await
374                    .err()
375                    .unwrap();
376                assert_eq!(error, "Invalid API key");
377            },
378        )
379        .await;
380    }
381}