Skip to main content

agentmux_srv_core/backend/model_gateway/
cap.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The spend caps (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` section 3.2): how much an agent may use
5//! through the gateway in a UTC day, and how much a route may. The gateway reads them at each request, so a
6//! cap raised mid-turn lets the next request through.
7//!
8//! - **Per agent:** the agent definition's content `agent:spend_cap_usd`. Absent is the app setting
9//!   `model:agent_spend_cap_usd` (the default for every agent without a cap of its own), and absent that
10//!   [`DEFAULT_AGENT_CAP_USD`]; `none` or `0` is no cap.
11//! - **Per route:** the app setting `model:spend_cap_usd:<route id>`. Absent is [`DEFAULT_ROUTE_CAP_USD`];
12//!   `none` or `0` is no cap. A route is the OpenRouter route or the Anthropic API-key route
13//!   ([`super::catalog::KEY_ROUTE_ID`]); an agent on a login has plan limits and no cap.
14
15use super::spend;
16use super::token::Grant;
17use crate::backend::storage::content::AgentContent;
18use crate::backend::storage::store::Store;
19use std::collections::HashMap;
20
21/// The agent-definition content type the agent's cap is kept under.
22pub const AGENT_CAP_TYPE: &str = "agent:spend_cap_usd";
23/// The prefix of the app setting a route's cap is kept under; the route id follows.
24pub const ROUTE_CAP_SETTING: &str = "model:spend_cap_usd:";
25/// The app setting the default per-agent cap is kept under.
26pub const DEFAULT_AGENT_CAP_SETTING: &str = "model:agent_spend_cap_usd";
27/// What an agent without a cap of its own may use in a day when the setting is not set.
28pub const DEFAULT_AGENT_CAP_USD: f64 = 50.0;
29/// What a route may be used for in a day when its setting is not set.
30pub const DEFAULT_ROUTE_CAP_USD: f64 = 500.0;
31/// The least a cap may be set to: a smaller one is not a cap anyone meant.
32pub const MIN_CAP_USD: f64 = 0.01;
33
34/// What a cap was reached for.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Scope {
37    Agent,
38    Route,
39}
40
41/// A cap that has been reached.
42#[derive(Debug, Clone, PartialEq)]
43pub struct Hit {
44    pub scope: Scope,
45    pub cap: f64,
46    pub spent: f64,
47}
48
49/// A cap as written: a positive number of dollars, or `none` (also `0`) for no cap. `None` for anything else.
50fn parse(value: &serde_json::Value) -> Option<Option<f64>> {
51    let number = match value {
52        serde_json::Value::String(s) if matches!(s.trim().to_ascii_lowercase().as_str(), "none" | "unlimited" | "off") => return Some(None),
53        serde_json::Value::String(s) => s.trim().trim_start_matches('$').parse::<f64>().ok()?,
54        other => other.as_f64()?,
55    };
56    match number {
57        n if !n.is_finite() || n < 0.0 => None,
58        n if n == 0.0 => Some(None),
59        n => Some(Some(n)),
60    }
61}
62
63/// The cap an agent has when it has none of its own: the setting, or [`DEFAULT_AGENT_CAP_USD`]. `None` is no cap.
64pub fn default_agent_cap(settings: &HashMap<String, serde_json::Value>) -> Option<f64> {
65    match settings.get(DEFAULT_AGENT_CAP_SETTING).and_then(parse) {
66        Some(cap) => cap,
67        None => Some(DEFAULT_AGENT_CAP_USD),
68    }
69}
70
71/// The agent's cap in dollars a day, or `None` when it has none.
72pub fn agent_cap(mstore: &Store, settings: &HashMap<String, serde_json::Value>, def_id: &str) -> Option<f64> {
73    let stored = mstore.agent_content_get(def_id, AGENT_CAP_TYPE).ok().flatten();
74    match stored.and_then(|c| parse(&serde_json::Value::String(c.content))) {
75        Some(cap) => cap,
76        None => default_agent_cap(settings),
77    }
78}
79
80/// Sets the agent's cap: `Some(dollars)`, or `None` for no cap.
81pub fn set_agent_cap(mstore: &Store, def_id: &str, cap: Option<f64>) -> Result<(), String> {
82    let content = cap.map_or_else(|| "none".to_string(), |c| c.to_string());
83    mstore
84        .agent_content_set(&AgentContent {
85            agent_id: def_id.to_string(),
86            content_type: AGENT_CAP_TYPE.to_string(),
87            content,
88            updated_at: agentmux_common::time::now_ms(),
89        })
90        .map_err(|e| e.to_string())
91}
92
93/// Takes the agent's own cap away, so it has the default again.
94pub fn clear_agent_cap(mstore: &Store, def_id: &str) -> Result<(), String> {
95    mstore.agent_content_delete(def_id, AGENT_CAP_TYPE).map(|_| ()).map_err(|e| e.to_string())
96}
97
98/// Whether the agent has a cap of its own (a number or `none`), and not the default.
99pub fn has_own_cap(mstore: &Store, def_id: &str) -> bool {
100    let stored = mstore.agent_content_get(def_id, AGENT_CAP_TYPE).ok().flatten();
101    stored.and_then(|c| parse(&serde_json::Value::String(c.content))).is_some()
102}
103
104/// What `Agents update spend_cap_usd` takes: a positive number of dollars, `0` or `"none"` for no cap.
105pub fn parse_request(value: &serde_json::Value) -> Result<Option<f64>, String> {
106    let cap = parse(value).ok_or_else(|| "spend_cap_usd is a positive number of dollars a day, or 0 / \"none\" for no cap".to_string())?;
107    match cap {
108        Some(c) if c < MIN_CAP_USD => Err(format!("spend_cap_usd is at least ${MIN_CAP_USD:.2}; 0 or \"none\" removes the cap")),
109        other => Ok(other),
110    }
111}
112
113/// The route's cap in dollars a day, or `None` when it has none.
114pub fn route_cap(settings: &HashMap<String, serde_json::Value>, route: &str) -> Option<f64> {
115    match settings.get(&format!("{ROUTE_CAP_SETTING}{route}")).and_then(parse) {
116        Some(cap) => cap,
117        None => Some(DEFAULT_ROUTE_CAP_USD),
118    }
119}
120
121/// The cap the agent's use today has reached, if any. The agent's own is checked first.
122pub fn reached(mstore: &Store, settings: &HashMap<String, serde_json::Value>, grant: &Grant, now_ms: i64) -> Option<Hit> {
123    if let Some(cap) = agent_cap(mstore, settings, &grant.def_id) {
124        let spent = spend::today(&grant.agent, now_ms).cost_usd;
125        if spent >= cap {
126            return Some(Hit { scope: Scope::Agent, cap, spent });
127        }
128    }
129    let cap = route_cap(settings, &grant.route)?;
130    let spent = spend::route_today_usd(&grant.route, now_ms);
131    (spent >= cap).then_some(Hit { scope: Scope::Route, cap, spent })
132}
133
134/// How far `spent` is into `cap`, as the alert level it has passed: 0, 50, 80 or 100.
135pub fn level(spent: f64, cap: f64) -> u8 {
136    match spent / cap {
137        r if r >= 1.0 => 100,
138        r if r >= 0.8 => 80,
139        r if r >= 0.5 => 50,
140        _ => 0,
141    }
142}
143
144/// The alert level the agent's day is at under its own cap; 0 when it has none.
145pub fn agent_level(mstore: &Store, settings: &HashMap<String, serde_json::Value>, grant: &Grant, now_ms: i64) -> (u8, Option<f64>, f64) {
146    let spent = spend::today(&grant.agent, now_ms).cost_usd;
147    match agent_cap(mstore, settings, &grant.def_id) {
148        Some(cap) => (level(spent, cap), Some(cap), spent),
149        None => (0, None, spent),
150    }
151}
152
153/// The refusal the harness shows: what was used, what the cap is and who can lift it.
154pub fn refusal_text(hit: &Hit) -> String {
155    match hit.scope {
156        Scope::Agent => format!(
157            "spend cap: this agent has used ${:.2} of its ${:.2} for today (UTC). A person or its leader can raise the cap.",
158            hit.spent, hit.cap
159        ),
160        Scope::Route => format!(
161            "spend cap: the daily cap of ${:.2} for this agent's model route or API key is used by all agents together (${:.2}). A person can raise it in Settings.",
162            hit.cap, hit.spent
163        ),
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::agents::types::TokenCounts;
171    use crate::backend::model_gateway::catalog;
172    use serde_json::json;
173
174    fn store_with(def_id: &str) -> Store {
175        let store = Store::open_in_memory().unwrap();
176        let mut def = crate::backend::storage::agents::test_agent_def(def_id, def_id, "claude", "host", 1, "");
177        store.agent_def_insert(&mut def).unwrap();
178        store
179    }
180
181    #[test]
182    fn a_cap_is_dollars_or_none_and_anything_else_is_refused() {
183        assert_eq!(parse_request(&json!(40)), Ok(Some(40.0)));
184        assert_eq!(parse_request(&json!("12.5")), Ok(Some(12.5)));
185        assert_eq!(parse_request(&json!("$7")), Ok(Some(7.0)));
186        assert_eq!(parse_request(&json!(0)), Ok(None));
187        assert_eq!(parse_request(&json!("none")), Ok(None));
188        assert!(parse_request(&json!(-1)).is_err());
189        assert!(parse_request(&json!(0.004)).is_err(), "a cap under a cent would read back as none");
190        assert_eq!(parse_request(&json!(0.01)), Ok(Some(0.01)));
191        assert!(parse_request(&json!("lots")).is_err());
192        assert!(parse_request(&json!(true)).is_err());
193    }
194
195    #[test]
196    fn levels_are_the_thresholds_passed() {
197        assert_eq!([0.0, 9.99, 10.0, 15.99, 16.0, 19.99, 20.0, 31.0].map(|s| level(s, 20.0)), [0, 0, 50, 50, 80, 80, 100, 100]);
198    }
199
200    #[test]
201    fn an_agent_has_the_default_cap_until_one_is_set_and_none_means_no_cap() {
202        let store = store_with("cap-def");
203        let settings = HashMap::new();
204        assert_eq!(agent_cap(&store, &settings, "cap-def"), Some(DEFAULT_AGENT_CAP_USD));
205        set_agent_cap(&store, "cap-def", Some(40.0)).unwrap();
206        assert_eq!(agent_cap(&store, &settings, "cap-def"), Some(40.0));
207        set_agent_cap(&store, "cap-def", Some(0.013)).unwrap();
208        assert_eq!(agent_cap(&store, &settings, "cap-def"), Some(0.013), "kept as given, not rounded to a cent");
209        set_agent_cap(&store, "cap-def", None).unwrap();
210        assert_eq!(agent_cap(&store, &settings, "cap-def"), None);
211    }
212
213    #[test]
214    fn clearing_an_agents_own_cap_gives_it_the_default_again() {
215        let store = store_with("clr-def");
216        let settings = HashMap::new();
217        assert!(!has_own_cap(&store, "clr-def"));
218        set_agent_cap(&store, "clr-def", None).unwrap();
219        assert!(has_own_cap(&store, "clr-def"), "none is a cap of its own");
220        assert_eq!(agent_cap(&store, &settings, "clr-def"), None);
221        set_agent_cap(&store, "clr-def", Some(30.0)).unwrap();
222        assert!(has_own_cap(&store, "clr-def"));
223        clear_agent_cap(&store, "clr-def").unwrap();
224        assert!(!has_own_cap(&store, "clr-def"));
225        assert_eq!(agent_cap(&store, &settings, "clr-def"), Some(DEFAULT_AGENT_CAP_USD));
226        clear_agent_cap(&store, "clr-def").unwrap();
227    }
228
229    #[test]
230    fn the_default_cap_is_read_from_the_settings_each_time_and_an_agents_own_cap_wins() {
231        let store = store_with("dflt-def");
232        let mut settings = HashMap::new();
233        assert_eq!((DEFAULT_AGENT_CAP_USD, DEFAULT_ROUTE_CAP_USD), (50.0, 500.0), "the shipped defaults");
234        assert_eq!(agent_cap(&store, &settings, "dflt-def"), Some(50.0));
235        settings.insert(DEFAULT_AGENT_CAP_SETTING.to_string(), json!(75));
236        assert_eq!(agent_cap(&store, &settings, "dflt-def"), Some(75.0), "the next request sees a changed setting");
237        settings.insert(DEFAULT_AGENT_CAP_SETTING.to_string(), json!("none"));
238        assert_eq!(agent_cap(&store, &settings, "dflt-def"), None, "none is no cap for agents without their own");
239        settings.insert(DEFAULT_AGENT_CAP_SETTING.to_string(), json!("lots"));
240        assert_eq!(agent_cap(&store, &settings, "dflt-def"), Some(50.0), "an unreadable setting falls back to the shipped default");
241        settings.insert(DEFAULT_AGENT_CAP_SETTING.to_string(), json!(75));
242        set_agent_cap(&store, "dflt-def", Some(10.0)).unwrap();
243        assert_eq!(agent_cap(&store, &settings, "dflt-def"), Some(10.0), "an agent's own cap wins over the default");
244        set_agent_cap(&store, "dflt-def", None).unwrap();
245        assert_eq!(agent_cap(&store, &settings, "dflt-def"), None, "its own none wins too");
246    }
247
248    #[test]
249    fn a_route_has_the_default_cap_unless_the_settings_say_otherwise() {
250        let mut settings = HashMap::new();
251        assert_eq!(route_cap(&settings, "openrouter"), Some(DEFAULT_ROUTE_CAP_USD));
252        settings.insert(format!("{ROUTE_CAP_SETTING}openrouter"), json!(250));
253        assert_eq!(route_cap(&settings, "openrouter"), Some(250.0));
254        settings.insert(format!("{ROUTE_CAP_SETTING}openrouter"), json!("none"));
255        assert_eq!(route_cap(&settings, "openrouter"), None);
256        assert_eq!(route_cap(&settings, "other"), Some(DEFAULT_ROUTE_CAP_USD));
257    }
258
259    #[test]
260    fn the_agents_cap_is_reached_before_the_routes_and_the_text_says_which() {
261        let store = store_with("reach-def");
262        let model = catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
263        let used = TokenCounts { input: 1, ..Default::default() };
264        let grant = Grant { agent: "reach-agent".into(), def_id: "reach-def".into(), route: "reach-route".into(), account: String::new(), peer: None };
265        let now = agentmux_common::time::now_ms();
266        let mut settings = HashMap::new();
267        settings.insert(DEFAULT_AGENT_CAP_SETTING.to_string(), json!(20));
268        spend::record("reach-agent", "reach-route", model, &used, Some(19.0), now);
269        assert_eq!(reached(&store, &settings, &grant, now), None);
270        assert_eq!(agent_level(&store, &settings, &grant, now).0, 80);
271        spend::record("reach-agent", "reach-route", model, &used, Some(1.0), now);
272        let hit = reached(&store, &settings, &grant, now).expect("the agent's $20 is used");
273        assert_eq!((hit.scope, hit.cap), (Scope::Agent, 20.0));
274        assert!(refusal_text(&hit).starts_with("spend cap: this agent has used $20.00 of its $20.00"));
275
276        // No cap of its own, but other agents have used the route's cap: the route's cap stops it.
277        set_agent_cap(&store, "reach-def", None).unwrap();
278        settings.insert(format!("{ROUTE_CAP_SETTING}reach-route"), json!(100));
279        assert_eq!(reached(&store, &settings, &grant, now), None);
280        spend::record("reach-other", "reach-route", model, &used, Some(80.0), now);
281        let hit = reached(&store, &settings, &grant, now).expect("the route's $100 is used");
282        assert_eq!((hit.scope, hit.cap), (Scope::Route, 100.0));
283        assert!(refusal_text(&hit).contains("cap of $100.00 for this agent's model route or API key"));
284        // The next UTC day starts again.
285        assert_eq!(reached(&store, &settings, &grant, now + 86_400_000), None);
286    }
287}