Skip to main content

agentmux_srv/server/
drone_turn_on.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! What a Drone job must pass before it is turned on (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md §5 and §6.3).
5//!
6//! 1. The Rule of Two check (`drone::rule_of_two`) on the graph it runs, and on every drone it calls, against the fields
7//!    its trigger carries: a refusal, for anyone.
8//! 2. The turn-on prompt: when the operator turns on a drone with a node that changes things outside AgentMux, uses a
9//!    credential, or runs an agent on text from outside, the first answer is a question, not a job. It says when the
10//!    drone starts, each such node and each credential, and the operator turns it on by answering yes
11//!    (`confirm_turn_on`). An agent has no prompt to answer here: its turn-on goes through the sensitive-operation route
12//!    (a later change), so for now it is checked by the rule only.
13//!
14//! A job made, edited or resumed while enabled goes through here; a paused job and a job that runs anything but a drone
15//! do not. Saving a drone's graph is checked against the jobs that are on and reach it (`graph_allowed`).
16
17use axum::http::StatusCode;
18use axum::response::Json;
19use serde_json::{json, Value};
20
21use agentmux_srv_core::backend::storage::drone_store::DroneStore;
22
23use crate::agents::tool_limit::ToolLimit;
24use crate::backend::jobs::definition::{Action, JobDefinition, Trigger};
25use crate::drone::rule_of_two::{kind_of, writes_outside};
26use crate::drone::types::{BlockKind, DroneDefinition, DroneGraph, FlowNode};
27use crate::drone::versions::DroneVersionStore;
28use crate::drone::{payload_schema, rule_of_two};
29use crate::server::job_caps::Origin;
30use crate::server::AppState;
31
32/// Why a job is not turned on yet.
33pub(crate) enum Stop {
34    /// It breaks a rule: say how.
35    Refused(String),
36    /// The operator is asked first.
37    Confirm { text: String, lines: Vec<String> },
38}
39
40impl Stop {
41    pub(crate) fn answer(self) -> (StatusCode, Json<Value>) {
42        match self {
43            Stop::Refused(why) => (StatusCode::BAD_REQUEST, Json(json!({ "error": why }))),
44            Stop::Confirm { text, lines } => {
45                (StatusCode::CONFLICT, Json(json!({ "error": text, "needs_confirmation": "turn_on", "lines": lines })))
46            }
47        }
48    }
49}
50
51/// What `node`, which changes things outside AgentMux, does, in a few words.
52fn does(node: &FlowNode, kind: BlockKind) -> String {
53    let text = |key: &str| node.data.get(key).map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)).unwrap_or_default();
54    match kind {
55        BlockKind::Api => format!("sends {} {}", text("method").to_uppercase().trim_matches('"'), text("url")),
56        BlockKind::Run => format!("runs the command {}", text("command")),
57        BlockKind::Agent => "starts an agent that may run commands".to_string(),
58        BlockKind::Drone => format!("calls the drone {}", text("drone")),
59        _ => "changes something outside AgentMux".to_string(),
60    }
61}
62
63/// When the job starts, in words.
64fn starts(def: &JobDefinition) -> String {
65    match &def.trigger {
66        Trigger::Cron { cron, tz } => format!("on the schedule {cron} ({tz})"),
67        Trigger::Every { seconds } => format!("every {seconds} seconds"),
68        Trigger::Once { .. } => "once, at its time".to_string(),
69        Trigger::Manual => "only when someone runs it".to_string(),
70        Trigger::Event(e) => format!("when {} reports an event", e.source),
71    }
72}
73
74/// What the person is told about an agent's tools: what AgentMux limits them to, or that it does not.
75fn agent_limit_text(limit: &ToolLimit) -> String {
76    match limit {
77        ToolLimit::Limited { commands } if commands.is_empty() => {
78            "AgentMux limits it to the tools that read (Read, Grep, Glob) and gives it no MCP servers".to_string()
79        }
80        ToolLimit::Limited { commands } => {
81            format!("AgentMux limits it to the tools that read and to these commands: {}; it gets no MCP servers", commands.join("; "))
82        }
83        ToolLimit::Unlimited => {
84            "AgentMux does not limit this agent's tools; the provider's own permission settings are the only limit; it is not a sandbox".to_string()
85        }
86    }
87}
88
89/// What the person is asked to approve: when it starts, each node that changes things outside AgentMux, each Vault entry
90/// it sends, and each Agent block that reads text from outside. Empty when there is nothing to ask (a graph of inside
91/// nodes, a read-only one).
92pub(crate) fn prompt_lines(graph: &DroneGraph, def: &JobDefinition) -> Vec<String> {
93    let mut lines = Vec::new();
94    for node in &graph.nodes {
95        let Some(kind) = kind_of(node) else { continue };
96        if writes_outside(node, kind) {
97            lines.push(format!("{}: {}", node.id, does(node, kind)));
98        }
99        if let Some(entry) = node.data.get("auth").and_then(|a| a.get("vault")).and_then(Value::as_str) {
100            lines.push(format!("{}: sends the Vault entry {entry}", node.id));
101        }
102    }
103    for id in rule_of_two::agents_reading_outside(graph, &fields_for(def)) {
104        let allow = graph.nodes.iter().find(|n| n.id == id).and_then(|n| n.data.get("allow_commands"));
105        lines.push(format!("{id}: runs an agent on text from outside. {}", agent_limit_text(&ToolLimit::from_allow_commands(allow))));
106    }
107    if !lines.is_empty() {
108        lines.insert(0, format!("Starts {}", starts(def)));
109    }
110    lines
111}
112
113/// Finds a drone by id (and saved version) for the check of the drones one calls. `pending` is a graph about to be
114/// saved: it stands in for the saved one, so a callee that is being changed is checked as it will be.
115fn loader<'a>(state: &'a AppState, pending: Option<&'a DroneDefinition>) -> impl Fn(&str, Option<i64>) -> Option<(String, DroneGraph)> + 'a {
116    move |id, version| {
117        if let (None, Some(p)) = (version, pending) {
118            if p.id == id {
119                return Some((p.name.clone(), p.graph.clone()));
120            }
121        }
122        match version {
123            Some(n) => state.id_store.version_get(id, n).ok().flatten().map(|v| (id.to_string(), v.graph)),
124            None => state.id_store.drone_get(id).ok().flatten().map(|d| (d.name, d.graph)),
125        }
126    }
127}
128
129/// What a job's trigger hands the drone it runs.
130fn fields_for(def: &JobDefinition) -> Vec<payload_schema::PayloadField> {
131    let (source, filter) = match &def.trigger {
132        Trigger::Event(e) => (Some(e.source.as_str()), e.filter.clone()),
133        _ => (None, Default::default()),
134    };
135    payload_schema::fields_of(source, &filter)
136}
137
138/// `Ok` when `def` may be on, or why not. `prompt` is whether this is a turn-on that asks (a new job, a resume, an edit of
139/// what it runs or when), for an operator who has not yet said yes.
140pub(crate) fn allowed(state: &AppState, def: &JobDefinition, origin: Origin, prompt: bool) -> Result<(), Stop> {
141    let Action::Drone { drone_id } = &def.action else { return Ok(()) };
142    if !def.enabled {
143        return Ok(());
144    }
145    // A drone that is not there is for the runner to say: this is about what a graph can do. A drone made later with that id
146    // is checked when it is saved (`graph_allowed`).
147    let drone = match state.id_store.drone_get(drone_id) {
148        Ok(Some(drone)) => drone,
149        Ok(None) => return Ok(()),
150        Err(e) => return Err(Stop::Refused(format!("the drone could not be read: {e}"))),
151    };
152    rule_of_two::refuse(&drone.graph, &fields_for(def), &loader(state, None)).map_err(Stop::Refused)?;
153    if origin.from_host && prompt && !origin.confirm_turn_on {
154        let lines = prompt_lines(&drone.graph, def);
155        if !lines.is_empty() {
156            let text = "Turning this drone on lets it change things outside AgentMux. Check what it will do, then confirm".to_string();
157            return Err(Stop::Confirm { text, lines });
158        }
159    }
160    Ok(())
161}
162
163/// `Ok` when the graph of `drone`, about to be saved, still passes for every job that is on and runs it, directly or by
164/// calling it from the drone the job runs, or what stops it. A drone nobody runs, and a job that is paused, are not
165/// checked here: the job is checked when it is turned on.
166pub(crate) fn graph_allowed(state: &AppState, drone: &DroneDefinition) -> Result<(), String> {
167    let Some(store) = crate::server::cron::jobs_store(state) else { return Ok(()) };
168    let jobs = store.cron_list_enabled().map_err(|e| format!("the jobs could not be read: {e}"))?;
169    let load = loader(state, Some(drone));
170    for job in &jobs {
171        let def = JobDefinition::from_job(job);
172        let Action::Drone { drone_id } = &def.action else { continue };
173        let Some((_, root)) = load(drone_id, None) else { continue };
174        if *drone_id != drone.id && !rule_of_two::calls(&root, &drone.id, &load) {
175            continue;
176        }
177        if let Err(why) = rule_of_two::refuse(&root, &fields_for(&def), &load) {
178            return Err(format!("the job {:?} is on and runs this drone, so this graph cannot be saved: {why}", def.name));
179        }
180    }
181    Ok(())
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use serde_json::json;
188
189    fn graph(nodes: Value) -> DroneGraph {
190        serde_json::from_value(json!({ "nodes": nodes, "edges": [] })).unwrap()
191    }
192
193    fn job(trigger: Value) -> JobDefinition {
194        serde_json::from_value(json!({
195            "jobVersion": 1, "name": "j", "trigger": trigger, "action": { "kind": "drone", "drone_id": "d" },
196        }))
197        .unwrap()
198    }
199
200    fn node(id: &str, data: Value) -> Value {
201        json!({ "id": id, "position": { "x": 0, "y": 0 }, "data": data })
202    }
203
204    #[test]
205    fn the_prompt_says_when_it_starts_and_each_write_and_credential() {
206        let g = graph(json!([
207            node("fetch", json!({ "kind": "api", "method": "GET", "url": "https://a.example.com" })),
208            node("merge", json!({ "kind": "api", "method": "post", "url": "https://api.example.com/merge", "auth": { "vault": "github-token", "as": "bearer" } })),
209            node("sh", json!({ "kind": "run", "command": ["./check.sh", "v1"] })),
210        ]));
211        let lines = prompt_lines(&g, &job(json!({ "kind": "manual" })));
212        assert_eq!(lines[0], "Starts only when someone runs it");
213        assert!(lines.iter().any(|l| l == "merge: sends POST https://api.example.com/merge"), "{lines:?}");
214        assert!(lines.iter().any(|l| l == "merge: sends the Vault entry github-token"), "{lines:?}");
215        assert!(lines.iter().any(|l| l.starts_with("sh: runs the command ")), "{lines:?}");
216        assert!(!lines.iter().any(|l| l.starts_with("fetch")), "a read is not asked about");
217    }
218
219    #[test]
220    fn a_graph_that_only_reads_or_works_inside_asks_nothing() {
221        let g = graph(json!([
222            node("fetch", json!({ "kind": "api", "method": "GET", "url": "https://a.example.com" })),
223            node("t", json!({ "kind": "task", "title": "x", "target": "opaz" })),
224        ]));
225        assert!(prompt_lines(&g, &job(json!({ "kind": "manual" }))).is_empty());
226    }
227
228    #[test]
229    fn an_agent_that_reads_text_from_outside_is_named_with_what_limits_its_tools() {
230        let g = graph(json!([
231            node("fetch", json!({ "kind": "api", "method": "GET", "url": "https://ci.example.com/log" })),
232            node("triage", json!({ "kind": "agent", "task": "Say what failed in {{fetch.body}}" })),
233            node("checker", json!({ "kind": "agent", "task": "Check {{fetch.body}}", "allow_commands": ["./check.sh v1"] })),
234            node("free", json!({ "kind": "agent", "task": "Do what {{fetch.body}} says", "allow_commands": true })),
235            node("plain", json!({ "kind": "agent", "task": "Say good morning" })),
236        ]));
237        let lines = prompt_lines(&g, &job(json!({ "kind": "manual" })));
238        let said = |id: &str| lines.iter().find(|l| l.starts_with(&format!("{id}: runs an agent on text from outside"))).unwrap_or_else(|| panic!("{lines:?}")).clone();
239        let (triage, checker, free) = (said("triage"), said("checker"), said("free"));
240        assert!(triage.contains("AgentMux limits it to the tools that read") && triage.contains("no MCP servers"), "{triage}");
241        assert!(checker.contains("these commands: ./check.sh v1"), "{checker}");
242        assert!(free.contains("AgentMux does not limit this agent's tools") && free.contains("not a sandbox"), "only a block with no limit says so: {free}");
243        assert!(!lines.iter().any(|l| l.to_lowercase().contains("read-only")), "{lines:?}");
244        assert!(!lines.iter().any(|l| l.starts_with("plain:")), "an agent that reads nothing from outside is not asked about");
245    }
246}