Skip to main content

agentmux_srv_core/backend/jobs/
caps.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Spending caps for job runs (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
5//! §5.3): the defaults Settings → Jobs holds, the figures a job's
6//! `policy.caps` may lower, and the rules that decide, from the spend the
7//! ledger found, whether a run may start. Pure: `reservation.rs` reads the
8//! ledger and acts on the answer.
9//!
10//! A day is the operator's local calendar day (§10, decision 7).
11
12use chrono::{NaiveTime, TimeZone};
13
14use crate::backend::jobs::definition::Caps;
15use crate::backend::storage::cron::CronJob;
16use crate::backend::storage::job_runs::reason;
17use crate::backend::wconfig::types::SettingsType;
18
19/// The defaults when Settings leaves a cap unset (§5.3, operator decision 2).
20pub const DEFAULT_RUN_USD: f64 = 5.0;
21pub const DEFAULT_JOB_DAY_USD: f64 = 20.0;
22pub const DEFAULT_ACCOUNT_DAY_USD: f64 = 50.0;
23pub const DEFAULT_MESSAGES_PER_DAY: u32 = 24;
24
25/// Room left on a cap smaller than this counts as none: dollar sums are
26/// floating point.
27const EPSILON: f64 = 1e-9;
28
29/// The caps Settings → Jobs holds: what a job without figures of its own
30/// gets, and the most an agent can ask for.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct Limits {
33    pub run_usd: f64,
34    pub job_day_usd: f64,
35    pub account_day_usd: f64,
36    pub messages_per_day: u32,
37}
38
39impl Default for Limits {
40    fn default() -> Self {
41        Limits {
42            run_usd: DEFAULT_RUN_USD,
43            job_day_usd: DEFAULT_JOB_DAY_USD,
44            account_day_usd: DEFAULT_ACCOUNT_DAY_USD,
45            messages_per_day: DEFAULT_MESSAGES_PER_DAY,
46        }
47    }
48}
49
50impl Limits {
51    /// Read `jobs:cap:*`. A figure that isn't a number of 0 or more is the
52    /// default: a typo must not turn a cap off.
53    pub fn from_settings(s: &SettingsType) -> Limits {
54        let usd = |v: Option<f64>, default: f64| v.filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(default);
55        Limits {
56            run_usd: usd(s.jobs_cap_run_usd, DEFAULT_RUN_USD),
57            job_day_usd: usd(s.jobs_cap_job_day_usd, DEFAULT_JOB_DAY_USD),
58            account_day_usd: usd(s.jobs_cap_account_day_usd, DEFAULT_ACCOUNT_DAY_USD),
59            messages_per_day: s.jobs_cap_messages_day.unwrap_or(DEFAULT_MESSAGES_PER_DAY),
60        }
61    }
62}
63
64/// The figures that apply to one job: its own, else the defaults.
65#[derive(Debug, Clone, Copy, PartialEq)]
66pub struct Effective {
67    pub run_usd: f64,
68    pub day_usd: f64,
69    pub messages_per_day: u32,
70}
71
72pub fn effective(caps: Option<&Caps>, limits: &Limits) -> Effective {
73    Effective {
74        run_usd: caps.and_then(|c| c.run_usd).unwrap_or(limits.run_usd),
75        day_usd: caps.and_then(|c| c.day_usd).unwrap_or(limits.job_day_usd),
76        messages_per_day: caps.and_then(|c| c.messages_per_day).unwrap_or(limits.messages_per_day),
77    }
78}
79
80/// An agent's `caps`, held to the defaults: a higher figure becomes the
81/// default (only the operator raises a cap, §7). A figure the job already had
82/// (`before`, on an edit) is kept as it is, so an agent changing a job's brief
83/// doesn't lower a cap the operator raised. Returns the caps to store and, for
84/// each figure changed, a sentence for the reply.
85pub fn clamp_to_defaults(caps: Option<Caps>, limits: &Limits, before: Option<&Caps>) -> (Option<Caps>, Vec<String>) {
86    let Some(mut caps) = caps else { return (None, Vec::new()) };
87    let mut notes = Vec::new();
88    let mut dollars = |name: &str, field: &mut Option<f64>, was: Option<f64>, default: f64| {
89        if let Some(asked) = field.filter(|v| *v > default + EPSILON && was != Some(*v)) {
90            notes.push(format!(
91                "policy.caps.{name} {asked} is over the default {default}, so {default} applies: only the operator raises a cap"
92            ));
93            *field = Some(default);
94        }
95    };
96    dollars("run_usd", &mut caps.run_usd, before.and_then(|b| b.run_usd), limits.run_usd);
97    dollars("day_usd", &mut caps.day_usd, before.and_then(|b| b.day_usd), limits.job_day_usd);
98    let was = before.and_then(|b| b.messages_per_day);
99    if let Some(asked) = caps.messages_per_day.filter(|v| *v > limits.messages_per_day && was != Some(*v)) {
100        let default = limits.messages_per_day;
101        notes.push(format!(
102            "policy.caps.messages_per_day {asked} is over the default {default}, so {default} applies: only the operator raises a cap"
103        ));
104        caps.messages_per_day = Some(default);
105    }
106    (Some(caps), notes)
107}
108
109/// Local midnight at or before `now_ms` in `tz`, ms epoch. A zone whose
110/// midnight doesn't exist that day (a daylight-saving gap at 00:00) starts
111/// its day at the first hour that does.
112pub fn day_start_ms<Tz: TimeZone>(now_ms: i64, tz: &Tz) -> i64 {
113    let Some(now) = tz.timestamp_millis_opt(now_ms).single() else { return now_ms - 24 * 3_600_000 };
114    for hour in 0..=3 {
115        let start = now.date_naive().and_time(NaiveTime::from_hms_opt(hour, 0, 0).unwrap_or_default());
116        if let Some(at) = tz.from_local_datetime(&start).earliest() {
117            return at.timestamp_millis();
118        }
119    }
120    now_ms - 24 * 3_600_000
121}
122
123/// The operator's local midnight (the machine's time zone).
124pub fn local_day_start_ms(now_ms: i64) -> i64 {
125    day_start_ms(now_ms, &chrono::Local)
126}
127
128/// What a start may not do, in the order checked.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum Refusal {
131    JobCap,
132    AccountCap,
133    MessageCap,
134    /// An event job's `max_per_hour` (§3.7 of the Drone real-world jobs spec): not a spending cap, but it is told the
135    /// same way.
136    Rate,
137}
138
139impl Refusal {
140    /// The run's `reason`.
141    pub fn reason(self) -> &'static str {
142        match self {
143            Refusal::JobCap => reason::JOB_CAP,
144            Refusal::AccountCap => reason::ACCOUNT_CAP,
145            Refusal::MessageCap => reason::MESSAGE_CAP,
146            Refusal::Rate => reason::RATE,
147        }
148    }
149
150    /// A few words for a notification's title.
151    pub fn label(self) -> &'static str {
152        match self {
153            Refusal::JobCap | Refusal::AccountCap => "daily spending cap",
154            Refusal::MessageCap => "daily message limit",
155            Refusal::Rate => "event rate limit",
156        }
157    }
158
159    /// In words, for Run now's refusal.
160    pub fn words(self) -> &'static str {
161        match self {
162            Refusal::JobCap => "this job's spending for today leaves no room for another run (its daily cap)",
163            Refusal::AccountCap => "the account's spending on jobs for today leaves no room for another run (the account's daily cap)",
164            Refusal::MessageCap => "this job has sent its messages for today to another agent (messages_per_day)",
165            Refusal::Rate => "this job already started its events for this hour (the trigger's max_per_hour); more events are skipped until the hour's runs age out",
166        }
167    }
168}
169
170/// The spend a start is weighed against: what was spent today plus what the
171/// runs in flight may still spend (each at its whole per-run cap).
172#[derive(Debug, Clone, Copy, PartialEq)]
173pub struct Spend {
174    pub job_usd: f64,
175    /// `None` when the run's account isn't known: only the job's cap applies.
176    pub account_usd: Option<f64>,
177    /// Messages delivered today (a `message` job to another agent).
178    pub messages: i64,
179}
180
181/// The reservation (§5.3): the run starts only if the job's spend today plus
182/// the run's whole per-run cap fits the job's daily cap, and the same for its
183/// account. Every run that starts this way spends at most its cap, so the
184/// day's total can't pass the daily cap even if each one spends all of it.
185pub fn check(eff: &Effective, limits: &Limits, spend: &Spend, sends_to_another: bool) -> Option<Refusal> {
186    if spend.job_usd + eff.run_usd > eff.day_usd + EPSILON {
187        return Some(Refusal::JobCap);
188    }
189    if spend.account_usd.is_some_and(|a| a + eff.run_usd > limits.account_day_usd + EPSILON) {
190        return Some(Refusal::AccountCap);
191    }
192    if sends_to_another && spend.messages >= i64::from(eff.messages_per_day) {
193        return Some(Refusal::MessageCap);
194    }
195    None
196}
197
198/// Whether a run that has spent `cost_usd` has reached `cap_usd`: it is
199/// stopped. A run that spent nothing hasn't, whatever the cap.
200pub fn reached(cost_usd: f64, cap_usd: f64) -> bool {
201    cost_usd > 0.0 && cost_usd + EPSILON >= cap_usd
202}
203
204/// Whether a run on `provider` reports what it cost. Only Claude's `result`
205/// frame carries a cost today (`PassStats::from_result_frame`); any other
206/// provider's runs have `cost_known = false`, count $0 toward the dollar caps
207/// and are bounded by their timeout (§5.3). A provider not known yet is
208/// assumed to report one.
209pub fn reports_cost(provider: &str) -> bool {
210    provider.trim().is_empty() || crate::backend::providers::resolve_provider_alias(provider) == "claude"
211}
212
213/// Whether `job` is a `message` job aimed at an agent other than its owner
214/// (§5.3). A job with no owner, the operator's own, isn't: the limit is for
215/// an agent's job that could flood another agent's conversation.
216pub fn sends_to_another(job: &CronJob) -> bool {
217    if !matches!(job.action_kind.as_str(), "" | "message") {
218        return false;
219    }
220    let owner = job.owner_uid();
221    if owner.is_empty() && job.created_by.trim().is_empty() {
222        return false;
223    }
224    if !owner.is_empty() && !job.target_uid.is_empty() {
225        return job.target_uid != owner;
226    }
227    // A job by name: compare names with its creator's.
228    let (target, creator) = (job.target.trim(), job.created_by.trim());
229    if creator.eq_ignore_ascii_case("operator") && owner.is_empty() {
230        return false;
231    }
232    !target.eq_ignore_ascii_case(creator)
233}
234
235#[cfg(test)]
236#[path = "caps_tests.rs"]
237mod tests;