//! 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 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, } pub struct Switcher { kind: Kind, models: Vec, make_provider: MakeProvider, auto_compact: bool, } impl Switcher { /// `kind` is the provider the agent starts with. `auto_compact`: re-derive the compaction /// threshold from the model's window on every switch (false when it is configured explicitly). pub fn new( kind: Kind, models: Vec, make_provider: MakeProvider, auto_compact: bool, ) -> Self { Self { kind, models, make_provider, auto_compact, } } /// 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.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.apply(agent, kind, model, true) } fn apply( &mut self, agent: &mut Agent, kind: Kind, model: String, rebuild: 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()); } let window = models::window(&self.models, &model); if self.auto_compact { agent.fit_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)) } }), auto, ); 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, ); 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 configured_threshold_is_left_alone() { let (mut sw, mut a, _m, _d) = setup(false, false); a.set_compact_at(12_345); sw.set_model(&mut a, "claude-haiku-x").unwrap(); assert_eq!(a.compact_at(), 12_345); } }