agentmux_srv_core/backend/model_gateway/
trial.rs1use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use super::launch;
20use super::switch::{self, Previous};
21use crate::backend::storage::content::AgentContent;
22use crate::backend::storage::store::Store;
23
24pub const TRIAL_TYPE: &str = "agent:model_route_trial";
26pub const UNDONE_META_KEY: &str = "agent:model_switch_undone";
28const REASON_CHARS: usize = 300;
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Trial {
34 pub from: Previous,
36 #[serde(default)]
38 pub armed: bool,
39 #[serde(default)]
41 pub block: String,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum Verdict {
47 Commit,
49 Refused(u16),
51 Wait,
54}
55
56pub fn pending(mstore: &Store, def_id: &str) -> Option<Trial> {
58 serde_json::from_str(&mstore.agent_content_get(def_id, TRIAL_TYPE).ok()??.content).ok()
59}
60
61fn save(mstore: &Store, def_id: &str, trial: &Trial) -> Result<(), String> {
62 let content = serde_json::to_string(trial).map_err(|e| e.to_string())?;
63 mstore
64 .agent_content_set(&AgentContent { agent_id: def_id.to_string(), content_type: TRIAL_TYPE.to_string(), content, updated_at: agentmux_common::time::now_ms() })
65 .map_err(|e| e.to_string())
66}
67
68fn clear(mstore: &Store, def_id: &str) {
69 if let Err(e) = mstore.agent_content_delete(def_id, TRIAL_TYPE) {
70 tracing::warn!(def_id, error = %e, "model route: the trial of a change was not cleared");
71 }
72}
73
74pub fn begin(mstore: &Store, def_id: &str, from: &Previous, to: &Previous) -> Result<(), String> {
77 let origin = pending(mstore, def_id).filter(|t| !t.armed).map_or_else(|| from.clone(), |t| t.from);
78 if &origin == to {
79 clear(mstore, def_id);
80 return Ok(());
81 }
82 save(mstore, def_id, &Trial { from: origin, armed: false, block: String::new() })
83}
84
85pub fn arm(mstore: &Store, def_id: &str, block_id: &str) {
88 let Some(mut trial) = pending(mstore, def_id).filter(|t| !t.armed || t.block != block_id) else { return };
89 trial.armed = true;
90 trial.block = block_id.to_string();
91 if let Err(e) = save(mstore, def_id, &trial) {
92 tracing::warn!(def_id, error = %e, "model route: the trial of a change was not armed");
93 }
94}
95
96pub fn arm_for_block(mstore: &Store, block_id: &str) {
99 let Ok(Some(instance)) = mstore.instance_get_active_for_block(block_id) else { return };
100 arm(mstore, &instance.definition_id, block_id);
101}
102
103pub fn verdict(frame: &Value) -> Verdict {
105 if !crate::agents::failure::is_error_result_frame(frame) {
106 return Verdict::Commit;
107 }
108 match api_status(frame.get("result").and_then(Value::as_str).unwrap_or_default()) {
109 Some(status @ (400 | 404 | 413 | 422)) => Verdict::Refused(status),
111 _ => Verdict::Wait,
112 }
113}
114
115fn api_status(text: &str) -> Option<u16> {
117 let rest = &text[text.find("API Error: ")? + "API Error: ".len()..];
118 let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
119 digits.parse().ok().filter(|s| (100..600).contains(s))
120}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Undone {
125 pub back_on: Previous,
127 pub tried: Previous,
129}
130
131pub fn settle(mstore: &Store, def_id: &str, block_id: &str, frame: &Value) -> Option<Undone> {
134 let trial = pending(mstore, def_id).filter(|t| t.armed && t.block == block_id)?;
135 let status = match verdict(frame) {
136 Verdict::Commit => {
137 clear(mstore, def_id);
138 return None;
139 }
140 Verdict::Wait => return None,
141 Verdict::Refused(status) => status,
142 };
143 let tried = switch::place_of(launch::choice_of(mstore, def_id).as_ref());
145 if let Err(e) = switch::restore(mstore, def_id, &trial.from) {
146 tracing::warn!(def_id, error = %e, "model route: a refused change was not undone");
147 return None;
148 }
149 clear(mstore, def_id);
150 let reason: String = frame.get("result").and_then(Value::as_str).unwrap_or_default().chars().take(REASON_CHARS).collect();
151 publish_undone(mstore, block_id, &tried, &trial.from, status, &reason);
152 tracing::info!(def_id, status, from = %trial.from.model, to = %tried.model, "model route: the first turn was refused; the change is undone");
153 Some(Undone { back_on: trial.from, tried })
154}
155
156fn publish_undone(mstore: &Store, block_id: &str, tried: &Previous, back_on: &Previous, status: u16, reason: &str) {
157 let label = |p: &Previous| {
158 if p.route.is_empty() {
159 "your plan".to_string()
160 } else {
161 super::catalog::route(&p.route).and_then(|r| r.model(&p.model)).map_or_else(|| p.model.clone(), |m| m.label.to_string())
162 }
163 };
164 let card = serde_json::json!({
165 "at": agentmux_common::time::now_ms(),
166 "tried": { "route": tried.route, "model": tried.model, "label": label(tried) },
167 "back_on": { "route": back_on.route, "model": back_on.model, "label": label(back_on) },
168 "status": status,
169 "reason": reason,
170 });
171 let mut update = crate::backend::obj::MetaMapType::new();
172 update.insert(UNDONE_META_KEY.to_string(), card);
173 if let Err(e) = crate::backend::wcore::object_meta::update_object_meta(mstore, &format!("block:{block_id}"), &update) {
174 tracing::warn!(block_id, error = %e, "model route: the pane was not told a change was undone");
175 }
176}
177
178#[cfg(test)]
179#[path = "trial_tests.rs"]
180mod tests;