Skip to main content

agentmux_srv/server/
drone_fire.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent fires a drone it did not make and was not given: the `drone_fire` sensitive operation
5//! (`docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md` §6.5). The request says who asked, which drone, what its
6//! graph can do and what payload goes in; the super agent reviews it and the person can stop it in the countdown.
7//! When the countdown ends unstopped the run starts, recorded as the agent that asked, on the graph the person was
8//! shown: a drone edited since is not run.
9//!
10//! The payload is not a fact (a banner line is short), so it waits here by the request's id, with the graph's hash.
11//! It is kept in memory, as the requests are: after a restart the request is gone too.
12
13use 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
28/// How long a payload waits for its request: longer than the longest countdown and its review.
29const HOLD: Duration = Duration::from_secs(30 * 60);
30/// The most payloads held at once. A request that is never decided ends (`prune` in the registry); this is the
31/// same bound, so a flood of fires cannot fill memory with payloads of 64 KB.
32const 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
47/// What the banner says the drone can do: its node kinds and how many of its nodes start an agent (each one spends).
48pub(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
62/// File the request for `slug` (whose uid is `uid`) to fire `drone` with `input`, and keep the payload for it.
63pub(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            // Without its payload the request could only fail at the end of the countdown: withdraw it now and say why.
75            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
87/// Keep the payload for `request_id`, after letting go of the payloads of requests that ended without running (cancelled,
88/// denied, vetoed or expired) or waited too long. False when the room is full.
89fn 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
99/// The drone as a fact: its name and its whole id. A long name is cut, never the id, so two drones are never one request.
100fn 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
113/// `text` cut to what a fact of a request may hold.
114fn 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
123/// The runner: the countdown ended unvetoed.
124pub(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;