agentmux_srv_core/backend/
route_credits.rs1use 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
33const EPISODE_MAX_MS: u64 = 6 * 60 * 60 * 1000;
36
37static EPISODES: LazyLock<parking_lot::Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub(crate) struct Opened {
43 pub key: String,
45 pub route: Option<String>,
47 pub agents: Vec<(String, String)>,
49}
50
51type Pane = (String, String);
53
54pub(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
64pub 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 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
89pub(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
125pub fn cleared(mstore: &Arc<Store>, bus: &Arc<EventBus>, broker: &Arc<Broker>, route: &str) {
128 {
129 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
143pub(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
164fn 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
176fn 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
186fn running_route(block: &Block) -> Option<String> {
190 block.meta.get(launch::BLOCK_META_KEY)?.get("route")?.as_str().map(str::to_string)
191}
192
193fn 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
207pub(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
241pub(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
254fn note_key(episode_key: &str) -> String {
256 format!("credits:{}", crate::backend::notify::policy::tag_for(episode_key))
257}
258
259fn 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(¬e_key(&opened.key), person_note(opened)));
264 }
265 None => tracing::info!("route credits: no notification router yet (no window connected)"),
266 }
267}
268
269fn 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
282fn take_down_note(broker: &Arc<Broker>, episode_key: &str) {
284 if let Some(router) = crate::backend::notify::router::get(broker) {
285 router.resolve(¬e_key(episode_key), crate::backend::notify::policy::Family::Account);
286 }
287}
288
289fn 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;