1use 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
32pub(crate) enum Stop {
34 Refused(String),
36 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
51fn 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
63fn 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
74fn 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
89pub(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
113fn 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
129fn 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
138pub(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 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
163pub(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}