use std::path::PathBuf;
use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::agent_loop::AgentLoopError;
use crate::runner::RunnerError;
use crate::tools::traits::{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.",
),
}
}
pub struct DelegateToAgentTool {
runner: Arc<dyn AgentRunner>,
config_dir: Option<PathBuf>,
}
impl DelegateToAgentTool {
pub fn new(runner: Arc<dyn AgentRunner>) -> Self {
Self {
runner,
config_dir: None,
}
}
pub fn with_config_dir(mut self, dir: PathBuf) -> Self {
self.config_dir = Some(dir);
self
}
fn available_agents(&self) -> Option<Vec<String>> {
let dir = self.config_dir.as_ref()?;
let entries = std::fs::read_dir(dir).ok()?;
let mut names: Vec<String> = entries
.flatten()
.filter_map(|e| {
let p = e.path();
if p.extension().and_then(|x| x.to_str()) == Some("toml") {
p.file_stem()
.and_then(|s| s.to_str())
.map(|s| s.to_string())
} else {
None
}
})
.collect();
names.sort();
Some(names)
}
}
#[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 {
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'");
};
if agent_name.is_empty()
|| !agent_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return ToolResult::err(format!(
"Invalid agent name '{agent_name}': \
agent names must be non-empty and contain only [a-zA-Z0-9_-]"
));
}
if let Some(dir) = &self.config_dir {
let agent_toml = dir.join(format!("{agent_name}.toml"));
if !agent_toml.exists() {
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) => ToolResult::ok(out.content),
Err(e) => {
let hint = redelegation_hint(&e).unwrap_or("");
ToolResult::err(format!("sub-agent '{agent_name}' failed: {e:#}{hint}"))
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::json;
use super::{DelegateToAgentTool, redelegation_hint};
use crate::agent_loop::AgentLoopError;
use crate::llm::LlmError;
use crate::runner::RunnerError;
use crate::tools::traits::{AgentOutput, AgentRunner, ToolExecutor};
struct RecordingRunner {
invoked: std::sync::Mutex<Vec<(String, String)>>,
}
#[async_trait]
impl AgentRunner for RecordingRunner {
async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
self.invoked
.lock()
.expect("lock poisoned")
.push((agent_name.to_string(), task.to_string()));
Ok(AgentOutput::from_content("ok"))
}
}
#[tokio::test]
async fn unknown_agent_returns_helpful_error() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("engineer.toml"),
"[agent]\nname = \"engineer\"\n",
)
.expect("write");
std::fs::write(
tmp.path().join("qa-agent.toml"),
"[agent]\nname = \"qa-agent\"\n",
)
.expect("write");
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool =
DelegateToAgentTool::new(runner.clone()).with_config_dir(tmp.path().to_path_buf());
let result = tool
.execute(json!({"agent_name": "ghost", "task": "do something"}))
.await;
assert!(result.is_error(), "must reject unknown agent");
let msg = result.content();
assert!(
msg.contains("Unknown agent 'ghost'"),
"error must name the unknown agent, got: {msg}"
);
assert!(
msg.contains("engineer") && msg.contains("qa-agent"),
"error must list available agents, got: {msg}"
);
assert!(
msg.contains("native tools"),
"error must clarify native-vs-agent, got: {msg}"
);
assert!(
runner.invoked.lock().expect("lock").is_empty(),
"runner must not be called when validation fails"
);
}
#[tokio::test]
async fn known_agent_reaches_runner() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("engineer.toml"),
"[agent]\nname = \"engineer\"\n",
)
.expect("write");
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool =
DelegateToAgentTool::new(runner.clone()).with_config_dir(tmp.path().to_path_buf());
let result = tool
.execute(json!({"agent_name": "engineer", "task": "do the thing"}))
.await;
assert!(
!result.is_error(),
"valid agent should succeed: {}",
result.content()
);
let invoked = runner.invoked.lock().expect("lock");
assert_eq!(invoked.len(), 1, "runner should be called exactly once");
assert_eq!(invoked[0].0, "engineer");
}
#[tokio::test]
async fn no_config_dir_skips_validation() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone());
let result = tool
.execute(json!({"agent_name": "anything-goes", "task": "do it"}))
.await;
assert!(!result.is_error(), "legacy mode should bypass validation");
assert_eq!(runner.invoked.lock().expect("lock").len(), 1);
}
#[tokio::test]
async fn missing_agent_name_returns_error() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner);
let result = tool.execute(json!({"task": "something"})).await;
assert!(result.is_error());
assert!(result.content().contains("missing 'agent_name'"));
}
#[tokio::test]
async fn path_traversal_agent_name_is_rejected() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone());
for bad_name in &[
"../../etc/passwd",
"../sibling",
"agent/sub",
"agent name",
"",
] {
let result = tool
.execute(json!({"agent_name": bad_name, "task": "do it"}))
.await;
assert!(
result.is_error(),
"traversal/invalid name '{bad_name}' must be rejected"
);
assert!(
result.content().contains("Invalid agent name"),
"error must describe the problem, got: {}",
result.content()
);
}
assert!(
runner.invoked.lock().expect("lock").is_empty(),
"runner must never be called for invalid names"
);
}
#[tokio::test]
async fn valid_agent_name_passes_sanitization() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone());
for good_name in &["engineer", "qa-agent", "python_engineer", "rust-2024"] {
let result = tool
.execute(json!({"agent_name": good_name, "task": "do it"}))
.await;
assert!(
!result.is_error(),
"valid name '{good_name}' must be accepted: {}",
result.content()
);
}
assert_eq!(
runner.invoked.lock().expect("lock").len(),
4,
"runner must be called for each valid name"
);
}
struct FailingRunner<F: Fn() -> anyhow::Error + Send + Sync> {
make_err: F,
}
#[async_trait]
impl<F: Fn() -> anyhow::Error + Send + Sync> AgentRunner for FailingRunner<F> {
async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
Err((self.make_err)())
}
}
#[tokio::test]
async fn redelegation_hint_present_on_turn_cap_exceeded() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::TurnCapExceeded {
max_turns: 8,
partial: Box::new(AgentOutput::from_content("partial work")),
},
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
let msg = result.content();
assert!(
msg.contains("READ and CONTINUE"),
"must instruct the PM to reuse existing work, got: {msg}"
);
assert!(
msg.contains("already written real, partial progress"),
"must explain why re-delegation should not start over, got: {msg}"
);
}
#[tokio::test]
async fn redelegation_hint_present_on_timeout() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Timeout {
timeout_secs: 120,
partial: Box::new(AgentOutput::from_content("partial work")),
},
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(result.content().contains("READ and CONTINUE"));
}
#[tokio::test]
async fn redelegation_hint_present_on_cancelled() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Cancelled {
partial: Box::new(AgentOutput::from_content("partial work")),
},
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(result.content().contains("READ and CONTINUE"));
}
#[tokio::test]
async fn redelegation_hint_absent_on_unknown_agent() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::UnknownAgent {
name: "ghost".to_string(),
dir: std::path::PathBuf::from("/agents"),
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "ghost", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(
!result.content().contains("READ and CONTINUE"),
"no partial work exists for an unresolved agent config, got: {}",
result.content()
);
}
#[tokio::test]
async fn redelegation_hint_present_on_llm_error() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Llm(LlmError::ApiError {
status: 500,
body: "internal error".to_string(),
}),
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(
result.content().contains("READ and CONTINUE"),
"an LLM/transport error must ALSO carry the reuse directive (#2265), got: {}",
result.content()
);
}
#[test]
fn redelegation_hint_fn_returns_some_for_llm_error() {
let err = anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Llm(LlmError::ApiError {
status: 503,
body: "bedrock throttled".to_string(),
}),
});
assert!(
redelegation_hint(&err).is_some(),
"redelegation_hint must return Some for AgentLoopError::Llm (#2265)"
);
}
}