Skip to main content

agentmux_srv/server/
job_caps.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Spending caps at the server's edge (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
5//! §5.3, §7): Settings' figures and where a run would go for the ledger's
6//! reservation, and what a job's author may ask for.
7//!
8//! **Who raises a cap.** Only the operator. A request that carries no agent
9//! token looks like the app's own window at the same-user boundary, so it
10//! proves nothing; the operator's decision arrives only through the host
11//! route (`POST /api/v1/host/jobs`, which needs the host's own token) or the
12//! app's own proven window (`jobs.save`, an operator-only RPC). Every other
13//! path holds a job's `policy.caps` to the defaults and says so.
14//!
15//! **A provider that reports no cost.** Its runs count $0 toward the dollar
16//! caps and only the timeout bounds them, so the operator confirms such a job
17//! (`confirm_no_cost`, passed through the host route). An agent can't.
18
19use std::sync::Arc;
20
21use axum::http::StatusCode;
22use axum::response::Json;
23use serde_json::{json, Value};
24
25use crate::backend::jobs::caps::{self, Limits};
26use crate::backend::jobs::definition::{Action, JobDefinition};
27use crate::backend::jobs::reservation::Target;
28use crate::backend::jobs::RunLedger;
29use crate::backend::obj::{self, Block};
30use crate::backend::providers::resolve_provider_alias;
31use crate::backend::storage::agents::AgentDefinition;
32use crate::backend::storage::cron::CronJob;
33
34use super::app_api::agent_spawn::{self, RUN_ACCOUNT_META_KEY};
35use super::AppState;
36
37type Answer = (StatusCode, Json<Value>);
38
39/// The timeout a job on a provider that reports no cost gets when it names
40/// none: the only limit on what it spends.
41pub(crate) const NO_COST_TIMEOUT_MINUTES: u32 = 60;
42
43/// Who asks, as far as the caps are concerned.
44#[derive(Debug, Clone, Copy, Default)]
45pub(crate) struct Origin {
46    /// The operator's decision: relayed by the host (`handle_host_jobs`), or
47    /// made in the app's own proven window (`jobs.save`).
48    pub from_host: bool,
49    /// The operator confirmed a job on a provider that reports no cost.
50    pub confirm_no_cost: bool,
51    /// The operator read the turn-on prompt of a drone job and said yes (`drone_turn_on`).
52    pub confirm_turn_on: bool,
53}
54
55/// Settings' caps (`jobs:cap:*`).
56pub(crate) fn limits(state: &AppState) -> Limits {
57    Limits::from_settings(&state.config_watcher.get_full_config().settings)
58}
59
60/// Weigh job runs against Settings' caps, finding where each would go.
61pub(crate) fn install(state: &AppState, ledger: &RunLedger) {
62    let (for_limits, for_target) = (state.clone(), state.clone());
63    ledger.install_caps(Arc::new(move || limits(&for_limits)), Arc::new(move |job| target_of(&for_target, job)));
64}
65
66/// The agent definition `who` names: a UID, else a slug or name.
67fn agent_named(state: &AppState, who: &str) -> Option<AgentDefinition> {
68    let who = who.trim();
69    if who.is_empty() {
70        return None;
71    }
72    if let Ok(Some(def)) = state.mstore.agent_def_get(who) {
73        return Some(def);
74    }
75    state.mstore.agent_def_list().ok()?.into_iter().find(|d| d.slug.eq_ignore_ascii_case(who) || d.name.eq_ignore_ascii_case(who))
76}
77
78fn provider_of(state: &AppState, def: &AgentDefinition) -> String {
79    resolve_provider_alias(&state.id_store.resolve_effective_provider_id(def)).to_string()
80}
81
82/// The agent an action starts or messages: a message's target, a spawn's leader.
83fn agent_of(action: &Action) -> Option<&str> {
84    match action {
85        Action::Message { to, .. } => Some(to),
86        Action::Spawn { leader, .. } => Some(leader),
87        _ => None,
88    }
89}
90
91/// The provider of the agent a definition's action starts or messages, when
92/// it can be told.
93pub(crate) fn action_provider(state: &AppState, action: &Action) -> Option<String> {
94    agent_named(state, agent_of(action)?).map(|def| provider_of(state, &def))
95}
96
97/// The provider of `job`'s agent when its runs report no cost.
98pub(crate) fn no_cost_provider(state: &AppState, job: &CronJob) -> Option<String> {
99    let action = JobDefinition::from_job(job).action;
100    action_provider(state, &action).filter(|p| !p.is_empty() && !caps::reports_cost(p))
101}
102
103/// Where `job`'s next run would go: a message's target pane (its account and
104/// its provider), the account a spawn would pick.
105fn target_of(state: &AppState, job: &CronJob) -> Target {
106    match job.action_kind.as_str() {
107        "" | "message" => pane_target(state, job),
108        "spawn" => match serde_json::from_value::<Action>(job.action.clone()) {
109            Ok(Action::Spawn { leader, account, .. }) => {
110                let asked = Some(account.as_str()).filter(|a| !a.is_empty());
111                agent_spawn::account_for_job(state, &leader, asked)
112                    .map(|(account, provider)| Target { account, provider })
113                    .unwrap_or_default()
114            }
115            _ => Target::default(),
116        },
117        _ => Target::default(),
118    }
119}
120
121fn pane_target(state: &AppState, job: &CronJob) -> Target {
122    let block_id = if job.target_uid.is_empty() {
123        state.reactive_handler.list_agents().into_iter().find(|r| r.agent_id.eq_ignore_ascii_case(&job.target)).map(|r| r.block_id)
124    } else {
125        state.reactive_handler.block_for_uid(&job.target_uid)
126    };
127    let Some(block) = block_id.and_then(|b| state.mstore.get::<Block>(&b).ok().flatten()) else { return Target::default() };
128    let account = obj::meta_get_string(&block.meta, RUN_ACCOUNT_META_KEY, "");
129    let provider = agent_named(state, &obj::meta_get_string(&block.meta, "agentId", ""))
130        .map(|def| provider_of(state, &def))
131        .unwrap_or_default();
132    Target { account, provider }
133}
134
135fn refuse(status: StatusCode, body: Value) -> Answer {
136    (status, Json(body))
137}
138
139/// Apply what the caps ask of a job's author to `def`, before it is stored:
140/// - an agent's higher caps are clamped to the defaults (the operator's, via
141///   the host, are kept);
142/// - a job on a provider that reports no cost needs the operator's
143///   confirmation, unless it is the same agent as before, and gets a timeout
144///   when it names none.
145///
146/// `before` is the job's definition on an edit. Returns the sentences the
147/// reply should carry.
148pub(crate) fn apply_rules(
149    state: &AppState,
150    def: &mut JobDefinition,
151    before: Option<&JobDefinition>,
152    origin: Origin,
153) -> Result<Vec<String>, Answer> {
154    let mut notes = Vec::new();
155    if !origin.from_host {
156        let (kept, clamped) =
157            caps::clamp_to_defaults(def.policy.caps.take(), &limits(state), before.and_then(|b| b.policy.caps.as_ref()));
158        def.policy.caps = kept;
159        notes.extend(clamped);
160    }
161    let Some(provider) = action_provider(state, &def.action).filter(|p| !p.is_empty() && !caps::reports_cost(p)) else {
162        return Ok(notes);
163    };
164    if before.is_none_or(|b| agent_of(&b.action) != agent_of(&def.action)) {
165        let why = format!(
166            "this job's agent runs on {provider}, which doesn't report what a run costs: the spending caps can't stop it and only its \
167             timeout limits it"
168        );
169        if !origin.from_host {
170            return Err(refuse(
171                StatusCode::FORBIDDEN,
172                json!({ "error": format!("{why}. The operator confirms each such job: ask the operator to create it from the Jobs tab") }),
173            ));
174        }
175        if !origin.confirm_no_cost {
176            return Err(refuse(
177                StatusCode::CONFLICT,
178                json!({
179                    "error": format!("{why}. Confirm it to create the job (confirm_no_cost: true)"),
180                    "needs_confirmation": "no_cost",
181                    "provider": provider,
182                }),
183            ));
184        }
185    }
186    if def.policy.timeout_minutes.is_none() {
187        def.policy.timeout_minutes = Some(NO_COST_TIMEOUT_MINUTES);
188        notes.push(format!(
189            "{provider} doesn't report what a run costs, so policy.timeout_minutes is {NO_COST_TIMEOUT_MINUTES}: only the timeout limits this job"
190        ));
191    }
192    Ok(notes)
193}
194
195#[cfg(test)]
196#[path = "job_caps_tests.rs"]
197mod tests;