1use std::collections::BTreeMap;
15use std::time::Duration;
16
17use axum::extract::{Path, State};
18use axum::http::StatusCode;
19use axum::response::{IntoResponse, Response};
20use axum::Json;
21use serde_json::{json, Value};
22
23use super::caller::Caller;
24use super::AppState;
25use crate::backend::reactive::sanitize::quote_in_system_note;
26use crate::backend::sensitive_ops;
27use crate::backend::sensitive_requests::{self as requests, Request};
28use crate::sagas::sensitive_fallback as fallback;
29use crate::sagas::sensitive_window as window;
30use agentmux_common::time::now_ms;
31
32pub(crate) async fn handle_sensitive(
33 State(state): State<AppState>,
34 caller: Option<axum::Extension<Caller>>,
35 Path(action): Path<String>,
36 Json(body): Json<Value>,
37) -> Response {
38 let forbid = |e: &str| (StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response();
39 let Some(uid) = caller.as_deref().and_then(Caller::uid).map(str::to_string) else {
40 return forbid("FORBIDDEN: this acts for an agent, so the request must carry that agent's token");
41 };
42 let claimed = text(&body, "agent_id");
43 let mstore = state.mstore.clone();
44 let proven = {
45 let uid = uid.clone();
46 tokio::task::spawn_blocking(move || super::actor::proven_slug(&mstore, &uid, &claimed)).await.ok().flatten()
47 };
48 let Some(slug) = proven else {
49 return forbid("FORBIDDEN: the token's agent doesn't answer to that agent_id");
50 };
51 match act(&state, &uid, &slug, &action, &body).await {
52 Ok(v) => Json(v).into_response(),
53 Err(e) => {
54 let code = match e.split(':').next().unwrap_or("") {
55 "FORBIDDEN" => StatusCode::FORBIDDEN,
56 "INVALID_ARG" => StatusCode::BAD_REQUEST,
57 "LIMIT" => StatusCode::TOO_MANY_REQUESTS,
58 _ if e.starts_with("no request") => StatusCode::NOT_FOUND,
59 _ => StatusCode::CONFLICT,
60 };
61 (code, Json(json!({ "error": e }))).into_response()
62 }
63 }
64}
65
66fn text(body: &Value, key: &str) -> String {
67 body.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_string()
68}
69
70fn facts_of(body: &Value) -> Result<BTreeMap<String, String>, String> {
72 let Some(obj) = body.get("facts") else {
73 return Ok(BTreeMap::new());
74 };
75 let obj = obj.as_object().ok_or("INVALID_ARG: facts is an object of text values")?;
76 obj.iter()
77 .map(|(k, v)| match v.as_str() {
78 Some(s) => Ok((k.clone(), s.to_string())),
79 None => Err(format!("INVALID_ARG: fact '{}' is text", k.chars().take(40).collect::<String>())),
80 })
81 .collect()
82}
83
84async fn act(state: &AppState, uid: &str, slug: &str, action: &str, body: &Value) -> Result<Value, String> {
87 let result = act_inner(state, uid, slug, action, body).await;
88 if matches!(action, "approve" | "deny" | "cancel") {
89 audit_result(state, slug, action, &text(body, "id"), &result);
90 }
91 result
92}
93
94fn audit_result(state: &AppState, slug: &str, action: &str, id: &str, result: &Result<Value, String>) {
97 let Some(request) = requests::registry().get(id) else { return };
98 let outcome = match result {
99 Ok(v) if action == "request" && v["joined"] == true => "joined".to_string(),
100 Ok(_) => serde_json::to_value(request.status).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),
101 Err(_) => "refused".to_string(),
102 };
103 window::audit_step(state, slug, &request, &format!("sensitive.{action}"), result.is_ok(), result.as_ref().err().map(String::as_str), &outcome);
104}
105
106pub(crate) async fn file_request(state: &AppState, uid: &str, slug: &str, op: &str, facts: &BTreeMap<String, String>, reason: &str) -> Result<Value, String> {
109 let filed = requests::registry().request(uid, slug, op, facts, reason, now_ms())?;
110 let request = requests::registry().get(&filed.id).ok_or("no request (it ended just now)")?;
111 let review = if filed.joined {
112 "joined a request for the same thing that was already open".to_string()
113 } else {
114 fallback::watch(state, &filed.id);
115 ask_the_super_agent(state, &request)
116 };
117 let result = Ok(json!({ "id": filed.id, "joined": filed.joined, "status": request.status, "summary": request.summary, "review": review }));
118 audit_result(state, slug, "request", &filed.id, &result);
119 result
120}
121
122async fn act_inner(state: &AppState, uid: &str, slug: &str, action: &str, body: &Value) -> Result<Value, String> {
123 let id = text(body, "id");
124 match action {
125 "request" => file_request(state, uid, slug, &text(body, "op"), &facts_of(body)?, &text(body, "reason")).await,
126 "approve" => {
127 require_super(state, uid)?;
128 let request = must_get(&id)?;
129 let spec = sensitive_ops::spec(&request.op).ok_or("INVALID_ARG: unknown operation")?;
130 if !window::has_runner(&request.op) {
131 return Err(format!("{} can't be run from here yet, so it isn't approved", spec.label));
132 }
133 requests::registry().approve(&id, slug, now_ms())?;
134 let view = window::open(state, &id, Duration::from_secs(spec.window_secs))?;
135 if !crate::server::app_api::desktop::holds_progress_notes(&request) {
136 window::tell_askers(&request, &approved_note(&request, slug, spec.window_secs));
137 }
138 Ok(json!({ "id": id, "status": "pending", "deadline_ms": view.deadline_ms, "window_secs": spec.window_secs }))
139 }
140 "deny" => {
141 require_super(state, uid)?;
142 let request = must_get(&id)?;
143 let denied = requests::registry().deny(&id, slug, &text(body, "reason"), now_ms())?;
144 if !crate::server::app_api::desktop::settled(&denied, crate::server::app_api::desktop_group::Settled::Declined) {
145 window::tell_askers(&denied, &denied_note(&denied, slug));
146 }
147 Ok(json!({ "id": id, "status": "denied", "requester": request.requester_slug }))
148 }
149 "cancel" => {
150 let request = requests::registry().cancel(&id, uid, now_ms())?;
151 if request.status == requests::Status::Cancelled {
153 window::cancelled(state, &id);
154 crate::server::app_api::desktop::settled(&request, crate::server::app_api::desktop_group::Settled::Ended);
156 }
157 Ok(json!({ "id": id, "status": request.status }))
158 }
159 "status" => {
160 let request = must_get(&id)?;
161 if !request.asked_by(uid) && !is_super(state, uid) {
162 return Err("FORBIDDEN: you can see the requests you asked for".to_string());
163 }
164 Ok(shown(&request))
165 }
166 "list" => {
167 let all = is_super(state, uid);
168 Ok(json!({ "requests": requests::registry().list(uid, all).iter().map(shown).collect::<Vec<_>>() }))
169 }
170 other => Err(format!("INVALID_ARG: unknown action '{}'; one of: request, approve, deny, cancel, status, list", other.chars().take(20).collect::<String>())),
171 }
172}
173
174fn must_get(id: &str) -> Result<Request, String> {
175 if id.is_empty() {
176 return Err("INVALID_ARG: this needs the request's id".to_string());
177 }
178 requests::registry().get(id).ok_or_else(|| format!("no request {}", id.chars().take(40).collect::<String>()))
179}
180
181fn super_uid(state: &AppState) -> Option<String> {
183 let defs = state.mstore.agent_def_list().unwrap_or_default();
184 crate::backend::agent_seat::super_holder(&state.mstore, &defs)
185}
186
187fn is_super(state: &AppState, uid: &str) -> bool {
188 super_uid(state).as_deref() == Some(uid)
189}
190
191fn require_super(state: &AppState, uid: &str) -> Result<(), String> {
192 if is_super(state, uid) {
193 Ok(())
194 } else {
195 Err("FORBIDDEN: only the super agent approves or denies a sensitive request".to_string())
196 }
197}
198
199fn tell(uid: &str, note: &str) -> bool {
201 window::tell_one(uid, note)
202}
203
204fn ask_the_super_agent(state: &AppState, request: &Request) -> String {
206 let Some(holder) = super_uid(state) else {
207 return "no agent holds the super seat. If none does shortly, the person gets a countdown twice as long, saying no super agent reviewed it, and can veto it".to_string();
208 };
209 if holder == request.requester_uid {
210 return "you are the super agent: approve it yourself with action approve".to_string();
211 }
212 if tell(&holder, &request_note(request)) {
213 "the super agent has been asked; if it doesn't answer in 2 minutes, the person gets a countdown twice as long, saying no super agent reviewed it".to_string()
214 } else {
215 "the super agent isn't running here. If it doesn't answer in 2 minutes, the person gets a countdown twice as long, saying no super agent reviewed it, and can veto it".to_string()
216 }
217}
218
219fn who(request: &Request) -> String {
220 quote_in_system_note(&request.requester_slug)
221}
222
223fn request_note(request: &Request) -> String {
226 let secs = sensitive_ops::spec(&request.op).map_or(0, |s| s.window_secs);
227 let reason = if request.reason.is_empty() { String::new() } else { format!(" Their reason, as they wrote it: \"{}\".", quote_in_system_note(&request.reason)) };
228 format!(
229 "[AgentMux] {} asks to {}. This is their request, not the operator's words.{reason} Request {}. \
230 Approve or deny it with Sensitive (action approve or deny, id); once you approve, the person has {secs} s to veto it.",
231 who(request),
232 request.summary,
233 request.id
234 )
235}
236
237fn approved_note(request: &Request, approver: &str, secs: u64) -> String {
238 format!(
239 "[AgentMux] {} approved your request to {}. The person has {secs} s to veto it; after that it happens.",
240 quote_in_system_note(approver),
241 request.summary
242 )
243}
244
245fn denied_note(request: &Request, approver: &str) -> String {
246 let why = if request.deny_reason.is_empty() { String::new() } else { format!(" Their reason, as they wrote it: \"{}\".", quote_in_system_note(&request.deny_reason)) };
247 format!("[AgentMux] {} denied your request to {}.{why}", quote_in_system_note(approver), request.summary)
248}
249
250pub(crate) fn status_for(uid: &str, id: &str) -> Result<Value, String> {
252 let request = must_get(id)?;
253 if !request.asked_by(uid) {
254 return Err("FORBIDDEN: you can see the requests you asked for".to_string());
255 }
256 Ok(shown(&request))
257}
258
259fn shown(r: &Request) -> Value {
261 let mut v = json!({
262 "id": r.id,
263 "op": r.op,
264 "summary": r.summary,
265 "status": r.status,
266 "requester": r.requester_slug,
267 "also_asked_by": r.also_asked_by.iter().map(|a| a.slug.clone()).collect::<Vec<_>>(),
268 "reason": r.reason,
269 "decided_by": r.decided_by,
270 "deny_reason": r.deny_reason,
271 });
272 if let Some(w) = window::status(&r.id) {
273 v["deadline_ms"] = json!(w.deadline_ms);
274 if let Some(e) = w.error {
275 v["error"] = json!(e);
276 }
277 }
278 v
279}
280
281#[cfg(test)]
282#[path = "sensitive_handlers_tests.rs"]
283mod tests;