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