1use std::sync::Arc;
11
12use serde::{Deserialize, Serialize};
13
14use crate::backend::model_gateway::catalog::{self, Model, Route};
15use crate::backend::model_gateway::launch::{self, Choice};
16use crate::backend::model_gateway::switch::{self, Target};
17use crate::backend::rpc::engine::WshRpcEngine;
18use crate::backend::rpc_types::{COMMAND_AGENT_MODEL_PANEL, COMMAND_AGENT_MODEL_SWITCH, COMMAND_AGENT_PEER_LABELS};
19use crate::backend::storage::agents::AgentDefinition;
20use crate::backend::vault::route_key;
21use crate::server::AppState;
22
23const REREAD_WARNING_TOKENS: u32 = 50_000;
26
27const COMPACTED_TOKENS: u32 = 40_000;
30
31#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
32#[ts(export, export_to = "../../../frontend/types/rpc/")]
33pub struct AgentModelPanelReq {
34 pub blockid: String,
36 #[serde(default)]
38 pub conversation_tokens: Option<u32>,
39 #[serde(default)]
41 pub images: Option<u32>,
42}
43
44#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
45#[ts(export, export_to = "../../../frontend/types/rpc/")]
46pub struct AgentModelPanelModel {
47 pub id: String,
48 pub label: String,
49 pub context: u32,
50 pub price_in: f64,
52 pub price_out: f64,
53 pub tools: bool,
54 pub thinking: bool,
55 pub images: bool,
56 pub default: bool,
58 pub current: bool,
60 pub unavailable: Option<String>,
62 pub compact_first: Option<String>,
65 pub reread_cost_usd: Option<f64>,
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71pub struct AgentModelPanelRoute {
72 pub id: String,
73 pub label: String,
74 pub key_present: bool,
75 pub key_label: String,
77 pub models: Vec<AgentModelPanelModel>,
78}
79
80#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
82#[ts(export, export_to = "../../../frontend/types/rpc/")]
83pub struct AgentModelPlace {
84 pub route: String,
85 pub model: String,
86 pub label: String,
87}
88
89#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
90#[ts(export, export_to = "../../../frontend/types/rpc/")]
91pub struct AgentModelPanel {
92 pub harness: String,
93 pub current: Option<AgentModelPlace>,
95 pub previous: Option<AgentModelPlace>,
97 pub routes: Vec<AgentModelPanelRoute>,
98}
99
100#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
101#[ts(export, export_to = "../../../frontend/types/rpc/")]
102pub struct AgentModelSwitchReq {
103 pub blockid: String,
104 pub route: String,
106 #[serde(default)]
108 pub model: String,
109 #[serde(default = "yes")]
112 pub restart: bool,
113 #[serde(default)]
117 pub fresh: bool,
118 #[serde(default)]
120 pub handoff: Option<String>,
121}
122
123fn yes() -> bool {
124 true
125}
126
127#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
128#[ts(export, export_to = "../../../frontend/types/rpc/")]
129pub struct AgentModelSwitchResult {
130 pub changed: bool,
132 pub restarted: u32,
133 pub failed: Vec<String>,
134 #[serde(default)]
136 pub fresh: u32,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
141#[ts(export, export_to = "../../../frontend/types/rpc/")]
142pub struct AgentPeerLabels {
143 pub labels: std::collections::HashMap<String, String>,
146}
147
148fn peer_label(harness: &str, choice: Option<&Choice>) -> Option<String> {
151 let choice = choice?;
152 let (route, model) = catalog::validate(harness, &choice.route, &choice.model).ok()?;
153 Some(format!("{} via {}", model.label, route.label))
154}
155
156fn peer_labels(state: &AppState) -> Result<AgentPeerLabels, String> {
157 let defs = state.mstore.agent_def_list().map_err(|e| e.to_string())?;
158 let labels = defs
159 .iter()
160 .filter_map(|def| {
161 let harness = state.id_store.resolve_effective_provider_id(def);
162 peer_label(&harness, launch::choice_of(&state.mstore, &def.id).as_ref()).map(|l| (def.id.clone(), l))
163 })
164 .collect();
165 Ok(AgentPeerLabels { labels })
166}
167
168fn agent_of_block(state: &AppState, block_id: &str) -> Result<AgentDefinition, String> {
169 let instance = state
170 .mstore
171 .instance_get_active_for_block(block_id)
172 .map_err(|e| e.to_string())?
173 .ok_or_else(|| format!("no agent runs in block {block_id}"))?;
174 state.mstore.agent_def_get(&instance.definition_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no agent definition {}", instance.definition_id))
175}
176
177fn place(route: &str, model: &str) -> AgentModelPlace {
178 let label = catalog::route(route).and_then(|r| r.model(model)).map_or_else(|| model.to_string(), |m| m.label.to_string());
179 AgentModelPlace { route: route.to_string(), model: model.to_string(), label }
180}
181
182fn unavailable(route: &Route, model: &Model, key_present: bool, images: u32) -> Option<String> {
184 if !key_present {
185 return Some(format!("key missing: add \"{}\" in the Vault", route.key_label));
186 }
187 if images > 0 && !model.images {
188 return Some(format!("can't read images ({images} in this conversation)"));
189 }
190 None
191}
192
193#[derive(Debug, PartialEq, Eq)]
196enum Fit {
197 Yes,
198 AfterCompact(String),
199 No(String),
200}
201
202fn kilo(tokens: u32) -> String {
203 if tokens >= 1_000_000 {
204 format!("{:.1}M", f64::from(tokens) / 1_000_000.0).replace(".0M", "M")
205 } else {
206 format!("{}K", tokens.div_ceil(1000))
207 }
208}
209
210fn fit(context: u32, tokens: u32) -> Fit {
211 if tokens <= context {
212 return Fit::Yes;
213 }
214 let sizes = format!("the conversation ({}) is larger than this model's context ({})", kilo(tokens), kilo(context));
215 if context > COMPACTED_TOKENS {
216 Fit::AfterCompact(sizes)
217 } else {
218 Fit::No(format!("{sizes}, even compacted"))
219 }
220}
221
222fn panel_model(route: &Route, model: &Model, current: Option<&Choice>, key_present: bool, req: &AgentModelPanelReq) -> AgentModelPanelModel {
223 let tokens = req.conversation_tokens.unwrap_or(0);
224 let is_current = current.is_some_and(|c| c.route == route.id && c.model == model.id);
225 let mut unavailable = unavailable(route, model, key_present, req.images.unwrap_or(0));
226 let mut compact_first = None;
228 if unavailable.is_none() && !is_current {
229 match fit(model.context, tokens) {
230 Fit::Yes => {}
231 Fit::AfterCompact(why) => compact_first = Some(why),
232 Fit::No(why) => unavailable = Some(why),
233 }
234 }
235 AgentModelPanelModel {
236 id: model.id.to_string(),
237 label: model.label.to_string(),
238 context: model.context,
239 price_in: model.price_in,
240 price_out: model.price_out,
241 tools: model.tools,
242 thinking: model.thinking,
243 images: model.images,
244 default: model.id == route.default_model,
245 current: is_current,
246 unavailable,
247 compact_first,
248 reread_cost_usd: (tokens >= REREAD_WARNING_TOKENS).then(|| f64::from(tokens) / 1_000_000.0 * model.price_in),
249 }
250}
251
252fn images_in_conversation(def: &AgentDefinition) -> u32 {
255 let Some(gfs) = crate::backend::agent_session::global_transcript_store() else { return 0 };
256 let zone = crate::backend::agent_session::agent_current_zone(&def.id);
257 crate::backend::transcript::images::count_in_zone(gfs, &zone).unwrap_or_else(|e| {
258 tracing::warn!(agent = %def.slug, error = %e, "model panel: the images in the conversation were not counted");
259 0
260 })
261}
262
263fn images_known(def: &AgentDefinition) -> u32 {
267 let Some(gfs) = crate::backend::agent_session::global_transcript_store() else { return 0 };
268 let zone = crate::backend::agent_session::agent_current_zone(&def.id);
269 crate::backend::transcript::images::warm(gfs, &zone);
270 crate::backend::transcript::images::counted(&zone).unwrap_or(0)
271}
272
273fn panel(state: &AppState, req: &AgentModelPanelReq) -> Result<AgentModelPanel, String> {
274 let def = agent_of_block(state, &req.blockid)?;
275 let harness = state.id_store.resolve_effective_provider_id(&def);
276 let req = &AgentModelPanelReq { images: Some(req.images.unwrap_or(0).max(images_known(&def))), ..req.clone() };
278 let current = launch::choice_of(&state.mstore, &def.id);
279 let routes = catalog::ROUTES
280 .iter()
281 .filter(|r| r.harness == harness)
282 .map(|route| {
283 let key_present = route_key::present(&state.identity_store, route.key_label);
284 AgentModelPanelRoute {
285 id: route.id.to_string(),
286 label: route.label.to_string(),
287 key_present,
288 key_label: route.key_label.to_string(),
289 models: route.models.iter().map(|m| panel_model(route, m, current.as_ref(), key_present, req)).collect(),
290 }
291 })
292 .collect();
293 Ok(AgentModelPanel {
294 harness,
295 current: current.map(|c| place(&c.route, &c.model)),
296 previous: switch::previous_of(&state.mstore, &def.id).map(|p| place(&p.route, &p.model)),
297 routes,
298 })
299}
300
301fn refuse_unreadable(harness: &str, route: &str, model: &str, images: u32) -> Result<(), String> {
304 match catalog::validate(harness, route, model) {
305 Ok((r, m)) => unavailable(r, m, true, images).map_or(Ok(()), Err),
306 Err(_) => Ok(()),
307 }
308}
309
310pub(crate) fn check_fresh(state: &AppState, def_id: &str, handoff: &str) -> Result<(), String> {
313 if handoff.chars().count() > super::agent_context::HANDOFF_MAX_CHARS {
314 return Err(format!("the handoff is over {} characters: shorten it, with the next step in it", super::agent_context::HANDOFF_MAX_CHARS));
315 }
316 for block in crate::server::account_episodes::panes_of(state, def_id) {
317 super::agent_context::fresh_refusal(state, &block.oid).map_err(fresh_refused)?;
318 }
319 Ok(())
320}
321
322fn fresh_refused(why: &str) -> String {
324 format!("a fresh session is not possible for this agent ({why}), so this model change was not made: change it without fresh to resume the conversation, or compact it first")
325}
326
327pub(crate) fn start_fresh_panes(state: &AppState, def_id: &str, message: &str) -> (u32, Vec<String>) {
331 let (mut started, mut failed, mut running) = (0, Vec::new(), 0);
332 for block in crate::server::account_episodes::panes_of(state, def_id) {
333 if crate::backend::blockcontroller::get_controller(&block.oid).is_some() {
334 if super::agent_context::start_fresh_after_switch(state, &block.oid, message.to_string()) {
335 started += 1;
336 running += 1;
337 } else {
338 failed.push("no runtime to start the fresh session on".to_string());
339 }
340 } else {
341 crate::backend::blockcontroller::core::forget_saved_session(&block.oid, &state.mstore, &state.event_bus);
342 started += 1;
343 }
344 }
345 if running == 0 || !failed.is_empty() {
348 switch::finish_leaving_after_relaunch(&state.mstore, def_id, "", |b| switch::pane_in_a_turn(&state.mstore, b));
349 }
350 (started, failed)
351}
352
353pub(crate) fn place_label(harness: &str, route: &str, model: &str) -> String {
355 if route.is_empty() {
356 return "the harness's own sign-in".to_string();
357 }
358 match catalog::validate(harness, route, model) {
359 Ok((r, m)) => format!("{} on {}", m.label, r.label),
360 Err(_) => format!("{route} {model}").trim().to_string(),
361 }
362}
363
364pub(crate) fn switch_model(state: &AppState, req: &AgentModelSwitchReq) -> Result<AgentModelSwitchResult, String> {
365 let def = agent_of_block(state, &req.blockid)?;
366 let harness = state.id_store.resolve_effective_provider_id(&def);
367 let route = req.route.trim();
368 let target = if route.is_empty() { Target::OwnLogin } else { Target::Route { route, model: req.model.trim() } };
369 if let Target::Route { route, model } = target {
370 refuse_unreadable(&harness, route, model, images_in_conversation(&def))?;
371 if crate::server::spend_watch::on_a_key(&state.mstore, &state.identity_store, &def.id) {
373 return Err("ACCOUNT_CANT_RUN: this agent is on an API key, which is billed to the key; move it back to a plan account first".to_string());
374 }
375 }
376 let handoff = req.handoff.as_deref().map(str::trim).unwrap_or_default();
377 if req.fresh {
379 check_fresh(state, &def.id, handoff)?;
380 }
381 let moved = switch::move_to(&state.mstore, &def.id, &harness, target, |r| route_key::present(&state.identity_store, r.key_label))?;
382 if !moved.changed() || (!req.restart && !req.fresh) {
383 return Ok(AgentModelSwitchResult { changed: moved.changed(), restarted: 0, failed: Vec::new(), fresh: 0 });
384 }
385 if req.fresh {
386 let message = super::agent_context::switch_message(&place_label(&harness, route, req.model.trim()), handoff);
387 let (fresh, failed) = start_fresh_panes(state, &def.id, &message);
388 return Ok(AgentModelSwitchResult { changed: true, restarted: 0, failed, fresh });
389 }
390 let (restarted, failed) = restart_panes(state, &def.id);
391 Ok(AgentModelSwitchResult { changed: true, restarted, failed, fresh: 0 })
392}
393
394pub(crate) fn restart_panes(state: &AppState, def_id: &str) -> (u32, Vec<String>) {
397 let (restarted, next_turn, failed) = crate::server::account_episodes::restart_panes_of(state, def_id);
398 if (restarted == 0 && next_turn == 0) || !failed.is_empty() {
400 switch::finish_leaving_after_relaunch(&state.mstore, def_id, "", |b| switch::pane_in_a_turn(&state.mstore, b));
401 }
402 (restarted, failed)
403}
404
405const SLOW_REQUEST_MS: u128 = 2_000;
407
408fn logged<T>(command: &str, block: &str, started: std::time::Instant, result: Result<T, String>) -> Result<T, String> {
411 let ms = started.elapsed().as_millis();
412 match &result {
413 Err(error) => tracing::warn!(command, block, ms = ms as u64, %error, "model panel: the request failed"),
414 Ok(_) if ms >= SLOW_REQUEST_MS => tracing::warn!(command, block, ms = ms as u64, "model panel: the request was slow"),
415 Ok(_) => {}
416 }
417 result
418}
419
420pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
423 let s = state.clone();
424 engine.register_typed(COMMAND_AGENT_MODEL_PANEL, move |req: AgentModelPanelReq, ctx| {
425 let s = s.clone();
426 async move {
427 let (block, started) = (req.blockid.clone(), std::time::Instant::now());
428 let result = match ctx.operator_only("only the AgentMux window reads the model panel") {
429 Ok(()) => tokio::task::spawn_blocking(move || panel(&s, &req)).await.map_err(|e| format!("the panel request panicked: {e}")).and_then(|r| r),
430 Err(refused) => Err(refused),
431 };
432 logged(COMMAND_AGENT_MODEL_PANEL, &block, started, result)
433 }
434 });
435 let s = state.clone();
436 engine.register_typed(COMMAND_AGENT_PEER_LABELS, move |_data: serde_json::Value, _ctx| {
438 let s = s.clone();
439 async move { tokio::task::spawn_blocking(move || peer_labels(&s)).await.map_err(|e| e.to_string())? }
440 });
441 let s = state.clone();
442 engine.register_typed(COMMAND_AGENT_MODEL_SWITCH, move |req: AgentModelSwitchReq, ctx| {
443 let s = s.clone();
444 async move {
445 let (block, started) = (req.blockid.clone(), std::time::Instant::now());
446 let result = match ctx.operator_only("only a person moves an agent to a model route, because it spends their key") {
447 Ok(()) => tokio::task::spawn_blocking(move || switch_model(&s, &req)).await.map_err(|e| format!("the switch request panicked: {e}")).and_then(|r| r),
448 Err(refused) => Err(refused),
449 };
450 logged(COMMAND_AGENT_MODEL_SWITCH, &block, started, result)
451 }
452 });
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 fn req(tokens: Option<u32>, images: Option<u32>) -> AgentModelPanelReq {
460 AgentModelPanelReq { blockid: "b".into(), conversation_tokens: tokens, images }
461 }
462
463 #[test]
464 fn a_logged_request_answers_as_it_did() {
465 let now = std::time::Instant::now();
466 assert_eq!(logged("c", "b", now, Ok::<_, String>(3)), Ok(3));
467 assert_eq!(logged::<u8>("c", "b", now, Err("no agent runs in block b".into())), Err("no agent runs in block b".to_string()));
468 }
469
470 #[test]
471 fn a_route_agent_is_labelled_with_its_model_and_route() {
472 let on_route = Choice { route: "openrouter".into(), model: "deepseek/deepseek-v4.1-flash-1017".into() };
473 assert_eq!(peer_label("claude", Some(&on_route)).as_deref(), Some("DeepSeek V4.1 Flash via OpenRouter"));
474 assert_eq!(peer_label("claude", None), None);
476 assert_eq!(peer_label("codex", Some(&on_route)), None);
477 let gone = Choice { route: "openrouter".into(), model: "nobody/retired".into() };
478 assert_eq!(peer_label("claude", Some(&gone)), None);
479 }
480
481 #[test]
482 fn a_model_that_cannot_be_picked_says_why() {
483 let route = catalog::route("openrouter").unwrap();
484 let pro = route.model("deepseek/deepseek-v4-pro-0813").unwrap();
485 let no_key = unavailable(route, pro, false, 0).unwrap();
486 assert!(no_key.starts_with("key missing") && no_key.contains("OpenRouter API key"), "{no_key}");
487 assert!(unavailable(route, pro, true, 0).is_none());
488 assert_eq!(unavailable(route, pro, true, 3).unwrap(), "can't read images (3 in this conversation)");
489 let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
490 assert!(unavailable(route, flash, true, 3).is_none(), "this one reads images");
491 }
492
493 #[test]
494 fn a_switch_to_a_model_that_cannot_read_the_conversations_images_is_refused_with_the_panels_reason() {
495 let pro = "deepseek/deepseek-v4-pro-0813";
496 assert_eq!(refuse_unreadable("claude", "openrouter", pro, 2).unwrap_err(), "can't read images (2 in this conversation)");
497 assert!(refuse_unreadable("claude", "openrouter", pro, 0).is_ok(), "no image, no refusal");
498 assert!(refuse_unreadable("claude", "openrouter", "deepseek/deepseek-v4.1-flash-1017", 2).is_ok(), "this one reads images");
499 assert!(refuse_unreadable("claude", "openrouter", "nobody/retired", 2).is_ok(), "the switch says what is wrong with it");
500 }
501
502 #[test]
503 fn a_big_conversation_shows_what_re_reading_it_costs() {
504 let route = catalog::route("openrouter").unwrap();
505 let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
506 let big = panel_model(route, flash, None, true, &req(Some(200_000), None));
507 assert!((big.reread_cost_usd.unwrap() - 0.03).abs() < 1e-9, "{:?}", big.reread_cost_usd);
508 assert!(panel_model(route, flash, None, true, &req(Some(10_000), None)).reread_cost_usd.is_none());
509 assert!(panel_model(route, flash, None, true, &req(None, None)).reread_cost_usd.is_none());
510 }
511
512 #[test]
513 fn the_model_the_agent_runs_is_marked_current() {
514 let route = catalog::route("openrouter").unwrap();
515 let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
516 let on = Choice { route: "openrouter".into(), model: flash.id.into() };
517 assert!(panel_model(route, flash, Some(&on), true, &req(None, None)).current);
518 assert!(!panel_model(route, flash, None, true, &req(None, None)).current);
519 }
520
521 #[test]
522 fn sizes_read_in_thousands_and_in_millions_to_one_decimal() {
523 assert_eq!(kilo(40_000), "40K");
524 assert_eq!(kilo(1_000_000), "1M");
525 assert_eq!(kilo(1_048_576), "1M");
526 assert_eq!(kilo(1_500_000), "1.5M");
527 }
528
529 #[test]
530 fn a_conversation_larger_than_a_models_context_is_offered_compacted_when_that_would_fit() {
531 assert_eq!(fit(1_000_000, 200_000), Fit::Yes);
532 assert_eq!(fit(128_000, 128_000), Fit::Yes, "exactly the size");
533 assert_eq!(fit(128_000, 200_000), Fit::AfterCompact("the conversation (200K) is larger than this model's context (128K)".into()));
534 assert_eq!(fit(32_000, 100_000), Fit::No("the conversation (100K) is larger than this model's context (32K), even compacted".into()));
535 assert_eq!(fit(40_000, 100_000), Fit::No("the conversation (100K) is larger than this model's context (40K), even compacted".into()), "no room left over for the work");
536 }
537
538 #[test]
539 fn a_model_too_small_for_the_conversation_is_offered_compacted_and_the_current_one_is_left_alone() {
540 let route = catalog::route("openrouter").unwrap();
541 let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
542 let over = req(Some(flash.context + 1), None);
543 let offered = panel_model(route, flash, None, true, &over);
544 assert!(offered.unavailable.is_none() && offered.compact_first.is_some(), "{offered:?}");
545 let on = Choice { route: "openrouter".into(), model: flash.id.into() };
546 let running = panel_model(route, flash, Some(&on), true, &over);
547 assert!(running.current && running.unavailable.is_none() && running.compact_first.is_none(), "{running:?}");
548 assert!(panel_model(route, flash, None, true, &req(Some(10_000), None)).compact_first.is_none());
549 }
550
551 #[test]
552 fn the_fresh_sessions_first_message_names_the_move_and_carries_the_handoff() {
553 let said = super::super::agent_context::switch_message("DeepSeek V4.1 Flash on OpenRouter", "Task 31427 is yours; the next step is the card.");
554 assert!(said.starts_with("[AgentMux] You were moved to DeepSeek V4.1 Flash on OpenRouter and this is a fresh session"), "{said}");
555 assert!(said.contains("Agents search_history"), "it says where the earlier conversation is: {said}");
556 assert!(said.ends_with("Task 31427 is yours; the next step is the card."), "{said}");
557 let none = super::super::agent_context::switch_message("x", " ");
558 assert!(none.contains("Tasks list"), "with no handoff it says where to look: {none}");
559 }
560
561 #[test]
562 fn a_place_is_named_by_its_model_and_route_or_as_the_harness_own_sign_in() {
563 assert_eq!(place_label("claude", "", ""), "the harness's own sign-in");
564 let flash = place_label("claude", "openrouter", "deepseek/deepseek-v4.1-flash-1017");
565 assert!(flash.contains("Flash") && flash.contains(" on "), "{flash}");
566 assert_eq!(place_label("claude", "nowhere", "m"), "nowhere m", "a place that does not validate is named as given");
567 }
568}