agentmux_srv/server/
drone_fire.rs1use std::collections::{BTreeMap, HashMap};
14use std::sync::{LazyLock, Mutex};
15use std::time::Duration;
16
17use serde_json::{json, Value};
18use sha2::{Digest, Sha256};
19
20use crate::backend::job_templates::graph;
21use crate::backend::sensitive_ops::VALUE_MAX;
22use crate::backend::sensitive_requests::{registry, Request};
23use crate::drone::storage::DroneStore;
24use crate::drone::types::DroneDefinition;
25use crate::drone::versions::graph_hash;
26use crate::server::AppState;
27
28const HOLD: Duration = Duration::from_secs(30 * 60);
30const MAX_HELD: usize = 64;
33
34struct Held {
35 drone_id: String,
36 graph_hash: String,
37 input: Value,
38 at: std::time::Instant,
39}
40
41static HELD: LazyLock<Mutex<HashMap<String, Held>>> = LazyLock::new(Mutex::default);
42
43fn held() -> std::sync::MutexGuard<'static, HashMap<String, Held>> {
44 HELD.lock().unwrap_or_else(|e| e.into_inner())
45}
46
47pub(crate) fn can_do(drone: &DroneDefinition) -> String {
49 let summary = graph::summarize(&drone.graph);
50 format!("{} nodes ({}); {} start an agent, which spends", summary.nodes, crate::server::drone_agent::kinds(drone).join(", "), summary.agents)
51}
52
53fn payload_fact(input: &Value) -> String {
54 if input.is_null() {
55 return "none".to_string();
56 }
57 let text = input.to_string();
58 let digest = Sha256::digest(text.as_bytes());
59 format!("{} bytes, sha256 {}", text.len(), digest.iter().take(4).map(|b| format!("{b:02x}")).collect::<String>())
60}
61
62pub(crate) async fn ask(state: &AppState, (uid, slug): (&str, &str), drone: &DroneDefinition, input: Value) -> Result<Value, String> {
64 let facts = BTreeMap::from([
65 ("drone".to_string(), drone_fact(drone)),
66 ("can_do".to_string(), fit(&can_do(drone))),
67 ("payload".to_string(), payload_fact(&input)),
68 ]);
69 let filed = crate::server::sensitive_handlers::file_request(state, uid, slug, "drone_fire", &facts, &format!("fire the drone {}", drone.name)).await?;
70 let id = filed.get("id").and_then(Value::as_str).unwrap_or_default().to_string();
71 if !id.is_empty() && filed.get("joined") != Some(&json!(true)) {
72 let entry = Held { drone_id: drone.id.clone(), graph_hash: graph_hash(&drone.graph), input, at: std::time::Instant::now() };
73 if !hold(&id, entry) {
74 let _ = registry().cancel(&id, uid, agentmux_common::time::now_ms());
76 return Err("LIMIT: too many drone fires are waiting for an answer; try again when one has been decided".to_string());
77 }
78 }
79 Ok(json!({
80 "asked": true,
81 "request_id": id,
82 "drone_id": drone.id,
83 "note": "You don't own this drone and weren't given it, so the person is asked first: the super agent reviews it and the person has a countdown to stop it. It runs when the countdown ends unless it is stopped, recorded as you; you are told. Ask the person to give you the drone (Drone pane) to fire it at once."
84 }))
85}
86
87fn hold(request_id: &str, entry: Held) -> bool {
90 let mut all = held();
91 all.retain(|id, h| h.at.elapsed() < HOLD && registry().get(id).is_some_and(|r| r.status.is_open()));
92 if all.len() >= MAX_HELD {
93 return false;
94 }
95 all.insert(request_id.to_string(), entry);
96 true
97}
98
99fn drone_fact(drone: &DroneDefinition) -> String {
101 let id = format!(" ({})", drone.id);
102 let room = VALUE_MAX.saturating_sub(id.chars().count());
103 let name = if drone.name.chars().count() <= room {
104 drone.name.clone()
105 } else {
106 let mut cut: String = drone.name.chars().take(room.saturating_sub(1)).collect();
107 cut.push('…');
108 cut
109 };
110 format!("{name}{id}")
111}
112
113fn fit(text: &str) -> String {
115 if text.chars().count() <= VALUE_MAX {
116 return text.to_string();
117 }
118 let mut cut: String = text.chars().take(VALUE_MAX - 1).collect();
119 cut.push('…');
120 cut
121}
122
123pub(crate) async fn run_after_countdown(state: AppState, request: Request) -> Result<(), String> {
125 let entry = held().remove(&request.id).ok_or("the payload for this request is gone (AgentMux restarted, or it waited too long); ask again")?;
126 let drone = state
127 .id_store
128 .drone_get(&entry.drone_id)
129 .map_err(|e| format!("drone: {e}"))?
130 .ok_or("the drone was deleted while the request waited")?;
131 if graph_hash(&drone.graph) != entry.graph_hash {
132 return Err(format!("{:?} was edited while the request waited, so it is not what the person saw; ask again", drone.name));
133 }
134 if let Some(why) = crate::server::drone_agent::why_not_fireable(&drone) {
135 return Err(format!("an agent can't fire {:?}: {why}", drone.name));
136 }
137 let run_id = crate::server::drone_handlers::start_agent_drone_run(&state, &drone, entry.input, &request.requester_uid).await?;
138 crate::sagas::sensitive_window::tell_askers(&request, &format!("The person didn't stop it: {:?} is running as your fire (run {run_id}). Read it with Drone runs.", drone.name));
139 Ok(())
140}
141
142#[cfg(test)]
143#[path = "drone_fire_tests.rs"]
144mod tests;