use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use anyhow::Result;
use async_trait::async_trait;
use crate::tools::delegate::redelegation_hint;
use crate::tools::{AgentOutput, AgentRunner, RunContext};
pub const MAX_REDELEGATIONS: u32 = 3;
#[derive(Debug, Default)]
struct RedelegationCapState {
attempts: AtomicU32,
cap_reached: AtomicBool,
}
#[derive(Debug, Clone, Default)]
pub struct RedelegationCapSignal(Arc<RedelegationCapState>);
impl RedelegationCapSignal {
pub fn new() -> Self {
Self::default()
}
fn record_attempt(&self) -> u32 {
self.0.attempts.fetch_add(1, Ordering::SeqCst) + 1
}
fn mark_cap_reached(&self) {
self.0.cap_reached.store(true, Ordering::SeqCst);
}
pub fn is_cap_reached(&self) -> bool {
self.0.cap_reached.load(Ordering::SeqCst)
}
pub fn attempts(&self) -> u32 {
self.0.attempts.load(Ordering::SeqCst)
}
}
pub struct RedelegatingRunner {
inner: Arc<dyn AgentRunner>,
signal: RedelegationCapSignal,
project: PathBuf,
}
impl RedelegatingRunner {
pub fn new(
inner: Arc<dyn AgentRunner>,
signal: RedelegationCapSignal,
project: PathBuf,
) -> Self {
Self {
inner,
signal,
project,
}
}
async fn run_with_retries(
&self,
agent_name: &str,
task: &str,
ctx: &RunContext,
) -> Result<AgentOutput> {
let mut current_task = task.to_string();
loop {
let attempt = self.signal.record_attempt();
if attempt > MAX_REDELEGATIONS {
self.signal.mark_cap_reached();
return Err(anyhow::anyhow!(
"re-delegation limit reached after {MAX_REDELEGATIONS} attempts; \
partial work preserved at {}",
self.project.display()
));
}
match self
.inner
.run_with_context(agent_name, ¤t_task, ctx)
.await
{
Ok(out) => return Ok(out),
Err(e) => {
let Some(hint) = redelegation_hint(&e) else {
return Err(e);
};
current_task = format!("{task}{hint}");
}
}
}
}
}
#[async_trait]
impl AgentRunner for RedelegatingRunner {
async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
self.run_with_retries(agent_name, task, &RunContext::default())
.await
}
async fn run_with_context(
&self,
agent_name: &str,
task: &str,
ctx: &RunContext,
) -> Result<AgentOutput> {
self.run_with_retries(agent_name, task, ctx).await
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use anyhow::anyhow;
use super::*;
use crate::agent_loop::AgentLoopError;
use crate::llm::LlmError;
use crate::runner::RunnerError;
struct ScriptedInner {
outcomes: Mutex<std::collections::VecDeque<Result<AgentOutput>>>,
calls: Mutex<Vec<String>>,
}
impl ScriptedInner {
fn new(outcomes: Vec<Result<AgentOutput>>) -> Self {
Self {
outcomes: Mutex::new(outcomes.into_iter().collect()),
calls: Mutex::new(Vec::new()),
}
}
}
#[async_trait]
impl AgentRunner for ScriptedInner {
async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
self.calls
.lock()
.expect("calls lock")
.push(task.to_string());
self.outcomes
.lock()
.expect("outcomes lock")
.pop_front()
.unwrap_or_else(|| Err(anyhow!("ScriptedInner exhausted for {agent_name}")))
}
}
fn llm_error() -> anyhow::Error {
anyhow::Error::from(RunnerError::Loop {
name: "python-engineer".to_string(),
source: AgentLoopError::Llm(LlmError::ApiError {
status: 500,
body: "bedrock hiccup".to_string(),
}),
})
}
fn unknown_agent_error() -> anyhow::Error {
anyhow::Error::from(RunnerError::UnknownAgent {
name: "python-engineer".to_string(),
dir: PathBuf::from("/agents"),
})
}
#[tokio::test]
async fn redelegating_runner_retries_on_llm_error_then_succeeds() {
let inner = Arc::new(ScriptedInner::new(vec![
Err(llm_error()),
Ok(AgentOutput::from_content("done")),
]));
let signal = RedelegationCapSignal::new();
let runner = RedelegatingRunner::new(
Arc::clone(&inner) as Arc<dyn AgentRunner>,
signal.clone(),
PathBuf::from("/tmp/project"),
);
let out = runner
.run("python-engineer", "build the package")
.await
.expect("second attempt must succeed");
assert_eq!(out.content, "done");
let calls = inner.calls.lock().expect("calls lock");
assert_eq!(
calls.len(),
2,
"must retry exactly once after the LLM error"
);
assert_eq!(calls[0], "build the package");
assert!(
calls[1].contains("READ and CONTINUE"),
"the retried task must carry the reuse hint, got: {}",
calls[1]
);
assert!(
!signal.is_cap_reached(),
"cap must not be reached on a successful retry"
);
assert_eq!(signal.attempts(), 2);
}
#[tokio::test]
async fn redelegating_runner_stops_at_cap_and_marks_signal() {
let outcomes = (0..MAX_REDELEGATIONS).map(|_| Err(llm_error())).collect();
let inner = Arc::new(ScriptedInner::new(outcomes));
let signal = RedelegationCapSignal::new();
let runner = RedelegatingRunner::new(
Arc::clone(&inner) as Arc<dyn AgentRunner>,
signal.clone(),
PathBuf::from("/tmp/project"),
);
let err = runner
.run("python-engineer", "build the package")
.await
.expect_err("must fail once the cap is exceeded");
assert!(
err.to_string().contains("re-delegation limit reached"),
"error must name the cap condition, got: {err}"
);
assert!(
err.to_string().contains(&MAX_REDELEGATIONS.to_string()),
"error must name the attempt count, got: {err}"
);
let calls = inner.calls.lock().expect("calls lock");
assert_eq!(
calls.len(),
MAX_REDELEGATIONS as usize,
"the inner runner must be called exactly MAX_REDELEGATIONS times, not more"
);
assert!(signal.is_cap_reached(), "signal must latch cap-reached");
assert_eq!(signal.attempts(), MAX_REDELEGATIONS + 1);
}
#[tokio::test]
async fn redelegating_runner_propagates_non_retryable_errors_immediately() {
let inner = Arc::new(ScriptedInner::new(vec![Err(unknown_agent_error())]));
let signal = RedelegationCapSignal::new();
let runner = RedelegatingRunner::new(
Arc::clone(&inner) as Arc<dyn AgentRunner>,
signal.clone(),
PathBuf::from("/tmp/project"),
);
let err = runner
.run("python-engineer", "build the package")
.await
.expect_err("unknown-agent failures must propagate");
assert!(err.to_string().contains("unknown agent"));
let calls = inner.calls.lock().expect("calls lock");
assert_eq!(calls.len(), 1, "must not retry a non-retryable failure");
assert!(
!signal.is_cap_reached(),
"cap must not be marked reached for a non-retryable failure"
);
}
#[tokio::test]
async fn cap_reached_message_names_the_project_path() {
let outcomes = (0..MAX_REDELEGATIONS).map(|_| Err(llm_error())).collect();
let inner = Arc::new(ScriptedInner::new(outcomes));
let signal = RedelegationCapSignal::new();
let runner = RedelegatingRunner::new(
Arc::clone(&inner) as Arc<dyn AgentRunner>,
signal,
PathBuf::from("/very/distinctive/project/path"),
);
let err = runner
.run("python-engineer", "build the package")
.await
.expect_err("must fail once the cap is exceeded");
assert!(
err.to_string().contains("/very/distinctive/project/path"),
"error must name the project path, got: {err}"
);
}
}