Skip to main content

agentmux_srv/server/
quota_mode_handler.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! `Message` action `quota_mode` (`SPEC_CHEAPER_FLEET_MESSAGING_2026_10_30.md` ยง5):
4//!
5//! - `POST /api/v1/quota-mode`: set the fleet's quota mode (`off` or `tight`, and the priority floor) and tell
6//!   every agent with one bulletin under the key `mode`, instead of a broadcast to each.
7//! - `GET /api/v1/quota-mode`: the mode now.
8//!
9//! The setting is `settings.json`'s `fleet:quota_mode` and `fleet:quota_min_priority`
10//! (`backend::quota_mode`); `Tasks claim` reads it.
11
12use axum::extract::State;
13use axum::http::StatusCode;
14use axum::response::{IntoResponse, Json, Response};
15use serde::Deserialize;
16use serde_json::json;
17
18use crate::backend::bulletin;
19use crate::backend::quota_mode::{self, DEFAULT_MIN_PRIORITY, SETTING_MIN_PRIORITY, SETTING_MODE};
20use crate::backend::storage::bulletins::Bulletin;
21
22use super::bulletin_handlers::push_to_running;
23use super::caller::Caller;
24use super::work_claims_handlers::claimer;
25use super::AppState;
26
27#[derive(Debug, Default, Deserialize)]
28pub struct SetParams {
29    pub mode: Option<String>,
30    pub min_priority: Option<i64>,
31    pub agent: Option<String>,
32    pub block: Option<String>,
33}
34
35fn bad_request(msg: impl Into<String>) -> Response {
36    (StatusCode::BAD_REQUEST, Json(json!({ "error": msg.into() }))).into_response()
37}
38
39fn current(state: &AppState) -> serde_json::Value {
40    let extra = state.config_watcher.get_full_config().settings.extra.clone();
41    match quota_mode::claim_floor(&extra) {
42        Some(n) => json!({ "mode": "tight", "min_priority": n }),
43        None => json!({ "mode": "off", "min_priority": extra.get(SETTING_MIN_PRIORITY).and_then(|v| v.as_i64()).unwrap_or(DEFAULT_MIN_PRIORITY) }),
44    }
45}
46
47/// What the bulletin says about a mode.
48fn notice(mode: &str, floor: i64) -> String {
49    if mode == "tight" {
50        format!(
51            "Quota mode is tight. Tasks claim with no id now takes only tasks aimed at you and ones with priority {floor} or \
52             more; claim a named task by its id as before. A routine message to an agent with no turn in flight waits until it is next \
53             active; urgent ones and ones naming a task (#N) go at once. No reply needed."
54        )
55    } else {
56        "Quota mode is off. Tasks claim takes any open task again. No reply needed.".to_string()
57    }
58}
59
60/// `GET /api/v1/quota-mode`.
61pub(crate) async fn handle_get_quota_mode(State(state): State<AppState>) -> Response {
62    Json(current(&state)).into_response()
63}
64
65/// `POST /api/v1/quota-mode`.
66pub(crate) async fn handle_set_quota_mode(
67    State(state): State<AppState>,
68    caller: Option<axum::Extension<Caller>>,
69    Json(p): Json<SetParams>,
70) -> Response {
71    let mode = match p.mode.as_deref().map(|m| m.trim().to_ascii_lowercase()) {
72        Some(m) if m == "off" || m == "tight" => m,
73        _ => return bad_request("mode must be \"off\" or \"tight\""),
74    };
75    if p.min_priority.is_some_and(|n| !(0..=1000).contains(&n)) {
76        return bad_request("min_priority must be between 0 and 1000");
77    }
78    if !caller.as_ref().is_some_and(|c| c.0.uid().is_some()) {
79        return bad_request("who is setting it is not proven: this needs an agent started by AgentMux");
80    }
81    let Some((author, uid, _)) = claimer(&state, caller.as_ref().map(|c| &c.0), p.agent.as_deref(), p.block.as_deref()) else {
82        return bad_request("who is setting it is unknown: this needs an agent started by AgentMux");
83    };
84    let mut keys = serde_json::Map::new();
85    keys.insert(SETTING_MODE.to_string(), json!(mode));
86    if let Some(n) = p.min_priority {
87        keys.insert(SETTING_MIN_PRIORITY.to_string(), json!(n));
88    }
89    let disk = keys.clone();
90    match tokio::task::spawn_blocking(move || crate::backend::config_watcher_fs::merge_settings_to_disk(disk)).await {
91        Ok(Ok(())) => {}
92        Ok(Err(e)) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("not set: {e}") }))).into_response(),
93        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("not set: {e}") }))).into_response(),
94    }
95    let merged = crate::backend::config_watcher_fs::merge_settings_into_current(&state.config_watcher, keys);
96    state.config_watcher.update_settings(merged);
97    crate::backend::config_watcher_fs::broadcast_full_config(&state.config_watcher, &state.event_bus);
98    // What the mode held back goes now when it is off.
99    crate::backend::reactive::held_jekt_wake().notify_one();
100    let now = state.config_watcher.get_full_config().settings.extra.clone();
101    let floor = now.get(SETTING_MIN_PRIORITY).and_then(|v| v.as_i64()).unwrap_or(DEFAULT_MIN_PRIORITY);
102    // One bulletin under the key `mode`, replacing the last one whoever posted it, reaches every running agent.
103    let at = agentmux_common::time::now_ms();
104    let post = Bulletin {
105        id: uuid::Uuid::new_v4().to_string(),
106        key: bulletin::FLEET_MODE_KEY.into(),
107        author,
108        author_uid: uid,
109        body: notice(&mode, floor),
110        targets: vec![],
111        created_at: at,
112        expires_at: at + if mode == "tight" { 24 * 60 } else { 60 } * 60_000,
113    };
114    let (store, stored, running) = (state.work_store.clone(), post.clone(), state.reactive_handler.list_agents());
115    let mstore = state.mstore.clone();
116    let reached = tokio::task::spawn_blocking(move || {
117        store.bulletin_put_for_fleet(&stored, at)?;
118        Ok::<_, crate::backend::storage::StoreError>(push_to_running(&mstore, &store, &stored, &running))
119    })
120    .await;
121    let mut answer = current(&state);
122    match reached {
123        Ok(Ok(n)) => answer["bulletin_reached_running_agents"] = json!(n),
124        Ok(Err(e)) => {
125            tracing::warn!("quota mode: the bulletin was not stored: {e}");
126            answer["bulletin_error"] = json!(format!("the mode is set but the bulletin was not posted: {e}; tell the agents yourself"));
127        }
128        Err(e) => {
129            tracing::warn!("quota mode: the bulletin task failed: {e}");
130            answer["bulletin_error"] = json!(format!("the mode is set but the bulletin was not posted: {e}; tell the agents yourself"));
131        }
132    }
133    Json(answer).into_response()
134}