use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::agent_loop::AgentLoopError;
use crate::runner::RunnerError;
use crate::tools::finish_task::FinishStatus;
use crate::tools::traits::{AgentOutput, AgentRunner, ToolExecutor, ToolResult};
pub(crate) fn redelegation_hint(err: &anyhow::Error) -> Option<&'static str> {
let RunnerError::Loop { source, .. } = err.downcast_ref::<RunnerError>()? else {
return None;
};
match source {
AgentLoopError::TurnCapExceeded { .. }
| AgentLoopError::Timeout { .. }
| AgentLoopError::Cancelled { .. }
| AgentLoopError::StoppedBySignal { .. }
| AgentLoopError::Llm(_) => Some(
"\n\nNOTE for re-delegation: the sub-agent's previous attempt did not reach a \
normal finish — it ran out of turns or time, was cancelled, or hit a \
transient LLM/transport error — NOT a task failure. It has likely already \
written real, partial progress to disk. Before delegating this task again: \
(1) inspect the project's current files to see what the sub-agent already \
produced, (2) instruct the next sub-agent to READ and CONTINUE/BUILD ON that \
existing work rather than rewriting it from scratch, and (3) consider a narrower \
follow-up task (or a higher turn budget) so it can finish what is already started \
instead of starting over.",
),
}
}
#[derive(Debug, Clone, Default)]
pub struct EngineerCompletionSignal(Arc<AtomicBool>);
impl EngineerCompletionSignal {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn mark_completed(&self) {
self.0.store(true, Ordering::SeqCst);
}
pub fn is_completed(&self) -> bool {
self.0.load(Ordering::SeqCst)
}
}
pub struct DelegateToAgentTool {
runner: Arc<dyn AgentRunner>,
config_dir: Option<PathBuf>,
completion_signal: Option<EngineerCompletionSignal>,
}
impl DelegateToAgentTool {
pub fn new(runner: Arc<dyn AgentRunner>) -> Self {
Self {
runner,
config_dir: None,
completion_signal: None,
}
}
pub fn with_config_dir(mut self, dir: PathBuf) -> Self {
self.config_dir = Some(dir);
self
}
pub fn with_completion_signal(mut self, signal: EngineerCompletionSignal) -> Self {
self.completion_signal = Some(signal);
self
}
fn available_agents(&self) -> Option<Vec<String>> {
let dir = self.config_dir.as_ref()?;
Some(crate::agents::available_agent_names(dir))
}
}
#[async_trait]
impl ToolExecutor for DelegateToAgentTool {
fn name(&self) -> &str {
"delegate_to_agent"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "delegate_to_agent",
"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.",
"parameters": {
"type": "object",
"properties": {
"agent_name": {
"type": "string",
"description": "Short name of the sub-agent. Must match an existing agent config; native tools are not agent names."
},
"task": {
"type": "string",
"description": "Concrete task description for the sub-agent."
}
},
"required": ["agent_name", "task"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
if let Some(signal) = &self.completion_signal
&& signal.is_completed()
{
tracing::warn!(
"delegate_to_agent refused (#2683 completion latch): the delegated engineer \
already reported a successful finish_task completion for this run — refusing \
further delegation without invoking the runner"
);
return ToolResult::err(
"delegate_to_agent refused: the delegated engineer already reported a \
successful completion (finish_task with status=completed) for this run. \
The deliverable is on disk and the task is done — do NOT re-delegate to \
re-verify. Call finish_task now to report the result.",
);
}
let Some(agent_name) = args.get("agent_name").and_then(Value::as_str) else {
return ToolResult::err("delegate_to_agent: missing 'agent_name'");
};
let Some(task) = args.get("task").and_then(Value::as_str) else {
return ToolResult::err("delegate_to_agent: missing 'task'");
};
let is_valid_plain_name = !agent_name.is_empty()
&& agent_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
if !is_valid_plain_name && !crate::plugins::is_valid_namespaced_name(agent_name) {
return ToolResult::err(format!(
"Invalid agent name '{agent_name}': agent names must be non-empty and contain \
only [a-zA-Z0-9_-], or be a namespaced <plugin>:<name> where both segments \
are [a-z0-9-]+ (<= 64 chars)"
));
}
if let Some(dir) = &self.config_dir
&& !crate::runner::agent_config_exists(dir, agent_name)
{
let available = self.available_agents().unwrap_or_default();
let available_str = if available.is_empty() {
"(none discovered)".to_string()
} else {
available.join(", ")
};
return ToolResult::err(format!(
"Unknown agent '{agent_name}'. Available agents: {available_str}. \
Note: native tools (search_code, web_search, etc.) are NOT agent \
names — call them directly as tools instead of via delegate_to_agent."
));
}
match self.runner.run(agent_name, task).await {
Ok(out) => {
self.mark_completion_if_finished(&out);
ToolResult::ok(out.content)
}
Err(e) => {
let hint = redelegation_hint(&e).unwrap_or("");
ToolResult::err(format!("sub-agent '{agent_name}' failed: {e:#}{hint}"))
}
}
}
}
impl DelegateToAgentTool {
fn mark_completion_if_finished(&self, out: &AgentOutput) {
if let Some(signal) = &self.completion_signal
&& out.finish_status == Some(FinishStatus::Completed)
{
signal.mark_completed();
}
}
}
#[cfg(test)]
#[path = "delegate_tests.rs"]
mod tests;