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