Skip to main content

agentmux_srv_core/backend/
route_credits.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A model route whose key has no credits left (HTTP 402).
5//!
6//! Every agent on the route fails the same way until someone adds credits. Without this, only the agent
7//! that happened to hit the 402 showed the failure; the others stayed idle and available, messages kept
8//! starting turns that failed, and nobody was told.
9//!
10//! What follows from the first 402 of an **episode** (a route, from its first 402 to its next success):
11//! - the failure (`agents::failure` classes it `UsageLimit` with `ROUTE_CREDITS_TITLE`, and
12//!   `limit_reset` gives it a reset ten minutes ahead) is written to every other open pane on the route,
13//!   so each shows as limited and holds its messages until the reset, when a turn probes the route;
14//! - each distinct lead of those agents gets one `[AgentMux]` note naming its agents, and no note about
15//!   the route after it (a worker's own failure note is left out, `worker_notes`);
16//! - the first successful response on the route (`spend_watch::settled`) ends the episode and takes the
17//!   failure off every pane that still shows it.
18//!
19//! An agent on no route (a harness on its own provider key) has an episode of its own, and is noted the
20//! same way; a turn that works clears its own failure.
21
22use std::collections::HashMap;
23use std::sync::{Arc, LazyLock};
24
25use crate::agents::failure::AgentFailure;
26use crate::backend::agent_state::failure_of_block;
27use crate::backend::eventbus::EventBus;
28use crate::backend::model_gateway::{catalog, launch};
29use crate::backend::mps::{Broker, MuxEvent};
30use crate::backend::obj::{self, Block, Tab};
31use crate::backend::storage::store::Store;
32
33/// An episode with no success is let go after this long, so a route fixed while srv could not see it
34/// (an agent that never ran again) is not silent about its next 402 forever.
35const EPISODE_MAX_MS: u64 = 6 * 60 * 60 * 1000;
36
37/// Episode key → when it began (unix ms). A route's id, or `agent:<definition id>` for an agent on no route.
38static EPISODES: LazyLock<parking_lot::Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);
39
40/// An episode that has just begun: who is on the route, for the notes.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub(crate) struct Opened {
43    /// The episode's key: the route's id, or `agent:<definition id>`. The person's note is taken down by it.
44    pub key: String,
45    /// The route's label, or `None` for an agent on no route.
46    pub route: Option<String>,
47    /// The agents with an open pane there, as (definition id, name).
48    pub agents: Vec<(String, String)>,
49}
50
51/// An open pane of an agent: (block id, definition id).
52type Pane = (String, String);
53
54/// The credits failure in a broker event, with the pane it is about.
55pub(crate) fn credits_failure(event: &str, scopes: &[String], data: Option<&serde_json::Value>) -> Option<(String, AgentFailure)> {
56    if event != crate::backend::mps::EVENT_AGENT_FAILURE {
57        return None;
58    }
59    let failure: AgentFailure = serde_json::from_value(data?.clone()).ok()?;
60    let block_id = scopes.iter().find_map(|s| s.strip_prefix("block:"))?.to_string();
61    failure.is_route_credits().then_some((block_id, failure))
62}
63
64/// Start listening. Called once from `main`.
65pub fn install(broker: Arc<Broker>, mstore: Arc<Store>, event_bus: Arc<EventBus>) {
66    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<(String, AgentFailure)>();
67    // Observers run inside `Broker::publish`, under its locks: parse and hand off only.
68    broker.add_observer(Arc::new(move |ev: &MuxEvent| {
69        if let Some(found) = credits_failure(&ev.event, &ev.scopes, ev.data.as_ref()) {
70            let _ = tx.send(found);
71        }
72    }));
73    let notify_broker = broker.clone();
74    tokio::spawn(async move {
75        while let Some((block_id, failure)) = rx.recv().await {
76            let (mstore, event_bus, broker) = (mstore.clone(), event_bus.clone(), notify_broker.clone());
77            let _ = tokio::task::spawn_blocking(move || {
78                let now = agentmux_common::time::now_ms_u64();
79                if let Some(opened) = on_failure(&mstore, &event_bus, &block_id, &failure, now) {
80                    tell_leaders(&mstore, &opened);
81                    tell_person(&broker, &opened);
82                }
83            })
84            .await;
85        }
86    });
87}
88
89/// `block_id`'s agent hit the credits failure `failure`: write it to the other open panes on its route, and
90/// say whether this opened the route's episode. BLOCKING (store reads and writes).
91pub(crate) fn on_failure(mstore: &Arc<Store>, bus: &Arc<EventBus>, block_id: &str, failure: &AgentFailure, now: u64) -> Option<Opened> {
92    let block = mstore.get::<Block>(block_id).ok()??;
93    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
94    if def_id.is_empty() {
95        return None;
96    }
97    let route = running_route(&block);
98    let mut panes: Vec<Pane> = vec![(block_id.to_string(), def_id.clone())];
99    for (other, other_def) in route.iter().flat_map(|r| panes_on(mstore, r)) {
100        if other == block_id {
101            continue;
102        }
103        if !shows_credits(mstore, &other) {
104            crate::backend::blockcontroller::core::persist_last_failure(&other, Some(failure), &Some(mstore.clone()), &Some(bus.clone()));
105        }
106        panes.push((other, other_def));
107    }
108    let key = route.clone().unwrap_or_else(|| format!("agent:{def_id}"));
109    if !open_episode(&key, now) {
110        return None;
111    }
112    let mut seen = std::collections::HashSet::new();
113    let agents = panes
114        .into_iter()
115        .filter(|(_, def)| seen.insert(def.clone()))
116        .map(|(_, def)| {
117            let name = mstore.agent_def_get(&def).ok().flatten().map_or_else(|| def.clone(), |d| d.name);
118            (def, name)
119        })
120        .collect();
121    let route = route.map(|r| catalog::route(&r).map_or(r, |known| known.label.to_string()));
122    Some(Opened { key, route, agents })
123}
124
125/// A response on `route` worked: its episode ends, and the failure goes off every pane that shows it.
126/// BLOCKING (store reads and writes), but only once per episode; any other call is a map lookup.
127pub fn cleared(mstore: &Arc<Store>, bus: &Arc<EventBus>, broker: &Arc<Broker>, route: &str) {
128    {
129        // The note comes down under the lock that ended the episode, so [`post_while_open`] can't post it between the two.
130        let mut episodes = EPISODES.lock();
131        if episodes.remove(route).is_none() {
132            return;
133        }
134        take_down_note(broker, route);
135    }
136    for (block_id, _) in panes_on(mstore, route) {
137        if shows_credits(mstore, &block_id) {
138            crate::backend::blockcontroller::core::persist_last_failure(&block_id, None, &Some(mstore.clone()), &Some(bus.clone()));
139        }
140    }
141}
142
143/// A turn on `block_id` worked: the agent's own episode (the one an agent on no route has, [`on_failure`]) ends, so
144/// its next credits failure is news again. A route's episode ends in [`cleared`], on a gateway answer; an agent on
145/// its own key never passes the gateway. A map lookup unless an episode is open.
146pub(crate) fn turn_succeeded(mstore: &Store, broker: Option<&Arc<Broker>>, block_id: &str) {
147    if EPISODES.lock().is_empty() {
148        return;
149    }
150    let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return };
151    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
152    if def_id.is_empty() {
153        return;
154    }
155    let key = format!("agent:{def_id}");
156    let mut episodes = EPISODES.lock();
157    if episodes.remove(&key).is_some() {
158        if let Some(broker) = broker {
159            take_down_note(broker, &key);
160        }
161    }
162}
163
164/// Whether the episode `key` is new (and now begun): none is open, or the open one is past `EPISODE_MAX_MS`.
165fn open_episode(key: &str, now: u64) -> bool {
166    let mut episodes = EPISODES.lock();
167    match episodes.get(key) {
168        Some(since) if now < since.saturating_add(EPISODE_MAX_MS) => false,
169        _ => {
170            episodes.insert(key.to_string(), now);
171            true
172        }
173    }
174}
175
176/// Whether the pane's stored failure is already the credits one.
177fn shows_credits(mstore: &Store, block_id: &str) -> bool {
178    mstore
179        .get::<Block>(block_id)
180        .ok()
181        .flatten()
182        .and_then(|b| failure_of_block(&b))
183        .is_some_and(|f| f.code == crate::agents::failure::FailureClass::UsageLimit && f.title == crate::agents::failure::ROUTE_CREDITS_TITLE)
184}
185
186/// The route the harness in `block` was launched on, as the launch recorded it on the pane. Not the agent's chosen
187/// route and not its left-route mark, which are the agent's as a whole: a model switch is recorded at once, but each
188/// pane is relaunched on it only when its own turn ends, so two panes of one agent can be on different routes (#47474).
189fn running_route(block: &Block) -> Option<String> {
190    block.meta.get(launch::BLOCK_META_KEY)?.get("route")?.as_str().map(str::to_string)
191}
192
193/// The open panes (in a tab) of agents whose harness is running on `route`.
194fn panes_on(mstore: &Store, route: &str) -> Vec<Pane> {
195    let Ok(tabs) = mstore.get_all::<Tab>() else { return Vec::new() };
196    tabs.iter()
197        .flat_map(|t| t.blockids.iter())
198        .filter_map(|id| {
199            let block = mstore.get::<Block>(id).ok().flatten()?;
200            let def_id = obj::meta_get_string(&block.meta, "agentId", "");
201            let on_it = !def_id.is_empty() && running_route(&block).is_some_and(|r| r == route);
202            on_it.then(|| (id.clone(), def_id))
203        })
204        .collect()
205}
206
207/// What each distinct lead of the agents in `opened` is told: their own, once. A lead on another machine, or
208/// an agent with none, is not told.
209pub(crate) fn notes_for(mstore: &Store, opened: &Opened) -> Vec<(String, String)> {
210    let mut by_lead: Vec<(String, Vec<&(String, String)>)> = Vec::new();
211    for agent in &opened.agents {
212        let lead = crate::backend::agent_seat::effective_seat_by_id(mstore, &agent.0)
213            .and_then(|seat| seat.lead)
214            .filter(|lead| !crate::backend::agent_seat::is_remote_lead(lead));
215        let Some(lead) = lead else { continue };
216        match by_lead.iter_mut().find(|(l, _)| *l == lead) {
217            Some((_, mine)) => mine.push(agent),
218            None => by_lead.push((lead, vec![agent])),
219        }
220    }
221    by_lead
222        .into_iter()
223        .map(|(_, mine)| {
224            let names = mine.iter().map(|(_, name)| name.as_str()).collect::<Vec<_>>().join(", ");
225            let body = match &opened.route {
226                Some(route) => format!(
227                    "{route} is out of credits (HTTP 402), so {names} can't work ({total} on the route in all). Add credits to the route's key in the provider's account. \
228                     Their messages wait, and each tries again every few minutes. This is the only note about it until it works again.",
229                    total = opened.agents.len()
230                ),
231                None => format!(
232                    "{names} is out of credits on its model provider's account (HTTP 402) and can't work. Add credits there. \
233                     Its messages wait, and it tries again every few minutes. This is the only note about it until it works again."
234                ),
235            };
236            (mine[0].0.clone(), body)
237        })
238        .collect()
239}
240
241/// What the person is told when an episode opens: the route and what to do, once, never an agent's name (a
242/// notification can show on a locked screen).
243pub(crate) fn person_note(opened: &Opened) -> String {
244    match &opened.route {
245        Some(route) => {
246            let n = opened.agents.len();
247            let agents = if n == 1 { "1 agent".to_string() } else { format!("{n} agents") };
248            format!("{route} is out of credits, so {agents} can't work. Add credits to the route's key in the provider's account; they start again by themselves.")
249        }
250        None => "An agent is out of credits on its model provider's account and can't work. Add credits there; it starts again by itself.".to_string(),
251    }
252}
253
254/// The note's key, which the notification is taken down by. Hashed, like an account's.
255fn note_key(episode_key: &str) -> String {
256    format!("credits:{}", crate::backend::notify::policy::tag_for(episode_key))
257}
258
259/// Tell the person once per episode (the notification router's account surface, as for a login that expired).
260fn tell_person(broker: &Arc<Broker>, opened: &Opened) {
261    match crate::backend::notify::router::get(broker) {
262        Some(router) => {
263            post_while_open(&opened.key, || router.account_unavailable(&note_key(&opened.key), person_note(opened)));
264        }
265        None => tracing::info!("route credits: no notification router yet (no window connected)"),
266    }
267}
268
269/// Runs `post` only while the episode `key` is still open, and says whether it did. A success can end the episode
270/// between [`on_failure`] opening it and the note being posted; the note it took down was not there yet, so posting
271/// now would leave one for a route that works, and nothing would take it down. The check and the post are under the
272/// episodes lock, as [`cleared`]'s removal and take-down are.
273fn post_while_open(key: &str, post: impl FnOnce()) -> bool {
274    let episodes = EPISODES.lock();
275    if !episodes.contains_key(key) {
276        return false;
277    }
278    post();
279    true
280}
281
282/// The episode ended: its note comes down.
283fn take_down_note(broker: &Arc<Broker>, episode_key: &str) {
284    if let Some(router) = crate::backend::notify::router::get(broker) {
285        router.resolve(&note_key(episode_key), crate::backend::notify::policy::Family::Account);
286    }
287}
288
289/// Tell each lead (see [`notes_for`]). BLOCKING.
290fn tell_leaders(mstore: &Store, opened: &Opened) {
291    for (def_id, body) in notes_for(mstore, opened) {
292        crate::backend::worker_notes::tell_leader(mstore, &def_id, &body);
293    }
294}
295
296#[cfg(test)]
297#[path = "route_credits_tests.rs"]
298mod tests;