modelbridge 0.5.2

One provider-neutral Rust client for OpenAI, Anthropic, Gemini, Groq, Ollama and friends: streaming, tool calling, an agent loop, usage accounting, and subscription sign-in
Documentation
//! Where sign-ins live: one JSON file the host application chooses.
//!
//! The contents are secrets in plain text, exactly as every CLI that stores a
//! refresh token does. The file is created private on Unix. Nothing is written
//! unless the user signs in or asks for a key to be remembered.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::Error;

/// Seconds since the epoch.
pub fn now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs() as i64)
        .unwrap_or(0)
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tokens {
    pub access_token: String,
    #[serde(default)]
    pub refresh_token: String,
    #[serde(default)]
    pub account_id: String,
    /// Seconds since the epoch; zero when the endpoint did not say.
    #[serde(default)]
    pub expires_at: i64,
}

impl Tokens {
    /// Judged two minutes early, so a long reply does not die on a 401
    /// halfway through.
    pub fn expired(&self) -> bool {
        self.expires_at != 0 && now() >= self.expires_at - 120
    }

    pub fn is_empty(&self) -> bool {
        self.access_token.trim().is_empty()
    }
}

/// Everything a host application remembers about who the user is.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Credentials {
    pub chatgpt: Option<Tokens>,
    pub claude: Option<Tokens>,
    /// Provider id to API key, for keys the user asked to have remembered
    /// rather than keep in the environment.
    pub keys: BTreeMap<String, String>,
}

impl Credentials {
    pub fn key(&self, provider: &str) -> Option<&str> {
        self.keys
            .get(provider)
            .map(String::as_str)
            .filter(|key| !key.trim().is_empty())
    }

    pub fn set_key(&mut self, provider: &str, key: &str) {
        match key.trim() {
            "" => {
                self.keys.remove(provider);
            }
            key => {
                self.keys.insert(provider.to_string(), key.to_string());
            }
        }
    }

    pub fn tokens(&self, provider: &str) -> Option<&Tokens> {
        match provider {
            "chatgpt" => self.chatgpt.as_ref(),
            "claude" => self.claude.as_ref(),
            _ => None,
        }
        .filter(|tokens| !tokens.is_empty())
    }

    pub fn set_tokens(&mut self, provider: &str, tokens: Option<Tokens>) {
        match provider {
            "chatgpt" => self.chatgpt = tokens,
            "claude" => self.claude = tokens,
            _ => {}
        }
    }
}

/// The credentials file. Reads never fail: a missing or unreadable file simply
/// means nobody is signed in.
#[derive(Clone, Debug)]
pub struct Store {
    path: PathBuf,
}

impl Store {
    pub fn at(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn load(&self) -> Credentials {
        std::fs::read_to_string(&self.path)
            .ok()
            .and_then(|text| serde_json::from_str(&text).ok())
            .unwrap_or_default()
    }

    pub fn save(&self, credentials: &Credentials) -> crate::Result<()> {
        let write =
            |error: std::io::Error| Error::Config(format!("{}: {error}", self.path.display()));
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent).map_err(write)?;
        }
        let text = serde_json::to_string_pretty(credentials)
            .map_err(|error| Error::Config(error.to_string()))?;
        std::fs::write(&self.path, text).map_err(write)?;
        restrict(&self.path);
        Ok(())
    }

    /// Replace one provider's tokens and write the file back.
    pub fn put_tokens(&self, provider: &str, tokens: Option<Tokens>) -> crate::Result<()> {
        let mut credentials = self.load();
        credentials.set_tokens(provider, tokens);
        self.save(&credentials)
    }
}

#[cfg(unix)]
fn restrict(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}

#[cfg(not(unix))]
fn restrict(_path: &Path) {}

#[cfg(test)]
mod tests {
    use super::*;

    fn scratch(name: &str) -> PathBuf {
        let path = std::env::temp_dir().join(format!("modelbridge-{name}-{}", now()));
        let _ = std::fs::remove_dir_all(&path);
        path.join("credentials.json")
    }

    #[test]
    fn a_token_without_an_expiry_never_looks_stale() {
        let tokens = Tokens {
            access_token: "a".into(),
            ..Tokens::default()
        };
        assert!(!tokens.expired());
        assert!(!tokens.is_empty());
    }

    #[test]
    fn expiry_is_judged_two_minutes_early() {
        let almost = Tokens {
            access_token: "a".into(),
            expires_at: now() + 60,
            ..Tokens::default()
        };
        let comfortable = Tokens {
            expires_at: now() + 600,
            ..almost.clone()
        };
        assert!(almost.expired());
        assert!(!comfortable.expired());
    }

    #[test]
    fn keys_are_stored_by_provider_and_blanks_clear_them() {
        let mut credentials = Credentials::default();
        credentials.set_key("openai", "sk-test");
        assert_eq!(credentials.key("openai"), Some("sk-test"));
        credentials.set_key("openai", "  ");
        assert_eq!(credentials.key("openai"), None);
    }

    #[test]
    fn only_the_subscription_providers_hold_tokens() {
        let mut credentials = Credentials::default();
        credentials.set_tokens(
            "claude",
            Some(Tokens {
                access_token: "t".into(),
                ..Tokens::default()
            }),
        );
        credentials.set_tokens("openai", Some(Tokens::default()));
        assert!(credentials.tokens("claude").is_some());
        assert!(credentials.tokens("openai").is_none());
    }

    #[test]
    fn an_empty_token_reads_as_signed_out() {
        let credentials = Credentials {
            chatgpt: Some(Tokens::default()),
            ..Credentials::default()
        };
        assert!(credentials.tokens("chatgpt").is_none());
    }

    #[test]
    fn a_store_round_trips_through_a_file_it_creates() {
        let store = Store::at(scratch("round-trip"));
        assert_eq!(store.load(), Credentials::default());

        store
            .put_tokens(
                "chatgpt",
                Some(Tokens {
                    access_token: "at".into(),
                    ..Tokens::default()
                }),
            )
            .unwrap();
        assert_eq!(store.load().tokens("chatgpt").unwrap().access_token, "at");

        store.put_tokens("chatgpt", None).unwrap();
        assert!(store.load().tokens("chatgpt").is_none());
        let _ = std::fs::remove_dir_all(store.path().parent().unwrap());
    }

    #[test]
    fn an_unreadable_file_reads_as_signed_out_rather_than_failing() {
        let store = Store::at(scratch("garbage"));
        std::fs::create_dir_all(store.path().parent().unwrap()).unwrap();
        std::fs::write(store.path(), "not json at all").unwrap();
        assert_eq!(store.load(), Credentials::default());
        let _ = std::fs::remove_dir_all(store.path().parent().unwrap());
    }
}