artifactize-provider 0.27.0

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! Static model metadata and provider-owned model APIs only.

use super::{Api, HttpRoute};
use crate::{auth::Location, secret::Inventory};
use rig_core::providers::{anthropic, gemini, openai};
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Model discovery is interactive metadata, not a review; stop a stalled listing
/// after thirty seconds for both API-key backends and the Codex account endpoint.
pub(super) const LIST_TIMEOUT: Duration = Duration::from_secs(30);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListedModel {
    pub slug: crate::names::ModelId,
    pub display_name: String,
    #[serde(default)]
    pub efforts: Vec<String>,
    #[serde(default)]
    pub default_effort: Option<String>,
}

impl ListedModel {
    pub fn new(slug: crate::names::ModelId, display_name: String) -> Self {
        Self {
            slug,
            display_name,
            efforts: Vec::new(),
            default_effort: None,
        }
    }

    pub fn with_efforts(
        mut self,
        efforts: impl IntoIterator<Item = String>,
        default: Option<String>,
    ) -> Self {
        for effort in efforts {
            if !effort.is_empty() && !self.efforts.contains(&effort) {
                self.efforts.push(effort);
            }
        }
        // The picker and new sessions share one order: a provider's declared default
        // first, otherwise the first advertised level is the starting choice.
        if let Some(index) =
            default.and_then(|default| self.efforts.iter().position(|effort| *effort == default))
        {
            let default = self.efforts.remove(index);
            self.efforts.insert(0, default);
        }
        self.default_effort = self.efforts.first().cloned();
        self
    }
}

/// List the models at a resolved direct HTTP target.
pub async fn list(
    route: &HttpRoute,
    location: Result<&Location, &str>,
) -> Result<Vec<ListedModel>, String> {
    let history = crate::secret::history::History::watch(route.location.as_ref(), location.ok())
        .map_err(|_| "Cannot protect credentials during model listing.".to_owned())?;
    let key = route.key.as_ref().map_or("", |key| key.expose());
    let managed = || {
        let mut inventory = Inventory::read(route.location.as_ref(), location.ok());
        inventory.include(key.to_owned());
        history.update(inventory)
    };
    let _ = managed();
    if route.api == Api::Codex {
        return super::codex::models(&route.base, location, managed).await;
    }
    list_at(route.api, key, super::adapter_base(&route.base), managed).await
}

pub(super) fn scrub_models(models: Vec<ListedModel>, managed: &Inventory) -> Vec<ListedModel> {
    models
        .into_iter()
        .filter_map(|mut model| {
            if managed.contains(model.slug.as_str()) {
                return None;
            }
            model.display_name = managed.scrub(&model.display_name);
            model.efforts.retain(|effort| !managed.contains(effort));
            if model
                .default_effort
                .as_ref()
                .is_some_and(|effort| managed.contains(effort))
            {
                model.default_effort = model.efforts.first().cloned();
            }
            Some(model)
        })
        .collect()
}

async fn list_at(
    api: Api,
    key: &str,
    base: &str,
    current: impl Fn() -> Inventory,
) -> Result<Vec<ListedModel>, String> {
    let http = rig_reqwest::ReqwestClient::from(
        super::http_client().map_err(|error| current().scrub(&error))?,
    );
    let request = async {
        match api {
            Api::OpenaiResponses | Api::OpenaiChat => {
                openai::OpenAIConfig::new(key.to_owned())
                    .with_base_url(base)
                    .connect(http)
                    .list_models()
                    .await
            }
            Api::Anthropic => {
                anthropic::AnthropicConfig::new(key.to_owned())
                    .with_base_url(base)
                    .connect(http)
                    .list_models()
                    .await
            }
            Api::Gemini => {
                gemini::GeminiConfig::new(key.to_owned())
                    .with_base_url(base)
                    .connect(http)
                    .list_models()
                    .await
            }
            Api::Codex => {
                unreachable!("they list their own models")
            }
        }
    };
    let result = tokio::time::timeout(LIST_TIMEOUT, request).await;
    let managed = current();
    let models = result
        .map_err(|_| managed.scrub("Model listing timed out."))?
        .map_err(|error| {
            let text =
                managed.diagnostic(&super::diagnostic_text(&error), super::MAX_DIAGNOSTIC_CHARS);
            if text == crate::secret::WITHHELD {
                managed.scrub(&format!("Model listing failed: {text}"))
            } else {
                text
            }
        })?;
    // A listed model without a usable id cannot be selected, so it is left out.
    Ok(scrub_models(
        models
            .into_iter()
            .filter_map(|model| {
                let slug = model.id.parse().ok()?;
                let (efforts, default) = super::api::model_efforts(api, &model.id);
                Some(
                    ListedModel::new(slug, model.name.unwrap_or(model.id)).with_efforts(
                        efforts.iter().map(|effort| (*effort).to_owned()),
                        default.map(str::to_owned),
                    ),
                )
            })
            .collect(),
        &managed,
    ))
}

#[cfg(test)]
mod tests;