Skip to main content

agentmux_srv_core/backend/
sensitive_requests.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The requests for sensitive operations (`SPEC_SUPER_AGENT_2026_10_25.md` §4):
5//! who asked for what, what became of it. A request is `asked` until the super
6//! agent answers; `approve` makes it `pending` (the countdown runs); the rest
7//! are the ways it ends. Kept in memory: a request is a minutes-long exchange,
8//! and an AgentMux that restarts mid-way has the requester ask again.
9//!
10//! This holds the state and its rules only. The `Sensitive` routes
11//! (`server/sensitive_handlers.rs`) decide who may file, approve or deny, and the
12//! countdown is `sagas/sensitive_window.rs`. Not every way a request ends has a
13//! caller yet (a request nobody reviewed arrives with a later step of that
14//! spec's §9).
15#![allow(dead_code)]
16
17use std::collections::BTreeMap;
18use std::sync::{LazyLock, Mutex};
19
20use crate::backend::sensitive_ops::{self, OpSpec};
21
22/// Requests one agent may have open (asked or pending) at once.
23/// A request filed by an agent of another machine is owned by `remote:<agent>@<machine>`: there is no agent here to tell.
24pub const REMOTE_OWNER_PREFIX: &str = "remote:";
25pub const MAX_OPEN_PER_REQUESTER: usize = 8;
26/// Requests open at once, all agents together.
27pub const MAX_OPEN: usize = 200;
28/// A finished request stays answerable this long, then is dropped.
29const KEEP_FINISHED_MS: i64 = 10 * 60 * 1000;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
32#[serde(rename_all = "snake_case")]
33pub enum Status {
34    /// Waiting for the super agent.
35    Asked,
36    /// Approved: the countdown runs and the person can still stop it.
37    Pending,
38    /// The countdown ended and the operation is under way: no longer cancellable.
39    Running,
40    Denied,
41    /// The requester withdrew it.
42    Cancelled,
43    /// The person stopped it in the window.
44    Vetoed,
45    Done,
46    Failed,
47    /// Nobody answered in time.
48    Expired,
49}
50
51impl Status {
52    /// Not ended: undecided, counting down or under way.
53    pub fn is_open(self) -> bool {
54        matches!(self, Status::Asked | Status::Pending | Status::Running)
55    }
56}
57
58/// An agent that asked for something already asked for.
59#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
60pub struct Asker {
61    pub uid: String,
62    pub slug: String,
63}
64
65#[derive(Debug, Clone, serde::Serialize)]
66pub struct Request {
67    pub id: String,
68    pub requester_uid: String,
69    pub requester_slug: String,
70    pub op: String,
71    /// The checked facts the banner is built from.
72    pub facts: BTreeMap<String, String>,
73    /// What the banner says, from `facts`.
74    pub summary: String,
75    /// The requester's own words, cleaned. Shown as theirs, never as the operator's.
76    pub reason: String,
77    pub status: Status,
78    /// The super agent that approved or denied it.
79    pub decided_by: Option<String>,
80    /// Why it was denied.
81    pub deny_reason: String,
82    /// Other agents that asked for the same thing while it was open.
83    pub also_asked_by: Vec<Asker>,
84    pub created_ms: i64,
85    /// When it was approved, or ended.
86    pub decided_ms: Option<i64>,
87    pub ended_ms: Option<i64>,
88}
89
90/// What filing a request came to.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Filed {
93    pub id: String,
94    /// It joined a request for the same thing that was already open, whose clock
95    /// keeps running.
96    pub joined: bool,
97}
98
99#[derive(Default)]
100pub struct Registry {
101    requests: Mutex<Vec<Request>>,
102}
103
104static GLOBAL: LazyLock<Registry> = LazyLock::new(Registry::default);
105
106/// The registry of this srv.
107pub fn registry() -> &'static Registry {
108    &GLOBAL
109}
110
111impl Registry {
112    pub fn new() -> Self {
113        Self::default()
114    }
115
116    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Request>> {
117        self.requests.lock().unwrap_or_else(|e| e.into_inner())
118    }
119
120    /// File a request for `op` from the agent `requester_uid`/`requester_slug`.
121    /// A second request for the same operation and facts while one is open joins it.
122    pub fn request(
123        &self,
124        requester_uid: &str,
125        requester_slug: &str,
126        op: &str,
127        given: &BTreeMap<String, String>,
128        reason: &str,
129        now_ms: i64,
130    ) -> Result<Filed, String> {
131        let spec: &OpSpec = sensitive_ops::spec(op).ok_or_else(|| {
132            let known: Vec<&str> = sensitive_ops::OPS.iter().filter(|o| o.reviewed).map(|o| o.op).collect();
133            format!("INVALID_ARG: unknown operation '{}'; one of: {}", op.chars().take(40).collect::<String>(), known.join(", "))
134        })?;
135        if !spec.reviewed {
136            return Err(format!("INVALID_ARG: {} has its own window and no super agent in front of it", spec.op));
137        }
138        let facts = spec.check_facts(given)?;
139        let mut all = self.lock();
140        prune(&mut all, now_ms);
141        if let Some(open) = all.iter_mut().find(|r| r.status.is_open() && r.op == spec.op && r.facts == facts) {
142            if !open.asked_by(requester_uid) {
143                open.also_asked_by.push(Asker { uid: requester_uid.to_string(), slug: requester_slug.to_string() });
144            }
145            return Ok(Filed { id: open.id.clone(), joined: true });
146        }
147        if all.iter().filter(|r| r.status.is_open() && r.requester_uid == requester_uid).count() >= MAX_OPEN_PER_REQUESTER {
148            return Err(format!("LIMIT: you have {MAX_OPEN_PER_REQUESTER} requests open; cancel or wait for one"));
149        }
150        if all.iter().filter(|r| r.status.is_open()).count() >= MAX_OPEN {
151            return Err("LIMIT: too many sensitive requests are open; try again shortly".to_string());
152        }
153        let id = uuid::Uuid::new_v4().to_string();
154        all.push(Request {
155            id: id.clone(),
156            requester_uid: requester_uid.to_string(),
157            requester_slug: requester_slug.to_string(),
158            op: spec.op.to_string(),
159            summary: spec.summary(&facts),
160            facts,
161            reason: crate::backend::shutdown_events::clean_reason(reason),
162            status: Status::Asked,
163            decided_by: None,
164            deny_reason: String::new(),
165            also_asked_by: Vec::new(),
166            created_ms: now_ms,
167            decided_ms: None,
168            ended_ms: None,
169        });
170        Ok(Filed { id, joined: false })
171    }
172
173    /// The super agent approves: `asked` becomes `pending`.
174    pub fn approve(&self, id: &str, approver_slug: &str, now_ms: i64) -> Result<Request, String> {
175        self.change(id, |r| {
176            if r.status != Status::Asked {
177                return Err(not_asked(r));
178            }
179            r.status = Status::Pending;
180            r.decided_by = Some(approver_slug.to_string());
181            r.decided_ms = Some(now_ms);
182            Ok(())
183        })
184    }
185
186    /// Nobody reviewed it in time: `asked` becomes `pending` with no approver, and the person's
187    /// veto is the only check.
188    pub fn fallback(&self, id: &str, now_ms: i64) -> Result<Request, String> {
189        self.change(id, |r| {
190            if r.status != Status::Asked {
191                return Err(not_asked(r));
192            }
193            r.status = Status::Pending;
194            r.decided_by = None;
195            r.decided_ms = Some(now_ms);
196            Ok(())
197        })
198    }
199
200    /// The super agent denies: `asked` ends, with its reason for the requester.
201    pub fn deny(&self, id: &str, approver_slug: &str, reason: &str, now_ms: i64) -> Result<Request, String> {
202        self.change(id, |r| {
203            if r.status != Status::Asked {
204                return Err(not_asked(r));
205            }
206            r.status = Status::Denied;
207            r.decided_by = Some(approver_slug.to_string());
208            r.deny_reason = crate::backend::shutdown_events::clean_reason(reason);
209            r.decided_ms = Some(now_ms);
210            r.ended_ms = Some(now_ms);
211            Ok(())
212        })
213    }
214
215    /// An agent that asked withdraws its own ask while the request is open. The
216    /// request goes on for the others that asked; it ends when the last one withdraws.
217    pub fn cancel(&self, id: &str, requester_uid: &str, now_ms: i64) -> Result<Request, String> {
218        self.change(id, |r| {
219            if !r.asked_by(requester_uid) {
220                return Err("FORBIDDEN: only an agent that asked can cancel it".to_string());
221            }
222            if r.status == Status::Running {
223                return Err(format!("request {} is already under way", r.id));
224            }
225            if !r.status.is_open() {
226                return Err(format!("request {} has ended ({})", r.id, status_word(r.status)));
227            }
228            if r.requester_uid != requester_uid {
229                r.also_asked_by.retain(|a| a.uid != requester_uid);
230            } else if r.also_asked_by.is_empty() {
231                r.status = Status::Cancelled;
232                r.ended_ms = Some(now_ms);
233            } else {
234                let next = r.also_asked_by.remove(0);
235                r.requester_uid = next.uid;
236                r.requester_slug = next.slug;
237            }
238            Ok(())
239        })
240    }
241
242    /// The countdown ended: `pending` becomes `running`, atomically, so a
243    /// request withdrawn or vetoed meanwhile is not run.
244    pub fn start(&self, id: &str) -> Result<Request, String> {
245        self.change(id, |r| {
246            if r.status != Status::Pending {
247                return Err(format!("request {} is {}, not approved", r.id, status_word(r.status)));
248            }
249            r.status = Status::Running;
250            Ok(())
251        })
252    }
253
254    /// End an open request as `outcome` (vetoed, done, failed or expired).
255    pub fn finish(&self, id: &str, outcome: Status, now_ms: i64) -> Result<Request, String> {
256        if !matches!(outcome, Status::Vetoed | Status::Done | Status::Failed | Status::Expired) {
257            return Err(format!("{} is not a way a request ends", status_word(outcome)));
258        }
259        self.change(id, |r| {
260            if !r.status.is_open() {
261                return Err(format!("request {} has ended ({})", r.id, status_word(r.status)));
262            }
263            r.status = outcome;
264            r.ended_ms = Some(now_ms);
265            Ok(())
266        })
267    }
268
269    /// The open requests for `op` whose fact `key` is `value`.
270    pub fn open_matching(&self, op: &str, key: &str, value: &str) -> Vec<Request> {
271        self.lock().iter().filter(|r| r.status.is_open() && r.status != Status::Running && r.op == op && r.facts.get(key).is_some_and(|v| v == value)).cloned().collect()
272    }
273
274    pub fn get(&self, id: &str) -> Option<Request> {
275        self.lock().iter().find(|r| r.id == id).cloned()
276    }
277
278    /// The requests `viewer_uid` may see: those it asked for, or all of them (the super agent).
279    pub fn list(&self, viewer_uid: &str, all: bool) -> Vec<Request> {
280        self.lock().iter().filter(|r| all || r.asked_by(viewer_uid)).cloned().collect()
281    }
282
283    fn change(&self, id: &str, edit: impl FnOnce(&mut Request) -> Result<(), String>) -> Result<Request, String> {
284        let mut all = self.lock();
285        let r = all.iter_mut().find(|r| r.id == id).ok_or_else(|| format!("no request {id}"))?;
286        edit(r)?;
287        Ok(r.clone())
288    }
289}
290
291impl Request {
292    /// The agents that asked for this: the first, then those that joined.
293    pub fn askers(&self) -> Vec<&str> {
294        std::iter::once(self.requester_uid.as_str()).chain(self.also_asked_by.iter().map(|a| a.uid.as_str())).collect()
295    }
296
297    /// Whether `uid` asked for this, first or by joining.
298    pub fn asked_by(&self, uid: &str) -> bool {
299        self.requester_uid == uid || self.also_asked_by.iter().any(|a| a.uid == uid)
300    }
301}
302
303fn not_asked(r: &Request) -> String {
304    format!("request {} is {}, not waiting for an answer", r.id, status_word(r.status))
305}
306
307fn status_word(s: Status) -> String {
308    serde_json::to_value(s).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default()
309}
310
311/// Drop what finished long enough ago.
312fn prune(all: &mut Vec<Request>, now_ms: i64) {
313    all.retain(|r| r.ended_ms.is_none_or(|ended| now_ms - ended < KEEP_FINISHED_MS));
314}
315
316#[cfg(test)]
317#[path = "sensitive_requests_tests.rs"]
318mod tests;