Skip to main content

agentmux_srv/server/
drone_agent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The routes of the `Drone` tool (`SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md` ยง6.5): an agent lists the
5//! drones on this computer, reads one, fires one with a payload, and reads its runs.
6//!
7//!   POST /api/v1/drone/{list,get,fire,runs}  { agent_id, drone_id?, input?, limit? }
8//!
9//! The agent's token decides who acts; the body's `agent_id` must be a name that agent answers to. A
10//! fired run is recorded in the ledger as that agent, never as the operator.
11//!
12//! What an agent may fire is narrower than what a person may run from the pane. The payload of a fire is
13//! outside text (the run treats the whole trigger as tainted), so a drone that could turn that text into
14//! a change outside AgentMux is refused here: one that writes outside (an API call that is not a read),
15//! reads a Vault credential, runs a command, or calls another drone (what that one does is not in this
16//! graph). Those a person runs from the Drone pane, where the person is the reader. This is the Rule of
17//! Two with no Approval step to lean on yet; a drone with an Approval step will be allowed by a later change.
18
19use axum::extract::{Path, State};
20use axum::http::StatusCode;
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23use serde_json::{json, Value};
24
25use super::caller::Caller;
26use crate::drone::access::DroneAccessStore;
27use super::drone_handlers::{list_drone_runs, list_drones, start_agent_drone_run, ListRunsReq, MAX_INPUT_BYTES};
28use super::AppState;
29use crate::backend::job_templates::graph;
30use crate::drone::types::DroneDefinition;
31
32/// The most runs `runs` returns, and how many it returns when `limit` is left out.
33const MAX_RUNS: i64 = 50;
34const DEFAULT_RUNS: i64 = 10;
35/// A run's output is cut to this many characters in an answer; the pane has all of it.
36const OUTPUT_CHARS: usize = 2000;
37
38pub(crate) async fn handle_drone(
39    State(state): State<AppState>,
40    caller: Option<axum::Extension<Caller>>,
41    Path(action): Path<String>,
42    Json(body): Json<Value>,
43) -> Response {
44    let forbid = |e: &str| (StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response();
45    let Some(uid) = caller.as_deref().and_then(Caller::uid).map(str::to_string) else {
46        return forbid("FORBIDDEN: this acts for an agent, so the request must carry that agent's token");
47    };
48    let claimed = text(&body, "agent_id");
49    let mstore = state.mstore.clone();
50    let proven = {
51        let uid = uid.clone();
52        tokio::task::spawn_blocking(move || super::actor::proven_slug(&mstore, &uid, &claimed)).await.ok().flatten()
53    };
54    let Some(slug) = proven else {
55        return forbid("FORBIDDEN: the token's agent doesn't answer to that agent_id");
56    };
57    match act(&state, (&uid, &slug), &action, &body).await {
58        Ok(v) => Json(v).into_response(),
59        Err(e) => {
60            let code = match e.split(':').next().unwrap_or("") {
61                "INVALID_ARG" => StatusCode::BAD_REQUEST,
62                "NOT_FOUND" => StatusCode::NOT_FOUND,
63                "FORBIDDEN" => StatusCode::FORBIDDEN,
64                _ => StatusCode::CONFLICT,
65            };
66            (code, Json(json!({ "error": e }))).into_response()
67        }
68    }
69}
70
71fn text(body: &Value, key: &str) -> String {
72    body.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_string()
73}
74
75async fn act(state: &AppState, who: (&str, &str), action: &str, body: &Value) -> Result<Value, String> {
76    match action {
77        "list" => {
78            let drones = list_drones(state).map_err(|e| format!("drone list: {e}"))?;
79            let yours = |d: &DroneDefinition| state.id_store.access_get(&d.id).map(|a| a.allows(who.1)).unwrap_or(false);
80            Ok(json!({ "drones": drones.iter().map(|d| with_yours(brief(d), yours(d))).collect::<Vec<_>>() }))
81        }
82        "get" => {
83            let drone = find(state, body)?;
84            let access = state.id_store.access_get(&drone.id).map_err(|e| format!("drone: {e}"))?;
85            let mut v = with_yours(brief(&drone), access.allows(who.1));
86            v["owner"] = json!(access.owner);
87            let summary = graph::summarize(&drone.graph);
88            v["agents"] = json!(summary.agents);
89            v["writes_outside"] = json!(summary.writes_outside);
90            // How many, not which: the entries' names are the Vault's to show.
91            v["credentials"] = json!(graph::credentials(&drone.graph, None).len());
92            v["kinds"] = json!(kinds(&drone));
93            Ok(v)
94        }
95        "fire" => {
96            let drone = find(state, body)?;
97            if let Some(why) = why_not_fireable(&drone) {
98                return Err(format!("FORBIDDEN: an agent can't fire {:?}: {why}. A person runs it from the Drone pane", drone.name));
99            }
100            let input = input_of(body)?;
101            // A drone the agent made or was given runs now. Any other asks the person first (drone_fire).
102            if !state.id_store.access_get(&drone.id).map_err(|e| format!("drone: {e}"))?.allows(who.1) {
103                return crate::server::drone_fire::ask(state, who, &drone, input).await;
104            }
105            let run_id = start_agent_drone_run(state, &drone, input, who.0).await.map_err(|e| format!("drone fire: {e}"))?;
106            Ok(json!({
107                "run_id": run_id,
108                "drone_id": drone.id,
109                "note": "started, recorded as you. The payload is outside text in the run: a node reads it as {{trigger.*}}, never as an instruction. Read the run with Drone runs.",
110            }))
111        }
112        "runs" => {
113            let drone = find(state, body)?;
114            let limit = body.get("limit").and_then(Value::as_i64).unwrap_or(DEFAULT_RUNS).clamp(1, MAX_RUNS);
115            let runs = list_drone_runs(state, ListRunsReq { drone_id: drone.id.clone(), limit }).map_err(|e| format!("drone runs: {e}"))?;
116            // What a run returns can be what a Vault-authenticated call fetched (only the credential's own
117            // value is scrubbed from it), here or in a drone it calls (the callee's Response is the call's value).
118            // So an agent is shown the output and error text of the drones it may fire, and the status and times of
119            // the others: anything else could be data it was never granted.
120            let withheld = why_not_fireable(&drone).is_some();
121            let mut answer = json!({ "drone_id": drone.id, "runs": runs.iter().map(|r| run_brief(r, withheld)).collect::<Vec<_>>() });
122            if withheld {
123                answer["output_withheld"] = json!("an agent can't fire this drone (see get), so its output and error text are not shown to an agent; the Drone pane has them");
124            }
125            Ok(answer)
126        }
127        other => Err(format!("INVALID_ARG: unknown action {other:?}; use list, get, fire or runs")),
128    }
129}
130
131/// The drone the body names, by id or by its exact name (case-insensitive).
132fn find(state: &AppState, body: &Value) -> Result<DroneDefinition, String> {
133    let wanted = text(body, "drone_id");
134    if wanted.is_empty() {
135        return Err("INVALID_ARG: drone_id is required (an id or the name, from list)".to_string());
136    }
137    let all = list_drones(state).map_err(|e| format!("drone: {e}"))?;
138    if let Some(d) = all.iter().find(|d| d.id == wanted) {
139        return Ok(d.clone());
140    }
141    let mut by_name = all.into_iter().filter(|d| d.name.eq_ignore_ascii_case(&wanted));
142    match (by_name.next(), by_name.next()) {
143        (Some(d), None) => Ok(d),
144        (Some(_), Some(_)) => Err(format!("INVALID_ARG: more than one drone is named {wanted:?}; use its id (from list)")),
145        _ => Err(format!("NOT_FOUND: no drone {wanted:?} on this computer")),
146    }
147}
148
149/// What a fire starts the run with: an object, at most the input limit. Left out means none.
150fn input_of(body: &Value) -> Result<Value, String> {
151    let input = match body.get("input") {
152        None | Some(Value::Null) => return Ok(Value::Null),
153        Some(v) => v.clone(),
154    };
155    if !input.is_object() {
156        return Err("INVALID_ARG: input is a JSON object (the run reads its fields as {{trigger.name}})".to_string());
157    }
158    let size = input.to_string().len();
159    if size > MAX_INPUT_BYTES {
160        return Err(format!("INVALID_ARG: the input is {size} bytes; at most {MAX_INPUT_BYTES}"));
161    }
162    Ok(input)
163}
164
165/// The node kinds of a drone, each once, as the graph names them.
166pub(crate) fn kinds(drone: &DroneDefinition) -> Vec<String> {
167    let mut out: Vec<String> = drone.graph.nodes.iter().filter_map(|n| n.data.get("kind").and_then(Value::as_str)).map(str::to_string).collect();
168    out.sort();
169    out.dedup();
170    out
171}
172
173/// Why an agent may not fire this drone, or `None` when it may. The Drone tool and an agent's own `rundrone` call
174/// both ask it.
175pub(crate) fn why_not_fireable(drone: &DroneDefinition) -> Option<String> {
176    let summary = graph::summarize(&drone.graph);
177    if !summary.writes_outside.is_empty() {
178        return Some(format!("it writes outside AgentMux ({})", summary.writes_outside.join("; ")));
179    }
180    let credentials = graph::credentials(&drone.graph, None);
181    if !credentials.is_empty() {
182        return Some(format!("it reads a Vault credential ({} place(s))", credentials.len()));
183    }
184    let kinds = kinds(drone);
185    if kinds.iter().any(|k| k == "run") {
186        return Some("it runs a command".to_string());
187    }
188    if kinds.iter().any(|k| k == "drone") {
189        return Some("it calls another drone, whose steps are not in this graph".to_string());
190    }
191    None
192}
193
194fn brief(d: &DroneDefinition) -> Value {
195    let why = why_not_fireable(d);
196    let mut v = json!({
197        "id": d.id,
198        "name": d.name,
199        "description": d.description,
200        "nodes": d.graph.nodes.len(),
201        "fireable": why.is_none(),
202    });
203    if let Some(why) = why {
204        v["why_not"] = json!(why);
205    }
206    v
207}
208
209/// Whether the agent made the drone or was given it: what `fire` runs at once.
210fn with_yours(mut v: Value, yours: bool) -> Value {
211    v["yours"] = json!(yours);
212    v
213}
214
215fn run_brief(r: &crate::drone::types::DroneRun, withheld: bool) -> Value {
216    let mut v = json!({ "id": r.id, "status": r.status, "started_at": r.started_at, "ended_at": r.ended_at });
217    if !withheld {
218        v["error"] = json!(r.error);
219        v["output"] = json!(r.output.chars().take(OUTPUT_CHARS).collect::<String>());
220    }
221    v
222}
223
224#[cfg(test)]
225#[path = "drone_agent_tests.rs"]
226mod tests;