use crate::config::NamedRoute;
use crate::error::Error;
use crate::hooks::LoopHooks;
use crate::provider::{ChatProvider, OpenAiProvider, ProviderProfile};
use crate::router::RouteInfo;
use crate::runtime::{Agent, AgentEvent};
use crate::session::SessionStore;
use crate::tools::{truncate, Approver, CallScope, Tool, ToolError, ToolRegistry};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::sync::{Arc, Mutex};
use std::time::Duration;
pub const MAX_CHILDREN_PER_RUN: usize = 4;
pub const DEFAULT_CHILD_ITERATIONS: usize = 6;
pub const MAX_CHILD_ITERATIONS: usize = 20;
const SUMMARY_PROMPT_CHARS: usize = 100;
const PREAMBLE: &str = "You are a subagent. Another agent handed you one job and will read \
only your final message, so make that message the answer itself: no greeting, no recap of \
what you did unless it matters, no questions back. You cannot ask the user anything and you \
cannot delegate. Use the tools you have to do the job, and finish within your iteration \
budget.";
pub struct ChildRoute {
pub name: String,
pub provider: Arc<dyn ChatProvider>,
pub context_budget_tokens: usize,
}
pub trait ChildProviders: Send + Sync {
fn routes(&self) -> Vec<RouteInfo>;
fn default_route(&self) -> String;
fn provider(&self, route: &str) -> Result<ChildRoute, String>;
fn refusal(&self, _route: &str) -> Option<String> {
None
}
}
pub struct ConfigRoutes {
routes: Vec<NamedRoute>,
profiles: Vec<ProviderProfile>,
delegate: Option<String>,
selected: String,
pinned: Option<String>,
model: Arc<Mutex<Option<String>>>,
}
impl ConfigRoutes {
pub fn new(
routes: Vec<NamedRoute>,
profiles: Vec<ProviderProfile>,
delegate: Option<String>,
selected: String,
pinned: Option<String>,
model: Arc<Mutex<Option<String>>>,
) -> Self {
Self {
routes,
profiles,
delegate,
selected,
pinned,
model,
}
}
}
impl ChildProviders for ConfigRoutes {
fn routes(&self) -> Vec<RouteInfo> {
self.routes
.iter()
.filter(|r| match &self.pinned {
Some(pinned) => &r.name == pinned,
None => true,
})
.map(|r| RouteInfo {
name: r.name.clone(),
model: r.config.model.clone(),
endpoint: r.config.base_url.clone(),
})
.collect()
}
fn default_route(&self) -> String {
self.delegate
.clone()
.unwrap_or_else(|| self.selected.clone())
}
fn refusal(&self, route: &str) -> Option<String> {
let pinned = self.pinned.as_deref()?;
if route == pinned || !self.routes.iter().any(|r| r.name == route) {
return None;
}
Some(format!(
"this run is pinned to `{pinned}` with --route, so a subagent cannot be sent to \
`{route}`. Drop `route`, or drop the pin."
))
}
fn provider(&self, route: &str) -> Result<ChildRoute, String> {
if let Some(why) = self.refusal(route) {
return Err(why);
}
let named = self
.routes
.iter()
.find(|r| r.name == route)
.ok_or_else(|| format!("route `{route}` is not configured"))?;
let mut cfg = named.config.clone();
if route == self.selected {
if let Some(model) = self.model.lock().ok().and_then(|m| m.clone()) {
cfg.model = model;
}
}
if cfg.base_url.trim().is_empty() || cfg.model.trim().is_empty() {
return Err(format!("route `{route}` has no base_url or no model"));
}
let provider = OpenAiProvider::with_profiles(&cfg, &self.profiles)
.map_err(|e| format!("route `{route}`: {e}"))?;
Ok(ChildRoute {
name: route.to_string(),
provider: Arc::new(provider),
context_budget_tokens: cfg.context_budget_tokens,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChildRun {
pub route: String,
pub session_id: String,
pub prompt_tokens: Option<u64>,
pub completion_tokens: Option<u64>,
pub iterations: usize,
pub failed: bool,
}
#[derive(Default)]
pub struct ChildLedger {
started: Mutex<usize>,
runs: Mutex<Vec<ChildRun>>,
}
impl ChildLedger {
fn reserve(&self) -> Option<()> {
let mut started = self.started.lock().ok()?;
(*started < MAX_CHILDREN_PER_RUN).then(|| *started += 1)
}
fn record(&self, run: ChildRun) {
if let Ok(mut runs) = self.runs.lock() {
runs.push(run);
}
}
pub fn runs(&self) -> Vec<ChildRun> {
self.runs.lock().map(|r| r.clone()).unwrap_or_default()
}
}
fn sum(values: impl Iterator<Item = Option<u64>>) -> Option<u64> {
values.flatten().reduce(|a, b| a.saturating_add(b))
}
fn count_tokens(n: Option<u64>) -> String {
n.map_or_else(|| "?".to_string(), |n| n.to_string())
}
fn usage_line(prompt: Option<u64>, completion: Option<u64>, iterations: usize) -> String {
let iterations = format!(
"{iterations} iteration{}",
if iterations == 1 { "" } else { "s" }
);
if prompt.is_none() && completion.is_none() {
return format!("child usage: tokens not reported by the server, {iterations}");
}
format!(
"child usage: {} prompt / {} completion tokens, {iterations}",
count_tokens(prompt),
count_tokens(completion)
)
}
pub fn describe_children(children: &[ChildRun]) -> Option<String> {
if children.is_empty() {
return None;
}
let routes: Vec<&str> = children.iter().map(|c| c.route.as_str()).collect();
let failed = children.iter().filter(|c| c.failed).count();
let usage = usage_line(
sum(children.iter().map(|c| c.prompt_tokens)),
sum(children.iter().map(|c| c.completion_tokens)),
children.iter().map(|c| c.iterations).sum(),
);
Some(format!(
"delegated: {} subagent{} ({}{}) \u{2014} {usage}",
children.len(),
if children.len() == 1 { "" } else { "s" },
routes.join(", "),
if failed == 0 {
String::new()
} else {
format!("; {failed} failed")
}
))
}
struct ChildApprover<'a> {
inner: &'a dyn Approver,
route: &'a str,
}
#[async_trait]
impl Approver for ChildApprover<'_> {
async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
let marked = crate::approvals::Pending::new(
call.call_id.clone(),
call.tool.clone(),
format!("[subagent on {}] {}", self.route, call.summary),
call.args.clone(),
);
self.inner.decide(&marked).await
}
}
pub struct DelegateSettings {
pub max_output_bytes: usize,
pub max_malformed_calls: usize,
pub tool_concurrency: usize,
pub lock_wait: Duration,
}
pub struct DelegateTool {
providers: Arc<dyn ChildProviders>,
tools: Arc<ToolRegistry>,
store: SessionStore,
settings: DelegateSettings,
hooks: LoopHooks,
turn_results: Arc<crate::tools_memory::TurnResults>,
description: String,
}
impl DelegateTool {
pub fn new(
providers: Arc<dyn ChildProviders>,
tools: Arc<ToolRegistry>,
store: SessionStore,
settings: DelegateSettings,
) -> Self {
let routes = providers.routes();
let listed: Vec<String> = routes
.iter()
.map(|r| format!("`{}` ({})", r.name, r.model))
.collect();
let description = format!(
"Hand one self-contained job to a subagent and get its final answer back as this \
tool's result. The subagent sees only `prompt` (and `system`), not this \
conversation, so put everything it needs in the prompt. It has the same tools as \
you except `delegate`, a small iteration budget (default {DEFAULT_CHILD_ITERATIONS}, \
at most {MAX_CHILD_ITERATIONS}), and a run may start at most \
{MAX_CHILDREN_PER_RUN} of them. Worth it for a large, separable job that can be \
stated completely, or one that suits a different model; not for a lookup you can do \
yourself. `route` picks the model: {}. Default: `{}`.",
if listed.is_empty() {
"none configured".to_string()
} else {
listed.join(", ")
},
providers.default_route(),
);
Self {
providers,
tools,
store,
settings,
hooks: LoopHooks::default(),
turn_results: Arc::default(),
description,
}
}
pub fn with_hooks(mut self, hooks: LoopHooks) -> Self {
self.hooks = hooks;
self
}
pub fn with_turn_results(
mut self,
turn_results: Arc<crate::tools_memory::TurnResults>,
) -> Self {
self.turn_results = turn_results;
self
}
fn known_routes(&self) -> String {
let names: Vec<String> = self
.providers
.routes()
.into_iter()
.map(|r| r.name)
.collect();
if names.is_empty() {
"none".to_string()
} else {
names.join(", ")
}
}
fn resolve_route(&self, args: &Value) -> Result<String, ToolError> {
match args.get("route") {
None | Some(Value::Null) => Ok(self.providers.default_route()),
Some(Value::String(name)) => {
if let Some(why) = self.providers.refusal(name) {
return Err(ToolError::Failed(why));
}
let known = self.providers.routes();
if known.iter().any(|r| &r.name == name) {
Ok(name.clone())
} else {
Err(ToolError::Failed(format!(
"unknown route `{name}`. Routes that exist: {}",
self.known_routes()
)))
}
}
Some(_) => Err(ToolError::InvalidArgs("`route` must be a string".into())),
}
}
}
fn optional_string<'a>(args: &'a Value, key: &str) -> Result<Option<&'a str>, ToolError> {
match args.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s)),
Some(_) => Err(ToolError::InvalidArgs(format!("`{key}` must be a string"))),
}
}
fn budget_arg(args: &Value) -> Result<usize, ToolError> {
match args.get("max_iterations") {
None | Some(Value::Null) => Ok(DEFAULT_CHILD_ITERATIONS),
Some(v) => match v.as_u64() {
Some(n) if (1..=MAX_CHILD_ITERATIONS as u64).contains(&n) => Ok(n as usize),
_ => Err(ToolError::InvalidArgs(format!(
"`max_iterations` must be a whole number from 1 to {MAX_CHILD_ITERATIONS}"
))),
},
}
}
fn first_line(prompt: &str) -> (String, usize) {
let mut lines = prompt.trim().lines();
let first: String = lines
.next()
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.collect();
let mut chars = first.chars();
let mut out: String = chars.by_ref().take(SUMMARY_PROMPT_CHARS).collect();
if chars.next().is_some() {
out.push_str("...");
}
(out, lines.count())
}
pub(crate) enum ChildOrigin<'a> {
Subagent { parent: &'a str, route: &'a str },
Flare { run: &'a str, n: usize },
}
pub(crate) struct ChildJob<'a> {
pub prompt: &'a str,
pub system: Option<&'a str>,
pub route: &'a str,
pub budget: usize,
pub origin: ChildOrigin<'a>,
pub session_id: &'a str,
}
pub struct ChildOutcome {
pub route: String,
pub session_id: String,
pub answer: std::result::Result<String, String>,
pub prompt_tokens: Option<u64>,
pub completion_tokens: Option<u64>,
pub iterations: usize,
}
impl ChildOutcome {
pub fn failed(&self) -> bool {
self.answer.is_err()
}
}
#[async_trait]
impl Tool for DelegateTool {
fn name(&self) -> &str {
"delegate"
}
fn description(&self) -> &str {
&self.description
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "The whole job, stated so it makes sense with no other context."
},
"route": {
"type": "string",
"description": "Which route (model) the subagent runs on. Unset: the \
configured delegate route, else the route this run is on."
},
"system": {
"type": "string",
"description": "Extra instructions for the subagent, added to its preamble."
},
"max_iterations": {
"type": "integer",
"minimum": 1,
"maximum": MAX_CHILD_ITERATIONS,
"description": format!(
"How many model requests the subagent may make (default {DEFAULT_CHILD_ITERATIONS})."
)
}
},
"required": ["prompt"]
})
}
fn describe_call(&self, args: &Value) -> String {
let route = match args.get("route") {
None | Some(Value::Null) => self.providers.default_route(),
Some(Value::String(s)) => s.clone(),
Some(_) => "(invalid route)".to_string(),
};
let prompt = args.get("prompt").and_then(Value::as_str).unwrap_or("");
let budget = match budget_arg(args) {
Ok(n) => n.to_string(),
Err(_) => "(invalid)".to_string(),
};
let custom = match args.get("system") {
Some(Value::String(s)) if !s.trim().is_empty() => ", with its own system prompt",
_ => "",
};
let (line, more) = first_line(prompt);
let more = match more {
0 => String::new(),
1 => " (+1 more line)".to_string(),
n => format!(" (+{n} more lines)"),
};
format!(
"delegate to a subagent on route `{route}`: \"{line}\"{more} \
(up to {budget} iterations{custom})"
)
}
async fn call(&self, _args: Value) -> Result<String, ToolError> {
Err(ToolError::Failed(
"`delegate` only runs inside an agent run".into(),
))
}
async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
let prompt = crate::tools::str_arg(&args, "prompt")?;
if prompt.trim().is_empty() {
return Err(ToolError::InvalidArgs("`prompt` is empty".into()));
}
let system = optional_string(&args, "system")?;
let budget = budget_arg(&args)?;
let route_name = self.resolve_route(&args)?;
if scope.run.children.reserve().is_none() {
return Err(ToolError::Failed(format!(
"this run has already started {MAX_CHILDREN_PER_RUN} subagents, which is the \
most one run may start. Do the remaining work yourself, or put it in one \
prompt to a subagent you already have the answer from."
)));
}
let session_id = self.store.new_id();
let outcome = self
.run_child(
Arc::clone(&self.tools),
ChildJob {
session_id: &session_id,
prompt,
system,
route: &route_name,
budget,
origin: ChildOrigin::Subagent {
parent: &scope.run.session,
route: &route_name,
},
},
scope.approver,
&scope.run.cancel,
)
.await;
scope.run.children.record(ChildRun {
route: outcome.route.clone(),
session_id: outcome.session_id.clone(),
prompt_tokens: outcome.prompt_tokens,
completion_tokens: outcome.completion_tokens,
iterations: outcome.iterations,
failed: outcome.failed(),
});
let footer = usage_line(
outcome.prompt_tokens,
outcome.completion_tokens,
outcome.iterations,
);
match outcome.answer {
Ok(reply) => {
let note = "\n[output truncated]".len();
let room = self
.settings
.max_output_bytes
.saturating_sub(footer.len() + 2 + note);
Ok(format!("{}\n\n{footer}", truncate(reply, room)))
}
Err(reason) => Err(ToolError::Failed(format!(
"the subagent on route `{}` failed: {reason}\n\n{footer}",
outcome.route
))),
}
}
}
impl DelegateTool {
pub(crate) fn flare_registry(&self) -> ToolRegistry {
self.tools.only(crate::flares::READ_TOOLS)
}
pub(crate) fn default_route(&self) -> String {
self.providers.default_route()
}
pub(crate) fn new_session_id(&self) -> String {
self.store.new_id()
}
pub(crate) async fn run_child(
&self,
tools: Arc<ToolRegistry>,
job: ChildJob<'_>,
approver: &dyn Approver,
cancel: &crate::cancel::Cancel,
) -> ChildOutcome {
let session_id = job.session_id.to_string();
let mut outcome = ChildOutcome {
route: job.route.to_string(),
session_id: session_id.clone(),
answer: Err("the subagent could not start".to_string()),
prompt_tokens: None,
completion_tokens: None,
iterations: 0,
};
let route = match self.providers.provider(job.route) {
Ok(route) => route,
Err(reason) => {
outcome.answer = Err(format!("the subagent could not start: {reason}"));
return outcome;
}
};
outcome.route = route.name.clone();
let begun = match job.origin {
ChildOrigin::Subagent { parent, route } => {
self.store.begin_subagent(&session_id, parent, route)
}
ChildOrigin::Flare { run, n } => self.store.begin_flare(&session_id, run, n),
};
if let Err(e) = begun {
outcome.answer = Err(format!("the subagent could not start: {e}"));
return outcome;
}
let mut preamble = PREAMBLE.to_string();
if let Some(extra) = job.system.filter(|s| !s.trim().is_empty()) {
preamble.push_str("\n\n");
preamble.push_str(extra.trim());
}
let child = Agent::new(
route.provider,
tools,
self.store.clone(),
preamble,
job.budget,
)
.with_context_budget(route.context_budget_tokens)
.with_max_malformed_calls(self.settings.max_malformed_calls)
.with_tool_concurrency(self.settings.tool_concurrency)
.with_lock_wait(self.settings.lock_wait)
.with_hooks(self.hooks.clone())
.with_turn_results(Arc::clone(&self.turn_results));
let usage = Mutex::new(Usage::default());
let marked = ChildApprover {
inner: approver,
route: &route.name,
};
let run = child
.run_cancellable(
Some(&session_id),
job.prompt,
&marked,
&|event| {
if let AgentEvent::TurnStats { usage: turn, .. } = event {
if let Ok(mut total) = usage.lock() {
total.add(&turn);
}
}
},
cancel,
)
.await;
let usage = usage.into_inner().unwrap_or_default();
outcome.prompt_tokens = usage.prompt;
outcome.completion_tokens = usage.completion;
outcome.iterations = usage.iterations;
outcome.answer = match run {
Ok(done) if !done.reply.trim().is_empty() => Ok(done.reply),
Ok(_) => Err("it finished without any text to return".to_string()),
Err(Error::MaxIterations(n)) => Err(format!(
"it used all {n} of its iterations without a final answer; raise \
`max_iterations` or split the job"
)),
Err(e) => Err(e.to_string()),
};
outcome
}
}
#[derive(Default)]
struct Usage {
prompt: Option<u64>,
completion: Option<u64>,
iterations: usize,
}
impl Usage {
fn add(&mut self, turn: &crate::usage::TurnUsage) {
self.iterations += 1;
self.prompt = sum([self.prompt, turn.prompt_tokens].into_iter());
self.completion = sum([self.completion, turn.completion_tokens].into_iter());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Policy, ToolsConfig};
use crate::message::Message;
use crate::message::{FunctionCall, ToolCall};
use crate::tools::{AllowAll, DenyAll, ToolSpec};
use crate::usage::TurnUsage;
struct Recording {
replies: Mutex<Vec<crate::error::Result<Message>>>,
seen: Mutex<Vec<Vec<Message>>>,
offered: Mutex<Vec<Vec<String>>>,
usage: Mutex<Option<TurnUsage>>,
reported: Option<(u64, u64)>,
}
impl Recording {
fn new(
mut replies: Vec<crate::error::Result<Message>>,
reported: Option<(u64, u64)>,
) -> Arc<Self> {
replies.reverse();
Arc::new(Self {
replies: Mutex::new(replies),
seen: Mutex::default(),
offered: Mutex::default(),
usage: Mutex::default(),
reported,
})
}
fn texts(&self) -> Vec<String> {
self.seen
.lock()
.unwrap()
.iter()
.flatten()
.filter_map(|m| m.content.clone())
.collect()
}
}
#[async_trait]
impl ChatProvider for Recording {
async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
self.seen.lock().unwrap().push(messages.to_vec());
self.offered
.lock()
.unwrap()
.push(tools.iter().map(|t| t.function.name.clone()).collect());
*self.usage.lock().unwrap() = self.reported.map(|(p, c)| TurnUsage {
prompt_tokens: Some(p),
completion_tokens: Some(c),
..TurnUsage::default()
});
self.replies
.lock()
.unwrap()
.pop()
.unwrap_or_else(|| Err(Error::Provider("script exhausted".into())))
}
fn take_usage(&self) -> Option<TurnUsage> {
self.usage.lock().unwrap().take()
}
}
struct Fixed {
routes: Vec<(String, Arc<dyn ChatProvider>)>,
default: String,
}
impl ChildProviders for Fixed {
fn routes(&self) -> Vec<RouteInfo> {
self.routes
.iter()
.map(|(n, _)| RouteInfo {
name: n.clone(),
model: format!("{n}-model"),
endpoint: String::new(),
})
.collect()
}
fn default_route(&self) -> String {
self.default.clone()
}
fn provider(&self, route: &str) -> Result<ChildRoute, String> {
let (name, provider) = self
.routes
.iter()
.find(|(n, _)| n == route)
.ok_or("no such route")?;
Ok(ChildRoute {
name: name.clone(),
provider: provider.clone(),
context_budget_tokens: 0,
})
}
}
fn tool_with(
routes: Vec<(&str, Arc<Recording>)>,
default: &str,
dir: &std::path::Path,
) -> DelegateTool {
let routes = routes
.into_iter()
.map(|(name, provider)| (name, provider as Arc<dyn ChatProvider>))
.collect();
tool_with_providers(routes, default, dir)
}
fn tool_with_providers(
routes: Vec<(&str, Arc<dyn ChatProvider>)>,
default: &str,
dir: &std::path::Path,
) -> DelegateTool {
let providers = Fixed {
routes: routes
.into_iter()
.map(|(n, p)| (n.to_string(), p))
.collect(),
default: default.to_string(),
};
let tools = ToolRegistry::from_config(&ToolsConfig::default(), dir.to_path_buf());
DelegateTool::new(
Arc::new(providers),
Arc::new(tools),
SessionStore::new(dir.join("sessions")),
DelegateSettings {
max_output_bytes: 4096,
max_malformed_calls: 3,
tool_concurrency: 1,
lock_wait: Duration::from_secs(1),
},
)
}
async fn call(
tool: &DelegateTool,
run: &crate::tools::RunScope,
approver: &dyn Approver,
args: Value,
) -> Result<String, ToolError> {
let registry = crate::tools::ToolRegistry::new(4096);
tool.call_scoped(
args,
&CallScope {
approver,
run,
registry: ®istry,
call_id: None,
},
)
.await
}
fn assistant_calling(tool: &str, args: &str) -> Message {
Message::assistant_tool_calls(
None,
vec![ToolCall {
id: "c1".into(),
kind: "function".into(),
function: FunctionCall {
name: tool.into(),
arguments: args.into(),
},
}],
)
}
#[tokio::test]
async fn the_childs_final_text_is_the_tool_result_with_its_own_usage_line() {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(vec![Ok(Message::assistant("the answer"))], Some((120, 7)));
let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
let run = crate::tools::RunScope::new("parent1");
let out = call(&tool, &run, &DenyAll, json!({"prompt": "work it out"}))
.await
.unwrap();
assert_eq!(
out,
"the answer\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration"
);
let children = run.children.runs();
assert_eq!(children.len(), 1);
assert_eq!(children[0].route, "big");
assert_eq!(
(children[0].prompt_tokens, children[0].completion_tokens),
(Some(120), Some(7))
);
assert!(!children[0].failed);
let child = tool.store.load(&children[0].session_id).unwrap();
assert_eq!(child.len(), 2);
assert_eq!(child[0].content.as_deref(), Some("work it out"));
let listed = tool.store.list().unwrap();
let info = listed
.iter()
.find(|s| s.id == children[0].session_id)
.unwrap();
let origin = info.subagent().unwrap();
assert_eq!((origin.parent, origin.route), ("parent1", "big"));
}
#[derive(Default)]
struct Hanging {
asked: Arc<tokio::sync::Notify>,
}
#[async_trait]
impl ChatProvider for Hanging {
async fn chat(&self, _messages: &[Message], _tools: &[ToolSpec]) -> crate::Result<Message> {
self.asked.notify_one();
tokio::time::sleep(Duration::from_secs(60)).await;
Ok(Message::assistant("too late"))
}
}
#[tokio::test]
async fn a_cancelled_parent_stops_the_child_run() {
let dir = tempfile::tempdir().unwrap();
let slow = Arc::new(Hanging::default());
let tool = tool_with_providers(
vec![("slow", Arc::clone(&slow) as Arc<dyn ChatProvider>)],
"slow",
dir.path(),
);
let cancel = crate::cancel::Cancel::new();
let run = crate::tools::RunScope::new("p").cancellable(&cancel);
let flag = cancel.clone();
let notifier = Arc::clone(&slow);
let canceller = tokio::spawn(async move {
notifier.asked.notified().await;
flag.cancel();
});
let started = std::time::Instant::now();
let outcome = tokio::time::timeout(
Duration::from_secs(10),
call(&tool, &run, &DenyAll, json!({"prompt": "work it out"})),
)
.await
.expect("the child stopped at the cancel, not at its own timeout");
canceller.abort();
assert!(
started.elapsed() < Duration::from_secs(10),
"the child kept working after the parent was cancelled"
);
let err = outcome.expect_err("a cancelled child has no answer to give");
assert!(
err.to_string().contains("cancelled"),
"the child's failure names the cancel: {err}"
);
let children = run.children.runs();
assert_eq!(children.len(), 1);
assert!(children[0].failed);
}
#[tokio::test]
async fn a_subagents_answer_arrives_as_a_tool_result_with_its_own_usage() {
let dir = tempfile::tempdir().unwrap();
let child = Recording::new(vec![Ok(Message::assistant("CHILD ANSWER"))], Some((120, 7)));
let tool = tool_with(vec![("big", child.clone())], "big", dir.path());
let mut registry = ToolRegistry::new(4096);
registry.register(Arc::new(tool), Policy::Ask);
let parent_provider = Recording::new(
vec![
Ok(assistant_calling(
"delegate",
r#"{"prompt":"find the thing","route":"big"}"#,
)),
Ok(Message::assistant("PARENT FINAL")),
],
Some((1000, 50)),
);
let store = SessionStore::new(dir.path().join("sessions"));
let agent = Agent::new(
parent_provider.clone(),
Arc::new(registry),
store.clone(),
"parent system".into(),
5,
);
let events = Mutex::new(Vec::new());
let run = agent
.run(None, "PARENT USER PROMPT", &AllowAll, &|e| {
events.lock().unwrap().push(e)
})
.await
.unwrap();
let events = events.into_inner().unwrap();
let want = "CHILD ANSWER\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration";
let result = events
.iter()
.find_map(|e| match e {
AgentEvent::ToolResult {
name,
output,
is_error,
..
} if name == "delegate" => Some((output.clone(), *is_error)),
_ => None,
})
.unwrap();
assert_eq!(result, (want.to_string(), false));
assert_eq!(run.reply, "PARENT FINAL");
let parent_prompt: u64 = events
.iter()
.filter_map(|e| match e {
AgentEvent::TurnStats { usage, .. } => usage.prompt_tokens,
_ => None,
})
.sum();
assert_eq!(parent_prompt, 2000);
assert_eq!(run.children.len(), 1);
assert_eq!(
(
run.children[0].route.as_str(),
run.children[0].prompt_tokens,
run.children[0].completion_tokens,
run.children[0].iterations,
),
("big", Some(120), Some(7), 1)
);
let parent = store.load(&run.session_id).unwrap();
let roles: Vec<_> = parent.iter().map(|m| m.role).collect();
assert_eq!(parent.len(), 4, "{roles:?}");
let parent_text: String = parent
.iter()
.map(|m| m.content.clone().unwrap_or_default())
.collect::<Vec<_>>()
.join("\n");
assert!(parent_text.contains(want), "{parent_text}");
assert!(!parent_text.contains("You are a subagent"), "{parent_text}");
assert!(!child.texts().iter().any(|t| t.contains("PARENT")));
assert!(child.texts().iter().any(|t| t == "find the thing"));
let child_row = store
.list()
.unwrap()
.into_iter()
.find(|s| s.id == run.children[0].session_id)
.unwrap();
assert_ne!(child_row.id, run.session_id);
assert_eq!(child_row.subagent().unwrap().parent, run.session_id);
}
fn parent_calling(
tool: DelegateTool,
dir: &std::path::Path,
calls: Vec<Message>,
concurrency: usize,
) -> (Agent, Arc<Recording>) {
let mut registry = ToolRegistry::new(4096);
registry.register(Arc::new(tool), Policy::Ask);
let mut replies = calls;
replies.push(Message::assistant("PARENT FINAL"));
let provider = Recording::new(replies.into_iter().map(Ok).collect(), None);
let agent = Agent::new(
provider.clone(),
Arc::new(registry),
SessionStore::new(dir.join("sessions")),
"parent".into(),
5,
)
.with_tool_concurrency(concurrency);
(agent, provider)
}
#[tokio::test]
async fn a_child_that_fails_is_a_tool_result_and_the_parent_run_carries_on() {
let dir = tempfile::tempdir().unwrap();
let broken = Recording::new(vec![Err(Error::Provider("HTTP 503".into()))], None);
let tool = tool_with(vec![("big", broken)], "big", dir.path());
let (agent, parent) = parent_calling(
tool,
dir.path(),
vec![assistant_calling("delegate", r#"{"prompt":"x"}"#)],
1,
);
let events = Mutex::new(Vec::new());
let run = agent
.run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
.await
.expect("the parent run does not fail with its child");
assert_eq!(run.reply, "PARENT FINAL");
let result = events
.into_inner()
.unwrap()
.into_iter()
.find_map(|e| match e {
AgentEvent::ToolResult {
output, is_error, ..
} => Some((output, is_error)),
_ => None,
})
.unwrap();
assert!(result.1, "a failed child is an error result");
assert!(
result.0.contains("failed") && result.0.contains("HTTP 503"),
"{}",
result.0
);
assert!(
parent.texts().iter().any(|t| t.contains("HTTP 503")),
"the model read the reason"
);
assert!(run.children[0].failed);
}
#[tokio::test]
async fn a_parent_that_asks_for_more_children_than_the_cap_in_one_turn_gets_the_cap_not_a_fifth(
) {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(
(0..MAX_CHILDREN_PER_RUN)
.map(|_| Ok(Message::assistant("ok")))
.collect(),
None,
);
let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
let many = Message::assistant_tool_calls(
None,
(0..MAX_CHILDREN_PER_RUN + 1)
.map(|i| ToolCall {
id: format!("c{i}"),
kind: "function".into(),
function: FunctionCall {
name: "delegate".into(),
arguments: r#"{"prompt":"x"}"#.into(),
},
})
.collect(),
);
let (agent, _) = parent_calling(tool, dir.path(), vec![many], MAX_CHILDREN_PER_RUN + 1);
let events = Mutex::new(Vec::new());
let run = agent
.run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
.await
.unwrap();
let results: Vec<bool> = events
.into_inner()
.unwrap()
.into_iter()
.filter_map(|e| match e {
AgentEvent::ToolResult { is_error, .. } => Some(is_error),
_ => None,
})
.collect();
assert_eq!(results.iter().filter(|e| **e).count(), 1, "{results:?}");
assert_eq!(run.children.len(), MAX_CHILDREN_PER_RUN);
assert_eq!(big.seen.lock().unwrap().len(), MAX_CHILDREN_PER_RUN);
}
#[tokio::test]
async fn a_child_is_told_what_it_is_and_given_only_the_job_and_the_callers_instructions() {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
let run = crate::tools::RunScope::new("p");
call(
&tool,
&run,
&DenyAll,
json!({"prompt": "JOB", "system": "ANSWER IN FRENCH"}),
)
.await
.unwrap();
let sent = big.seen.lock().unwrap()[0].clone();
let system = sent[0].content.clone().unwrap();
assert!(system.contains("You are a subagent"), "{system}");
assert!(system.ends_with("ANSWER IN FRENCH"), "{system}");
assert_eq!(
sent.len(),
2,
"the preamble and the prompt, nothing of the parent"
);
assert_eq!(sent[1].content.as_deref(), Some("JOB"));
}
#[tokio::test]
async fn a_child_that_reports_no_usage_says_so_instead_of_counting_zero() {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
let tool = tool_with(vec![("big", big)], "big", dir.path());
let out = call(
&tool,
&crate::tools::RunScope::new("p"),
&DenyAll,
json!({"prompt": "x"}),
)
.await
.unwrap();
assert!(
out.ends_with("child usage: tokens not reported by the server, 1 iteration"),
"{out}"
);
}
#[tokio::test]
async fn an_unknown_route_is_a_tool_error_listing_the_routes_that_exist() {
let dir = tempfile::tempdir().unwrap();
let tool = tool_with(
vec![
("big", Recording::new(vec![], None)),
("local", Recording::new(vec![], None)),
],
"big",
dir.path(),
);
let run = crate::tools::RunScope::new("p");
let e = call(
&tool,
&run,
&DenyAll,
json!({"prompt": "x", "route": "ghost"}),
)
.await
.unwrap_err();
assert!(matches!(e, ToolError::Failed(_)), "{e:?}");
let text = e.to_string();
assert!(
text.contains("unknown route `ghost`") && text.contains("big, local"),
"{text}"
);
assert!(
run.children.runs().is_empty(),
"a refused call spends no place"
);
}
#[tokio::test]
async fn the_n_plus_first_child_is_refused_with_a_reason_the_model_can_act_on() {
let dir = tempfile::tempdir().unwrap();
let replies = (0..MAX_CHILDREN_PER_RUN + 1)
.map(|_| Ok(Message::assistant("ok")))
.collect();
let tool = tool_with(
vec![("big", Recording::new(replies, None))],
"big",
dir.path(),
);
let run = crate::tools::RunScope::new("p");
for _ in 0..MAX_CHILDREN_PER_RUN {
call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
.await
.unwrap();
}
let e = call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
.await
.unwrap_err();
let text = e.to_string();
assert!(
text.contains(&format!("already started {MAX_CHILDREN_PER_RUN} subagents"))
&& text.contains("yourself"),
"{text}"
);
assert_eq!(run.children.runs().len(), MAX_CHILDREN_PER_RUN);
call(
&tool,
&crate::tools::RunScope::new("other"),
&DenyAll,
json!({"prompt": "x"}),
)
.await
.unwrap();
}
#[tokio::test]
async fn a_child_that_fails_comes_back_as_an_error_with_the_reason_and_its_cost() {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(
vec![
Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
],
Some((10, 1)),
);
let tool = tool_with(vec![("big", big)], "big", dir.path());
let run = crate::tools::RunScope::new("p");
let e = call(
&tool,
&run,
&DenyAll,
json!({"prompt": "x", "max_iterations": 2}),
)
.await
.unwrap_err();
let text = e.to_string();
assert!(
text.contains("failed")
&& text.contains("used all 2 of its iterations")
&& text.ends_with("child usage: 20 prompt / 2 completion tokens, 2 iterations"),
"{text}"
);
assert!(run.children.runs()[0].failed);
let broken = Recording::new(vec![Err(Error::Provider("HTTP 500".into()))], None);
let tool = tool_with(vec![("big", broken)], "big", dir.path());
let e = call(
&tool,
&crate::tools::RunScope::new("p"),
&DenyAll,
json!({"prompt": "x"}),
)
.await
.unwrap_err();
assert!(e.to_string().contains("HTTP 500"), "{e}");
}
#[tokio::test]
async fn a_child_is_offered_the_parents_tools_but_not_delegate() {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
call(
&tool,
&crate::tools::RunScope::new("p"),
&DenyAll,
json!({"prompt": "x"}),
)
.await
.unwrap();
let offered = big.offered.lock().unwrap()[0].clone();
assert!(offered.contains(&"read_file".to_string()), "{offered:?}");
assert!(!offered.contains(&"delegate".to_string()), "{offered:?}");
assert!(!tool
.tools
.advertised_names()
.contains(&"delegate".to_string()));
}
const FAKE_KEY: &str = "sk-proj-ZmFrZWtleWZvcnRlc3RzMDEyMzQ1Njc4OQ";
async fn child_reads_a_key(hooks: LoopHooks) -> (String, String, String) {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("env.txt"),
format!("key = {FAKE_KEY}\nplain\n"),
)
.unwrap();
let big = Recording::new(
vec![
Ok(assistant_calling("read_file", r#"{"path":"env.txt"}"#)),
Ok(Message::assistant("read it")),
],
None,
);
let tool = tool_with(vec![("big", big.clone())], "big", dir.path()).with_hooks(hooks);
let run = crate::tools::RunScope::new("parent");
call(&tool, &run, &DenyAll, json!({"prompt": "read env.txt"}))
.await
.unwrap();
let sent = big.seen.lock().unwrap()[1]
.iter()
.filter_map(|m| m.content.clone())
.collect::<Vec<_>>()
.join("\n");
let id = run.children.runs()[0].session_id.clone();
let stored = tool
.store
.load(&id)
.unwrap()
.iter()
.filter_map(|m| m.content.clone())
.collect::<Vec<_>>()
.join("\n");
(sent, stored, id)
}
#[tokio::test]
async fn a_childs_tool_output_is_redacted_when_the_parent_has_the_redact_hook() {
let cfg = crate::config::Config::from_toml_str("[hooks]\norder = [\"redact-secrets\"]\n")
.unwrap();
let hooks = crate::hooks::from_config_reporting(
&cfg,
&crate::session::SessionStore::new(
std::env::temp_dir().join(format!("eclipse-delegate-{}", std::process::id())),
),
crate::hooks::Reporting::to(Arc::new(|_| {})),
)
.unwrap();
assert_eq!(hooks.len(), 1);
let (sent, stored, _) = child_reads_a_key(hooks).await;
assert!(sent.contains("key = [redacted:api-key]"), "{sent}");
assert!(!sent.contains(FAKE_KEY), "the child's model read the key");
assert!(stored.contains("[redacted:api-key]"), "{stored}");
assert!(
!stored.contains(FAKE_KEY),
"the child's session stored the key"
);
}
#[tokio::test]
async fn a_child_with_no_hooks_reads_the_file_as_it_is() {
let (sent, stored, _) = child_reads_a_key(LoopHooks::default()).await;
assert!(sent.contains(FAKE_KEY), "{sent}");
assert!(stored.contains(FAKE_KEY), "{stored}");
}
#[derive(Default)]
struct Recorder(Mutex<Vec<(String, String)>>);
#[async_trait]
impl Approver for Recorder {
async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
self.0
.lock()
.unwrap()
.push((call.tool.clone(), call.summary.clone()));
crate::approvals::Decision::Deny("no".to_string())
}
}
#[tokio::test]
async fn a_childs_own_approvals_reach_the_same_approver_marked_as_the_childs() {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(
vec![
Ok(assistant_calling(
"shell",
r#"{"command":"rm -rf the-build"}"#,
)),
Ok(Message::assistant("it was declined")),
],
None,
);
let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
let approver = Recorder::default();
let out = call(
&tool,
&crate::tools::RunScope::new("p"),
&approver,
json!({"prompt": "x"}),
)
.await
.unwrap();
assert!(out.starts_with("it was declined"), "{out}");
let asked = approver.0.lock().unwrap().clone();
assert_eq!(asked.len(), 1, "{asked:?}");
assert_eq!(asked[0].0, "shell");
assert!(
asked[0].1.starts_with("[subagent on big] "),
"{}",
asked[0].1
);
assert!(
big.texts().iter().any(|t| t.contains("declined")),
"the child read the refusal as a tool result"
);
}
#[tokio::test]
async fn wrong_typed_arguments_are_invalid_args_naming_the_key() {
let dir = tempfile::tempdir().unwrap();
let tool = tool_with(
vec![("big", Recording::new(vec![], None))],
"big",
dir.path(),
);
let run = crate::tools::RunScope::new("p");
for (args, key) in [
(json!({}), "prompt"),
(json!({"prompt": 3}), "prompt"),
(json!({"prompt": " "}), "prompt"),
(json!({"prompt": "x", "route": 3}), "route"),
(json!({"prompt": "x", "system": []}), "system"),
(
json!({"prompt": "x", "max_iterations": "8"}),
"max_iterations",
),
(
json!({"prompt": "x", "max_iterations": 0}),
"max_iterations",
),
(
json!({"prompt": "x", "max_iterations": 21}),
"max_iterations",
),
(
json!({"prompt": "x", "max_iterations": 1.5}),
"max_iterations",
),
] {
let e = call(&tool, &run, &DenyAll, args.clone()).await.unwrap_err();
assert!(
matches!(e, ToolError::InvalidArgs(_)) && e.to_string().contains(key),
"{args}: {e}"
);
}
assert!(run.children.runs().is_empty());
}
#[test]
fn the_approval_summary_names_the_route_the_first_line_and_the_budget() {
let dir = tempfile::tempdir().unwrap();
let tool = tool_with(
vec![
("big", Recording::new(vec![], None)),
("local", Recording::new(vec![], None)),
],
"big",
dir.path(),
);
let s =
tool.describe_call(&json!({"prompt": "Audit the parser\nthen the lexer\nand more"}));
assert_eq!(
s,
"delegate to a subagent on route `big`: \"Audit the parser\" (+2 more lines) \
(up to 6 iterations)"
);
let s = tool.describe_call(
&json!({"prompt": "x", "route": "local", "max_iterations": 3, "system": "be brief"}),
);
assert!(
s.contains("route `local`")
&& s.contains("up to 3 iterations, with its own system prompt"),
"{s}"
);
let s = tool.describe_call(&json!({"prompt": 3, "route": 4, "max_iterations": "x"}));
assert!(
s.contains("(invalid route)") && s.contains("(invalid)"),
"{s}"
);
let long = "x".repeat(500);
assert!(tool.describe_call(&json!({ "prompt": long })).len() < 260);
}
#[test]
fn the_delegate_policy_defaults_to_ask() {
assert_eq!(ToolsConfig::default().delegate, Policy::Ask);
}
#[test]
fn the_description_lists_the_routes_and_says_which_is_the_default() {
let dir = tempfile::tempdir().unwrap();
let tool = tool_with(
vec![
("big", Recording::new(vec![], None)),
("local", Recording::new(vec![], None)),
],
"local",
dir.path(),
);
let d = tool.description();
assert!(
d.contains("`big` (big-model)") && d.contains("Default: `local`"),
"{d}"
);
}
#[tokio::test]
async fn an_answer_too_long_for_the_output_cap_is_cut_but_keeps_the_usage_line() {
let dir = tempfile::tempdir().unwrap();
let big = Recording::new(
vec![Ok(Message::assistant("a".repeat(10_000)))],
Some((5, 5)),
);
let tool = tool_with(vec![("big", big)], "big", dir.path());
let out = call(
&tool,
&crate::tools::RunScope::new("p"),
&AllowAll,
json!({"prompt": "x"}),
)
.await
.unwrap();
assert!(out.len() <= 4096, "{}", out.len());
assert!(out.contains("[output truncated]"));
assert!(out.ends_with("child usage: 5 prompt / 5 completion tokens, 1 iteration"));
}
#[test]
fn the_readout_sums_the_children_and_says_how_many_failed() {
assert_eq!(describe_children(&[]), None);
let run = |route: &str, p, c, i, failed| ChildRun {
route: route.into(),
session_id: "s".into(),
prompt_tokens: p,
completion_tokens: c,
iterations: i,
failed,
};
let one = describe_children(&[run("big", Some(100), Some(10), 2, false)]).unwrap();
assert_eq!(
one,
"delegated: 1 subagent (big) \u{2014} child usage: 100 prompt / 10 completion tokens, 2 iterations"
);
let two = describe_children(&[
run("big", Some(100), Some(10), 2, false),
run("local", None, None, 1, true),
])
.unwrap();
assert_eq!(
two,
"delegated: 2 subagents (big, local; 1 failed) \u{2014} child usage: 100 prompt / 10 completion tokens, 3 iterations"
);
let none = describe_children(&[run("big", None, None, 1, false)]).unwrap();
assert!(none.contains("tokens not reported by the server"), "{none}");
}
}