Skip to main content

agentmux_srv/drone/executor/blocks/
agent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent block — one-shot Claude Code spawn driven by an `AgentRef`
5//! and a per-call task template.
6//!
7//! Phase 1.5 PR 2: replaces the original stub
8//! (`{ response: "[stub]" }`) with a real invocation of
9//! `agents::runner::run_agent`. The runner spawns
10//! `claude --print --output-format=stream-json`, drains its stdout
11//! through `ClaudeTranslator`, and produces a structured
12//! `AgentRunResult` that this function flattens into the
13//! snake_case drone-block output shape.
14//!
15//! Block config (`node.data`):
16//!   * `task`         — required. Mustache-style template resolved
17//!                      against `scope.outputs + scope.vars` before
18//!                      spawning.
19//!   * `agent_ref`    — optional. Object matching `AgentRef` shape
20//!                      (camelCase keys): identityId, memoryId,
21//!                      instanceName, workingDirectory. All fields
22//!                      optional; missing = blank agent.
23//!   * `max_turns`    — optional. Hard cap on claude turns.
24//!   * `output_schema` — optional. The few short fields the reply must carry
25//!                      (agent_output.rs): the reply format is added to the
26//!                      prompt, and the reply is checked against it. The
27//!                      validated fields are the block's `output`, read as
28//!                      `{{<this_block_id>.output.<field>}}`; a reply that does
29//!                      not fit fails the block.
30//!
31//! Output (snake_case to match other drone blocks — see spec
32//! §4.5):
33//!
34//!   ```json
35//!   {
36//!     "response": "<text>",
37//!     "tokens": { "input": .., "output": .., "cache_creation": .., "cache_read": .. },
38//!     "cost_usd": 0.001,
39//!     "status": "done",
40//!     "output": { "<field>": .. }   // only with `output_schema`
41//!   }
42//!   ```
43//!
44//! Downstream blocks read `{{<this_block_id>.response}}` for the
45//! agent's reply and `{{<this_block_id>.cost_usd}}` for accounting.
46
47use 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
56/// The node's `agent_ref`: its identity and memory, or a blank agent when it has none.
57fn 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            // Pre-Phase-1.5 nodes persisted a single `forge_agent_id`
62            // string; the runner can't honor it because identity and
63            // memory are now separate bundles. Surface the legacy data
64            // in the log so the user knows why the agent launches
65            // blank (#835).
66            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
80/// The block's `allow_commands` with each command line's `{{references}}` resolved, as the task is: the line the agent runs
81/// is the one that was allowed.
82fn 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    // A schema that cannot be used is found before an agent is started, not after its tokens are spent.
99    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        // The runner doesn't currently use the `context` map (claude
120        // takes the prompt on argv); leave it empty. Phase 2 may
121        // surface scope vars as a `system` message section.
122        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    // Forward AgentEvents into a local channel and discard for now.
128    // Phase 1.5 PR 3 will re-emit them on the `dronerun:<id>`
129    // broker so the inspector pane can render the live stream.
130    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    // Drain the event channel concurrently so the runner's sender
140    // can make progress. Drop the events for now — the captured
141    // accumulator from `final_result` is the authoritative output.
142    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    // The fields the next node branches on. What the agent wrote is not in the error: it is the agent's text.
153    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
165/// The block's output, flattened to snake_case to match other drone block outputs (the AgentRunResult's serde camelCase
166/// is for the IPC seam with the frontend, NOT for drone templates — see spec §4.5 NOTE), with the validated `output`
167/// fields when the node declared a schema.
168fn 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    // The spawn-failure → "agent block: spawn failed: ..." mapping is
240    // covered by `agents::runner::tests::run_agent_with_bin_surfaces_spawn_failure`,
241    // which injects a nonexistent binary path via the internal
242    // `run_agent_with_bin` entry point instead of `std::env::set_var`
243    // (unsound under concurrent test execution in Rust 1.81+).
244    // Reagent P2 on PR #834.
245
246    /// Reproduces the parse-only path of `run()` for a node carrying
247    /// legacy `forge_agent_id` (no `agent_ref`). The runner shim isn't
248    /// invoked — the assertion is that we accept the node and fall back
249    /// to a default `AgentRef`. The deprecation warning fires as a side
250    /// effect; we keep this test free of `tracing` plumbing.
251    #[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        // Confirms the legacy field is still present in node.data — the
264        // production path reads it for the warn-log; tests don't.
265        assert_eq!(
266            data.get("forge_agent_id").and_then(|v| v.as_str()),
267            Some("legacy-id-123")
268        );
269    }
270}