Skip to main content

agentmux_srv_core/backend/model_gateway/
trial.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A change of route or model that is kept only once the first turn on it has worked (spec section 7a.3, "Thinking
5//! blocks across providers"). A backend that is not Anthropic's may refuse a history it did not write: a thinking
6//! block's signature, an image it cannot read, a setting it does not take. Left alone, the agent is on a place that
7//! answers every turn with a 400. So a change starts a trial: the place the agent came from is kept, the first turn the
8//! relaunched harness runs decides it, and a request the new place refuses puts the agent back where it was and says why.
9//!
10//! The trial is armed when the harness is relaunched on the new place ([`arm_for_block`], from the persistent
11//! controller's install of the new process, not from building its environment, which a message to a process that is
12//! already running does too): a turn that was still running on the old one when the change was recorded must not settle it. It is armed for that pane: an agent's other
13//! panes, still on the old place, do not decide it. (A late frame of a process the pane has since replaced is dropped
14//! by the pane's reader before it gets here.)
15
16use 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
24/// The definition content type that holds the [`Trial`].
25pub const TRIAL_TYPE: &str = "agent:model_route_trial";
26/// The block meta key the pane reads to say a change was undone and why; absent when none was.
27pub const UNDONE_META_KEY: &str = "agent:model_switch_undone";
28/// How much of the harness's error is kept for the person.
29const REASON_CHARS: usize = 300;
30
31/// A change waiting for its first turn.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Trial {
34    /// Where the agent was before the change. An empty `route` is the harness's own sign-in.
35    pub from: Previous,
36    /// The harness was relaunched on the new place: its next turn settles the change.
37    #[serde(default)]
38    pub armed: bool,
39    /// The pane whose harness was relaunched; only its turns settle the change.
40    #[serde(default)]
41    pub block: String,
42}
43
44/// What a turn's end says about the change.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum Verdict {
47    /// The turn worked: the change stands.
48    Commit,
49    /// The place refused the request (this HTTP status): the change is undone.
50    Refused(u16),
51    /// The turn failed for something that is not about the history (a limit, a network error, a server error): the change
52    /// waits for another turn.
53    Wait,
54}
55
56/// The trial of the agent definition `def_id`, if one is waiting.
57pub 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
74/// A change from `from` to `to` was recorded. A trial that never got to run keeps the place the agent last worked on: it
75/// is not moved on by a second change, and a change back to it ends the trial.
76pub 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
85/// The harness of the agent in pane `block_id` was relaunched on its recorded place. The latest relaunch is the pane
86/// that decides: one that was closed before its first turn cannot leave the change waiting for good.
87pub 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
96/// The persistent harness of pane `block_id` was started (a new process is installed): arms the trial of its agent, if
97/// one is waiting. A message that only reaches a process already running does not come here.
98pub 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
103/// What the `result` frame that ends a turn says about the change.
104pub 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        // The request was not accepted as it was sent: the history, a setting or the model itself.
110        Some(status @ (400 | 404 | 413 | 422)) => Verdict::Refused(status),
111        _ => Verdict::Wait,
112    }
113}
114
115/// The status in the harness's `API Error: 400 ...`.
116fn 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/// A change that was undone.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Undone {
125    /// Where the agent is again.
126    pub back_on: Previous,
127    /// What it tried.
128    pub tried: Previous,
129}
130
131/// A turn of the agent in pane `block_id` ended with `frame`. When it settles an armed trial, the change stands (`None`) or is undone
132/// (`Some`: the record is back on the old place and the pane says why; the caller restarts the harness).
133pub 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    // An empty place is the harness's own sign-in: a change onto it can be refused and undone like any other.
144    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;