Skip to main content

agentmux_srv/server/app_api/
agent_spend.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The pane card's buttons for an agent that reached its daily spend cap (`agent.spend`): raise the cap, or reset
5//! today's figure (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` section 3.4). The operator's window only: an
6//! agent uses `Agents update spend_cap_usd`, where a leader's change is allowed and an agent's own is lowered only. Each
7//! change is audited with the cap before and after.
8
9use std::sync::Arc;
10
11use serde::{Deserialize, Serialize};
12
13use crate::backend::model_gateway::{cap, spend};
14use crate::backend::rpc::engine::WshRpcEngine;
15use crate::backend::rpc_types::COMMAND_AGENT_SPEND;
16use crate::server::AppState;
17
18#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
19#[ts(export, export_to = "../../../frontend/types/rpc/")]
20pub struct AgentSpendReq {
21    /// The agent pane. Empty when `agent` names the agent instead.
22    #[serde(default)]
23    pub blockid: String,
24    /// An agent by its id or slug, for one with no pane open (My Agents). Used when `blockid` is empty.
25    #[serde(default)]
26    pub agent: Option<String>,
27    /// `get` the cap and today's figure, `set` the day's cap to `cap_usd` (absent: no cap), `default` to take the agent's
28    /// own cap away so it has the default, or `reset` today's figure to zero.
29    pub action: String,
30    #[serde(default)]
31    pub cap_usd: Option<f64>,
32}
33
34#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
35#[ts(export, export_to = "../../../frontend/types/rpc/")]
36pub struct AgentSpendResult {
37    /// The agent's cap now; absent when it has none.
38    pub cap_usd: Option<f64>,
39    /// What it has used today.
40    pub spent_usd: f64,
41    /// Whether a cap applies to the agent at all: it is on a model route or an API key. An agent on a login has plan limits.
42    pub applies: bool,
43    /// Whether the cap is the agent's own, and not the default every agent without one has.
44    pub own_cap: bool,
45    /// The default cap (the setting `model:agent_spend_cap_usd`); absent when the default is no cap.
46    pub default_cap_usd: Option<f64>,
47}
48
49fn show(c: Option<f64>) -> String {
50    c.map_or("none".to_string(), |c| format!("${c:.2}"))
51}
52
53/// The agent the request is about: the one running in the pane, or the one named.
54fn definition_of(state: &AppState, req: &AgentSpendReq) -> Result<crate::backend::storage::AgentDefinition, String> {
55    if !req.blockid.is_empty() {
56        let instance = state
57            .mstore
58            .instance_get_active_for_block(&req.blockid)
59            .map_err(|e| e.to_string())?
60            .ok_or_else(|| format!("no agent runs in block {}", req.blockid))?;
61        return state.mstore.agent_def_get(&instance.definition_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no agent definition {}", instance.definition_id));
62    }
63    let named = req.agent.as_deref().filter(|a| !a.is_empty()).ok_or("name an agent pane (blockid) or an agent")?;
64    let defs = state.mstore.agent_def_list().map_err(|e| e.to_string())?;
65    defs.into_iter().find(|d| d.id == named || d.slug == named).ok_or_else(|| format!("no agent {named}"))
66}
67
68fn act(state: &AppState, req: &AgentSpendReq) -> Result<(AgentSpendResult, String, String), String> {
69    let def = definition_of(state, req)?;
70    let note = match req.action.as_str() {
71        "get" => String::new(),
72        "default" => {
73            let change = crate::server::spend_watch::clear_cap(state, &def.id)?;
74            format!("spend cap {} to {} (the default)", show(change.from), show(change.to))
75        }
76        "set" => {
77            if let Some(c) = req.cap_usd.filter(|c| !c.is_finite() || *c < cap::MIN_CAP_USD) {
78                return Err(format!("a cap is at least ${:.2}, or none (got {c})", cap::MIN_CAP_USD));
79            }
80            let change = crate::server::spend_watch::change_cap(state, &def.id, req.cap_usd)?;
81            format!("spend cap {} to {}", show(change.from), show(change.to))
82        }
83        "reset" => {
84            let removed = crate::server::spend_watch::reset_today(state, &def.id)?;
85            format!("reset today's spend (${removed:.2} counted)")
86        }
87        other => return Err(format!("action is get, set, default or reset, not {other}")),
88    };
89    let settings = state.config_watcher.get_settings().extra;
90    let result = AgentSpendResult {
91        cap_usd: cap::agent_cap(&state.mstore, &settings, &def.id),
92        spent_usd: spend::today(&def.slug, agentmux_common::time::now_ms()).cost_usd,
93        applies: crate::server::spend_watch::spends_through_gateway(state, &def.id),
94        own_cap: cap::has_own_cap(&state.mstore, &def.id),
95        default_cap_usd: cap::default_agent_cap(&settings),
96    };
97    Ok((result, def.name, note))
98}
99
100pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
101    let s = state.clone();
102    engine.register_typed(COMMAND_AGENT_SPEND, move |req: AgentSpendReq, ctx| {
103        let s = s.clone();
104        async move {
105            ctx.operator_only("only a person changes an agent's spend cap in the window; an agent uses Agents update spend_cap_usd")?;
106            tokio::task::spawn_blocking(move || {
107                let outcome = act(&s, &req);
108                if req.action == "get" {
109                    return outcome.map(|(result, _, _)| result);
110                }
111                let request_id = uuid::Uuid::new_v4().to_string();
112                // The audit row names where the change was made: the pane, or the agent when it was named with no pane.
113                let place = if req.blockid.is_empty() { req.agent.clone().unwrap_or_default() } else { req.blockid.clone() };
114                match &outcome {
115                    Ok((_, name, note)) => s.reactive_handler.log_fleet_action_audit(Some("you"), name, &place, "agent.spend", true, None, &request_id, Some(note)),
116                    Err(e) => s.reactive_handler.log_fleet_action_audit(Some("you"), &place, &place, "agent.spend", false, Some(e), &request_id, Some("refused")),
117                }
118                outcome.map(|(result, _, _)| result)
119            })
120            .await
121            .map_err(|e| e.to_string())?
122        }
123    });
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::server::model_gateway_tests::agent_on_route;
130    use crate::server::tests::test_state;
131
132    fn req(agent: &str, action: &str, cap_usd: Option<f64>) -> AgentSpendReq {
133        AgentSpendReq { blockid: String::new(), agent: Some(agent.to_string()), action: action.to_string(), cap_usd }
134    }
135
136    #[tokio::test]
137    async fn a_person_reads_sets_and_clears_an_agents_cap_by_naming_the_agent() {
138        let state = test_state();
139        let (_, def_id) = agent_on_route(&state, "spend-named", false);
140        let default = Some(cap::DEFAULT_AGENT_CAP_USD);
141
142        let (got, _, _) = act(&state, &req(&def_id, "get", None)).unwrap();
143        assert_eq!((got.cap_usd, got.own_cap, got.default_cap_usd, got.applies), (default, false, default, true), "no cap of its own: the default");
144
145        let (set, _, note) = act(&state, &req(&def_id, "set", Some(100.0))).unwrap();
146        assert_eq!((set.cap_usd, set.own_cap), (Some(100.0), true));
147        assert!(note.ends_with("to $100.00"), "{note}");
148        assert_eq!(act(&state, &req(&def_id, "get", None)).unwrap().0.cap_usd, Some(100.0), "kept");
149
150        let (none, _, _) = act(&state, &req(&def_id, "set", None)).unwrap();
151        assert_eq!((none.cap_usd, none.own_cap), (None, true), "no cap is a cap of its own");
152
153        let (back, _, note) = act(&state, &req(&def_id, "default", None)).unwrap();
154        assert_eq!((back.cap_usd, back.own_cap), (default, false), "the default again");
155        assert!(note.ends_with("(the default)"), "{note}");
156
157        // The slug names it too, and what cannot be done is refused by name and changes nothing.
158        let slug = state.mstore.agent_def_get(&def_id).unwrap().unwrap().slug;
159        assert_eq!(act(&state, &req(&slug, "get", None)).unwrap().0.cap_usd, default);
160        assert!(act(&state, &req("no-such-agent", "get", None)).is_err());
161        assert!(act(&state, &AgentSpendReq { blockid: String::new(), agent: None, action: "get".into(), cap_usd: None }).is_err());
162        assert!(act(&state, &req(&def_id, "lots", None)).is_err());
163        assert!(act(&state, &req(&def_id, "set", Some(0.001))).is_err(), "a cap under a cent is not a cap anyone meant");
164        assert_eq!(act(&state, &req(&def_id, "get", None)).unwrap().0.cap_usd, default, "nothing changed");
165    }
166}