1use std::collections::HashMap;
15
16use serde_json::Value;
17
18use super::state::{Reducer, RunState};
19use super::value::Tv;
20
21mod filters;
22
23const DRONE_ENV_PREFIX: &str = "AGENTMUX_DR_";
27
28#[derive(Debug, Default, Clone)]
37pub struct ExecutionScope {
38 pub outputs: HashMap<String, Value>,
39 pub vars: HashMap<String, Value>,
41 pub trigger: Value,
42 pub state: RunState,
45 pub bits: HashMap<String, (bool, bool)>,
48 pub locals: HashMap<String, Value>,
51 pub local_bits: (bool, bool),
52 pub drone_id: String,
53 pub never_ask: bool,
56}
57
58impl ExecutionScope {
59 pub fn new() -> Self {
60 Self::default()
61 }
62
63 pub fn with_trigger(trigger: Value) -> Self {
65 Self { trigger, ..Self::default() }
66 }
67
68 pub fn value_of(&self, template: &str) -> Value {
72 let t = template.trim();
73 let one = t.strip_prefix("{{").and_then(|r| r.strip_suffix("}}")).filter(|inner| !inner.contains("{{") && !inner.contains("}}"));
74 if let Some(v) = one.and_then(|inner| self.lookup(inner.trim())) {
75 return v;
76 }
77 Value::String(self.resolve(template))
78 }
79
80 pub fn lookup_ref(&self, path: &str) -> Option<Value> {
83 self.lookup(path.trim())
84 }
85
86 pub fn declare_var(&mut self, name: &str, reducer: Reducer) -> Result<(), String> {
88 self.state.declare(name, reducer).map_err(|e| e.to_string())
89 }
90
91 pub fn write_var(&mut self, name: &str, value: Tv) -> Result<(), String> {
94 self.state.write(name, value).map_err(|e| e.to_string())?;
95 if let Some(now) = self.state.get(name) {
96 self.vars.insert(name.to_string(), now.v.clone());
97 }
98 Ok(())
99 }
100
101 pub fn bits_of(&self, template: &str) -> (bool, bool) {
105 let (mut tainted, mut derived) = (false, false);
106 let mut rest = template;
107 while let Some(open) = rest.find("{{") {
108 let Some(len) = find_close(&rest[open + 2..]) else { break };
109 let (path, _) = filters::split(&rest[open + 2..open + 2 + len]);
111 rest = &rest[open + 2 + len + 2..];
112 let mut parts = path.split('.');
113 let (t, d) = match parts.next().unwrap_or("") {
114 "trigger" => (!self.trigger.is_null(), false),
115 "env" => (false, false),
116 "item" | "index" if self.locals.contains_key(path.split('.').next().unwrap_or("")) => self.local_bits,
117 "var" | "vars" => parts.next().and_then(|name| self.state.get(name)).map(|tv| (tv.tainted, tv.derived)).unwrap_or((false, false)),
118 node => self.bits.get(node).copied().unwrap_or((false, false)),
119 };
120 tainted |= t;
121 derived |= d;
122 }
123 (tainted, !tainted && derived)
124 }
125
126 pub fn for_drone(drone_id: &str, trigger: Value) -> Self {
128 Self { trigger, drone_id: drone_id.to_string(), ..Self::default() }
129 }
130
131 pub fn resolve(&self, input: &str) -> String {
135 self.resolve_with(input, |v| v)
136 }
137
138 pub fn resolve_with(&self, input: &str, wrap: impl Fn(String) -> String) -> String {
143 let mut out = String::with_capacity(input.len());
144 let bytes = input.as_bytes();
145 let mut i = 0;
146 while i < bytes.len() {
147 if i + 1 < bytes.len() && bytes[i] == b'{' && bytes[i + 1] == b'{' {
154 if let Some(end_rel) = find_close(&input[i + 2..]) {
156 let token = &input[i + 2..i + 2 + end_rel];
157 let resolved = self.lookup(token.trim());
158 match resolved {
159 Some(v) => out.push_str(&wrap(value_to_string(&v))),
160 None => {
161 out.push_str("{{");
163 out.push_str(token);
164 out.push_str("}}");
165 }
166 }
167 i = i + 2 + end_rel + 2;
168 continue;
169 }
170 }
171 let ch_len = input[i..]
174 .chars()
175 .next()
176 .expect("byte index inside &str must start a valid char")
177 .len_utf8();
178 out.push_str(&input[i..i + ch_len]);
179 i += ch_len;
180 }
181 out
182 }
183
184 fn lookup(&self, token: &str) -> Option<Value> {
186 match filters::split(token) {
187 (path, Some(steps)) => filters::apply(self.lookup_path(path), steps),
188 (path, None) => self.lookup_path(path),
189 }
190 }
191
192 fn lookup_path(&self, path: &str) -> Option<Value> {
193 let mut parts = path.split('.');
195 let head = parts.next()?;
196 let rest: Vec<&str> = parts.collect();
197
198 let root = if head == "var" || head == "vars" {
199 let name = rest.first()?;
201 let v = self.vars.get(*name)?;
202 return Some(walk(v.clone(), &rest[1..]));
203 } else if (head == "item" || head == "index") && self.locals.contains_key(head) {
204 return Some(walk(self.locals.get(head)?.clone(), &rest));
206 } else if head == "trigger" {
207 let mut v = &self.trigger;
210 for key in &rest {
211 v = v.get(*key)?;
212 }
213 return Some(v.clone());
214 } else if head == "env" {
215 let name = rest.first()?;
223 if !name.starts_with(DRONE_ENV_PREFIX) {
224 return None;
225 }
226 return std::env::var(name).ok().map(Value::String);
227 } else {
228 self.outputs.get(head)?
230 };
231 Some(walk(root.clone(), &rest))
232 }
233}
234
235fn find_close(s: &str) -> Option<usize> {
236 let bytes = s.as_bytes();
237 let mut i = 0;
238 while i + 1 < bytes.len() {
239 if bytes[i] == b'}' && bytes[i + 1] == b'}' {
240 return Some(i);
241 }
242 i += 1;
243 }
244 None
245}
246
247fn walk(mut v: Value, path: &[&str]) -> Value {
248 for key in path {
249 match v {
250 Value::Object(mut m) => {
251 v = m.remove(*key).unwrap_or(Value::Null);
252 }
253 _ => return Value::Null,
254 }
255 }
256 v
257}
258
259fn value_to_string(v: &Value) -> String {
260 match v {
261 Value::String(s) => s.clone(),
262 Value::Null => String::new(),
263 other => other.to_string(),
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270 use serde_json::json;
271
272 #[test]
273 fn resolves_block_output_path() {
274 let mut scope = ExecutionScope::new();
275 scope
276 .outputs
277 .insert("agent_1".to_string(), json!({ "response": "hello" }));
278 assert_eq!(scope.resolve("Got: {{agent_1.response}}"), "Got: hello");
279 }
280
281 #[test]
282 fn resolves_drone_var() {
283 let mut scope = ExecutionScope::new();
284 scope.vars.insert("name".to_string(), json!("world"));
285 assert_eq!(scope.resolve("hi {{var.name}}"), "hi world");
286 }
287
288 #[test]
289 fn resolves_trigger_path() {
290 let scope = ExecutionScope::with_trigger(json!({ "run": { "conclusion": "failure", "attempt": 2 } }));
291 assert_eq!(scope.resolve("{{trigger.run.conclusion}} #{{trigger.run.attempt}}"), "failure #2");
292 }
293
294 #[test]
295 fn trigger_without_input_or_key_stays_visible() {
296 let none = ExecutionScope::new();
297 assert_eq!(none.resolve("{{trigger.x}}"), "{{trigger.x}}");
298 let scope = ExecutionScope::with_trigger(json!({ "a": 1 }));
299 assert_eq!(scope.resolve("{{trigger.b}}"), "{{trigger.b}}");
300 }
301
302 #[test]
303 fn leaves_unknown_tokens_intact() {
304 let scope = ExecutionScope::new();
305 assert_eq!(scope.resolve("{{ghost.x}}"), "{{ghost.x}}");
306 }
307
308 #[test]
309 fn deep_path_into_object() {
310 let mut scope = ExecutionScope::new();
311 scope
312 .outputs
313 .insert("api1".to_string(), json!({ "body": { "id": 42 } }));
314 assert_eq!(scope.resolve("got id={{api1.body.id}}"), "got id=42");
315 }
316
317 #[test]
318 fn preserves_text_around_tokens() {
319 let mut scope = ExecutionScope::new();
320 scope.vars.insert("x".to_string(), json!("X"));
321 assert_eq!(scope.resolve("a {{var.x}} b {{var.x}} c"), "a X b X c");
322 }
323
324 #[test]
325 fn empty_input_is_empty() {
326 let scope = ExecutionScope::new();
327 assert_eq!(scope.resolve(""), "");
328 }
329
330 #[test]
335 fn preserves_multibyte_chars_around_tokens() {
336 let mut scope = ExecutionScope::new();
337 scope.vars.insert("name".to_string(), json!("world"));
338 assert_eq!(scope.resolve("Olá {{var.name}}"), "Olá world");
340 }
341
342 #[test]
343 fn preserves_multibyte_token_value() {
344 let mut scope = ExecutionScope::new();
345 scope.vars.insert("greeting".to_string(), json!("こんにちは"));
346 assert_eq!(scope.resolve("hi: {{var.greeting}}"), "hi: こんにちは");
347 }
348
349 #[test]
350 fn preserves_emoji_passthrough() {
351 let scope = ExecutionScope::new();
352 assert_eq!(scope.resolve("ship it 🚀"), "ship it 🚀");
356 }
357
358 #[test]
359 fn preserves_multibyte_in_unresolved_token_passthrough() {
360 let scope = ExecutionScope::new();
361 assert_eq!(scope.resolve("café {{ghost}} ☕"), "café {{ghost}} ☕");
364 }
365
366 #[test]
371 fn env_var_allowed_under_drone_prefix() {
372 let key = "AGENTMUX_DR_TEST_PASS_KEY";
373 std::env::set_var(key, "hello");
374 let scope = ExecutionScope::new();
375 assert_eq!(
376 scope.resolve(&format!("got: {{{{env.{key}}}}}")),
377 "got: hello"
378 );
379 std::env::remove_var(key);
380 }
381
382 #[test]
383 fn env_var_outside_prefix_is_blocked() {
384 let secret_key = "AWS_TEST_SECRET_DO_NOT_LEAK";
388 std::env::set_var(secret_key, "TOPSECRET");
389 let scope = ExecutionScope::new();
390 let out = scope.resolve(&format!("leak: {{{{env.{secret_key}}}}}"));
393 assert!(!out.contains("TOPSECRET"), "secret value leaked: {out}");
394 std::env::remove_var(secret_key);
395 }
396
397 #[test]
398 fn env_var_path_blocked() {
399 let scope = ExecutionScope::new();
403 assert_eq!(scope.resolve("{{env.PATH}}"), "{{env.PATH}}");
404 }
405
406 #[test]
407 fn filters_cut_and_reshape_a_reference() {
408 let mut scope = ExecutionScope::new();
409 scope.outputs.insert("run".to_string(), json!({ "log": "a\nb\nc\nd", "body": r#"{"conclusion":"FAILURE","n":3}"# }));
410 assert_eq!(scope.resolve("{{run.log | tail:2}}"), "c\nd");
411 assert_eq!(scope.resolve("{{ run.body | json:conclusion | lower }}!"), "failure!");
412 assert_eq!(scope.resolve("{{run.body | json:n}}"), "3");
413 assert_eq!(scope.resolve("{{run.nothing | default:none}}"), "none");
414 assert_eq!(scope.value_of("{{run.body | json:n}}"), json!(3), "a single token keeps its type");
415 assert_eq!(scope.value_of("{{run.log | head:1}}"), json!("a"));
416 }
417
418 #[test]
419 fn a_bad_filter_or_a_missing_value_leaves_the_token_visible() {
420 let mut scope = ExecutionScope::new();
421 scope.vars.insert("x".to_string(), json!("v"));
422 assert_eq!(scope.resolve("{{var.x | shout}}"), "{{var.x | shout}}");
423 assert_eq!(scope.resolve("{{var.gone | lower}}"), "{{var.gone | lower}}");
424 assert_eq!(scope.resolve("{{env.PATH | default:x}}"), "x", "the env guard still applies, and default fills the refusal");
425 }
426
427 #[test]
428 fn a_filter_does_not_clean_what_a_reference_holds() {
429 let mut scope = ExecutionScope::with_trigger(json!({ "title": "t" }));
430 scope.outputs.insert("a".to_string(), json!({ "r": "x" }));
431 scope.bits.insert("a".to_string(), (true, false));
432 assert_eq!(scope.bits_of("{{a.r}}"), (true, false));
433 assert_eq!(scope.bits_of("{{a.r | trunc:1 | lower}}"), (true, false));
434 assert_eq!(scope.bits_of("{{trigger.title | head:1}}"), (true, false));
435 assert_eq!(scope.bits_of("{{a.r | default:ok}}"), (true, false), "a default does not make the reference clean");
436 }
437}