diff --git a/README.md b/README.md index f09c200..f473dc2 100644 --- a/README.md +++ b/README.md @@ -84,10 +84,14 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off ## Auto model -`/model auto` (or `model = "auto"`, `--model auto`) picks model and thinking level for every prompt, across all logged-in providers; `/model ` or `/provider` turns it off. No extra LLM call: the prompt is scored from cheap signals (length, keywords like `refactor`/`race condition` vs. `typo`/`explain`, a stack trace, a failed tool result in the last turn, a long session) into a tier: `fast` (Haiku/Luna), `balanced` (Sonnet/Terra), `deep` (Opus/Sol). Stepping up is immediate, stepping down needs `down_after` (default 3) light prompts in a row, because every switch costs the prompt cache. Very short replies ("ja", "continue") keep the current tier. The provider stays unless the other one has the tier exactly or the current one reported a used-up quota window. Each choice and its reason is shown as a line in the chat; the footer shows `auto→model`. +`/model auto` (or `model = "auto"`, `--model auto`) picks model and thinking level for every prompt, across all logged-in providers; `/model ` or `/provider` turns it off. No extra LLM call: the prompt is scored from cheap signals (length, keywords like `refactor`/`race condition` vs. `typo`/`explain`, a stack trace, a failed tool result in the last turn, a long session) into a tier: `fast` (Haiku/Luna), `balanced` (Sonnet/Terra), `deep` (Opus/Sol). Stepping up is immediate, stepping down needs `down_after` (default 3) light prompts in a row, because every switch costs the prompt cache. Very short replies ("ja", "continue") keep the current tier. The provider stays unless the other one has the tier exactly or the current one reported a used-up quota window. Common words (`implement`, `design`, `debug`, `plan`) count one point, not a tier; failed tool results escalate (+2, +4 when the last two turns failed), and many recent edits add a point. With a big history (>100k tokens) the default `down_after` is 5, since a switch re-reads it uncached. Each choice and its reason is shown as a line in the chat; the footer shows `auto→model`. + +**Fable** is never chosen by default. `/fable on` (or `[auto] fable = true`; the command is remembered across starts and wins over the config) lets auto escalate to a fifth `max` tier (Fable, $10/$50 per Mtok) after two failed turns in a row or a score of 7+; the next ordinary prompt drops back at once. Without Fable in the catalog it stays on `deep`. `/fable` shows the state; `@fable ...` / `@max ...` always work for one turn. One-turn override, with or without auto: start the prompt with `@opus fix this`, `@codex ...`, `@fast ...`, `@deep ...` or `@` (any unique part of an id, 3+ chars). A file with that name wins, so `@notes.md` stays a file mention. The previous model comes back after the turn (in auto mode, the router just chooses again). +Within a tier the highest-versioned model is used (`claude-opus-5-5` over `claude-opus-4-1-20250805`, `gpt-5.6-sol` over `gpt-5.5-sol`), whatever order the API lists them in; no model id is hard-coded except the offline fallback list and your `[auto]` pins. + Switching provider mid-session converts history: Codex reasoning items and unsigned thinking are dropped for Claude, tool-call ids are made Anthropic-safe. `hx stats` lists requests per model and the cache re-written after each switch. ```toml @@ -95,6 +99,7 @@ Switching provider mid-session converts history: Codex reasoning items and unsig fast = "claude-haiku-4-5" deep = "gpt-5.6-sol" # pins can name another provider's model down_after = 3 +fable = false # same as /fable on|off ``` ## Subagents diff --git a/crates/hx-ai/src/models.rs b/crates/hx-ai/src/models.rs index 4fc4f45..db2baf2 100644 --- a/crates/hx-ai/src/models.rs +++ b/crates/hx-ai/src/models.rs @@ -39,14 +39,40 @@ pub fn fallback(k: Kind) -> Vec { } } +/// Version of a model id: its numbers in order, a date snapshot (8+ digits) after the rest, so +/// `claude-opus-5-5` > `claude-opus-4-1-20250805` and `gpt-5.6-sol` > `gpt-5.5-sol`. +fn version(id: &str) -> Vec { + let n: Vec = id + .split(|c: char| !c.is_ascii_digit()) + .filter_map(|p| p.parse().ok()) + .collect(); + let (dates, mut v): (Vec, Vec) = n.into_iter().partition(|n| *n >= 10_000_000); + v.extend(dates); + v +} + +/// Stable models rank above previews, then by version. +fn key(m: &ModelInfo) -> (bool, Vec) { + (!m.id.contains("preview"), version(&m.id)) +} + +/// The highest-versioned model of `ms` (the first listed on a tie), whatever order the API lists them in. +pub fn newest<'a>(ms: impl IntoIterator) -> 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), + }) +} + /// 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::Claude => newest(mine.iter().copied().filter(|m| m.id.contains("sonnet"))), Kind::Codex | Kind::Custom => None, }; - pick.or(mine.first()) + pick.or(mine.first().copied()) .map(|m| m.id.clone()) .or_else(|| fallback(k).first().map(|m| m.id.clone())) .unwrap_or_default() @@ -59,10 +85,7 @@ pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option { Kind::Codex => "luna", Kind::Custom => return None, }; - models - .iter() - .find(|m| m.kind == k && m.id.contains(tag)) - .map(|m| m.id.clone()) + newest(models.iter().filter(|m| m.kind == k && m.id.contains(tag))).map(|m| m.id.clone()) } /// Context window for `id`: exact match, then dated-snapshot prefix match, then a family guess. diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index de5afca..569b9a4 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -830,6 +830,7 @@ async fn main() -> Result<()> { _ => kind, }; // the remembered model applies only to the provider it was chosen on + let last_fable = last.as_ref().and_then(|l| l.fable); let last = last.filter(|l| l.provider == kind); let last_effort = last.as_ref().and_then(|l| l.effort); // auto mode: `--model auto` / `model = "auto"`, else whatever was on last time @@ -889,8 +890,10 @@ async fn main() -> Result<()> { model: model.clone(), effort: Some(effort), auto: want_auto, + fable: last_fable, }; - let auto_cfg = cfg.auto.clone().unwrap_or_default(); + let mut auto_cfg = cfg.auto.clone().unwrap_or_default(); + auto_cfg.fable = last_fable.or(auto_cfg.fable); if hx_core::herdr::init() { hx_core::herdr::set_session(&path); agent.bus.add(hx_core::herdr::Hook); diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index ce21baa..cd0cc48 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -58,6 +58,11 @@ pub fn builtins(models: &[&str]) -> Vec { .collect(), ), ), + b( + "fable", + "let auto mode escalate to Fable (costly)", + Enum(vec!["on".into(), "off".into()]), + ), b( "provider", "switch provider", diff --git a/crates/hx-core/src/route.rs b/crates/hx-core/src/route.rs index 0d88824..b24a910 100644 --- a/crates/hx-core/src/route.rs +++ b/crates/hx-core/src/route.rs @@ -15,6 +15,8 @@ pub enum Tier { Fast, Balanced, Deep, + /// Fable: only with `[auto] fable` / `/fable on`, for repeated failures and the hardest prompts. + Max, } impl Tier { @@ -23,6 +25,7 @@ impl Tier { Tier::Fast => "fast", Tier::Balanced => "balanced", Tier::Deep => "deep", + Tier::Max => "max", } } @@ -35,17 +38,20 @@ impl Tier { 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) -> [Tier; 3] { + 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::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], } } } @@ -59,6 +65,9 @@ pub struct Cfg { 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 { @@ -67,6 +76,7 @@ impl Cfg { Tier::Fast => &self.fast, Tier::Balanced => &self.balanced, Tier::Deep => &self.deep, + Tier::Max => &None, } .as_deref() } @@ -80,6 +90,10 @@ pub struct Signals { /// 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] = &[ @@ -99,11 +113,9 @@ const DEEP: &[&str] = &[ "rewrite", "from scratch", "entwirf", - "design", - "implement", - "debug", - "plan", ]; +/// 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", @@ -149,6 +161,13 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals { 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; @@ -158,19 +177,42 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals { score += 1; hits.push("trace".into()); } - let failed = history.iter().rev().take(2).any(|m| { - m.content - .iter() - .any(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. })) - }); - if failed { - score += 2; - hits.push("last turn failed".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, @@ -182,6 +224,8 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals { tier, keep, hits, + max: score >= 7 || streak >= 2, + ctx, } } @@ -207,8 +251,10 @@ pub fn model_for(k: Kind, t: Tier, models: &[ModelInfo], cfg: &Cfg) -> Option = models.iter().filter(|m| m.kind == k).collect(); t.nearest() .iter() - .find_map(|t| mine.iter().find(|m| Tier::of(&m.id) == Some(*t))) - .or(mine.first()) + .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()) } @@ -297,28 +343,44 @@ impl Router { avoid: Option, models: &[ModelInfo], ) -> Option { - let n = self.cfg.down_after.unwrap_or(3); + // 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 sig.tier < c => { + Some((_, c)) if want < c => { self.down += 1; - if self.down >= n { + if self.down >= if c == Tier::Max { 1 } else { n } { self.down = 0; - sig.tier + want } else { c } } _ => { self.down = 0; - sig.tier + 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 != sig.tier && !sig.keep { - format!(", holding (wanted {})", sig.tier.name()) + let held = if tier != want && !sig.keep { + format!(", holding (wanted {})", want.name()) } else { String::new() }; @@ -363,6 +425,7 @@ pub fn parse_override( "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()) @@ -454,7 +517,99 @@ mod tests { }]; let s = signals("try again with a different approach", &h); assert_eq!(s.score, 2); - assert!(s.hits.iter().any(|h| h == "last turn failed")); + 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] diff --git a/crates/hx-core/src/switch.rs b/crates/hx-core/src/switch.rs index b2def62..a6fa003 100644 --- a/crates/hx-core/src/switch.rs +++ b/crates/hx-core/src/switch.rs @@ -35,6 +35,9 @@ pub struct Last { /// `/model auto` was on. #[serde(default)] pub auto: bool, + /// `/fable on|off`; overrides `[auto] fable` in the config. + #[serde(default)] + pub fable: Option, } impl Last { @@ -100,6 +103,19 @@ impl Switcher { self } + /// Allow (or forbid) Fable in auto mode; saved for the next start. + pub fn set_fable(&mut self, on: bool) { + self.auto_cfg.fable = Some(on); + if let Some(r) = &mut self.router { + r.cfg.fable = Some(on); + } + self.save(|l| l.fable = Some(on)); + } + + pub fn fable(&self) -> bool { + self.auto_cfg.fable == Some(true) + } + pub fn is_auto(&self) -> bool { self.router.is_some() } @@ -476,6 +492,7 @@ mod tests { model: "m".into(), effort: None, auto: false, + fable: None, }; let mut sw = sw.remember_in(f.clone(), start); sw.set_model(&mut a, "gpt-x").unwrap(); @@ -485,6 +502,7 @@ mod tests { model: "gpt-x".into(), effort: Some(hx_ai::Effort::High), auto: false, + fable: None, }; assert_eq!(Last::load(&f), Some(want)); std::fs::write(&f, "junk").unwrap(); diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 49ea3a9..2690e12 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -1507,6 +1507,19 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { "model: auto. Picked per prompt across logged-in providers; `@opus ...`, `@codex ...`, `@fast ...` force one turn.".into(), )); } + "fable" if arg.is_empty() => app.t.push(Item::Info(format!( + "fable in auto mode: {}", + if app.sw.fable() { "on" } else { "off" } + ))), + "fable" if arg == "on" || arg == "off" => { + app.sw.set_fable(arg == "on"); + app.t.push(Item::Info(if arg == "on" { + "fable on: auto escalates to Fable after 2 failed turns in a row or a very hard prompt ($10/$50 per Mtok). `@fable ...` always works.".into() + } else { + "fable off".into() + })); + } + "fable" => app.t.push(Item::Error("/fable on|off".into())), "model" => { let mut a = agent.lock().await; match app.sw.set_model(&mut a, arg) {