//! Model catalog: live list from the provider (cached a day), static fallback, context windows. use crate::auth::Kind; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ModelInfo { pub id: String, pub kind: Kind, /// Input context window in tokens. pub context_window: u64, } const CACHE_SECS: u64 = 3_600; /// Used when nothing better is known about a model. pub const DEFAULT_WINDOW: u64 = 200_000; /// Known models, newest first; used when the live list can't be fetched. /// Claude: platform.claude.com models overview (2026-09). Codex: GPT-5.6 tiers (2026-07). pub fn fallback(k: Kind) -> Vec { let m = |id: &str, w: u64| ModelInfo { id: id.into(), kind: k, context_window: w, }; match k { Kind::Claude => vec![ m("claude-opus-5-5", 1_000_000), m("claude-sonnet-5-5", 1_000_000), m("claude-fable-5-1", 1_000_000), m("claude-haiku-4-5", 200_000), ], Kind::Codex => vec![ m("gpt-5.6-sol", 1_050_000), m("gpt-5.6-terra", 1_050_000), m("gpt-5.6-luna", 1_050_000), ], Kind::Custom => vec![], } } /// Version of a model id: its numbers in order, a date snapshot (8+ digits) after the rest, so /// `claude-opus-5-5` > `claude-opus-4-1-20250805` and `gpt-5.6-sol` > `gpt-5.5-sol`. fn version(id: &str) -> Vec { let n: Vec = id .split(|c: char| !c.is_ascii_digit()) .filter_map(|p| p.parse().ok()) .collect(); let (dates, mut v): (Vec, Vec) = n.into_iter().partition(|n| *n >= 10_000_000); v.extend(dates); v } /// Stable models rank above previews, then by version. fn key(m: &ModelInfo) -> (bool, Vec) { (!m.id.contains("preview"), version(&m.id)) } /// The highest-versioned model of `ms` (the first listed on a tie), whatever order the API lists them in. pub fn newest<'a>(ms: impl IntoIterator) -> Option<&'a ModelInfo> { ms.into_iter() .fold(None, |b: Option<&ModelInfo>, m| match b { Some(b) if key(b) >= key(m) => Some(b), _ => Some(m), }) } /// Default model for a provider: Sonnet for Claude, the provider's first-listed model otherwise. pub fn default_for(k: Kind, models: &[ModelInfo]) -> String { let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect(); let pick = match k { Kind::Claude => newest(mine.iter().copied().filter(|m| m.id.contains("sonnet"))), Kind::Codex | Kind::Custom => None, }; pick.or(mine.first().copied()) .map(|m| m.id.clone()) .or_else(|| fallback(k).first().map(|m| m.id.clone())) .unwrap_or_default() } /// Cheapest known tier of a provider (Haiku / Luna), for read-only subagents. pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option { let tag = match k { Kind::Claude => "haiku", Kind::Codex => "luna", Kind::Custom => return None, }; newest(models.iter().filter(|m| m.kind == k && m.id.contains(tag))).map(|m| m.id.clone()) } /// Context window for `id`: exact match, then dated-snapshot prefix match, then a family guess. pub fn window(models: &[ModelInfo], id: &str) -> u64 { models .iter() .find(|m| m.id == id) .or_else(|| { models .iter() .find(|m| id.starts_with(&m.id) || m.id.starts_with(id)) }) .map(|m| m.context_window) .unwrap_or_else(|| { // 5.x Claude and GPT-5.6+ generations ship 1M windows; older ones 200k let gen5 = [ "claude-opus-5", "claude-sonnet-5", "claude-fable", "gpt-5.6", "gpt-6", ]; if gen5.iter().any(|p| id.starts_with(p)) { 1_000_000 } else { DEFAULT_WINDOW } }) } /// Provider serving `id`: catalog entry, else by name (`claude-*` vs OpenAI families). pub fn kind_of(models: &[ModelInfo], id: &str) -> Option { if let Some(m) = models.iter().find(|m| m.id == id) { return Some(m.kind); } let openai = id.starts_with("gpt-") || id.starts_with("codex") || (id.starts_with('o') && id[1..].starts_with(|c: char| c.is_ascii_digit())); if id.starts_with("claude") { Some(Kind::Claude) } else if openai { Some(Kind::Codex) } else { None } } /// Auto-compaction threshold: 90% of the window, leaving room for the reply. pub fn compact_threshold(window: u64, max_output: u32) -> usize { (window * 9 / 10).min(window.saturating_sub(max_output as u64)) as usize } #[derive(Serialize, Deserialize)] struct Cache { fetched: u64, models: Vec, } fn cache_path(k: Kind) -> std::path::PathBuf { let p = crate::auth::store_path(); p.with_file_name(format!("models-{}.json", format!("{k:?}").to_lowercase())) } fn now() -> u64 { crate::auth::now_ms() / 1000 } /// Where a model list came from. #[derive(Debug, PartialEq)] pub enum Source { Cache, Live, /// Fetch failed (reason); the list is an expired cache or the built-in fallback. Failed(String, bool), } fn read_cache(k: Kind) -> Option { std::fs::read(cache_path(k)) .ok() .and_then(|b| serde_json::from_slice::(&b).ok()) .filter(|c| !c.models.is_empty()) } /// Cached list for `k` at any age, and whether it is still fresh. pub fn cached(k: Kind) -> Option<(Vec, bool)> { read_cache(k).map(|c| { let fresh = now().saturating_sub(c.fetched) < CACHE_SECS; (c.models, fresh) }) } /// Live model list for `k` via `p`, cached for an hour (`refresh` skips the cache). /// On fetch failure: the expired cache if any, else the built-in list; `Source::Failed` says which. pub async fn load_with( k: Kind, p: &dyn crate::Provider, refresh: bool, ) -> (Vec, Source) { let cached = read_cache(k); // custom endpoints are cheap to ask and their config changes by hand: never serve the cache first let refresh = refresh || k == Kind::Custom; if let Some(c) = cached .as_ref() .filter(|c| !refresh && now().saturating_sub(c.fetched) < CACHE_SECS) { return (c.models.clone(), Source::Cache); } let r = match tokio::time::timeout(std::time::Duration::from_secs(4), p.models()).await { Ok(Ok(v)) if !v.is_empty() => Ok(v), Ok(Ok(_)) => Err("server returned no models".to_string()), Ok(Err(e)) => Err(e.to_string()), Err(_) => Err("timed out".to_string()), }; match r { Ok(models) => { let c = Cache { fetched: now(), models, }; if let Ok(b) = serde_json::to_vec_pretty(&c) { let _ = std::fs::write(cache_path(k), b); } (c.models, Source::Live) } Err(e) => match cached { Some(c) => (c.models, Source::Failed(e, true)), None => (fallback(k), Source::Failed(e, false)), }, } } pub async fn load(k: Kind, p: &dyn crate::Provider) -> Vec { load_with(k, p, false).await.0 } #[cfg(test)] mod tests { use super::*; #[test] fn windows_and_defaults() { let mut ms = fallback(Kind::Claude); assert_eq!(window(&ms, "claude-sonnet-5-5"), 1_000_000); assert_eq!( window(&ms, "claude-haiku-4-5-20251001"), 200_000, "dated snapshot" ); assert_eq!( window(&ms, "claude-sonnet-4-5"), 200_000, "older generation" ); assert_eq!(window(&ms, "claude-opus-5-9"), 1_000_000, "unknown 5.x"); assert_eq!(default_for(Kind::Claude, &ms), "claude-sonnet-5-5"); assert_eq!( default_for(Kind::Codex, &ms), "gpt-5.6-sol", "nothing listed: fallback" ); ms.extend(fallback(Kind::Codex)); assert_eq!(default_for(Kind::Codex, &ms), "gpt-5.6-sol"); assert_eq!(compact_threshold(1_000_000, 16_384), 900_000); assert_eq!(kind_of(&ms, "gpt-5.6-terra"), Some(Kind::Codex), "catalog"); assert_eq!(kind_of(&[], "gpt-7"), Some(Kind::Codex), "by name"); assert_eq!(kind_of(&[], "o4-mini"), Some(Kind::Codex)); assert_eq!(kind_of(&[], "claude-x"), Some(Kind::Claude)); assert_eq!(kind_of(&[], "opus"), None); assert_eq!(compact_threshold(20_000, 16_384), 3_616); } }