//! Automatic model choice per prompt (`/model auto`) and one-turn overrides (`@opus fix this`). //! //! Pure functions plus a small [`Router`] that remembers the last tier for hysteresis. No LLM call: //! a prompt is scored from cheap signals (length, keywords, trace, last turn failed), the score //! maps to a [`Tier`], and the tier maps to a model per provider by name. //! ponytail: keyword heuristics; replace [`signals`] with a classifier call if stats show misses. use hx_ai::auth::Kind; use hx_ai::models::ModelInfo; use hx_ai::{ContentBlock, Effort, Message}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Tier { Fast, Balanced, Deep, /// Fable: only with `[auto] fable` / `/fable on`, for repeated failures and the hardest prompts. Max, } impl Tier { pub fn name(self) -> &'static str { match self { Tier::Fast => "fast", Tier::Balanced => "balanced", Tier::Deep => "deep", Tier::Max => "max", } } /// Tier of a model by family name (Haiku/Luna, Sonnet/Terra, Opus/Sol); unknown models have none. pub fn of(id: &str) -> Option { let has = |a: &[&str]| a.iter().any(|t| id.contains(t)); if has(&["haiku", "luna", "mini"]) { Some(Tier::Fast) } else if has(&["sonnet", "terra"]) { Some(Tier::Balanced) } else if has(&["opus", "sol"]) { Some(Tier::Deep) } else if has(&["fable"]) { Some(Tier::Max) } else { None } } /// Tiers to try for a provider lacking this one: the closest first. fn nearest(self) -> &'static [Tier] { match self { Tier::Fast => &[Tier::Fast, Tier::Balanced, Tier::Deep], Tier::Balanced => &[Tier::Balanced, Tier::Deep, Tier::Fast], Tier::Deep => &[Tier::Deep, Tier::Balanced, Tier::Fast], Tier::Max => &[Tier::Max, Tier::Deep, Tier::Balanced, Tier::Fast], } } } /// `[auto]` in config: pin a tier to a model (of any provider), tune the step-down delay. #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct Cfg { pub fast: Option, pub balanced: Option, pub deep: Option, /// Light prompts in a row before dropping to a cheaper tier (default 3). Stepping up is immediate. pub down_after: Option, /// Let auto mode escalate to Fable (repeated failures, very hard prompts). Off by default; /// `/fable on|off` overrides it. pub fable: Option, } impl Cfg { fn pin(&self, t: Tier) -> Option<&str> { match t { Tier::Fast => &self.fast, Tier::Balanced => &self.balanced, Tier::Deep => &self.deep, Tier::Max => &None, } .as_deref() } } /// What the prompt and the last turn say about difficulty. #[derive(Debug, Clone, PartialEq)] pub struct Signals { pub score: i32, pub tier: Tier, /// Too short and plain ("continue", "ja") to say anything: keep the current tier. pub keep: bool, pub hits: Vec, /// Hard enough for Fable when that is on: score 7+ or two failed turns in a row. pub max: bool, /// Estimated tokens of history (a tier switch re-reads them uncached). pub ctx: usize, } const DEEP: &[&str] = &[ "refactor", "architect", "architektur", "redesign", "migrat", "race condition", "deadlock", "concurren", "security", "sicherheit", "root cause", "performance", "optimi", "rewrite", "from scratch", "entwirf", ]; /// Common words: worth one point, never a whole tier on their own. Matched as word starts. const WEAK: &[&str] = &["design", "implement", "debug", "plan"]; const LIGHT: &[&str] = &[ "typo", "rename", "format", "explain", "erkl", "what is", "what does", "was ist", "was macht", "show me", "zeig", "commit", "comment", "kommentar", "summar", "zusammenfass", ]; const TRACE: &[&str] = &[ "traceback", "panicked at", "error[e", "stack trace", "exception", ]; /// Score `prompt`; `history` is the session so far (a failed tool result in the last two messages /// escalates). pub fn signals(prompt: &str, history: &[Message]) -> Signals { let p = prompt.to_lowercase(); let mut hits = vec![]; let mut score = 0; let len = prompt.chars().count(); if len > 2000 { score += 2; hits.push("long prompt".into()); } else if len > 600 { score += 1; hits.push("long-ish prompt".into()); } let deep: Vec<&str> = DEEP.iter().copied().filter(|k| p.contains(k)).collect(); if !deep.is_empty() { score += 2 * deep.len().min(2) as i32; hits.push(deep.join(",")); } let weak = p .split(|c: char| !c.is_alphanumeric()) .find(|w| WEAK.iter().any(|k| w.starts_with(k))); if let Some(w) = weak { score += 1; hits.push(w.to_string()); } let light: Vec<&str> = LIGHT.iter().copied().filter(|k| p.contains(k)).collect(); if !light.is_empty() { score -= 2; hits.push(light.join(",")); } if TRACE.iter().any(|k| p.contains(k)) { score += 1; hits.push("trace".into()); } // consecutive turns (tool-result messages) that failed, newest first let streak = history .iter() .rev() .filter(|m| { m.content .iter() .any(|b| matches!(b, ContentBlock::ToolResult { .. })) }) .map(|m| { m.content .iter() .any(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. })) }) .take_while(|f| *f) .count(); if streak > 0 { score += if streak > 1 { 4 } else { 2 }; hits.push(format!("{streak} failed in a row")); } let edits = history .iter() .rev() .take(20) .flat_map(|m| &m.content) .filter(|b| matches!(b, ContentBlock::ToolUse { name, .. } if name == "edit" || name == "write")) .count(); if edits >= 4 { score += 1; hits.push(format!("{edits} recent edits")); } if history.len() > 40 { score += 1; hits.push("long session".into()); } let ctx = serde_json::to_vec(history).map_or(0, |v| v.len() / 4); let keep = hits.is_empty() && prompt.split_whitespace().count() <= 3; let tier = match score { i32::MIN..=-1 => Tier::Fast, 0..=2 => Tier::Balanced, _ => Tier::Deep, }; Signals { score, tier, keep, hits, max: score >= 7 || streak >= 2, ctx, } } /// Thinking level for a score: lowest for light prompts, high for hard ones, else the provider default. fn effort_for(score: i32, k: Kind) -> Effort { let lv = Effort::levels(k); let e = match score { i32::MIN..=-1 => lv[0], 3..=i32::MAX => Effort::High, _ => Effort::default_for(k), }; if lv.contains(&e) { e } else { lv[0] } } /// Model of provider `k` for tier `t`: the config pin, else the catalog by family name, else the /// closest tier it has, else its first model (custom endpoints). pub fn model_for(k: Kind, t: Tier, models: &[ModelInfo], cfg: &Cfg) -> Option { if let Some(m) = cfg.pin(t) && hx_ai::models::kind_of(models, m) == Some(k) { return Some(m.to_string()); } let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect(); t.nearest() .iter() .find_map(|t| { hx_ai::models::newest(mine.iter().copied().filter(|m| Tier::of(&m.id) == Some(*t))) }) .or(mine.first().copied()) .map(|m| m.id.clone()) } /// Provider for tier `t`: the config pin's provider, else `prefer` (keeps the prompt cache), else /// any logged-in one with that exact tier, else any. `avoid` (out of quota) is skipped when /// something else exists. Custom endpoints only serve when nothing else is logged in. pub fn pick_for( t: Tier, prefer: Kind, avoid: Option, models: &[ModelInfo], cfg: &Cfg, ) -> Option<(Kind, String)> { let mut kinds: Vec = vec![]; for m in models { if !kinds.contains(&m.kind) { kinds.push(m.kind); } } if kinds.iter().any(|k| *k != Kind::Custom) { kinds.retain(|k| *k != Kind::Custom); } if kinds.len() > 1 && avoid.is_some() { kinds.retain(|k| Some(*k) != avoid); } let pinned = cfg .pin(t) .and_then(|m| hx_ai::models::kind_of(models, m)) .filter(|k| kinds.contains(k)); let order: Vec = pinned .into_iter() .chain(kinds.iter().copied().filter(|k| *k == prefer)) .chain(kinds.iter().copied()) .collect(); let exact = |k: &Kind| { models .iter() .any(|m| m.kind == *k && Tier::of(&m.id) == Some(t)) || cfg .pin(t) .is_some_and(|p| hx_ai::models::kind_of(models, p) == Some(*k)) }; let k = order.iter().find(|k| exact(k)).or(order.first()).copied()?; model_for(k, t, models, cfg).map(|m| (k, m)) } /// What to use for the next prompt. #[derive(Debug, Clone, PartialEq)] pub struct Pick { pub kind: Kind, pub model: String, pub tier: Tier, pub effort: Effort, pub why: String, } #[derive(Debug, Default)] pub struct Router { pub cfg: Cfg, cur: Option<(Kind, Tier)>, down: u32, } impl Router { pub fn new(cfg: Cfg) -> Self { Self { cfg, cur: None, down: 0, } } /// Forget the last choice (auto mode was switched on again). pub fn reset(&mut self) { self.cur = None; self.down = 0; } /// Choose for a prompt. Up-tiers apply at once; a cheaper tier only after `down_after` light /// prompts in a row (a switch costs the prompt cache). `start` is the provider in use when /// nothing was chosen yet; `avoid` is a provider that is out of quota. pub fn route( &mut self, sig: &Signals, start: Kind, avoid: Option, models: &[ModelInfo], ) -> Option { // a switch re-reads the history uncached: the bigger it is, the longer a tier is held; // Fable is dropped at once, it costs the most let n = self .cfg .down_after .unwrap_or(if sig.ctx > 100_000 { 5 } else { 3 }); let want = if sig.max && self.cfg.fable == Some(true) { Tier::Max } else { sig.tier }; let tier = match self.cur { Some((_, c)) if sig.keep => c, Some((_, c)) if want < c => { self.down += 1; if self.down >= if c == Tier::Max { 1 } else { n } { self.down = 0; want } else { c } } _ => { self.down = 0; want } }; let prefer = self.cur.map_or(start, |(k, _)| k); let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?; // no Fable in the catalog: it ran as Deep let tier = if tier == Tier::Max && Tier::of(&model) != Some(Tier::Max) { Tier::Deep } else { tier }; self.cur = Some((kind, tier)); let held = if tier != want && !sig.keep { format!(", holding (wanted {})", want.name()) } else { String::new() }; let hits = if sig.hits.is_empty() { String::new() } else { format!(": {}", sig.hits.join(" ยท ")) }; Some(Pick { kind, model, tier, effort: effort_for(sig.score, kind), why: format!("{} (score {}{hits}{held})", tier.name(), sig.score), }) } } /// One line per routed prompt in `.route` (JSON), read back by `hx stats`: the data to /// tune the keyword lists and thresholds from. Best effort. pub fn log(session: &std::path::Path, sig: &Signals, p: &Pick, effort: Effort, forced: bool) { use std::io::Write; let line = serde_json::json!({ "ts": hx_ai::auth::now_ms() / 1000, "model": p.model, "tier": p.tier.name(), "wanted": sig.tier.name(), "score": sig.score, "effort": effort.name(), "ctx": sig.ctx, "hits": sig.hits, "forced": forced, }); // ponytail: a failed log write must not fail the prompt let _ = std::fs::OpenOptions::new() .create(true) .append(true) .open(session.with_extension("route")) .and_then(|mut f| writeln!(f, "{line}")); } /// What `@word` at the start of a prompt asks for. #[derive(Debug, Clone, PartialEq)] pub enum Target { Tier(Tier), Provider(Kind), Model(String), } /// `@opus fix this` -> (model, "fix this"). The word is a tier (`fast`, `balanced`, `deep`), a /// provider (`claude`, `codex`), a model id, or a unique part of one (min 3 chars: `opus`, `sol`). /// Needs text after it, and a file of that name wins (`@notes.md` stays a file mention). pub fn parse_override( line: &str, models: &[ModelInfo], is_file: &dyn Fn(&str) -> bool, ) -> Option<(Target, String)> { let (w, rest) = line.strip_prefix('@')?.split_once(char::is_whitespace)?; let rest = rest.trim(); if rest.is_empty() || w.is_empty() || is_file(w) { return None; } let lw = w.to_lowercase(); let t = match lw.as_str() { "fast" => Target::Tier(Tier::Fast), "balanced" => Target::Tier(Tier::Balanced), "deep" => Target::Tier(Tier::Deep), "max" => Target::Tier(Tier::Max), _ => { if let Some(m) = models.iter().find(|m| m.id.to_lowercase() == lw) { Target::Model(m.id.clone()) } else if let Some(k) = ["claude", "codex"] .contains(&lw.as_str()) .then(|| lw.parse::().ok()) .flatten() { Target::Provider(k) } else if lw.len() >= 3 && lw.starts_with(|c: char| c.is_ascii_alphabetic()) { let hit: Vec<&ModelInfo> = models .iter() .filter(|m| m.id.to_lowercase().contains(&lw)) .collect(); match hit.as_slice() { [m] => Target::Model(m.id.clone()), // `@sonnet` with several dated snapshots: the first listed (newest) [m, ..] if hit.iter().all(|h| h.kind == m.kind) => Target::Model(m.id.clone()), _ => return None, } } else { return None; } } }; Some((t, rest.to_string())) } #[cfg(test)] mod tests { use super::*; fn m(id: &str, kind: Kind) -> ModelInfo { ModelInfo { id: id.into(), kind, context_window: 1, } } fn cat() -> Vec { vec![ m("claude-opus-5-5", Kind::Claude), m("claude-sonnet-5-5", Kind::Claude), m("claude-haiku-4-5", Kind::Claude), m("gpt-5.6-sol", Kind::Codex), m("gpt-5.6-terra", Kind::Codex), m("gpt-5.6-luna", Kind::Codex), ] } fn tier(p: &str) -> Tier { signals(p, &[]).tier } #[test] fn tiers_by_name() { assert_eq!(Tier::of("claude-haiku-4-5"), Some(Tier::Fast)); assert_eq!(Tier::of("gpt-5.6-terra"), Some(Tier::Balanced)); assert_eq!(Tier::of("gpt-5.6-sol"), Some(Tier::Deep)); assert_eq!(Tier::of("llama3"), None); } #[test] fn prompts_score_into_tiers() { assert_eq!(tier("fix the typo in README"), Tier::Fast); assert_eq!( tier("add a --foo flag to the cli parser please"), Tier::Balanced ); assert_eq!( tier("refactor the auth module and remove the race condition"), Tier::Deep ); assert_eq!(tier(&"x ".repeat(1500)), Tier::Balanced); assert!(signals("ja", &[]).keep && signals("continue please", &[]).keep); assert!(!signals("fix typo", &[]).keep, "keyword hit is a signal"); } #[test] fn failed_tool_result_escalates() { let h = vec![Message { role: hx_ai::Role::User, content: vec![ContentBlock::ToolResult { tool_use_id: "t".into(), content: "boom".into(), is_error: true, }], }]; let s = signals("try again with a different approach", &h); assert_eq!(s.score, 2); assert!(s.hits.iter().any(|h| h == "1 failed in a row")); } fn fail() -> Message { Message { role: hx_ai::Role::User, content: vec![ContentBlock::ToolResult { tool_use_id: "t".into(), content: "boom".into(), is_error: true, }], } } #[test] fn weak_words_alone_stay_balanced() { assert_eq!(tier("implement the --foo flag"), Tier::Balanced); assert_eq!(tier("plan the release notes"), Tier::Balanced); } #[test] fn fable_only_when_on_and_escalates_on_repeated_failure() { let mut models = cat(); models.push(m("claude-fable-5-1", Kind::Claude)); let h = vec![fail(), fail()]; let s = signals("try again", &h); assert!(s.max && !signals("try again", &h[..1]).max); let mut off = Router::new(Cfg::default()); let p = off.route(&s, Kind::Claude, None, &models).unwrap(); assert_eq!(p.model, "claude-opus-5-5"); let on = Cfg { fable: Some(true), ..Default::default() }; let mut r = Router::new(on.clone()); let p = r.route(&s, Kind::Claude, None, &models).unwrap(); assert_eq!((p.tier, p.model.as_str()), (Tier::Max, "claude-fable-5-1")); // one light prompt drops Fable at once let light = signals("fix the typo in README", &[]); assert_ne!( r.route(&light, Kind::Claude, None, &models).unwrap().tier, Tier::Max ); // on, but no Fable in the catalog: Deep let mut r = Router::new(on); let p = r.route(&s, Kind::Claude, None, &cat()).unwrap(); assert_eq!((p.tier, p.model.as_str()), (Tier::Deep, "claude-opus-5-5")); assert_eq!( parse_override("@max go", &cat(), &|_| false).unwrap().0, Target::Tier(Tier::Max) ); } #[test] fn newest_version_wins_whatever_the_list_order() { let ms = vec![ m("claude-opus-4-1-20250805", Kind::Claude), m("claude-opus-5-5", Kind::Claude), m("claude-opus-4-5", Kind::Claude), m("claude-sonnet-5-5", Kind::Claude), m("claude-sonnet-5-6-preview", Kind::Claude), ]; let c = Cfg::default(); assert_eq!( model_for(Kind::Claude, Tier::Deep, &ms, &c).unwrap(), "claude-opus-5-5" ); assert_eq!( hx_ai::models::default_for(Kind::Claude, &ms), "claude-sonnet-5-5" ); } #[test] fn big_context_holds_the_tier_longer() { let mut r = Router::new(Cfg::default()); let hard = signals( "refactor the auth module and remove the race condition", &[], ); r.route(&hard, Kind::Codex, None, &cat()).unwrap(); let mut light = signals("fix the typo in README", &[]); light.ctx = 200_000; for _ in 0..4 { assert_eq!( r.route(&light, Kind::Codex, None, &cat()).unwrap().tier, Tier::Deep ); } assert_eq!( r.route(&light, Kind::Codex, None, &cat()).unwrap().tier, Tier::Fast ); } #[test] fn effort_follows_score_and_provider() { assert_eq!(effort_for(-2, Kind::Claude), Effort::Off); assert_eq!(effort_for(-2, Kind::Codex), Effort::Low); assert_eq!(effort_for(0, Kind::Claude), Effort::Off); assert_eq!(effort_for(0, Kind::Codex), Effort::Medium); assert_eq!(effort_for(4, Kind::Claude), Effort::High); } #[test] fn stays_on_provider_and_steps_down_slowly() { let mut r = Router::new(Cfg::default()); let light = signals("fix the typo in README", &[]); let hard = signals( "refactor the auth module and remove the race condition", &[], ); let p = r.route(&hard, Kind::Codex, None, &cat()).unwrap(); assert_eq!((p.kind, p.model.as_str()), (Kind::Codex, "gpt-5.6-sol")); // two light prompts hold the tier, the third drops it for _ in 0..2 { let p = r.route(&light, Kind::Codex, None, &cat()).unwrap(); assert_eq!(p.tier, Tier::Deep); } let p = r.route(&light, Kind::Codex, None, &cat()).unwrap(); assert_eq!((p.tier, p.model.as_str()), (Tier::Fast, "gpt-5.6-luna")); // up again at once assert_eq!( r.route(&hard, Kind::Codex, None, &cat()).unwrap().tier, Tier::Deep ); // "ja" keeps whatever is current let ack = signals("ja", &[]); assert_eq!( r.route(&ack, Kind::Codex, None, &cat()).unwrap().tier, Tier::Deep ); } #[test] fn quota_and_pins_cross_providers() { let mut r = Router::new(Cfg::default()); let p = r .route( &signals("add a flag to the cli parser please", &[]), Kind::Claude, Some(Kind::Claude), &cat(), ) .unwrap(); assert_eq!(p.kind, Kind::Codex, "claude out of quota"); let cfg = Cfg { deep: Some("gpt-5.6-sol".into()), ..Default::default() }; let mut r = Router::new(cfg); let hard = signals( "refactor the auth module and remove the race condition", &[], ); let p = r.route(&hard, Kind::Claude, None, &cat()).unwrap(); assert_eq!((p.kind, p.model.as_str()), (Kind::Codex, "gpt-5.6-sol")); let easy = signals("add a flag to the cli parser please", &[]); let mut r2 = Router::new(Cfg::default()); assert_eq!( r2.route(&easy, Kind::Claude, None, &cat()).unwrap().model, "claude-sonnet-5-5" ); } #[test] fn only_claude_logged_in_never_picks_codex() { let only: Vec = cat() .into_iter() .filter(|m| m.kind == Kind::Claude) .collect(); let mut r = Router::new(Cfg::default()); let p = r .route( &signals("typo", &[]), Kind::Claude, Some(Kind::Claude), &only, ) .unwrap(); assert_eq!( p.kind, Kind::Claude, "avoid is ignored when nothing else exists" ); } #[test] fn override_words() { let no = |_: &str| false; let p = |l: &str| parse_override(l, &cat(), &no); assert_eq!( p("@opus fix das"), Some((Target::Model("claude-opus-5-5".into()), "fix das".into())) ); assert_eq!( p("@fast what is this"), Some((Target::Tier(Tier::Fast), "what is this".into())) ); assert_eq!( p("@codex go"), Some((Target::Provider(Kind::Codex), "go".into())) ); assert_eq!( p("@gpt-5.6-sol x").unwrap().0, Target::Model("gpt-5.6-sol".into()) ); // ambiguous across providers, too short, no text, unknown assert_eq!(p("@5 x"), None); assert_eq!(p("@5.6 x"), None); assert_eq!(p("@opus"), None); assert_eq!(p("@src/main.rs explain"), None); // a file of that name wins assert_eq!(parse_override("@opus hi", &cat(), &|w| w == "opus"), None); assert_eq!(p("opus fix"), None); } }