diff --git a/README.md b/README.md index 2d2c411..10b625a 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,20 @@ hx -r parser # resume the session whose title best matche ``` TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output, `pgup`/`pgdn` scroll. -`/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/skills`, `/new`, `/sessions`, `/resume`, `/quit`), MCP +`/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/skills`, `/new`, `/sessions`, `/resume`, `/usage`, `/quit`), MCP prompts (`/server:prompt`) and skills. Typing `/` opens a completion popup for commands and their arguments (`up`/`down` select, `tab`/`enter` accept, `esc` close); `tab` completes `@file` (mentioned files are attached). `ctrl-p` opens a picker over commands, skills, models and the 5 newest sessions. +Models: the list comes from the provider (`/v1/models` for Claude, the Codex backend's model list), cached a +day in `~/.hx/models-.json`, with a built-in list as fallback. Only logged-in providers are +offered; the default provider is the configured one, else the first logged in. The context bar and +auto-compaction follow the active model's window (e.g. 1M for Claude 5.x). + +Usage: once a response arrives, the footer shows subscription limits from the provider's headers: +time windows with used % and time to reset (`5h 42% ↻2h13m · week 13%`) and, for credit billing, the +credit balance or extra-usage state. `/usage` shows the details. + Sessions: `/new` (or `/clear`) starts a new session file; the old one stays resumable. `/sessions` opens a full-screen picker with a preview: type to filter by title, `tab` toggles this project / all projects, `ctrl-d` deletes (asks first), `enter` resumes. The title (first prompt) shows in the footer and the @@ -32,9 +41,9 @@ Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`: ```toml provider = "claude" # or "codex" -claude_model = "claude-sonnet-4-5" -codex_model = "gpt-5-codex" -compact_at = 150000 # auto-compact threshold (estimated tokens) +# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet +# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model +# compact_at = 900000 # default: 90% of the model's context window max_tokens = 16384 # system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended diff --git a/crates/hx-ai/src/anthropic.rs b/crates/hx-ai/src/anthropic.rs index b459912..f6eb8f3 100644 --- a/crates/hx-ai/src/anthropic.rs +++ b/crates/hx-ai/src/anthropic.rs @@ -236,8 +236,62 @@ impl Assembler { } } +/// Claude subscription limits from `anthropic-ratelimit-unified-*` headers (5h and 7d windows, +/// utilization as a 0–1 fraction, reset as unix seconds) plus extra-usage (overage) state. +pub fn quota(h: &reqwest::header::HeaderMap) -> Option { + use crate::hdr; + let mut q = crate::Quota::default(); + for (abbr, label) in [("5h", "5h"), ("7d", "week")] { + let util = hdr( + h, + &format!("anthropic-ratelimit-unified-{abbr}-utilization"), + ) + .and_then(|v| v.parse::().ok()); + if let Some(u) = util { + q.windows.push(crate::QuotaWindow { + label: label.into(), + used_pct: (u * 100.0).clamp(0.0, 100.0), + resets_at: hdr(h, &format!("anthropic-ratelimit-unified-{abbr}-reset")) + .and_then(|v| v.parse().ok()), + }); + } + } + q.credits = match hdr(h, "anthropic-ratelimit-unified-overage-status") { + Some(s @ ("allowed" | "allowed_warning")) + if hdr(h, "anthropic-ratelimit-unified-status") == Some("rejected") => + { + Some(format!("using extra usage ({s})")) + } + Some("rejected") => hdr(h, "anthropic-ratelimit-unified-overage-disabled-reason") + .map(|r| format!("extra usage off: {r}")), + _ => None, + }; + (!q.windows.is_empty() || q.credits.is_some()).then_some(q) +} + #[async_trait::async_trait] impl Provider for Anthropic { + /// `GET /v1/models` — ids, newest first, with `max_input_tokens` as the window. + async fn models(&self) -> Result> { + let (token, _) = self.auth.token().await?; + let v: Value = self + .http + .get(format!("{}/v1/models?limit=100", self.base_url)) + .bearer_auth(token) + .header("anthropic-version", "2023-06-01") + .header("anthropic-beta", "oauth-2025-04-20") + .header("user-agent", format!("claude-cli/{CC_VERSION}")) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Http(e.to_string()))? + .json() + .await + .map_err(|e| Error::Decode(e.to_string()))?; + Ok(parse_models(&v)) + } + async fn stream(&self, req: Request) -> Result>> { let (token, _) = self.auth.token().await?; let r = self @@ -260,6 +314,7 @@ impl Provider for Anthropic { let body = r.text().await.unwrap_or_default(); return Err(Error::Api { status, body }); } + let q = quota(r.headers()); let s = r .bytes_stream() .eventsource() @@ -274,15 +329,76 @@ impl Provider for Anthropic { futures::future::ready(Some(futures::stream::iter(out))) }) .flatten(); - Ok(s.boxed()) + Ok(crate::with_quota(q, s.boxed())) } } +/// `/v1/models` body to catalog entries (aliases only when the API lists them; else ids as-is). +pub fn parse_models(v: &Value) -> Vec { + v["data"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| { + let id = m["id"].as_str()?; + Some(crate::models::ModelInfo { + id: id.into(), + kind: Kind::Claude, + context_window: m["max_input_tokens"] + .as_u64() + .filter(|n| *n > 0) + .unwrap_or_else(|| { + crate::models::window(&crate::models::fallback(Kind::Claude), id) + }), + }) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; use crate::ToolSpec; + #[test] + fn quota_and_models() { + let mut h = reqwest::header::HeaderMap::new(); + for (k, v) in [ + ("anthropic-ratelimit-unified-5h-utilization", "0.42"), + ("anthropic-ratelimit-unified-5h-reset", "1790850000"), + ("anthropic-ratelimit-unified-7d-utilization", "0.13"), + ("anthropic-ratelimit-unified-status", "rejected"), + ("anthropic-ratelimit-unified-overage-status", "allowed"), + ] { + h.insert(k, v.parse().unwrap()); + } + let q = quota(&h).unwrap(); + assert_eq!(q.windows[0].label, "5h"); + assert!((q.windows[0].used_pct - 42.0).abs() < 1e-9); + assert_eq!(q.windows[0].resets_at, Some(1_790_850_000)); + assert_eq!( + (q.windows[1].label.as_str(), q.windows[1].resets_at), + ("week", None) + ); + assert_eq!(q.credits.as_deref(), Some("using extra usage (allowed)")); + assert!(quota(&reqwest::header::HeaderMap::new()).is_none()); + + let m = parse_models(&json!({"data": [ + {"id": "claude-opus-5-5", "max_input_tokens": 1000000}, + {"id": "claude-haiku-4-5-20251001", "max_input_tokens": null}, + {"type": "model"} + ]})); + assert_eq!(m.len(), 2); + assert_eq!( + (m[0].id.as_str(), m[0].context_window), + ("claude-opus-5-5", 1_000_000) + ); + assert_eq!( + m[1].context_window, 200_000, + "missing window: catalog guess" + ); + } + fn req() -> Request { Request { model: "claude-sonnet-4-5".into(), diff --git a/crates/hx-ai/src/codex.rs b/crates/hx-ai/src/codex.rs index d4b2eed..9a0e364 100644 --- a/crates/hx-ai/src/codex.rs +++ b/crates/hx-ai/src/codex.rs @@ -253,8 +253,94 @@ impl Assembler { } } +/// ChatGPT subscription limits from `x-codex-*` headers: primary/secondary windows (used %, +/// window length in minutes, reset as unix seconds) and the credit balance. +pub fn quota(h: &reqwest::header::HeaderMap) -> Option { + use crate::hdr; + let mut q = crate::Quota::default(); + for w in ["primary", "secondary"] { + let Some(used) = hdr(h, &format!("x-codex-{w}-used-percent")).and_then(|v| v.parse().ok()) + else { + continue; + }; + let mins: Option = + hdr(h, &format!("x-codex-{w}-window-minutes")).and_then(|v| v.parse().ok()); + q.windows.push(crate::QuotaWindow { + label: match mins { + Some(m) if m >= 10_080 => "week".into(), + Some(m) if m >= 1440 => format!("{}d", m / 1440), + Some(m) if m >= 60 => format!("{}h", m / 60), + Some(m) => format!("{m}m"), + None => w.into(), + }, + used_pct: used, + resets_at: hdr(h, &format!("x-codex-{w}-reset-at")).and_then(|v| v.parse().ok()), + }); + } + let yes = |k: &str| hdr(h, k).is_some_and(|v| v.eq_ignore_ascii_case("true")); + q.credits = if yes("x-codex-credits-unlimited") { + Some("credits: unlimited".into()) + } else if hdr(h, "x-codex-credits-has-credits").is_some() { + Some(match hdr(h, "x-codex-credits-balance") { + Some(b) => format!("credits: {b}"), + None if yes("x-codex-credits-has-credits") => "credits: available".into(), + None => "credits: none".into(), + }) + } else { + None + }; + (!q.windows.is_empty() || q.credits.is_some()).then_some(q) +} + +/// `GET {base}/models` body (Codex backend) to catalog entries, by the server's priority. +pub fn parse_models(v: &Value) -> Vec { + 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_map(|m| { + let id = m["slug"].as_str()?; + Some(( + m["priority"].as_i64().unwrap_or(i64::MAX), + crate::models::ModelInfo { + id: id.into(), + kind: Kind::Codex, + context_window: m["context_window"] + .as_u64() + .unwrap_or_else(|| crate::models::window(&[], id)), + }, + )) + }) + .collect(); + v.sort_by_key(|(p, _)| *p); + v.into_iter().map(|(_, m)| m).collect() +} + #[async_trait::async_trait] impl Provider for Codex { + async fn models(&self) -> Result> { + let (token, account) = self.auth.token().await?; + let mut r = self + .http + .get(format!("{}/models?client_version=0.99.0", self.base_url)) + .bearer_auth(token) + .header("originator", "hx"); + if let Some(a) = account { + r = r.header("chatgpt-account-id", a); + } + let v: Value = r + .send() + .await + .map_err(|e| Error::Http(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Http(e.to_string()))? + .json() + .await + .map_err(|e| Error::Decode(e.to_string()))?; + Ok(parse_models(&v)) + } + async fn stream(&self, req: Request) -> Result>> { let (token, account) = self.auth.token().await?; let account = account.ok_or_else(|| { @@ -278,6 +364,7 @@ impl Provider for Codex { let body = r.text().await.unwrap_or_default(); return Err(Error::Api { status, body }); } + let q = quota(r.headers()); let s = r .bytes_stream() .eventsource() @@ -292,13 +379,49 @@ impl Provider for Codex { futures::future::ready(Some(futures::stream::iter(out))) }) .flatten(); - Ok(s.boxed()) + Ok(crate::with_quota(q, s.boxed())) } } #[cfg(test)] mod tests { use super::*; + + #[test] + fn quota_and_models() { + let mut h = reqwest::header::HeaderMap::new(); + for (k, v) in [ + ("x-codex-primary-used-percent", "12.5"), + ("x-codex-primary-window-minutes", "300"), + ("x-codex-primary-reset-at", "1790850000"), + ("x-codex-secondary-used-percent", "40"), + ("x-codex-secondary-window-minutes", "10080"), + ("x-codex-credits-has-credits", "true"), + ("x-codex-credits-unlimited", "false"), + ("x-codex-credits-balance", "37.5"), + ] { + h.insert(k, v.parse().unwrap()); + } + let q = quota(&h).unwrap(); + let w: Vec<_> = q + .windows + .iter() + .map(|w| (w.label.as_str(), w.used_pct, w.resets_at)) + .collect(); + assert_eq!(w, [("5h", 12.5, Some(1_790_850_000)), ("week", 40.0, None)]); + assert_eq!(q.credits.as_deref(), Some("credits: 37.5")); + + 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"} + ]})); + 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)]); + } use crate::ToolSpec; #[test] diff --git a/crates/hx-ai/src/lib.rs b/crates/hx-ai/src/lib.rs index 1335dfa..07c0421 100644 --- a/crates/hx-ai/src/lib.rs +++ b/crates/hx-ai/src/lib.rs @@ -3,6 +3,7 @@ pub mod anthropic; pub mod auth; pub mod codex; +pub mod models; use futures::stream::BoxStream; use serde::{Deserialize, Serialize}; @@ -111,6 +112,23 @@ pub struct Pricing { pub cache_write: f64, } +/// Subscription limits reported by the provider with each response. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Quota { + /// Time-based windows (5h, 7d, …). + pub windows: Vec, + /// Credit / extra-usage state for credit-based billing, human readable. + pub credits: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct QuotaWindow { + pub label: String, + pub used_pct: f64, + /// Unix seconds when the window resets. + pub resets_at: Option, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StopReason { @@ -143,6 +161,8 @@ pub enum StreamEvent { id: String, name: String, }, + /// Rate-limit / credit snapshot from the response headers (sent first, when present). + Quota(Quota), Done { message: Message, stop: StopReason, @@ -165,6 +185,30 @@ pub type Result = std::result::Result; #[async_trait::async_trait] pub trait Provider: Send + Sync { async fn stream(&self, req: Request) -> Result>>; + /// Models this account can use. Empty = unknown (callers fall back to a static list). + async fn models(&self) -> Result> { + Ok(vec![]) + } +} + +/// `Quota` first (when the response carried one), then the body events. +pub(crate) fn with_quota( + q: Option, + s: BoxStream<'static, Result>, +) -> BoxStream<'static, Result> { + use futures::StreamExt; + futures::stream::iter(q.map(|q| Ok(StreamEvent::Quota(q)))) + .chain(s) + .boxed() +} + +/// Header value as &str. +pub(crate) fn hdr<'a>(h: &'a reqwest::header::HeaderMap, k: &str) -> Option<&'a str> { + h.get(k)? + .to_str() + .ok() + .map(str::trim) + .filter(|v| !v.is_empty()) } #[cfg(test)] diff --git a/crates/hx-ai/src/models.rs b/crates/hx-ai/src/models.rs new file mode 100644 index 0000000..569fb3b --- /dev/null +++ b/crates/hx-ai/src/models.rs @@ -0,0 +1,161 @@ +//! 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 DAY_SECS: u64 = 86_400; +/// 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), + ], + } +} + +/// 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 => mine.iter().find(|m| m.id.contains("sonnet")), + Kind::Codex => None, + }; + pick.or(mine.first()) + .map(|m| m.id.clone()) + .unwrap_or_else(|| fallback(k)[0].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 + } + }) +} + +/// 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 +} + +/// 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 { + let path = cache_path(k); + if let Some(c) = std::fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .filter(|c| now().saturating_sub(c.fetched) < DAY_SECS && !c.models.is_empty()) + { + return c.models; + } + 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 c = Cache { + fetched: now(), + models, + }; + if let Ok(b) = serde_json::to_vec_pretty(&c) { + let _ = std::fs::write(&path, b); + } + c.models + } + None => fallback(k), + } +} + +#[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!(compact_threshold(20_000, 16_384), 3_616); + } +} diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index b21aba3..9df9eff 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -1,6 +1,7 @@ use anyhow::Result; use clap::{Parser, Subcommand}; use hx_ai::auth::{self, Kind}; +use hx_ai::models::ModelInfo; use hx_ai::{Provider, StreamEvent, anthropic::Anthropic, codex::Codex}; use hx_core::agent::Agent; use hx_core::context; @@ -121,19 +122,25 @@ impl Config { } } -/// Offered by `/model` completion; any other id still works. -const MODELS: &[&str] = &[ - "claude-sonnet-4-5", - "claude-opus-4-1", - "claude-haiku-4-5", - "gpt-5-codex", - "gpt-5", -]; - /// Builtins, MCP prompts (`/server:prompt`), then skills (builtins win name clashes). -fn command_specs(mcp: &hx_mcp::Hub, cwd: &std::path::Path) -> Vec { +/// `models` feeds `/model` completion (any other id still works); `kinds` = logged-in providers. +fn command_specs( + mcp: &hx_mcp::Hub, + cwd: &std::path::Path, + models: &[ModelInfo], + kinds: &[Kind], +) -> Vec { use hx_core::command::{self as c, ArgKind, CmdSpec, Source}; - let mut v = c::builtins(MODELS); + let ids: Vec<&str> = models.iter().map(|m| m.id.as_str()).collect(); + let mut v = c::builtins(&ids); + if let Some(p) = v.iter_mut().find(|s| s.name == "provider") { + p.args = ArgKind::Enum( + kinds + .iter() + .map(|k| format!("{k:?}").to_lowercase()) + .collect(), + ); + } v.push(CmdSpec::new( "mcp", "MCP servers and prompts", @@ -155,12 +162,24 @@ fn command_specs(mcp: &hx_mcp::Hub, cwd: &std::path::Path) -> Vec String { - match k { - Kind::Claude => "claude-sonnet-4-5", - Kind::Codex => "gpt-5-codex", +/// Providers with stored or importable credentials. +fn logged_in() -> Vec { + [Kind::Claude, Kind::Codex] + .into_iter() + .filter(|k| hx_ai::auth::Auth::load(*k).is_ok()) + .collect() +} + +/// Model catalog of every logged-in provider (live list cached a day, else the built-in list). +async fn catalog(kinds: &[Kind]) -> Vec { + let mut v = vec![]; + for k in kinds { + match provider(*k) { + Ok(p) => v.extend(hx_ai::models::load(*k, p.as_ref()).await), + Err(_) => v.extend(hx_ai::models::fallback(*k)), + } } - .into() + v } /// USD per million tokens. ponytail: subscription usage isn't billed per token; this is an API-equivalent estimate. @@ -171,10 +190,18 @@ fn pricing(model: &str) -> Option { cache_read, cache_write, }; + // 5.x generation prices first; older ids keep their own Some(match model { + m if m.contains("fable") => p(10.0, 50.0, 1.0, 12.5), + m if m.contains("opus-5") => p(4.0, 20.0, 0.4, 5.0), + m if m.contains("sonnet-5") => p(2.0, 10.0, 0.2, 2.5), m if m.contains("opus") => p(15.0, 75.0, 1.5, 18.75), m if m.contains("sonnet") => p(3.0, 15.0, 0.3, 3.75), m if m.contains("haiku") => p(1.0, 5.0, 0.1, 1.25), + m if m.contains("sol") || m.starts_with("gpt-5.5") => p(5.0, 30.0, 0.5, 0.0), + m if m.contains("terra") => p(2.5, 15.0, 0.25, 0.0), + m if m.contains("luna") => p(1.0, 6.0, 0.1, 0.0), + m if m.starts_with("gpt-6") => p(10.0, 50.0, 1.0, 0.0), m if m.starts_with("gpt-5") => p(1.25, 10.0, 0.125, 0.0), _ => return None, }) @@ -289,13 +316,20 @@ async fn main() -> Result<()> { } let cwd = std::env::current_dir()?; let cfg = Config::load(&cwd)?; - let kind = cli.provider.or(cfg.provider).unwrap_or(Kind::Claude); + let kinds = logged_in(); + // default provider: configured, else the first one logged in + let kind = cli + .provider + .or(cfg.provider) + .or(kinds.first().copied()) + .unwrap_or(Kind::Claude); + let models = catalog(&kinds).await; let model = cli.model.or(cfg.model).unwrap_or_else(|| { match kind { Kind::Claude => cfg.claude_model.clone(), Kind::Codex => cfg.codex_model.clone(), } - .unwrap_or_else(|| default_model(kind)) + .unwrap_or_else(|| hx_ai::models::default_for(kind, &models)) }); let dir = session_dir(&cwd); let query = cli.resume.as_deref().filter(|q| !q.is_empty()); @@ -349,12 +383,15 @@ async fn main() -> Result<()> { eprintln!("[mcp] {n}: {e}"); } } - if let Some(n) = cfg.compact_at { - agent.compact_at = n; - } if let Some(n) = cfg.max_tokens { agent.max_tokens = n; } + agent.compact_at = cfg.compact_at.unwrap_or_else(|| { + hx_ai::models::compact_threshold( + hx_ai::models::window(&models, &agent.model), + agent.max_tokens, + ) + }); for e in &cfg.extensions { let x = hx_core::ext::Extension::start(e, &cwd) .await @@ -416,7 +453,7 @@ async fn main() -> Result<()> { .collect(); mgr.warm(probe).await; } - let specs = command_specs(&mcp, &cwd); + let specs = command_specs(&mcp, &cwd, &models, &kinds); if cli.mode == Mode::Rpc { let r = rpc::serve(agent, abort, specs, hx_tui::project_files(&cwd), dir).await; mgr.shutdown().await; @@ -430,10 +467,11 @@ async fn main() -> Result<()> { agent, kind, make_provider: Box::new(provider), - default_model, pricing, specs, open_sessions, + models: models.clone(), + auto_compact: cfg.compact_at.is_none(), commands: { let mcp = mcp.clone(); Box::new(move |name: &str, arg: &str| { @@ -550,5 +588,7 @@ mod tests { assert_eq!(c.codex_model.as_deref(), Some("gpt-5")); assert!(toml::from_str::("typo = 1").is_err()); assert!(pricing("claude-sonnet-4-5").is_some() && pricing("mystery").is_none()); + assert_eq!(pricing("claude-sonnet-5-5").unwrap().input, 2.0); + assert_eq!(pricing("gpt-5.6-terra").unwrap().input, 2.5); } } diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index 8b3adba..feec843 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -61,6 +61,7 @@ pub fn builtins(models: &[&str]) -> Vec { b("clear", "alias of /new", None), b("sessions", "browse, resume, delete sessions", None), b("lsp", "language server status", None), + b("usage", "subscription limits, resets, credits", None), b("skills", "list skills and where they load from", None), b( "resume", @@ -267,7 +268,7 @@ mod tests { std::fs::create_dir_all(t.path().join("help")).unwrap(); std::fs::write(t.path().join("help/SKILL.md"), "---\nname: help\n---\nx").unwrap(); let skills = crate::context::skills_in(&[t.path().to_path_buf()]); - let mut specs = builtins(&["claude-sonnet-4-5", "claude-opus-4-1", "gpt-5-codex"]); + let mut specs = builtins(&["claude-sonnet-5-5", "claude-opus-5-5", "gpt-5.6-sol"]); let sk = skill_specs(&skills, &specs); assert_eq!(sk.len(), 1, "builtin /help wins over the skill"); specs.extend(sk); @@ -294,7 +295,7 @@ mod tests { assert_eq!(labels(&r), ["/review"]); assert_eq!(r.items[0].detail, "skill · code review"); let m = c("/model op"); - assert_eq!((m.start, labels(&m)), (7, vec!["claude-opus-4-1"])); + assert_eq!((m.start, labels(&m)), (7, vec!["claude-opus-5-5"])); assert_eq!(c("/model ").items.len(), 3); assert_eq!(labels(&c("/provider c")), ["codex", "claude"]); assert_eq!(labels(&c("/fs:grep lib")), ["src/lib.rs"]); diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 9ef5714..21fc48c 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -33,8 +33,6 @@ pub struct Setup { pub agent: Agent, pub kind: Kind, pub make_provider: MakeProvider, - /// Default model per provider, used on `/provider`. - pub default_model: fn(Kind) -> String, /// Pricing lookup for the footer; None = unknown. pub pricing: fn(&str) -> Option, /// `/lsp` status lines. @@ -46,6 +44,11 @@ pub struct Setup { pub specs: Vec, /// Open the session picker at startup (`hx -r`). pub open_sessions: bool, + /// Model catalog of logged-in providers: `/provider` defaults, context windows. + pub models: Vec, + /// Re-derive the compaction threshold from the window when the model changes + /// (false when `compact_at` is configured). + pub auto_compact: bool, } pub enum CmdOut { @@ -99,6 +102,8 @@ struct App { ctx_tokens: usize, /// auto-compact threshold: the context bar's 100% ctx_max: usize, + /// last subscription limits reported by the provider + quota: Option, pricing: fn(&str) -> Option, /// when the current run started (activity line) since: Instant, @@ -161,12 +166,13 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { mut agent, kind, make_provider, - default_model, pricing, lsp_status, commands, specs, open_sessions, + models, + auto_compact, } = setup; let (tx, mut rx) = mpsc::unbounded_channel(); agent.bus.add(Forward(tx.clone())); @@ -197,6 +203,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { usage: Usage::default(), ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()), ctx_max: agent.compact_at, + quota: None, pricing, since: Instant::now(), quit: false, @@ -223,7 +230,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { agent: &agent, tx: &tx, make_provider: &make_provider, - default_model, + models: &models, + auto_compact, cwd: &cwd, lsp_status: &lsp_status, commands: &commands, @@ -276,6 +284,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { match u { Ui::Ask(q, reply) => app.ask = Some((q, reply)), Ui::Ev(e) => { + if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e { + app.quota = Some(q.clone()); + } if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e { app.usage.add(usage); app.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize; @@ -553,12 +564,22 @@ fn accept(app: &mut App) { } } +/// Context bar max and (unless configured) the compaction threshold follow the model's window. +fn set_window(app: &mut App, a: &mut Agent, models: &[hx_ai::models::ModelInfo], auto: bool) { + let w = hx_ai::models::window(models, &a.model); + if auto { + a.compact_at = hx_ai::models::compact_threshold(w, a.max_tokens); + } + app.ctx_max = a.compact_at; +} + /// Everything `submit` needs besides the app state. struct Ctx<'a> { agent: &'a Arc>, tx: &'a mpsc::UnboundedSender, make_provider: &'a MakeProvider, - default_model: fn(Kind) -> String, + models: &'a [hx_ai::models::ModelInfo], + auto_compact: bool, cwd: &'a std::path::Path, lsp_status: &'a LspStatus, commands: &'a Commands, @@ -569,7 +590,8 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { agent, tx, make_provider, - default_model, + models, + auto_compact, cwd, lsp_status, commands, @@ -590,6 +612,10 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { let h = format!("{}\n\nkeys: {KEYS} · ctrl-p picker", cmd::help(&app.specs)); show(app, "help", h); } + "usage" => { + let r = usage_report(app, now_secs()); + show(app, "usage", r); + } "skills" => { let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd); let l = skills_list(&app.specs, &dirs); @@ -624,9 +650,14 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { } "model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))), "model" => { - agent.lock().await.model = arg.into(); + let mut a = agent.lock().await; + a.model = arg.into(); + set_window(app, &mut a, models, auto_compact); app.model = arg.into(); - app.t.push(Item::Info(format!("model → {arg}"))); + app.t.push(Item::Info(format!( + "model → {arg} · context {}k", + hx_ai::models::window(models, arg) / 1000 + ))); } "provider" => match arg .parse::() @@ -636,7 +667,9 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { Ok((k, p)) => { let mut a = agent.lock().await; a.provider = p; - a.model = default_model(k); + a.model = hx_ai::models::default_for(k, models); + set_window(app, &mut a, models, auto_compact); + app.quota = None; app.kind = k; app.model = a.model.clone(); app.t @@ -819,9 +852,13 @@ fn footer(app: &App, width: u16) -> Line<'static> { f if f >= 0.7 => th.warn(), _ => th.accent(), }; - let cost = (app.pricing)(&app.model) - .map(|p| format!(" ~${:.2}", app.usage.cost(&p))) - .unwrap_or_default(); + // subscription quota replaces the API-equivalent cost estimate once the provider reports it + let cost = match app.quota { + Some(_) => String::new(), + None => (app.pricing)(&app.model) + .map(|p| format!(" ~${:.2}", app.usage.cost(&p))) + .unwrap_or_default(), + }; let mut left = vec![ Span::styled("ctx ", th.dim()), Span::styled(th.sym.bar_full.repeat(full), bar_st), @@ -830,15 +867,18 @@ fn footer(app: &App, width: u16) -> Line<'static> { format!(" {}k/{}k", app.ctx_tokens / 1000, app.ctx_max / 1000), th.dim(), ), - Span::styled( - format!( - " · {}↑ {}↓{cost}", - k(app.usage.input_tokens + app.usage.cache_read_tokens), - k(app.usage.output_tokens) - ), - th.dim(), - ), ]; + if let Some(q) = &app.quota { + left.extend(quota_spans(q, now_secs())); + } + left.extend([Span::styled( + format!( + " · {}↑ {}↓{cost}", + k(app.usage.input_tokens + app.usage.cache_read_tokens), + k(app.usage.output_tokens) + ), + th.dim(), + )]); let w = width as usize; let lw = |l: &[Span]| l.iter().map(Span::width).sum::(); if !app.hint.is_empty() { @@ -888,6 +928,85 @@ fn footer(app: &App, width: u16) -> Line<'static> { Line::from(left) } +fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// `2h13m`, `3d4h`, `45m` until `at`. +fn until(at: u64, now: u64) -> String { + let s = at.saturating_sub(now); + let (d, h, m) = (s / 86_400, s % 86_400 / 3600, s % 3600 / 60); + match (d, h) { + (0, 0) => format!("{}m", m.max(1)), + (0, _) => format!("{h}h{m:02}m"), + _ => format!("{d}d{h}h"), + } +} + +/// ` · 5h 42% ↻2h13m · week 13%`, then credits; warn at 70%, error at 90%. +fn quota_spans(q: &hx_ai::Quota, now: u64) -> Vec> { + let th = theme::t(); + let mut v = vec![]; + for w in &q.windows { + let st = match w.used_pct { + p if p >= 90.0 => th.err(), + p if p >= 70.0 => th.warn(), + _ => th.dim(), + }; + let reset = w + .resets_at + .map(|r| format!(" {}{}", th.sym.reset, until(r, now))) + .unwrap_or_default(); + v.push(Span::styled(" · ", th.dim())); + v.push(Span::styled( + format!("{} {:.0}%{reset}", w.label, w.used_pct), + st, + )); + } + if let Some(c) = &q.credits { + v.push(Span::styled(format!(" · {c}"), th.dim())); + } + v +} + +/// `/usage`: every window with its reset time, credits, and this session's tokens. +fn usage_report(app: &App, now: u64) -> String { + let mut out = vec![format!("{:?} · {}", app.kind, app.model)]; + match &app.quota { + None => out.push("subscription limits: not reported yet (send a prompt first)".into()), + Some(q) => { + for w in &q.windows { + let reset = w + .resets_at + .map(|r| format!(", resets in {}", until(r, now))) + .unwrap_or_default(); + out.push(format!( + "{:<5} {:>3.0}% used, {:.0}% left{reset}", + w.label, + w.used_pct, + 100.0 - w.used_pct + )); + } + if let Some(c) = &q.credits { + out.push(c.clone()); + } + } + } + out.push(format!( + "context {}k of {}k before auto-compact", + app.ctx_tokens / 1000, + app.ctx_max / 1000 + )); + out.push(format!( + "session tokens: {} in, {} out", + app.usage.input_tokens + app.usage.cache_read_tokens, + app.usage.output_tokens + )); + out.join("\n") +} + /// `/skills`: each skill with its file, then the searched dirs (so a missing skill is easy to debug). fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String { let sk: Vec = specs @@ -981,6 +1100,7 @@ mod tests { usage: Usage::default(), ctx_tokens: 12_000, ctx_max: 150_000, + quota: None, pricing: |_| None, since: Instant::now(), quit: false, @@ -1034,6 +1154,7 @@ mod tests { usage: Usage::default(), ctx_tokens: 0, ctx_max: 150_000, + quota: None, pricing: |_| None, since: Instant::now(), quit: false, @@ -1250,7 +1371,8 @@ mod tests { agent: &agent, tx: &tx, make_provider: &mp, - default_model: |_| String::new(), + models: &[], + auto_compact: true, cwd: t.path(), lsp_status: &ls, commands: &cmds, @@ -1281,6 +1403,59 @@ mod tests { assert_eq!(app.title.as_deref(), Some("first")); } + #[test] + fn quota_footer_and_usage() { + let q = hx_ai::Quota { + windows: vec![ + hx_ai::QuotaWindow { + label: "5h".into(), + used_pct: 42.0, + resets_at: Some(10_000 + 2 * 3600 + 13 * 60), + }, + hx_ai::QuotaWindow { + label: "week".into(), + used_pct: 91.0, + resets_at: Some(10_000 + 3 * 86_400 + 4 * 3600), + }, + ], + credits: Some("credits: 37.5".into()), + }; + let text: String = quota_spans(&q, 10_000) + .iter() + .map(|s| s.content.to_string()) + .collect(); + assert_eq!(text, " · 5h 42% ↻2h13m · week 91% ↻3d4h · credits: 37.5"); + assert_eq!( + quota_spans(&q, 10_000)[3].style.fg, + Some(ratatui::style::Color::Red) + ); + let mut app = test_app(); + assert!(usage_report(&app, 10_000).contains("not reported yet")); + app.quota = Some(q); + let r = usage_report(&app, 10_000); + assert!( + r.contains("5h 42% used, 58% left, resets in 2h13m"), + "{r}" + ); + assert!( + r.contains("week 91% used, 9% left, resets in 3d4h"), + "{r}" + ); + assert!( + r.contains("credits: 37.5") && r.contains("context 0k of 150k"), + "{r}" + ); + // quota replaces the $ estimate in the footer + app.pricing = |_| Some(hx_ai::Pricing::default()); + let line: String = footer(&app, 140) + .spans + .iter() + .map(|s| s.content.to_string()) + .collect(); + assert!(line.contains("5h 42%") && !line.contains('$'), "{line}"); + assert_eq!(until(10_030, 10_000), "1m"); + } + struct NoProvider; #[async_trait::async_trait] impl Provider for NoProvider { diff --git a/crates/hx-tui/src/theme.rs b/crates/hx-tui/src/theme.rs index 202dfb0..1a536b0 100644 --- a/crates/hx-tui/src/theme.rs +++ b/crates/hx-tui/src/theme.rs @@ -16,6 +16,7 @@ pub struct Sym { pub info: &'static str, pub ellipsis: &'static str, pub minus: &'static str, + pub reset: &'static str, } const UNICODE: Sym = Sym { @@ -31,6 +32,7 @@ const UNICODE: Sym = Sym { info: "·", ellipsis: "…", minus: "−", + reset: "↻", }; const ASCII: Sym = Sym { @@ -46,6 +48,7 @@ const ASCII: Sym = Sym { info: "-", ellipsis: "...", minus: "-", + reset: "@", }; pub struct Theme { diff --git a/tests/fake_anthropic.py b/tests/fake_anthropic.py index 6a1bd57..369babe 100644 --- a/tests/fake_anthropic.py +++ b/tests/fake_anthropic.py @@ -26,6 +26,9 @@ class H(http.server.BaseHTTPRequestHandler): LOG.append({"auth": self.headers.get("authorization"), "beta": self.headers.get("anthropic-beta"), "body": body}) turn = TURNS[min(len(LOG) - 1, len(TURNS) - 1)] self.send_response(200) + self.send_header("anthropic-ratelimit-unified-5h-utilization", "0.42") + self.send_header("anthropic-ratelimit-unified-5h-reset", str(int(__import__("time").time()) + 7980)) + self.send_header("anthropic-ratelimit-unified-7d-utilization", "0.13") self.send_header("content-type", "text/event-stream") self.end_headers() w = self.wfile.write @@ -46,6 +49,15 @@ class H(http.server.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() + if self.path.startswith("/v1/models"): + # live catalog: newest first, includes a model the static fallback doesn't know + self.wfile.write(json.dumps({"data": [ + {"id": "claude-opus-5-5", "max_input_tokens": 1000000}, + {"id": "claude-sonnet-5-5", "max_input_tokens": 1000000}, + {"id": "claude-sonnet-5-6-preview", "max_input_tokens": 2000000}, + {"id": "claude-haiku-4-5", "max_input_tokens": 200000}, + ]}).encode()) + return self.wfile.write(json.dumps(LOG).encode()) diff --git a/tests/tui_smoke.py b/tests/tui_smoke.py index f86b86c..102c075 100644 --- a/tests/tui_smoke.py +++ b/tests/tui_smoke.py @@ -52,6 +52,8 @@ def check(label, needle): pump(1.5) check("startup footer", "Claude") +check("latest default model", "claude-sonnet-5-5") +check("1M window", "/900k") send(b"/skills\r") check("skills from ~/.agents", "/deploy — ship it") check("project .agents skills", "/lint — project lint") @@ -63,8 +65,19 @@ check("tool call shown", "hello.txt") check("tool outcome", "1 lines") check("final answer", "Done: file says hi from hx.") check("file written", "") if os.path.exists(f"{tmp}/repo/hello.txt") else (print("FAIL file"), None) -send(b"/model claude-opus-4-1\r") -check("model switch", "model → claude-opus-4-1") +check("quota in footer", "5h 42%") +send(b"/usage\r") +check("usage report", "58% left, resets in 2h1") +send(b"/model claude-opus-5-5\r") +check("model switch", "model → claude-opus-5-5 · context 1000k") +send(b"/model claude-sonnet-5-6-preview\r") +check("live catalog window", "context 2000k") +check("live catalog cached", "") if os.path.exists(f"{tmp}/home/.hx/models-claude.json") else (print("FAIL no model cache"), globals().update(ok=False)) +buf = b"" +send(b"/provider ") +check("only logged-in providers offered", "claude") +ok &= "codex" not in plain(); print("PASS no codex without login" if "codex" not in plain() else "FAIL codex offered") +send(b"\x15") send(b"/bogus\r") check("unknown cmd", "unknown command /bogus") send(b"\x10") # ctrl-p