Skip to main content

agentmux_srv/server/
limit_check_api.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Identity` with action `check_limits`: look again, now, at the agents marked out of quota, for
5//! an agent that learns the plan was raised or the quota refilled (task #2648). Without it the only
6//! way to start a check was to know that an urgent message does.
7//!
8//! The same check as the Swarm's "Check now" (`limit_probe::check_limited`): each limited agent gets
9//! a small turn, staggered by account, and one that works clears the limit, wakes what was held for
10//! the agent and clears the account's other panes (`limit_evidence`). It sends nothing in anyone's
11//! name, so any agent may ask.
12
13use serde::Serialize;
14
15use crate::backend::agent_state::{unavailable_of_block, AgentState};
16use crate::backend::obj::{self, Block};
17use crate::server::api_error::ApiError;
18use crate::server::AppState;
19
20/// What `check_limits` did.
21#[derive(Debug, Default, PartialEq, Eq, Serialize)]
22pub(crate) struct CheckLimitsResult {
23    /// The agents whose check started or runs, by name.
24    pub checked: Vec<String>,
25    /// The agents whose check could not start, and why.
26    pub failed: Vec<CheckLimitsFailure>,
27    /// A note when nothing was out of quota to check.
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub note: Option<String>,
30}
31
32#[derive(Debug, PartialEq, Eq, Serialize)]
33pub(crate) struct CheckLimitsFailure {
34    pub agent: String,
35    pub error: String,
36}
37
38/// The panes out of quota that a check is asked for: `(block id, agent name, account id)` of every pane
39/// of `blocks` that is limited by its plan. BLOCKING.
40fn limited_panes(state: &AppState, blocks: &[Block], now_ms: u64) -> Vec<(String, String, Option<String>)> {
41    blocks
42        .iter()
43        .filter_map(|b| {
44            let u = unavailable_of_block(&state.mstore, Some(&state.identity_store), &b.oid, now_ms)?;
45            if u.state != AgentState::Limited || u.title == crate::agents::failure::ROUTE_CREDITS_TITLE {
46                return None;
47            }
48            let id = obj::meta_get_string(&b.meta, "agentId", "");
49            let name = state.mstore.agent_def_get(&id).ok().flatten().map_or(id, |d| d.name);
50            Some((b.oid.clone(), name, u.account_id))
51        })
52        .collect()
53}
54
55/// Checks the agents out of quota: those on `account` (its id, label or email) when given, else all of them.
56/// BLOCKING.
57fn check_blocking(state: &AppState, account: Option<&str>) -> Result<CheckLimitsResult, ApiError> {
58    let now_ms = agentmux_common::time::now_ms_u64();
59    let accounts = state.id_store.identity_list(None).unwrap_or_default();
60    let wanted: Option<String> = match account.map(str::trim).filter(|a| !a.is_empty()) {
61        None => None,
62        Some(wanted) => {
63            let found: Vec<&_> = accounts.iter().filter(|a| crate::identity::account_numbering::names(a, wanted, &accounts)).collect();
64            match found.as_slice() {
65                [one] => Some(one.id.clone()),
66                [] => return Err(ApiError::not_found(format!("no account named \"{wanted}\"; Identity with action \"accounts\" lists them"))),
67                _ => return Err(ApiError::bad_request(format!("\"{wanted}\" names more than one account; use its id"))),
68            }
69        }
70    };
71    let blocks: Vec<Block> = super::app_api::agent_block::blocks_in_tabs_or_parked(&state.mstore)?.into_iter().map(|(b, _)| b).collect();
72    let panes: Vec<_> = limited_panes(state, &blocks, now_ms)
73        .into_iter()
74        .filter(|(_, _, pane_account)| wanted.as_ref().is_none_or(|w| pane_account.as_ref() == Some(w)))
75        .collect();
76    if panes.is_empty() {
77        return Ok(CheckLimitsResult { note: Some("no agent is out of quota".to_string()), ..Default::default() });
78    }
79    let ids: Vec<String> = panes.iter().map(|(id, _, _)| id.clone()).collect();
80    let mut result = CheckLimitsResult::default();
81    for ((_, name, _), (_, answer)) in panes.into_iter().zip(super::limit_probe::check_limited(&state.mstore, &ids)) {
82        match answer {
83            Ok(()) => result.checked.push(name),
84            Err(error) => result.failed.push(CheckLimitsFailure { agent: name, error }),
85        }
86    }
87    Ok(result)
88}
89
90/// [`check_blocking`] off the async workers.
91pub(crate) async fn check_account_limits(state: AppState, account: Option<String>) -> Result<CheckLimitsResult, ApiError> {
92    tokio::task::spawn_blocking(move || check_blocking(&state, account.as_deref())).await.map_err(|e| e.to_string())?
93}