Codex model list: all models, visible failures, hx models #124
No files matched your search
@@ -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)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn parse_models(v: &Value) -> Vec<crate::models::ModelInfo> {
|
||||
let mut v: Vec<(i64, crate::models::ModelInfo)> = v["models"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.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| {
|
||||
let id = m["slug"].as_str()?;
|
||||
Some((
|
||||
@@ -323,7 +332,11 @@ impl Provider for Codex {
|
||||
let (token, account) = self.auth.token().await?;
|
||||
let mut r = self
|
||||
.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)
|
||||
.header("originator", "hx");
|
||||
if let Some(a) = account {
|
||||
@@ -414,13 +427,24 @@ mod tests {
|
||||
let m = parse_models(&json!({"models": [
|
||||
{"slug": "gpt-5.6-terra", "priority": 2, "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
|
||||
.iter()
|
||||
.map(|m| (m.id.as_str(), m.context_window))
|
||||
.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;
|
||||
|
||||
|
||||
+45
-17
@@ -11,7 +11,7 @@ pub struct ModelInfo {
|
||||
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.
|
||||
pub const DEFAULT_WINDOW: u64 = 200_000;
|
||||
|
||||
@@ -127,36 +127,64 @@ fn now() -> u64 {
|
||||
crate::auth::now_ms() / 1000
|
||||
}
|
||||
|
||||
/// Live model list for `k` via `p`, cached for a day; fallback list when fetching fails.
|
||||
pub async fn load(k: Kind, p: &dyn crate::Provider) -> Vec<ModelInfo> {
|
||||
let path = cache_path(k);
|
||||
if let Some(c) = std::fs::read(&path)
|
||||
/// 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<Cache> {
|
||||
std::fs::read(cache_path(k))
|
||||
.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())
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.ok())
|
||||
.filter(|v| !v.is_empty());
|
||||
match fetched {
|
||||
Some(models) => {
|
||||
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(&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)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -61,6 +61,12 @@ enum Cmd {
|
||||
Stats { session: std::path::PathBuf },
|
||||
/// Token size of the fixed request prefix (system prompt parts, tool schemas, MCP index).
|
||||
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.
|
||||
Mcp,
|
||||
/// 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![];
|
||||
for k in kinds {
|
||||
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)),
|
||||
}
|
||||
}
|
||||
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.
|
||||
fn pricing(model: &str) -> Option<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));
|
||||
return Ok(());
|
||||
}
|
||||
Some(Cmd::Models { refresh }) => {
|
||||
print_models(refresh).await;
|
||||
return Ok(());
|
||||
}
|
||||
Some(Cmd::Prefix) => {
|
||||
let cwd = std::env::current_dir()?;
|
||||
let cfg = Config::load(&cwd)?;
|
||||
|
||||
@@ -149,6 +149,8 @@ pub struct Completion {
|
||||
}
|
||||
|
||||
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`:
|
||||
/// `/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)
|
||||
{
|
||||
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()
|
||||
.map(|x| cand(x.into(), ""))
|
||||
.collect(),
|
||||
|
||||
@@ -1412,10 +1412,17 @@ fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom
|
||||
.map(|i| i.label.chars().count())
|
||||
.max()
|
||||
.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
|
||||
.items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(off)
|
||||
.take(rows)
|
||||
.map(|(n, i)| {
|
||||
let base = if n == sel { th.sel() } else { th.plain() };
|
||||
Line::from(vec![
|
||||
|
||||
Reference in new issue
Block a user