Files
hx/crates/hx-ai/src/models.rs
T
johannesandClaude Sonnet 5.5 a94632ea3d chore: delete code comments, add ratchet lint and ADRs
Classify every comment as tautology, stale, excuse or decision record.
Tautology/stale/excuse comments are deleted (excuses filed as issues
#196-#236), decisions moved to docs/adr/0001-0034.

- scripts/lint-comments.sh + .comment-baseline: per-file comment count
  may only go down; wired into tests/all.sh
- .claude/skills/delete-comment: repeatable audit workflow
- cargo fmt applied to touched crates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 13:37:32 +01:00

238 lines
6.8 KiB
Rust

use crate::auth::Kind;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModelInfo {
pub id: String,
pub kind: Kind,
pub context_window: u64,
}
const CACHE_SECS: u64 = 3_600;
pub const DEFAULT_WINDOW: u64 = 200_000;
pub fn fallback(k: Kind) -> Vec<ModelInfo> {
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![],
}
}
fn version(id: &str) -> Vec<u64> {
let n: Vec<u64> = id
.split(|c: char| !c.is_ascii_digit())
.filter_map(|p| p.parse().ok())
.collect();
let (dates, mut v): (Vec<u64>, Vec<u64>) = n.into_iter().partition(|n| *n >= 10_000_000);
v.extend(dates);
v
}
fn key(m: &ModelInfo) -> (bool, Vec<u64>) {
(!m.id.contains("preview"), version(&m.id))
}
pub fn newest<'a>(ms: impl IntoIterator<Item = &'a ModelInfo>) -> 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),
})
}
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()
}
pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option<String> {
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())
}
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(|| {
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
}
})
}
pub fn kind_of(models: &[ModelInfo], id: &str) -> Option<Kind> {
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
}
}
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<ModelInfo>,
}
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
}
#[derive(Debug, PartialEq)]
pub enum Source {
Cache,
Live,
Failed(String, bool),
}
fn read_cache(k: Kind) -> Option<Cache> {
std::fs::read(cache_path(k))
.ok()
.and_then(|b| serde_json::from_slice::<Cache>(&b).ok())
.filter(|c| !c.models.is_empty())
}
pub fn cached(k: Kind) -> Option<(Vec<ModelInfo>, bool)> {
read_cache(k).map(|c| {
let fresh = now().saturating_sub(c.fetched) < CACHE_SECS;
(c.models, fresh)
})
}
pub async fn load_with(
k: Kind,
p: &dyn crate::Provider,
refresh: bool,
) -> (Vec<ModelInfo>, Source) {
let cached = read_cache(k);
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<ModelInfo> {
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);
}
}