//! Switching the agent's model or provider at runtime. //! //! A model id only means something to one provider, so changing the model can mean changing the //! provider too. And a new model has a new context window, so the compaction threshold has to //! follow. [`Switcher`] does all of that behind two calls; the TUI and the RPC server share it. use crate::agent::Agent; use crate::route::{self, Router}; use hx_ai::Provider; use hx_ai::auth::Kind; use hx_ai::models::{self, ModelInfo}; use std::sync::Arc; pub type MakeProvider = Box hx_ai::Result> + Send>; /// What a switch did. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Switched { pub kind: Kind, pub model: String, /// The provider client was rebuilt, not just the model: provider-specific state (quota) is stale. pub provider_changed: bool, /// Context window of the new model, in tokens. pub window: u64, } /// Last chosen provider + model, kept in `$HX_HOME/last.json` so the next start reuses it. #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)] pub struct Last { pub provider: Kind, pub model: String, /// Thinking level; absent in files written before it was saved. #[serde(default)] pub effort: Option, /// `/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 { /// `None` when the file is missing or unreadable. pub fn load(path: &std::path::Path) -> Option { serde_json::from_slice(&std::fs::read(path).ok()?).ok() } } pub struct Switcher { remember: Option<(std::path::PathBuf, Last)>, kind: Kind, models: Vec, make_provider: MakeProvider, /// `Some` while `/model auto` is on. router: Option, auto_cfg: route::Cfg, /// Providers out of quota until a unix second. spent: Vec<(Kind, u64)>, /// What to go back to after a one-turn override outside auto mode. restore: Option<(Kind, String, hx_ai::Effort)>, } /// The pick for one prompt, and how the agent was switched to it. #[derive(Debug, Clone, PartialEq)] pub struct Routed { pub pick: route::Pick, pub sw: Switched, /// The pick came from an `@word` override, not from auto. pub forced: bool, /// The prompt without the `@word`. pub prompt: String, } impl Switcher { /// `kind` is the provider the agent starts with. The agent's `ContextPolicy` decides whether a /// model switch moves the compaction threshold. pub fn new(kind: Kind, models: Vec, make_provider: MakeProvider) -> Self { Self { remember: None, kind, models, make_provider, router: None, auto_cfg: route::Cfg::default(), spent: vec![], restore: None, } } /// `[auto]` config: tier pins and the step-down delay. pub fn auto_cfg(mut self, c: route::Cfg) -> Self { self.auto_cfg = c; self } /// Start with auto mode on or off. pub fn auto_on(mut self, on: bool) -> Self { self.router = on.then(|| route::Router::new(self.auto_cfg.clone())); if let Some((_, l)) = &mut self.remember { l.auto = on; } 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() } /// `/model auto` (true) or a pinned model (false, done by `set_model`/`set_provider`). pub fn set_auto(&mut self, on: bool) { self.router = on.then(|| route::Router::new(self.auto_cfg.clone())); self.save(|l| l.auto = on); } fn save(&mut self, f: impl FnOnce(&mut Last)) { if let Some((p, l)) = &mut self.remember { f(l); // ponytail: failing to save must not fail the switch let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b)); } } /// The provider reported its limits: remember one that is used up until its window resets. pub fn note_quota(&mut self, kind: Kind, q: &hx_ai::Quota) { let now = hx_ai::auth::now_ms() / 1000; self.spent.retain(|(k, t)| *k != kind && *t > now); let full: Vec<&hx_ai::QuotaWindow> = q.windows.iter().filter(|w| w.used_pct >= 99.5).collect(); if !full.is_empty() { let until = full .iter() .filter_map(|w| w.resets_at) .max() .unwrap_or(now + 3600); self.spent.push((kind, until)); } } fn out_of_quota(&self) -> Option { let now = hx_ai::auth::now_ms() / 1000; self.spent.iter().find(|(_, t)| *t > now).map(|(k, _)| *k) } /// Before a prompt: in auto mode choose model and thinking level for it; an `@word` override /// (`@opus`, `@codex`, `@fast`) applies to this prompt only, with or without auto. `None` = /// leave the agent as it is. Call [`end_turn`](Self::end_turn) when the run is over. pub fn begin_turn( &mut self, agent: &mut Agent, prompt: &str, is_file: &dyn Fn(&str) -> bool, ) -> Result, String> { let forced = route::parse_override(prompt, &self.models, is_file); if self.router.is_none() && forced.is_none() { return Ok(None); } let hist = agent.session().messages(); let (text, target) = match &forced { Some((t, rest)) => (rest.as_str(), Some(t)), None => (prompt, None), }; let sig = route::signals(text, &hist); let before = (self.kind, agent.model().to_string(), agent.effort()); let avoid = self.out_of_quota(); let pick = match target { Some(route::Target::Model(m)) => { let kind = models::kind_of(&self.models, m).unwrap_or(self.kind); let tier = route::Tier::of(m).unwrap_or(sig.tier); route::Pick { kind, model: m.clone(), tier, effort: before.2, why: format!("@{m}"), } } Some(route::Target::Provider(k)) => { let (kind, model) = route::pick_for(sig.tier, *k, None, &self.models_of(*k), &self.auto_cfg) .ok_or_else(|| format!("no models for {k:?}"))?; route::Pick { kind, model, tier: sig.tier, effort: before.2, why: format!("@{k:?}, {} tier", sig.tier.name()).to_lowercase(), } } Some(route::Target::Tier(t)) => { let (kind, model) = route::pick_for(*t, self.kind, avoid, &self.models, &self.auto_cfg) .ok_or("no models")?; route::Pick { kind, model, tier: *t, effort: before.2, why: format!("@{}", t.name()), } } None => { let Some(r) = &mut self.router else { return Ok(None); }; match r.route(&sig, self.kind, avoid, &self.models) { Some(p) => p, None => return Ok(None), } } }; let was_auto = self.router.is_some(); if forced.is_some() && !was_auto { self.restore = Some(before.clone()); } let effort = if forced.is_some() { // the forced model keeps the user's level when it has it, else its first let lv = hx_ai::Effort::levels(pick.kind); if lv.contains(&before.2) { before.2 } else { lv[0] } } else { pick.effort }; let same = pick.kind == self.kind && pick.model == before.1; let sw = if same { Switched { kind: pick.kind, model: pick.model.clone(), provider_changed: false, window: models::window(&self.models, &pick.model), } } else { // auto picks and one-turn overrides are not the user's pinned choice self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)? }; agent.set_effort(effort); route::log( agent.session().path(), &sig, &pick, effort, forced.is_some(), ); Ok(Some(Routed { pick: route::Pick { effort, ..pick }, sw, forced: forced.is_some(), prompt: text.to_string(), })) } /// After the run: undo a one-turn override made outside auto mode. Returns what it went back to. pub fn end_turn(&mut self, agent: &mut Agent) -> Option { let (kind, model, effort) = self.restore.take()?; let sw = self.apply_inner(agent, kind, model, false, false).ok()?; agent.set_effort(effort); Some(sw) } fn models_of(&self, k: Kind) -> Vec { self.models .iter() .filter(|m| m.kind == k) .cloned() .collect() } /// Write every successful switch to `path` (best effort). /// `start` is what the agent starts with. pub fn remember_in(mut self, path: std::path::PathBuf, start: Last) -> Self { self.remember = Some((path, start)); self } /// Save a new thinking level next to the model (best effort). pub fn remember_effort(&mut self, e: hx_ai::Effort) { if let Some((p, l)) = &mut self.remember { l.effort = Some(e); let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b)); } } /// The provider the agent currently uses. pub fn kind(&self) -> Kind { self.kind } /// Use model `id`, on whichever provider it belongs to (the current one if unknown). /// On error the agent and the switcher are unchanged. pub fn set_model(&mut self, agent: &mut Agent, id: &str) -> Result { let kind = models::kind_of(&self.models, id).unwrap_or(self.kind); self.router = None; self.save(|l| l.auto = false); self.apply(agent, kind, id.to_string(), false) } /// Use provider `kind` with its default model. The client is rebuilt even for the current /// provider, which picks up refreshed credentials after a re-login. pub fn set_provider(&mut self, agent: &mut Agent, kind: Kind) -> Result { let model = models::default_for(kind, &self.models); self.router = None; self.save(|l| l.auto = false); self.apply(agent, kind, model, true) } fn apply( &mut self, agent: &mut Agent, kind: Kind, model: String, rebuild: bool, ) -> Result { self.apply_inner(agent, kind, model, rebuild, true) } fn apply_inner( &mut self, agent: &mut Agent, kind: Kind, model: String, rebuild: bool, remember: bool, ) -> Result { let provider_changed = rebuild || kind != self.kind; if provider_changed { let p = (self.make_provider)(kind).map_err(|e| e.to_string())?; agent.set_provider(p, model.as_str()); self.kind = kind; } else { agent.set_model(model.as_str()); } if remember { self.save(|l| { l.provider = kind; l.model = model.clone(); }); } let window = models::window(&self.models, &model); agent.set_model_window(window); Ok(Switched { kind, model, provider_changed, window, }) } } #[cfg(test)] mod tests { use super::*; use crate::session::Session; use crate::tool::{Registry, ToolCtx}; use std::sync::Mutex; struct Nop; #[async_trait::async_trait] impl Provider for Nop { async fn stream( &self, _: hx_ai::Request, ) -> hx_ai::Result>> { unreachable!() } } fn catalog() -> Vec { let m = |id: &str, kind, w| ModelInfo { id: id.into(), kind, context_window: w, }; vec![ m("claude-sonnet-x", Kind::Claude, 200_000), m("claude-haiku-x", Kind::Claude, 100_000), m("gpt-x", Kind::Codex, 400_000), ] } /// Switcher whose factory records the kinds it was asked for, and an agent to switch. fn setup( auto: bool, fail: bool, ) -> (Switcher, Agent, Arc>>, tempfile::TempDir) { let made = Arc::new(Mutex::new(vec![])); let m2 = made.clone(); let sw = Switcher::new( Kind::Claude, catalog(), Box::new(move |k| { m2.lock().unwrap().push(k); if fail { Err(hx_ai::Error::Http("not logged in".into())) } else { Ok(Arc::new(Nop)) } }), ); let dir = tempfile::tempdir().unwrap(); let cx = ToolCtx { cwd: dir.path().into(), state: Default::default(), }; let (mut a, _h) = Agent::new( Arc::new(Nop), Registry::default(), Session::open(dir.path().join("s.jsonl")).unwrap(), cx, ); if auto { a.set_context_policy(crate::window::ContextPolicy::FromModel { window: 0 }); } a.set_model("claude-sonnet-x"); (sw, a, made, dir) } #[test] fn same_provider_keeps_it_and_refits_the_window() { let (mut sw, mut a, made, _d) = setup(true, false); let s = sw.set_model(&mut a, "claude-haiku-x").unwrap(); assert_eq!( s, Switched { kind: Kind::Claude, model: "claude-haiku-x".into(), provider_changed: false, window: 100_000 } ); assert!(made.lock().unwrap().is_empty(), "no new provider needed"); assert_eq!(a.model(), "claude-haiku-x"); assert!(a.compact_at() <= 90_000, "threshold follows the window"); } #[test] fn model_of_another_provider_switches_provider() { let (mut sw, mut a, made, _d) = setup(true, false); let s = sw.set_model(&mut a, "gpt-x").unwrap(); assert!(s.provider_changed && s.kind == Kind::Codex); assert_eq!(*made.lock().unwrap(), vec![Kind::Codex]); assert_eq!((sw.kind(), a.model()), (Kind::Codex, "gpt-x")); // back on the same provider: no second factory call sw.set_model(&mut a, "gpt-y-unknown").unwrap(); assert_eq!(made.lock().unwrap().len(), 1); } #[test] fn provider_switch_uses_its_default_model() { let (mut sw, mut a, _m, _d) = setup(true, false); let s = sw.set_provider(&mut a, Kind::Codex).unwrap(); assert_eq!((s.model.as_str(), s.provider_changed), ("gpt-x", true)); assert_eq!(a.model(), "gpt-x"); } #[test] fn explicit_provider_switch_rebuilds_even_the_current_one() { let (mut sw, mut a, made, _d) = setup(true, false); let s = sw.set_provider(&mut a, Kind::Claude).unwrap(); assert!(s.provider_changed, "fresh client, so quota is stale"); assert_eq!(*made.lock().unwrap(), vec![Kind::Claude]); } #[test] fn failure_changes_nothing() { let (mut sw, mut a, _m, _d) = setup(true, true); let before = a.compact_at(); let e = sw.set_model(&mut a, "gpt-x").unwrap_err(); assert!(e.contains("not logged in"), "{e}"); assert_eq!( (sw.kind(), a.model(), a.compact_at()), (Kind::Claude, "claude-sonnet-x", before) ); } #[test] fn switches_are_remembered() { let (sw, mut a, _m, d) = setup(true, false); let f = d.path().join("last.json"); assert_eq!(Last::load(&f), None); let start = Last { provider: Kind::Claude, 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(); sw.remember_effort(hx_ai::Effort::High); let want = Last { provider: Kind::Codex, 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(); assert_eq!(Last::load(&f), None); } fn nofile(_: &str) -> bool { false } #[test] fn auto_routes_per_prompt_and_pin_turns_it_off() { let (mut sw, mut a, made, _d) = setup(true, false); sw.set_auto(true); assert!(sw.is_auto()); let r = sw .begin_turn(&mut a, "fix the typo in README", &nofile) .unwrap() .unwrap(); assert!(!r.forced); assert_eq!( (r.pick.model.as_str(), a.model()), ("claude-haiku-x", "claude-haiku-x") ); assert!(made.lock().unwrap().is_empty(), "same provider: no rebuild"); let rep = crate::stats::route_report(a.session().path()); assert!(rep.contains("fast: 1 prompts"), "{rep}"); sw.set_model(&mut a, "claude-sonnet-x").unwrap(); assert!(!sw.is_auto()); assert!( sw.begin_turn(&mut a, "fix the typo", &nofile) .unwrap() .is_none() ); } #[test] fn override_is_one_turn_and_restores() { let (mut sw, mut a, made, _d) = setup(true, false); a.set_effort(hx_ai::Effort::High); let r = sw .begin_turn(&mut a, "@gpt-x explain this", &nofile) .unwrap() .unwrap(); assert!(r.forced && r.sw.provider_changed); assert_eq!(r.prompt, "explain this"); assert_eq!((sw.kind(), a.model()), (Kind::Codex, "gpt-x")); let back = sw.end_turn(&mut a).unwrap(); assert_eq!(back.kind, Kind::Claude); assert_eq!( (sw.kind(), a.model(), a.effort()), (Kind::Claude, "claude-sonnet-x", hx_ai::Effort::High) ); assert_eq!(*made.lock().unwrap(), vec![Kind::Codex, Kind::Claude]); assert!(sw.end_turn(&mut a).is_none(), "nothing left to undo"); // a file with that name is a mention, not an override assert!( sw.begin_turn(&mut a, "@gpt-x explain", &|w| w == "gpt-x") .unwrap() .is_none() ); } #[test] fn override_in_auto_mode_keeps_auto() { let (mut sw, mut a, _m, _d) = setup(true, false); sw.set_auto(true); let r = sw .begin_turn(&mut a, "@haiku hi there", &nofile) .unwrap() .unwrap(); assert!(r.forced && sw.is_auto()); assert_eq!(a.model(), "claude-haiku-x"); assert!( sw.end_turn(&mut a).is_none(), "auto picks again next prompt" ); } #[test] fn spent_provider_is_avoided_until_reset() { let (mut sw, mut a, _m, _d) = setup(true, false); let q = hx_ai::Quota { windows: vec![hx_ai::QuotaWindow { label: "5h".into(), used_pct: 100.0, resets_at: Some(hx_ai::auth::now_ms() / 1000 + 600), }], credits: None, }; sw.note_quota(Kind::Claude, &q); sw.set_auto(true); let r = sw .begin_turn(&mut a, "add a flag to the parser please", &nofile) .unwrap() .unwrap(); assert_eq!(r.pick.kind, Kind::Codex); let ok = hx_ai::Quota { windows: vec![], credits: None, }; sw.note_quota(Kind::Claude, &ok); assert!(sw.out_of_quota().is_none()); } #[test] fn configured_threshold_is_left_alone() { let (mut sw, mut a, _m, _d) = setup(false, false); a.set_context_policy(crate::window::ContextPolicy::Fixed(12_345)); sw.set_model(&mut a, "claude-haiku-x").unwrap(); assert_eq!(a.compact_at(), 12_345); } }