Skip to main content

trusty_code/tools/
delegate.rs

1//! `delegate_to_agent` tool — the PM's primary tool for dispatching to sub-agents.
2//!
3//! Why: Keeps the delegation schema and its executor colocated so the PM's tool
4//! registry can register a single type that owns both. Pre-flight validation of
5//! `agent_name` against the on-disk agent config directory prevents the LLM from
6//! hallucinating sub-agent names and crashing the subprocess runner with a
7//! confusing IO error (#204 equivalent). (bake-off L1 diagnosis) A delegated
8//! engineer that exhausts its turn/time budget has usually already written
9//! real, partial progress to disk; the PM's recovery historically was a
10//! free-text "re-delegate with a streamlined brief" that never told the next
11//! engineer instance to look at what was already there, so it silently
12//! rebuilt a simpler (sometimes incomplete) solution and orphaned the correct
13//! work. `redelegation_hint` makes the safer instruction automatic: it fires
14//! on every `TurnCapExceeded`/`Timeout`/`Cancelled` abort, regardless of
15//! whether the PM's own free text remembers to ask for it.
16//! What: `DelegateToAgentTool` wraps an `AgentRunner` and (optionally) an agent
17//! config directory. `execute()` parses `{agent_name, task}`, validates the agent
18//! config exists, and hands off to the runner. On miss, returns a helpful error
19//! listing available agents. On a runner failure caused by the sub-agent's own
20//! loop aborting with partial work still on disk, the returned `ToolResult`
21//! error appends a fixed reuse/continue directive (`redelegation_hint`).
22//! (#2265) `redelegation_hint` is also `pub(crate)` so
23//! `run_task::redelegation::RedelegatingRunner` can reuse the SAME hint logic
24//! to decide, entirely inside one `delegate_to_agent` dispatch, whether a
25//! failed engineer attempt is worth automatically retrying — see that
26//! module's docs for the retry/cap mechanics.
27//! Test: `unknown_agent_returns_helpful_error` builds a tool pointed at a tempdir
28//! containing `engineer.toml` only, calls `execute({"agent_name":"ghost",...})`,
29//! and asserts the error names the unknown agent and lists `engineer`.
30//! `redelegation_hint_*` tests cover the reuse-directive behaviour.
31
32use std::path::PathBuf;
33use std::sync::Arc;
34use std::sync::atomic::{AtomicBool, Ordering};
35
36use async_trait::async_trait;
37use serde_json::{Value, json};
38
39use crate::agent_loop::AgentLoopError;
40use crate::runner::RunnerError;
41use crate::tools::finish_task::FinishStatus;
42use crate::tools::traits::{AgentOutput, AgentRunner, ToolExecutor, ToolResult};
43
44/// Detect whether an `AgentRunner` failure means the sub-agent's OWN attempt
45/// may have left partial work already on disk (turn cap, timeout,
46/// cancellation, or a retryable LLM/transport hiccup), as opposed to a hard
47/// failure (unknown agent, bad config) that leaves nothing to reuse.
48///
49/// Why: (bake-off L1 diagnosis) The PM only sees this failure as opaque error
50/// text; without a structured signal, its free-text re-delegation brief has no
51/// reliable reason to mention the sub-agent's partial progress, so the next
52/// delegated instance rebuilds from scratch and orphans correct prior work.
53/// Surfacing a fixed directive automatically — every time this specific
54/// failure shape occurs — makes "read existing files, then continue" the
55/// default recovery instead of something the PM must remember to ask for.
56/// (#2265) `AgentLoopError::Llm` — a recoverable Bedrock/transport error that
57/// aborts the engineer's sub-loop mid-session — is the DOMINANT failure mode
58/// observed in the bake-off transcripts, yet #2233 left it out of this match,
59/// so the reuse hint never fired for the most common case and every retry
60/// re-read PROBLEM.md from zero. It now gets the same hint: tool calls the
61/// engineer already dispatched before the failing `chat` call (e.g.
62/// `write_file`) already landed on disk even though `AgentLoopError::Llm`
63/// itself carries no `partial: Box<AgentOutput>` (unlike the three
64/// budget-abort variants) — there is real, on-disk work to reuse even though
65/// there is no partial transcript snapshot to point to.
66/// What: Downcasts `err` to [`RunnerError`] and matches `RunnerError::Loop`
67/// whose source is `AgentLoopError::TurnCapExceeded`, `Timeout`, `Cancelled`,
68/// (#2265) `Llm`, or (#2265 fix #5) `StoppedBySignal`. Returns `None` only
69/// for `UnknownAgent`/`ConfigLoad` — failures that never reached a sub-agent
70/// loop at all, so there is nothing on disk to reuse.
71/// Note: a delegated engineer's own sub-loop never actually attaches a stop
72/// signal today (only `run_task`'s PM loop does, via
73/// `AgentLoop::with_stop_signal`), so `StoppedBySignal` is unreachable from
74/// this call site in practice; it is included for exhaustiveness and to stay
75/// correct if that ever changes.
76/// Test: `redelegation_hint_present_on_turn_cap_exceeded`,
77/// `redelegation_hint_present_on_timeout`,
78/// `redelegation_hint_present_on_cancelled`,
79/// `redelegation_hint_present_on_llm_error`,
80/// `redelegation_hint_absent_on_unknown_agent`.
81pub(crate) fn redelegation_hint(err: &anyhow::Error) -> Option<&'static str> {
82    let RunnerError::Loop { source, .. } = err.downcast_ref::<RunnerError>()? else {
83        return None;
84    };
85    match source {
86        AgentLoopError::TurnCapExceeded { .. }
87        | AgentLoopError::Timeout { .. }
88        | AgentLoopError::Cancelled { .. }
89        | AgentLoopError::StoppedBySignal { .. }
90        | AgentLoopError::Llm(_) => Some(
91            "\n\nNOTE for re-delegation: the sub-agent's previous attempt did not reach a \
92             normal finish — it ran out of turns or time, was cancelled, or hit a \
93             transient LLM/transport error — NOT a task failure. It has likely already \
94             written real, partial progress to disk. Before delegating this task again: \
95             (1) inspect the project's current files to see what the sub-agent already \
96             produced, (2) instruct the next sub-agent to READ and CONTINUE/BUILD ON that \
97             existing work rather than rewriting it from scratch, and (3) consider a narrower \
98             follow-up task (or a higher turn budget) so it can finish what is already started \
99             instead of starting over.",
100        ),
101    }
102}
103
104/// Run-scoped latch recording that a delegated engineer already reported an
105/// EXPLICIT successful completion (`finish_task` with `status: completed`)
106/// during this run (#2683).
107///
108/// Why: The bake-off regression this closes is a PM that, after the engineer
109/// already called `finish_task` with all tests passing, fires ONE MORE
110/// gratuitous `delegate_to_agent` "re-verify" round; when that extra round
111/// then runs out of turns / wall-clock time, the run terminated mid-round and
112/// was mislabeled `partial`/exit-6 even though a complete, correct,
113/// all-tests-passing deliverable already sat on disk — corrupting run
114/// status/telemetry (issue #2683 recurrence comment, 2026-07-15). This shared
115/// latch is the authoritative "the task is genuinely done" signal: once set,
116/// [`DelegateToAgentTool`] refuses further re-delegation (part b of the fix)
117/// and `run_task::assemble_report` reports success rather than partial (the
118/// data-integrity half). Modeled as a cheap `Arc<AtomicBool>` handle,
119/// mirroring `run_task::redelegation::RedelegationCapSignal`, so the tool (the
120/// setter) and the report assembler (the reader) observe the SAME state.
121/// What: `new()` starts un-latched; `mark_completed` latches it (set only by
122/// [`DelegateToAgentTool::execute`] when the delegated runner returns an
123/// `AgentOutput` whose `finish_status` is `Some(FinishStatus::Completed)`);
124/// `is_completed` reads it. `Clone` shares the same underlying flag.
125/// Test: `tools::delegate::tests::completion_signal_latches_on_completed_finish`,
126/// `tools::delegate::tests::completion_signal_ignores_non_completed_finish`,
127/// `tools::delegate::tests::delegate_refused_once_engineer_completed`.
128#[derive(Debug, Clone, Default)]
129pub struct EngineerCompletionSignal(Arc<AtomicBool>);
130
131impl EngineerCompletionSignal {
132    /// Build a fresh, un-latched signal for one run.
133    ///
134    /// Why: Each `execute_run_task` call needs its OWN signal — a prior run's
135    /// completion must never leak into a later run's report.
136    /// What: `Self::default()`.
137    /// Test: `completion_signal_latches_on_completed_finish`.
138    pub fn new() -> Self {
139        Self::default()
140    }
141
142    /// Latch the "engineer completed successfully" flag.
143    ///
144    /// Why: Called exactly once, the first time a delegation returns an explicit
145    /// successful `finish_task` completion.
146    /// What: Stores `true` with `SeqCst` (paired with `is_completed`'s load).
147    /// Test: `completion_signal_latches_on_completed_finish`.
148    pub(crate) fn mark_completed(&self) {
149        self.0.store(true, Ordering::SeqCst);
150    }
151
152    /// Whether a delegated engineer has already completed successfully.
153    ///
154    /// Why: [`DelegateToAgentTool::execute`] reads this to refuse a gratuitous
155    /// re-delegation, and `run_task::assemble_report` reads it to report
156    /// success instead of partial.
157    /// What: Loads the latched flag.
158    /// Test: `completion_signal_latches_on_completed_finish`.
159    pub fn is_completed(&self) -> bool {
160        self.0.load(Ordering::SeqCst)
161    }
162}
163
164/// Tool executor that delegates a task to a named sub-agent.
165///
166/// Why: Encapsulates the `delegate_to_agent` tool so the PM loop registers a
167/// single `Arc<dyn ToolExecutor>` rather than branching on the tool name inline.
168/// What: Holds an `AgentRunner` for subprocess/in-process dispatch, an optional
169/// `config_dir` for pre-flight agent name validation, and (#2683) an optional
170/// shared [`EngineerCompletionSignal`] used to refuse a re-delegation once the
171/// engineer has already reported a successful `finish_task` completion.
172/// Test: `unknown_agent_returns_helpful_error`, `known_agent_reaches_runner`,
173/// `no_config_dir_skips_validation`, `delegate_refused_once_engineer_completed`.
174pub struct DelegateToAgentTool {
175    runner: Arc<dyn AgentRunner>,
176    /// Directory holding `<agent>.toml` files. When `Some`, `execute()` rejects
177    /// calls whose `agent_name` does not have a matching TOML. When `None`,
178    /// validation is skipped (legacy / test mode).
179    config_dir: Option<PathBuf>,
180    /// Shared, run-scoped completion latch (#2683). When `Some` and already
181    /// latched, `execute()` refuses further delegation with a recoverable error
182    /// that nudges the PM to call `finish_task`. When `None` (the default /
183    /// legacy path), the refusal behaviour is disabled entirely.
184    completion_signal: Option<EngineerCompletionSignal>,
185}
186
187impl DelegateToAgentTool {
188    /// Construct with an injected `AgentRunner`.
189    ///
190    /// Why: Lets tests substitute an in-process mock runner without touching
191    /// production subprocess code.
192    /// What: Stores `runner`; no pre-flight name validation until `with_config_dir`
193    /// is also called.
194    /// Test: `DelegateToAgentTool::new(Arc::new(MockRunner))` compiles and
195    /// yields a tool whose `name()` is `delegate_to_agent`.
196    pub fn new(runner: Arc<dyn AgentRunner>) -> Self {
197        Self {
198            runner,
199            config_dir: None,
200            completion_signal: None,
201        }
202    }
203
204    /// Attach an agent config directory for pre-flight `agent_name` validation.
205    ///
206    /// Why: When the LLM hallucinates an agent name, spawning the subprocess
207    /// fails with a generic IO error. Validating up front returns a structured
208    /// `ToolResult::err` listing available agents so the LLM can self-correct.
209    /// What: Stores `dir`. Files matching `<dir>/<agent_name>.toml` are
210    /// considered valid. Missing dir is treated as "no agents available".
211    /// Test: `unknown_agent_returns_helpful_error`.
212    pub fn with_config_dir(mut self, dir: PathBuf) -> Self {
213        self.config_dir = Some(dir);
214        self
215    }
216
217    /// Attach a shared [`EngineerCompletionSignal`] so a re-delegation after a
218    /// successful engineer completion is refused (#2683).
219    ///
220    /// Why: Once the delegated engineer has reported an explicit successful
221    /// `finish_task` completion, any further `delegate_to_agent` call is the
222    /// gratuitous post-finish re-delegation that mislabels a complete run as
223    /// `partial`; refusing it (and nudging the PM to `finish_task` instead) is
224    /// the "do not re-delegate once the finish gate is satisfied" half of the
225    /// fix. `run_task::execute_run_task` shares the SAME signal instance with
226    /// `assemble_report`.
227    /// What: Builder-style setter; returns `self` for chaining. When unset (the
228    /// default), the refusal behaviour is disabled and this tool behaves
229    /// exactly as before.
230    /// Test: `delegate_refused_once_engineer_completed`.
231    pub fn with_completion_signal(mut self, signal: EngineerCompletionSignal) -> Self {
232        self.completion_signal = Some(signal);
233        self
234    }
235
236    /// List agent names discoverable in `config_dir`, if any.
237    ///
238    /// Why: Builds the "available agents" hint in error messages so the LLM
239    /// gets immediate, structured feedback when it invents a name.
240    /// What: Reads `<config_dir>/*.toml` and returns each file stem. Returns
241    /// `None` when no `config_dir` was attached.
242    /// Test: Indirect via `unknown_agent_returns_helpful_error`.
243    fn available_agents(&self) -> Option<Vec<String>> {
244        let dir = self.config_dir.as_ref()?;
245        let entries = std::fs::read_dir(dir).ok()?;
246        let mut names: Vec<String> = entries
247            .flatten()
248            .filter_map(|e| {
249                let p = e.path();
250                if p.extension().and_then(|x| x.to_str()) == Some("toml") {
251                    p.file_stem()
252                        .and_then(|s| s.to_str())
253                        .map(|s| s.to_string())
254                } else {
255                    None
256                }
257            })
258            .collect();
259        names.sort();
260        Some(names)
261    }
262}
263
264#[async_trait]
265impl ToolExecutor for DelegateToAgentTool {
266    fn name(&self) -> &str {
267        "delegate_to_agent"
268    }
269
270    fn schema(&self) -> Value {
271        json!({
272            "type": "function",
273            "function": {
274                "name": "delegate_to_agent",
275                "description": "Delegate a task to a specialized sub-agent. Use this for any implementation work (writing code, running analysis, etc.). The sub-agent will be spawned and its result returned to you. NOTE: agent_name must be an actual sub-agent (e.g. 'engineer', 'python-engineer', 'qa-agent'); native tools like search_code, web_search are NOT agent names — call them directly.",
276                "parameters": {
277                    "type": "object",
278                    "properties": {
279                        "agent_name": {
280                            "type": "string",
281                            "description": "Short name of the sub-agent. Must match an existing agent config; native tools are not agent names."
282                        },
283                        "task": {
284                            "type": "string",
285                            "description": "Concrete task description for the sub-agent."
286                        }
287                    },
288                    "required": ["agent_name", "task"],
289                    "additionalProperties": false
290                }
291            }
292        })
293    }
294
295    async fn execute(&self, args: Value) -> ToolResult {
296        // #2683: once the delegated engineer has already reported a successful
297        // `finish_task` completion, refuse any further delegation BEFORE
298        // parsing/validating args or invoking the runner. This is the "do not
299        // re-delegate once the finish gate is satisfied" half of the fix: the
300        // deliverable is on disk and the task is done, so a re-verify round is
301        // gratuitous — nudge the PM to `finish_task` instead of spawning
302        // another engineer loop that can only end the run mid-round and
303        // mislabel it `partial`. Recoverable (not fatal) so the PM's loop
304        // continues and can act on the guidance.
305        if let Some(signal) = &self.completion_signal
306            && signal.is_completed()
307        {
308            return ToolResult::err(
309                "delegate_to_agent refused: the delegated engineer already reported a \
310                 successful completion (finish_task with status=completed) for this run. \
311                 The deliverable is on disk and the task is done — do NOT re-delegate to \
312                 re-verify. Call finish_task now to report the result.",
313            );
314        }
315
316        let Some(agent_name) = args.get("agent_name").and_then(Value::as_str) else {
317            return ToolResult::err("delegate_to_agent: missing 'agent_name'");
318        };
319        let Some(task) = args.get("task").and_then(Value::as_str) else {
320            return ToolResult::err("delegate_to_agent: missing 'task'");
321        };
322
323        // Guard against path traversal: the LLM supplies agent_name which is
324        // joined into a filesystem path. Reject any name that is not strictly
325        // [a-zA-Z0-9_-] before the path join so a crafted value like
326        // "../../etc/passwd" cannot escape the agents config directory.
327        if agent_name.is_empty()
328            || !agent_name
329                .chars()
330                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
331        {
332            return ToolResult::err(format!(
333                "Invalid agent name '{agent_name}': \
334                 agent names must be non-empty and contain only [a-zA-Z0-9_-]"
335            ));
336        }
337
338        // Pre-flight validation: if a config_dir was attached, verify the agent
339        // config exists before spawning. Converts a generic IO error into a
340        // structured tool error the LLM can act on.
341        if let Some(dir) = &self.config_dir {
342            let agent_toml = dir.join(format!("{agent_name}.toml"));
343            if !agent_toml.exists() {
344                let available = self.available_agents().unwrap_or_default();
345                let available_str = if available.is_empty() {
346                    "(none discovered)".to_string()
347                } else {
348                    available.join(", ")
349                };
350                return ToolResult::err(format!(
351                    "Unknown agent '{agent_name}'. Available agents: {available_str}. \
352                     Note: native tools (search_code, web_search, etc.) are NOT agent \
353                     names — call them directly as tools instead of via delegate_to_agent."
354                ));
355            }
356        }
357
358        match self.runner.run(agent_name, task).await {
359            Ok(out) => {
360                // #2683: latch the run-scoped completion signal when the engineer
361                // terminated via an EXPLICIT successful `finish_task` — the
362                // authoritative "task is genuinely done" signal both the refusal
363                // above and `run_task::assemble_report` key off. A `failed` /
364                // `cancelled` finish, or a plain no-tool-call stop, does NOT
365                // latch it: those leave re-delegation legitimately available.
366                self.mark_completion_if_finished(&out);
367                ToolResult::ok(out.content)
368            }
369            Err(e) => {
370                let hint = redelegation_hint(&e).unwrap_or("");
371                ToolResult::err(format!("sub-agent '{agent_name}' failed: {e:#}{hint}"))
372            }
373        }
374    }
375}
376
377impl DelegateToAgentTool {
378    /// Latch the shared completion signal iff `out` represents an explicit
379    /// successful `finish_task` completion (#2683).
380    ///
381    /// Why: Factored out of `execute` so the "what counts as a successful
382    /// completion" rule lives in one named place and is unit-testable.
383    /// What: No-op when no `completion_signal` is attached; otherwise latches it
384    /// only when `out.finish_status == Some(FinishStatus::Completed)`.
385    /// Test: `completion_signal_latches_on_completed_finish`,
386    /// `completion_signal_ignores_non_completed_finish`.
387    fn mark_completion_if_finished(&self, out: &AgentOutput) {
388        if let Some(signal) = &self.completion_signal
389            && out.finish_status == Some(FinishStatus::Completed)
390        {
391            signal.mark_completed();
392        }
393    }
394}
395
396// ── Tests ─────────────────────────────────────────────────────────────────────
397
398#[cfg(test)]
399#[path = "delegate_tests.rs"]
400mod tests;