agentmux_srv/drone/executor/blocks/
agent.rs1use serde_json::{json, Value};
48
49use crate::agents::runner::{run_agent, AgentError};
50use crate::agents::tool_limit::ToolLimit;
51use crate::agents::types::{AgentRef, AgentRunResult, AgentTask};
52use crate::drone::data_flow::ExecutionScope;
53use crate::drone::executor::blocks::agent_output::Schema;
54use crate::drone::types::FlowNode;
55
56fn agent_ref_of(node: &FlowNode) -> Result<AgentRef, String> {
58 match node.data.get("agent_ref") {
59 Some(v) => serde_json::from_value(v.clone()).map_err(|e| format!("agent block: invalid agent_ref: {e}")),
60 None => {
61 if let Some(legacy) = node.data.get("forge_agent_id").and_then(|v| v.as_str()) {
67 if !legacy.is_empty() {
68 tracing::warn!(
69 block_id = %node.id,
70 legacy_forge_agent_id = %legacy,
71 "agent block: legacy `forge_agent_id` ignored — re-pick identity/memory after Phase 1.5 PR 3"
72 );
73 }
74 }
75 Ok(AgentRef::default())
76 }
77 }
78}
79
80fn resolved_allowance(allow: Option<&Value>, scope: &ExecutionScope) -> Option<Value> {
83 Some(match allow? {
84 Value::String(s) => Value::String(scope.resolve(s)),
85 Value::Array(list) => Value::Array(list.iter().map(|v| v.as_str().map_or_else(|| v.clone(), |s| Value::String(scope.resolve(s)))).collect()),
86 other => other.clone(),
87 })
88}
89
90pub async fn run(node: &FlowNode, scope: &ExecutionScope) -> Result<Value, String> {
91 let task_raw = node
92 .data
93 .get("task")
94 .and_then(|v| v.as_str())
95 .ok_or_else(|| "agent block missing `task`".to_string())?;
96 let mut prompt = scope.resolve(task_raw);
97
98 let schema = match node.data.get("output_schema") {
100 Some(declared) if !declared.is_null() => {
101 Some(Schema::parse(declared).map_err(|e| format!("agent block: {e}"))?)
102 }
103 _ => None,
104 };
105 if let Some(schema) = &schema {
106 prompt.push_str(&schema.instructions());
107 }
108
109 let agent_ref = agent_ref_of(node)?;
110
111 let max_turns = node
112 .data
113 .get("max_turns")
114 .and_then(|v| v.as_u64())
115 .map(|n| n as u32);
116
117 let task = AgentTask {
118 prompt,
119 context: serde_json::Map::new(),
123 max_turns,
124 tools: ToolLimit::from_allow_commands(resolved_allowance(node.data.get("allow_commands"), scope).as_ref()),
125 };
126
127 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
131 let handle = run_agent(agent_ref, task, tx).await.map_err(|e| match e {
132 AgentError::Spawn(msg) => format!("agent block: spawn failed: {msg}"),
133 AgentError::FolderRule(msg) => format!("agent block: {msg}"),
134 AgentError::CommitPressure { avail_gb, reserve_gb } => format!(
135 "agent block: memory full — {avail_gb:.1} GB commit free, need {reserve_gb:.1} GB; try again when memory frees"
136 ),
137 })?;
138
139 tokio::spawn(async move {
143 while rx.recv().await.is_some() {}
144 });
145
146 let result = handle
147 .final_result
148 .await
149 .map_err(|e| format!("agent block: runner cancelled: {e}"))?
150 .map_err(|e| format!("agent block: agent run failed: {e}"))?;
151
152 let output = match &schema {
154 Some(schema) => Some(
155 schema
156 .extract(&result.response)
157 .map_err(|e| format!("agent block: the reply did not fit `output_schema`: {e}"))?,
158 ),
159 None => None,
160 };
161
162 Ok(flatten(&result, output))
163}
164
165fn flatten(result: &AgentRunResult, output: Option<Value>) -> Value {
169 let mut out = json!({
170 "response": result.response,
171 "tokens": {
172 "input": result.tokens.input,
173 "output": result.tokens.output,
174 "cache_creation": result.tokens.cache_creation,
175 "cache_read": result.tokens.cache_read,
176 },
177 "cost_usd": result.cost_usd,
178 "status": "done",
179 });
180 if let Some(output) = output {
181 out["output"] = output;
182 }
183 out
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use crate::drone::types::NodePosition;
190
191 fn mk_node(data: Value) -> FlowNode {
192 FlowNode {
193 id: "a1".to_string(),
194 position: NodePosition::default(),
195 data,
196 node_type: None,
197 }
198 }
199
200 #[test]
201 fn an_allowed_command_line_is_the_one_that_will_run() {
202 let scope = ExecutionScope { trigger: json!({ "tag": "v1" }), ..ExecutionScope::new() };
203 let limit = |v: Value| ToolLimit::from_allow_commands(resolved_allowance(Some(&v), &scope).as_ref());
204 let one = |c: &str| ToolLimit::Limited { commands: vec![c.to_string()] };
205 assert_eq!(limit(json!(["./release-check {{trigger.tag}}"])), one("./release-check v1"));
206 assert_eq!(limit(json!("./release-check {{trigger.tag}}")), one("./release-check v1"));
207 assert_eq!(limit(json!(true)), ToolLimit::Unlimited);
208 assert_eq!(ToolLimit::from_allow_commands(resolved_allowance(None, &scope).as_ref()), ToolLimit::default());
209 }
210
211 #[tokio::test]
212 async fn rejects_missing_task() {
213 let node = mk_node(json!({ "kind": "agent" }));
214 let scope = ExecutionScope::new();
215 let err = run(&node, &scope).await.expect_err("must error");
216 assert!(err.contains("missing `task`"), "got: {err}");
217 }
218
219 #[tokio::test]
220 async fn rejects_malformed_agent_ref() {
221 let node = mk_node(json!({
222 "kind": "agent",
223 "task": "hi",
224 "agent_ref": "not an object"
225 }));
226 let scope = ExecutionScope::new();
227 let err = run(&node, &scope).await.expect_err("must error");
228 assert!(err.contains("invalid agent_ref"), "got: {err}");
229 }
230
231 #[tokio::test]
232 async fn rejects_an_unusable_output_schema_before_any_agent_starts() {
233 let node = mk_node(json!({ "kind": "agent", "task": "hi", "output_schema": { "Bad Name": "string" } }));
234 let scope = ExecutionScope::new();
235 let err = run(&node, &scope).await.expect_err("must error");
236 assert!(err.starts_with("agent block: field `Bad Name`"), "got: {err}");
237 }
238
239 #[test]
252 fn legacy_forge_agent_id_falls_back_to_default_ref() {
253 let data = json!({
254 "kind": "agent",
255 "task": "hi",
256 "forge_agent_id": "legacy-id-123"
257 });
258 let agent_ref: AgentRef = match data.get("agent_ref") {
259 Some(v) => serde_json::from_value(v.clone()).unwrap(),
260 None => AgentRef::default(),
261 };
262 assert_eq!(agent_ref, AgentRef::default());
263 assert_eq!(
266 data.get("forge_agent_id").and_then(|v| v.as_str()),
267 Some("legacy-id-123")
268 );
269 }
270}