Codex model list: all models, visible failures, hx models #124

Merged
hermes merged 1 commits from fix/codex-model-list into main 2026-10-06 10:27:37 +00:00
5 changed files with 117 additions and 23 deletions

No files matched your search

+28 -4
View File
@@ -292,13 +292,22 @@ pub fn quota(h: &reqwest::header::HeaderMap) -> Option<crate::Quota> {
(!q.windows.is_empty() || q.credits.is_some()).then_some(q) (!q.windows.is_empty() || q.credits.is_some()).then_some(q)
} }
/// The server hides models whose `minimal_client_version` exceeds ours, so claim a high one
/// (override: `HX_CODEX_CLIENT_VERSION`). ponytail: we only list ids; the server still gates use.
fn client_version() -> String {
std::env::var("HX_CODEX_CLIENT_VERSION").unwrap_or_else(|_| "99.0.0".into())
}
/// `GET {base}/models` body (Codex backend) to catalog entries, by the server's priority. /// `GET {base}/models` body (Codex backend) to catalog entries, by the server's priority.
pub fn parse_models(v: &Value) -> Vec<crate::models::ModelInfo> { pub fn parse_models(v: &Value) -> Vec<crate::models::ModelInfo> {
let mut v: Vec<(i64, crate::models::ModelInfo)> = v["models"] let mut v: Vec<(i64, crate::models::ModelInfo)> = v["models"]
.as_array() .as_array()
.into_iter() .into_iter()
.flatten() .flatten()
.filter(|m| m["visibility"].as_str().is_none_or(|s| s == "list")) .filter(|m| {
m["visibility"].as_str() != Some("hide")
&& m["supported_in_api"].as_bool() != Some(false)
})
.filter_map(|m| { .filter_map(|m| {
let id = m["slug"].as_str()?; let id = m["slug"].as_str()?;
Some(( Some((
@@ -323,7 +332,11 @@ impl Provider for Codex {
let (token, account) = self.auth.token().await?; let (token, account) = self.auth.token().await?;
let mut r = self let mut r = self
.http .http
.get(format!("{}/models?client_version=0.99.0", self.base_url)) .get(format!(
"{}/models?client_version={}",
self.base_url,
client_version()
))
.bearer_auth(token) .bearer_auth(token)
.header("originator", "hx"); .header("originator", "hx");
if let Some(a) = account { if let Some(a) = account {
@@ -414,13 +427,24 @@ mod tests {
let m = parse_models(&json!({"models": [ let m = parse_models(&json!({"models": [
{"slug": "gpt-5.6-terra", "priority": 2, "context_window": 272000}, {"slug": "gpt-5.6-terra", "priority": 2, "context_window": 272000},
{"slug": "gpt-6-astra", "priority": 1, "context_window": 272000}, {"slug": "gpt-6-astra", "priority": 1, "context_window": 272000},
{"slug": "hidden", "priority": 0, "visibility": "hide"} {"slug": "hidden", "priority": 0, "visibility": "hide"},
{"slug": "gpt-6-nolist", "priority": 3, "visibility": "none", "context_window": 272000},
{"slug": "no-vis", "priority": 4, "context_window": 272000},
{"slug": "no-api", "priority": 5, "supported_in_api": false}
]})); ]}));
let ids: Vec<_> = m let ids: Vec<_> = m
.iter() .iter()
.map(|m| (m.id.as_str(), m.context_window)) .map(|m| (m.id.as_str(), m.context_window))
.collect(); .collect();
assert_eq!(ids, [("gpt-6-astra", 272_000), ("gpt-5.6-terra", 272_000)]); assert_eq!(
ids,
[
("gpt-6-astra", 272_000),
("gpt-5.6-terra", 272_000),
("gpt-6-nolist", 272_000),
("no-vis", 272_000)
]
);
} }
use crate::ToolSpec; use crate::ToolSpec;
+45 -17
View File
@@ -11,7 +11,7 @@ pub struct ModelInfo {
pub context_window: u64, pub context_window: u64,
} }
const DAY_SECS: u64 = 86_400; const CACHE_SECS: u64 = 3_600;
/// Used when nothing better is known about a model. /// Used when nothing better is known about a model.
pub const DEFAULT_WINDOW: u64 = 200_000; pub const DEFAULT_WINDOW: u64 = 200_000;
@@ -127,36 +127,64 @@ fn now() -> u64 {
crate::auth::now_ms() / 1000 crate::auth::now_ms() / 1000
} }
/// Live model list for `k` via `p`, cached for a day; fallback list when fetching fails. /// Where a model list came from.
pub async fn load(k: Kind, p: &dyn crate::Provider) -> Vec<ModelInfo> { #[derive(Debug, PartialEq)]
let path = cache_path(k); pub enum Source {
if let Some(c) = std::fs::read(&path) 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<Cache> {
std::fs::read(cache_path(k))
.ok() .ok()
.and_then(|b| serde_json::from_slice::<Cache>(&b).ok()) .and_then(|b| serde_json::from_slice::<Cache>(&b).ok())
.filter(|c| now().saturating_sub(c.fetched) < DAY_SECS && !c.models.is_empty()) .filter(|c| !c.models.is_empty())
}
/// 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<ModelInfo>, Source) {
let cached = read_cache(k);
if let Some(c) = cached
.as_ref()
.filter(|c| !refresh && now().saturating_sub(c.fetched) < CACHE_SECS)
{ {
return c.models; return (c.models.clone(), Source::Cache);
} }
let fetched = tokio::time::timeout(std::time::Duration::from_secs(4), p.models()) let r = match tokio::time::timeout(std::time::Duration::from_secs(4), p.models()).await {
.await Ok(Ok(v)) if !v.is_empty() => Ok(v),
.ok() Ok(Ok(_)) => Err("server returned no models".to_string()),
.and_then(|r| r.ok()) Ok(Err(e)) => Err(e.to_string()),
.filter(|v| !v.is_empty()); Err(_) => Err("timed out".to_string()),
match fetched { };
Some(models) => { match r {
Ok(models) => {
let c = Cache { let c = Cache {
fetched: now(), fetched: now(),
models, models,
}; };
if let Ok(b) = serde_json::to_vec_pretty(&c) { if let Ok(b) = serde_json::to_vec_pretty(&c) {
let _ = std::fs::write(&path, b); let _ = std::fs::write(cache_path(k), b);
} }
c.models (c.models, Source::Live)
} }
None => fallback(k), 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+34 -1
View File
@@ -61,6 +61,12 @@ enum Cmd {
Stats { session: std::path::PathBuf }, Stats { session: std::path::PathBuf },
/// Token size of the fixed request prefix (system prompt parts, tool schemas, MCP index). /// Token size of the fixed request prefix (system prompt parts, tool schemas, MCP index).
Prefix, Prefix,
/// Model list per logged-in provider: source (live/cache/fallback), errors, ids.
Models {
/// Skip the cache and fetch again.
#[arg(long)]
refresh: bool,
},
/// Connect to configured MCP servers and print tools + index/eager token cost. /// Connect to configured MCP servers and print tools + index/eager token cost.
Mcp, Mcp,
/// Serve lens diagnostics + LSP navigation as an MCP server over stdio. /// Serve lens diagnostics + LSP navigation as an MCP server over stdio.
@@ -192,13 +198,36 @@ async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
let mut v = vec![]; let mut v = vec![];
for k in kinds { for k in kinds {
match provider(*k) { match provider(*k) {
Ok(p) => v.extend(hx_ai::models::load(*k, p.as_ref()).await), Ok(p) => {
let (m, src) = hx_ai::models::load_with(*k, p.as_ref(), false).await;
if let hx_ai::models::Source::Failed(e, stale) = src {
let what = if stale {
"expired cache"
} else {
"built-in list"
};
eprintln!("[{k:?}: live model list failed ({e}); using {what}]");
}
v.extend(m)
}
Err(_) => v.extend(hx_ai::models::fallback(*k)), Err(_) => v.extend(hx_ai::models::fallback(*k)),
} }
} }
v v
} }
/// `hx models`: what each provider's `/models` returns, and where the list came from.
async fn print_models(refresh: bool) {
for k in logged_in() {
let Ok(p) = provider(k) else { continue };
let (m, src) = hx_ai::models::load_with(k, p.as_ref(), refresh).await;
println!("{k:?}: {src:?}");
for x in m {
println!(" {} ({} ctx)", x.id, x.context_window);
}
}
}
/// USD per million tokens. ponytail: subscription usage isn't billed per token; this is an API-equivalent estimate. /// USD per million tokens. ponytail: subscription usage isn't billed per token; this is an API-equivalent estimate.
fn pricing(model: &str) -> Option<hx_ai::Pricing> { fn pricing(model: &str) -> Option<hx_ai::Pricing> {
let p = |input, output, cache_read, cache_write| hx_ai::Pricing { let p = |input, output, cache_read, cache_write| hx_ai::Pricing {
@@ -300,6 +329,10 @@ async fn main() -> Result<()> {
print!("{}", hx_core::stats::sub_report(&session)); print!("{}", hx_core::stats::sub_report(&session));
return Ok(()); return Ok(());
} }
Some(Cmd::Models { refresh }) => {
print_models(refresh).await;
return Ok(());
}
Some(Cmd::Prefix) => { Some(Cmd::Prefix) => {
let cwd = std::env::current_dir()?; let cwd = std::env::current_dir()?;
let cfg = Config::load(&cwd)?; let cfg = Config::load(&cwd)?;
+3 -1
View File
@@ -149,6 +149,8 @@ pub struct Completion {
} }
pub const MAX_ITEMS: usize = 8; pub const MAX_ITEMS: usize = 8;
/// Enum args (model ids) show every match; the popup scrolls.
pub const MAX_ENUM_ITEMS: usize = 100;
/// Complete the token ending at byte `cur` of `line`: /// Complete the token ending at byte `cur` of `line`:
/// `/cmd` at line start → commands; `/cmd partial` → the command's args; `@partial` → files. /// `/cmd` at line start → commands; `/cmd partial` → the command's args; `@partial` → files.
@@ -184,7 +186,7 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
&& let Some(spec) = specs.iter().find(|s| s.name == name) && let Some(spec) = specs.iter().find(|s| s.name == name)
{ {
match &spec.args { match &spec.args {
ArgKind::Enum(v) => rank(v.iter().map(String::as_str), tok, MAX_ITEMS) ArgKind::Enum(v) => rank(v.iter().map(String::as_str), tok, MAX_ENUM_ITEMS)
.into_iter() .into_iter()
.map(|x| cand(x.into(), "")) .map(|x| cand(x.into(), ""))
.collect(), .collect(),
+7
View File
@@ -1412,10 +1412,17 @@ fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom
.map(|i| i.label.chars().count()) .map(|i| i.label.chars().count())
.max() .max()
.unwrap_or(0); .unwrap_or(0);
// scroll so the selected row stays visible when there are more items than rows
let rows = (bottom as usize).saturating_sub(2).max(1);
let off = (sel + 1)
.saturating_sub(rows)
.min(c.items.len().saturating_sub(rows));
let lines: Vec<Line> = c let lines: Vec<Line> = c
.items .items
.iter() .iter()
.enumerate() .enumerate()
.skip(off)
.take(rows)
.map(|(n, i)| { .map(|(n, i)| {
let base = if n == sel { th.sel() } else { th.plain() }; let base = if n == sel { th.sel() } else { th.plain() };
Line::from(vec![ Line::from(vec![