1use super::catalog::{self, Route};
9use super::launch::{self, Choice};
10use super::token;
11use crate::backend::storage::content::AgentContent;
12use crate::backend::storage::store::Store;
13use serde::{Deserialize, Serialize};
14use std::collections::{HashMap, VecDeque};
15use std::sync::{Mutex, OnceLock};
16use std::time::{Duration, Instant};
17
18pub const PREVIOUS_TYPE: &str = "agent:model_route_previous";
20pub const AGENT_SWITCHES_PER_HOUR: usize = 6;
22const HOUR: Duration = Duration::from_secs(3600);
23
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Previous {
28 pub route: String,
29 pub model: String,
30}
31
32pub fn previous_of(mstore: &Store, def_id: &str) -> Option<Previous> {
34 let content = mstore.agent_content_get(def_id, PREVIOUS_TYPE).ok()??;
35 serde_json::from_str(&content.content).ok()
36}
37
38#[derive(Debug, Clone, Copy)]
40pub enum Target<'a> {
41 Route { route: &'a str, model: &'a str },
43 OwnLogin,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Moved {
50 pub from: Option<Choice>,
51 pub to: Option<Choice>,
52}
53
54impl Moved {
55 pub fn changed(&self) -> bool {
56 self.from != self.to
57 }
58}
59
60pub fn move_to(mstore: &Store, def_id: &str, harness: &str, target: Target<'_>, key_present: impl Fn(&Route) -> bool) -> Result<Moved, String> {
64 let from = launch::choice_of(mstore, def_id);
65 let to = match target {
66 Target::OwnLogin => None,
67 Target::Route { route, model } => {
68 let (route, model) = catalog::validate(harness, route, model)?;
69 if !key_present(route) {
70 return Err(format!("KEY_MISSING: route {} needs a Vault api-key entry labelled \"{}\", and the Vault has none", route.id, route.key_label));
71 }
72 Some(Choice { route: route.id.to_string(), model: model.id.to_string() })
73 }
74 };
75 let moved = Moved { from, to };
76 if !moved.changed() {
77 return Ok(moved);
78 }
79 remember_previous(mstore, def_id, moved.from.as_ref())?;
80 match &moved.to {
81 Some(c) => {
82 launch::set_choice(mstore, def_id, harness, &c.route, &c.model)?;
83 }
84 None => {
85 mstore.agent_content_delete(def_id, launch::CONTENT_TYPE).map_err(|e| e.to_string())?;
86 }
87 }
88 if let Some(left) = moved.from.as_ref().filter(|f| moved.to.as_ref().is_none_or(|t| t.route != f.route)) {
89 mark_leaving(mstore, def_id, left)?;
90 }
91 super::trial::begin(mstore, def_id, &place_of(moved.from.as_ref()), &place_of(moved.to.as_ref()))?;
93 Ok(moved)
94}
95
96pub(super) fn place_of(choice: Option<&Choice>) -> Previous {
97 choice.map_or(Previous { route: String::new(), model: String::new() }, |c| Previous { route: c.route.clone(), model: c.model.clone() })
98}
99
100pub(super) fn restore(mstore: &Store, def_id: &str, to: &Previous) -> Result<(), String> {
103 let failed = launch::choice_of(mstore, def_id);
104 if to.route.is_empty() {
106 mstore.agent_content_delete(def_id, launch::CONTENT_TYPE).map_err(|e| e.to_string())?;
107 } else {
108 let harness = catalog::route(&to.route).map(|r| r.harness).ok_or_else(|| format!("unknown model route {:?}", to.route))?;
109 launch::set_choice(mstore, def_id, harness, &to.route, &to.model)?;
110 }
111 remember_previous(mstore, def_id, failed.as_ref())?;
112 if let Some(left) = failed.as_ref().filter(|f| f.route != to.route) {
113 mark_leaving(mstore, def_id, left)?;
114 }
115 Ok(())
116}
117
118fn mark_leaving(mstore: &Store, def_id: &str, left: &Choice) -> Result<(), String> {
119 let content = serde_json::to_string(left).map_err(|e| e.to_string())?;
120 mstore
121 .agent_content_set(&AgentContent { agent_id: def_id.to_string(), content_type: launch::LEAVING_TYPE.to_string(), content, updated_at: agentmux_common::time::now_ms() })
122 .map_err(|e| e.to_string())
123}
124
125pub fn finish_leaving(mstore: &Store, def_id: &str) {
128 let Some(left) = launch::leaving(mstore, def_id) else { return };
129 token::revoke(def_id, &left.route);
130 if let Err(e) = mstore.agent_content_delete(def_id, launch::LEAVING_TYPE) {
131 tracing::warn!(def_id, error = %e, "model route: the left route's mark was not cleared");
132 }
133}
134
135fn remember_previous(mstore: &Store, def_id: &str, from: Option<&Choice>) -> Result<(), String> {
136 let previous = from.map_or(Previous { route: String::new(), model: String::new() }, |c| Previous { route: c.route.clone(), model: c.model.clone() });
137 let content = serde_json::to_string(&previous).map_err(|e| e.to_string())?;
138 mstore
139 .agent_content_set(&AgentContent { agent_id: def_id.to_string(), content_type: PREVIOUS_TYPE.to_string(), content, updated_at: agentmux_common::time::now_ms() })
140 .map_err(|e| e.to_string())
141}
142
143pub fn pane_in_a_turn(mstore: &Store, block_id: &str) -> bool {
145 crate::backend::agent_state::in_turn(mstore, block_id)
146}
147
148pub fn finish_leaving_after_relaunch(mstore: &Store, def_id: &str, this_block: &str, in_a_turn: impl Fn(&str) -> bool) {
151 use crate::backend::obj::{meta_get_string, Block};
152 let busy = mstore
153 .get_all::<Block>()
154 .unwrap_or_default()
155 .iter()
156 .any(|b| b.oid != this_block && meta_get_string(&b.meta, "agentId", "") == def_id && in_a_turn(&b.oid));
157 if !busy {
158 finish_leaving(mstore, def_id);
159 }
160}
161
162fn switches() -> &'static Mutex<HashMap<String, VecDeque<Instant>>> {
163 static SWITCHES: OnceLock<Mutex<HashMap<String, VecDeque<Instant>>>> = OnceLock::new();
164 SWITCHES.get_or_init(Default::default)
165}
166
167pub fn agent_switch_allowed(agent: &str) -> Result<(), String> {
171 check_at(&mut switches().lock().unwrap(), agent, Instant::now())
172}
173
174pub fn count_agent_switch(agent: &str) {
176 switches().lock().unwrap().entry(agent.to_string()).or_default().push_back(Instant::now());
177}
178
179fn check_at(all: &mut HashMap<String, VecDeque<Instant>>, agent: &str, now: Instant) -> Result<(), String> {
180 let recent = all.entry(agent.to_string()).or_default();
181 while recent.front().is_some_and(|t| now.duration_since(*t) >= HOUR) {
182 recent.pop_front();
183 }
184 if recent.len() >= AGENT_SWITCHES_PER_HOUR {
185 return Err(format!(
186 "an agent may change its model {AGENT_SWITCHES_PER_HOUR} times an hour, because each change makes the new model read the whole conversation again at full price; try again later"
187 ));
188 }
189 Ok(())
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 const FLASH: &str = "deepseek/deepseek-v4.1-flash-1017";
197 const PRO: &str = "deepseek/deepseek-v4-pro-0813";
198
199 fn store() -> Store {
201 let store = Store::open_in_memory().unwrap();
202 for id in ["a1", "a2"] {
203 let mut def = crate::backend::storage::agents::test_agent_def(id, id, "claude", "host", 1, "");
204 store.agent_def_insert(&mut def).unwrap();
205 }
206 store
207 }
208
209 #[test]
210 fn a_move_keeps_where_the_agent_was_and_a_move_back_returns_to_it() {
211 let s = store();
212 let on = |model| Target::Route { route: "openrouter", model };
213 let first = move_to(&s, "a1", "claude", on(FLASH), |_| true).unwrap();
214 assert_eq!((first.from, first.to.unwrap().model), (None, FLASH.to_string()));
215 assert_eq!(previous_of(&s, "a1"), Some(Previous { route: String::new(), model: String::new() }));
216 let second = move_to(&s, "a1", "claude", on(PRO), |_| true).unwrap();
217 assert!(second.changed());
218 assert_eq!(previous_of(&s, "a1"), Some(Previous { route: "openrouter".into(), model: FLASH.into() }));
219 assert_eq!(launch::choice_of(&s, "a1").unwrap().model, PRO);
220 let left = move_to(&s, "a1", "claude", Target::OwnLogin, |_| true).unwrap();
221 assert_eq!(left.to, None);
222 assert_eq!(launch::leaving(&s, "a1").map(|c| (c.route, c.model)), Some(("openrouter".into(), PRO.into())), "a turn in flight keeps its token and model until the relaunch");
223 finish_leaving(&s, "a1");
224 assert!(launch::leaving(&s, "a1").is_none());
225 assert!(launch::choice_of(&s, "a1").is_none());
226 assert_eq!(previous_of(&s, "a1").unwrap().model, PRO);
227 }
228
229 #[test]
230 fn staying_where_it_is_changes_nothing_and_forgets_nothing() {
231 let s = store();
232 move_to(&s, "a1", "claude", Target::Route { route: "openrouter", model: FLASH }, |_| true).unwrap();
233 move_to(&s, "a1", "claude", Target::Route { route: "openrouter", model: PRO }, |_| true).unwrap();
234 let again = move_to(&s, "a1", "claude", Target::Route { route: "openrouter", model: PRO }, |_| true).unwrap();
235 assert!(!again.changed());
236 assert_eq!(previous_of(&s, "a1").unwrap().model, FLASH, "a no-op is not a change of place");
237 assert!(!move_to(&s, "a2", "claude", Target::OwnLogin, |_| true).unwrap().changed());
238 assert!(previous_of(&s, "a2").is_none());
239 }
240
241 #[test]
242 fn a_route_without_its_key_or_the_wrong_harness_is_not_moved_to() {
243 let s = store();
244 let e = move_to(&s, "a1", "claude", Target::Route { route: "openrouter", model: "" }, |_| false).unwrap_err();
245 assert!(e.starts_with("KEY_MISSING") && e.contains("OpenRouter API key"), "{e}");
246 assert!(move_to(&s, "a1", "codex", Target::Route { route: "openrouter", model: "" }, |_| true).is_err());
247 assert!(launch::choice_of(&s, "a1").is_none() && previous_of(&s, "a1").is_none(), "a refused move leaves no trace");
248 }
249
250 #[test]
251 fn the_left_route_ends_only_when_no_other_pane_of_the_agent_is_still_in_a_turn() {
252 use crate::backend::obj::{Block, MetaMapType};
253 let s = store();
254 for oid in ["5b1a3c52-7d0e-4d43-9a43-2f6a0f4f3c21", "5b1a3c52-7d0e-4d43-9a43-2f6a0f4f3c22"] {
255 let mut meta = MetaMapType::new();
256 meta.insert("agentId".to_string(), serde_json::json!("a1"));
257 let mut block = Block { oid: oid.to_string(), parentoref: String::new(), version: 0, runtimeopts: None, stickers: None, meta, subblockids: None };
258 s.insert(&mut block).unwrap();
259 }
260 let (idle, busy) = ("5b1a3c52-7d0e-4d43-9a43-2f6a0f4f3c21", "5b1a3c52-7d0e-4d43-9a43-2f6a0f4f3c22");
261 move_to(&s, "a1", "claude", Target::Route { route: "openrouter", model: FLASH }, |_| true).unwrap();
262 move_to(&s, "a1", "claude", Target::OwnLogin, |_| true).unwrap();
263 finish_leaving_after_relaunch(&s, "a1", idle, |b| b == busy);
264 assert!(launch::leaving(&s, "a1").is_some(), "the idle pane's relaunch leaves the busy pane its token");
265 finish_leaving_after_relaunch(&s, "a1", busy, |b| b == busy);
266 assert!(launch::leaving(&s, "a1").is_none(), "the busy pane's own relaunch ends it");
267 }
268
269 #[test]
270 fn an_agent_may_switch_six_times_an_hour_and_then_waits_and_a_refused_change_costs_nothing() {
271 let mut all = HashMap::new();
272 let start = Instant::now();
273 for i in 0..AGENT_SWITCHES_PER_HOUR {
274 let at = start + Duration::from_secs(i as u64);
275 check_at(&mut all, "x", at).unwrap();
276 all.get_mut("x").unwrap().push_back(at);
277 }
278 let refused = check_at(&mut all, "x", start + Duration::from_secs(60)).unwrap_err();
279 assert!(refused.contains("6 times an hour"), "{refused}");
280 assert_eq!(all["x"].len(), AGENT_SWITCHES_PER_HOUR, "checking counts nothing");
281 check_at(&mut all, "y", start + Duration::from_secs(60)).unwrap();
282 check_at(&mut all, "x", start + HOUR + Duration::from_secs(1)).unwrap();
283 }
284}