Skip to main content

eclipse_core/
tools_delegate.rs

1//! The `delegate` tool: hand one job to a child agent on a route of its own.
2//!
3//! A child is an [`Agent`], not a second loop. It has the provider of the route it was sent to,
4//! a session of its own that the parent never sees, a preamble that says what it is, a small
5//! iteration budget and the same tools as the parent minus this one. It runs to its final
6//! answer, and that text is the tool's result; what it cost is reported beside it, separately,
7//! so the parent's own usage line does not quietly absorb it.
8//!
9//! This is a cap, not a scheduler. A child cannot delegate (the tool is not in its registry), a
10//! run may start at most [`MAX_CHILDREN_PER_RUN`], and there is no queue, no background run and
11//! no write to the parent's session: the parent's transcript holds the call and the answer.
12//! A child that fails is a tool result with the reason, which the model reads like any other.
13
14use crate::config::NamedRoute;
15use crate::error::Error;
16use crate::hooks::LoopHooks;
17use crate::provider::{ChatProvider, OpenAiProvider, ProviderProfile};
18use crate::router::RouteInfo;
19use crate::runtime::{Agent, AgentEvent};
20use crate::session::SessionStore;
21use crate::tools::{truncate, Approver, CallScope, Tool, ToolError, ToolRegistry};
22use async_trait::async_trait;
23use serde_json::{json, Value};
24use std::sync::{Arc, Mutex};
25use std::time::Duration;
26
27/// The most children one run may start. A child is a request to a possibly bigger model that
28/// may run tools, so the bound is on spend, and four is room for a few independent jobs
29/// without leaving a model free to fan out on every turn.
30pub const MAX_CHILDREN_PER_RUN: usize = 4;
31
32/// The budget a child gets when the call names none. Each iteration is a request to a
33/// possibly big model; six is enough to look at a few things and answer, and short enough
34/// that a child that is wandering is stopped before it is expensive.
35pub const DEFAULT_CHILD_ITERATIONS: usize = 6;
36
37/// The most a call may ask for. A job that needs more is a job to split.
38pub const MAX_CHILD_ITERATIONS: usize = 20;
39
40/// How much of a prompt's first line the approval summary shows, in characters.
41const SUMMARY_PROMPT_CHARS: usize = 100;
42
43/// What the child is told it is. The parent's own system prompt, context files, skills and
44/// memory are deliberately not passed on: the child sees the job, not the conversation.
45const PREAMBLE: &str = "You are a subagent. Another agent handed you one job and will read \
46only your final message, so make that message the answer itself: no greeting, no recap of \
47what you did unless it matters, no questions back. You cannot ask the user anything and you \
48cannot delegate. Use the tools you have to do the job, and finish within your iteration \
49budget.";
50
51/// A route as a child needs it: a provider of its own and the per-agent settings that belong
52/// to that route.
53pub struct ChildRoute {
54    pub name: String,
55    pub provider: Arc<dyn ChatProvider>,
56    pub context_budget_tokens: usize,
57}
58
59/// Where children get their providers. A trait so the tool can be tested without a server and
60/// so it never holds the configuration itself.
61pub trait ChildProviders: Send + Sync {
62    /// The routes a call may name, in the order they are listed to the model.
63    fn routes(&self) -> Vec<RouteInfo>;
64    /// The route a call that names none goes to.
65    fn default_route(&self) -> String;
66    /// A provider for `route`, fresh for this child: a provider holds the usage of its last
67    /// request, so two children sharing one would read each other's cost.
68    fn provider(&self, route: &str) -> Result<ChildRoute, String>;
69    /// Why `route` cannot be used here even though it exists. Only a pin has something to say:
70    /// answering "unknown route" about a route the user did configure would send the model
71    /// hunting for a name it already knows.
72    fn refusal(&self, _route: &str) -> Option<String> {
73        None
74    }
75}
76
77/// [`ChildProviders`] over the configuration's routes.
78pub struct ConfigRoutes {
79    routes: Vec<NamedRoute>,
80    profiles: Vec<ProviderProfile>,
81    /// `[provider] delegate`: the route a call with no `route` goes to.
82    delegate: Option<String>,
83    /// The route the parent's run is on, which a call with no `route` goes to when the config
84    /// names none.
85    selected: String,
86    /// `--route` / `ECLIPSE_ROUTE`, when the run is pinned: the one route text may go to. A pin
87    /// bounds where the run's text may go, so under it only this route is offered to the model
88    /// and naming another is refused — the pin would mean nothing if the model could ask for a
89    /// subagent elsewhere.
90    pinned: Option<String>,
91    /// `--model` / `/model`, shared with the agent: it changes the selected route's model.
92    model: Arc<Mutex<Option<String>>>,
93}
94
95impl ConfigRoutes {
96    pub fn new(
97        routes: Vec<NamedRoute>,
98        profiles: Vec<ProviderProfile>,
99        delegate: Option<String>,
100        selected: String,
101        pinned: Option<String>,
102        model: Arc<Mutex<Option<String>>>,
103    ) -> Self {
104        Self {
105            routes,
106            profiles,
107            delegate,
108            selected,
109            pinned,
110            model,
111        }
112    }
113}
114
115impl ChildProviders for ConfigRoutes {
116    fn routes(&self) -> Vec<RouteInfo> {
117        self.routes
118            .iter()
119            .filter(|r| match &self.pinned {
120                Some(pinned) => &r.name == pinned,
121                None => true,
122            })
123            .map(|r| RouteInfo {
124                name: r.name.clone(),
125                model: r.config.model.clone(),
126                endpoint: r.config.base_url.clone(),
127            })
128            .collect()
129    }
130
131    fn default_route(&self) -> String {
132        self.delegate
133            .clone()
134            .unwrap_or_else(|| self.selected.clone())
135    }
136
137    fn refusal(&self, route: &str) -> Option<String> {
138        let pinned = self.pinned.as_deref()?;
139        if route == pinned || !self.routes.iter().any(|r| r.name == route) {
140            return None;
141        }
142        Some(format!(
143            "this run is pinned to `{pinned}` with --route, so a subagent cannot be sent to \
144             `{route}`. Drop `route`, or drop the pin."
145        ))
146    }
147
148    fn provider(&self, route: &str) -> Result<ChildRoute, String> {
149        if let Some(why) = self.refusal(route) {
150            return Err(why);
151        }
152        let named = self
153            .routes
154            .iter()
155            .find(|r| r.name == route)
156            .ok_or_else(|| format!("route `{route}` is not configured"))?;
157        let mut cfg = named.config.clone();
158        if route == self.selected {
159            if let Some(model) = self.model.lock().ok().and_then(|m| m.clone()) {
160                cfg.model = model;
161            }
162        }
163        if cfg.base_url.trim().is_empty() || cfg.model.trim().is_empty() {
164            return Err(format!("route `{route}` has no base_url or no model"));
165        }
166        let provider = OpenAiProvider::with_profiles(&cfg, &self.profiles)
167            .map_err(|e| format!("route `{route}`: {e}"))?;
168        Ok(ChildRoute {
169            name: route.to_string(),
170            provider: Arc::new(provider),
171            context_budget_tokens: cfg.context_budget_tokens,
172        })
173    }
174}
175
176/// What one child cost and how it ended.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct ChildRun {
179    pub route: String,
180    /// The child's own session, which `eclipse sessions list` shows as a subagent's.
181    pub session_id: String,
182    pub prompt_tokens: Option<u64>,
183    pub completion_tokens: Option<u64>,
184    /// Requests the child made to its model.
185    pub iterations: usize,
186    pub failed: bool,
187}
188
189/// The children one run has started: how many (the cap), and what each cost (the readout).
190/// One per run, so two runs on one agent do not share a cap.
191#[derive(Default)]
192pub struct ChildLedger {
193    started: Mutex<usize>,
194    runs: Mutex<Vec<ChildRun>>,
195}
196
197impl ChildLedger {
198    /// Claim a place for one more child, or `None` when the run is at the cap. Claimed before
199    /// the child starts, so calls running at the same time cannot get past it together.
200    fn reserve(&self) -> Option<()> {
201        let mut started = self.started.lock().ok()?;
202        (*started < MAX_CHILDREN_PER_RUN).then(|| *started += 1)
203    }
204
205    fn record(&self, run: ChildRun) {
206        if let Ok(mut runs) = self.runs.lock() {
207            runs.push(run);
208        }
209    }
210
211    /// The children that have finished, in the order they finished.
212    pub fn runs(&self) -> Vec<ChildRun> {
213        self.runs.lock().map(|r| r.clone()).unwrap_or_default()
214    }
215}
216
217fn sum(values: impl Iterator<Item = Option<u64>>) -> Option<u64> {
218    values.flatten().reduce(|a, b| a.saturating_add(b))
219}
220
221fn count_tokens(n: Option<u64>) -> String {
222    n.map_or_else(|| "?".to_string(), |n| n.to_string())
223}
224
225fn usage_line(prompt: Option<u64>, completion: Option<u64>, iterations: usize) -> String {
226    let iterations = format!(
227        "{iterations} iteration{}",
228        if iterations == 1 { "" } else { "s" }
229    );
230    if prompt.is_none() && completion.is_none() {
231        return format!("child usage: tokens not reported by the server, {iterations}");
232    }
233    format!(
234        "child usage: {} prompt / {} completion tokens, {iterations}",
235        count_tokens(prompt),
236        count_tokens(completion)
237    )
238}
239
240/// The line a run that delegated prints beside its own usage, or `None` when nothing was
241/// delegated. The children's cost is summed here and nowhere else, so it is never merged into
242/// the parent's token count.
243pub fn describe_children(children: &[ChildRun]) -> Option<String> {
244    if children.is_empty() {
245        return None;
246    }
247    let routes: Vec<&str> = children.iter().map(|c| c.route.as_str()).collect();
248    let failed = children.iter().filter(|c| c.failed).count();
249    let usage = usage_line(
250        sum(children.iter().map(|c| c.prompt_tokens)),
251        sum(children.iter().map(|c| c.completion_tokens)),
252        children.iter().map(|c| c.iterations).sum(),
253    );
254    Some(format!(
255        "delegated: {} subagent{} ({}{}) \u{2014} {usage}",
256        children.len(),
257        if children.len() == 1 { "" } else { "s" },
258        routes.join(", "),
259        if failed == 0 {
260            String::new()
261        } else {
262            format!("; {failed} failed")
263        }
264    ))
265}
266
267/// Puts the route in front of a child's approval requests, so a prompt for a child's `shell`
268/// says whose it is. Approving `delegate` is not approving what the child then does.
269struct ChildApprover<'a> {
270    inner: &'a dyn Approver,
271    route: &'a str,
272}
273
274#[async_trait]
275impl Approver for ChildApprover<'_> {
276    async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
277        let marked = crate::approvals::Pending::new(
278            call.call_id.clone(),
279            call.tool.clone(),
280            format!("[subagent on {}] {}", self.route, call.summary),
281            call.args.clone(),
282        );
283        self.inner.decide(&marked).await
284    }
285}
286
287/// What a child is built with that does not depend on the call.
288pub struct DelegateSettings {
289    pub max_output_bytes: usize,
290    pub max_malformed_calls: usize,
291    pub tool_concurrency: usize,
292    pub lock_wait: Duration,
293}
294
295pub struct DelegateTool {
296    providers: Arc<dyn ChildProviders>,
297    /// The registry every child gets: the parent's, built the same way, without this tool.
298    tools: Arc<ToolRegistry>,
299    store: SessionStore,
300    settings: DelegateSettings,
301    /// The loop hooks every child runs with: the parent's, so a child's tool output is
302    /// redacted the same way, and into the child's own stored transcript.
303    hooks: LoopHooks,
304    /// The child's per-turn tool-result buffer for `memory` taint detection (`#482`), isolated
305    /// from the parent's turn.
306    turn_results: Arc<crate::tools_memory::TurnResults>,
307    description: String,
308}
309
310impl DelegateTool {
311    pub fn new(
312        providers: Arc<dyn ChildProviders>,
313        tools: Arc<ToolRegistry>,
314        store: SessionStore,
315        settings: DelegateSettings,
316    ) -> Self {
317        let routes = providers.routes();
318        let listed: Vec<String> = routes
319            .iter()
320            .map(|r| format!("`{}` ({})", r.name, r.model))
321            .collect();
322        let description = format!(
323            "Hand one self-contained job to a subagent and get its final answer back as this \
324             tool's result. The subagent sees only `prompt` (and `system`), not this \
325             conversation, so put everything it needs in the prompt. It has the same tools as \
326             you except `delegate`, a small iteration budget (default {DEFAULT_CHILD_ITERATIONS}, \
327             at most {MAX_CHILD_ITERATIONS}), and a run may start at most \
328             {MAX_CHILDREN_PER_RUN} of them. Worth it for a large, separable job that can be \
329             stated completely, or one that suits a different model; not for a lookup you can do \
330             yourself. `route` picks the model: {}. Default: `{}`.",
331            if listed.is_empty() {
332                "none configured".to_string()
333            } else {
334                listed.join(", ")
335            },
336            providers.default_route(),
337        );
338        Self {
339            providers,
340            tools,
341            store,
342            settings,
343            hooks: LoopHooks::default(),
344            turn_results: Arc::default(),
345            description,
346        }
347    }
348
349    /// Give every child these loop hooks. Without this a subagent would be the one place a
350    /// tool result reaches a model unfiltered.
351    pub fn with_hooks(mut self, hooks: LoopHooks) -> Self {
352        self.hooks = hooks;
353        self
354    }
355
356    /// Share the child registry's per-turn tool-result buffer with the child [`Agent`].
357    pub fn with_turn_results(
358        mut self,
359        turn_results: Arc<crate::tools_memory::TurnResults>,
360    ) -> Self {
361        self.turn_results = turn_results;
362        self
363    }
364
365    fn known_routes(&self) -> String {
366        let names: Vec<String> = self
367            .providers
368            .routes()
369            .into_iter()
370            .map(|r| r.name)
371            .collect();
372        if names.is_empty() {
373            "none".to_string()
374        } else {
375            names.join(", ")
376        }
377    }
378
379    /// The route a call goes to: the one it names, else the configured default.
380    fn resolve_route(&self, args: &Value) -> Result<String, ToolError> {
381        match args.get("route") {
382            None | Some(Value::Null) => Ok(self.providers.default_route()),
383            Some(Value::String(name)) => {
384                if let Some(why) = self.providers.refusal(name) {
385                    return Err(ToolError::Failed(why));
386                }
387                let known = self.providers.routes();
388                if known.iter().any(|r| &r.name == name) {
389                    Ok(name.clone())
390                } else {
391                    Err(ToolError::Failed(format!(
392                        "unknown route `{name}`. Routes that exist: {}",
393                        self.known_routes()
394                    )))
395                }
396            }
397            Some(_) => Err(ToolError::InvalidArgs("`route` must be a string".into())),
398        }
399    }
400}
401
402fn optional_string<'a>(args: &'a Value, key: &str) -> Result<Option<&'a str>, ToolError> {
403    match args.get(key) {
404        None | Some(Value::Null) => Ok(None),
405        Some(Value::String(s)) => Ok(Some(s)),
406        Some(_) => Err(ToolError::InvalidArgs(format!("`{key}` must be a string"))),
407    }
408}
409
410fn budget_arg(args: &Value) -> Result<usize, ToolError> {
411    match args.get("max_iterations") {
412        None | Some(Value::Null) => Ok(DEFAULT_CHILD_ITERATIONS),
413        Some(v) => match v.as_u64() {
414            Some(n) if (1..=MAX_CHILD_ITERATIONS as u64).contains(&n) => Ok(n as usize),
415            _ => Err(ToolError::InvalidArgs(format!(
416                "`max_iterations` must be a whole number from 1 to {MAX_CHILD_ITERATIONS}"
417            ))),
418        },
419    }
420}
421
422/// The first line of a prompt for a one-line summary: control characters removed and cut to
423/// [`SUMMARY_PROMPT_CHARS`]; with how many further lines there are.
424fn first_line(prompt: &str) -> (String, usize) {
425    let mut lines = prompt.trim().lines();
426    let first: String = lines
427        .next()
428        .unwrap_or_default()
429        .chars()
430        .filter(|c| !c.is_control())
431        .collect();
432    let mut chars = first.chars();
433    let mut out: String = chars.by_ref().take(SUMMARY_PROMPT_CHARS).collect();
434    if chars.next().is_some() {
435        out.push_str("...");
436    }
437    (out, lines.count())
438}
439
440/// Where a child's session says it came from (`#171`): `delegate` records a subagent of the
441/// parent, and a flare records the run and its position in it.
442pub(crate) enum ChildOrigin<'a> {
443    Subagent { parent: &'a str, route: &'a str },
444    Flare { run: &'a str, n: usize },
445}
446
447/// One child's job: the words it was given, the route it runs on, and what it may spend.
448pub(crate) struct ChildJob<'a> {
449    pub prompt: &'a str,
450    pub system: Option<&'a str>,
451    pub route: &'a str,
452    pub budget: usize,
453    pub origin: ChildOrigin<'a>,
454    /// Made by the caller, not here: a flare run's ledger names the child's session before the
455    /// child exists, so a run that is cancelled mid-flight can still be listed.
456    pub session_id: &'a str,
457}
458
459/// What a child cost and what it said — the one shape both surfaces report (`#171`).
460///
461/// A failure is a value rather than an `Err`, because `delegate` turns it into a tool result and a
462/// flare run turns it into one line of its table: neither wants to lose the cost of a child that
463/// tried.
464pub struct ChildOutcome {
465    pub route: String,
466    pub session_id: String,
467    pub answer: std::result::Result<String, String>,
468    pub prompt_tokens: Option<u64>,
469    pub completion_tokens: Option<u64>,
470    pub iterations: usize,
471}
472
473impl ChildOutcome {
474    pub fn failed(&self) -> bool {
475        self.answer.is_err()
476    }
477}
478
479#[async_trait]
480impl Tool for DelegateTool {
481    fn name(&self) -> &str {
482        "delegate"
483    }
484
485    fn description(&self) -> &str {
486        &self.description
487    }
488
489    fn parameters(&self) -> Value {
490        json!({
491            "type": "object",
492            "properties": {
493                "prompt": {
494                    "type": "string",
495                    "description": "The whole job, stated so it makes sense with no other context."
496                },
497                "route": {
498                    "type": "string",
499                    "description": "Which route (model) the subagent runs on. Unset: the \
500                                    configured delegate route, else the route this run is on."
501                },
502                "system": {
503                    "type": "string",
504                    "description": "Extra instructions for the subagent, added to its preamble."
505                },
506                "max_iterations": {
507                    "type": "integer",
508                    "minimum": 1,
509                    "maximum": MAX_CHILD_ITERATIONS,
510                    "description": format!(
511                        "How many model requests the subagent may make (default {DEFAULT_CHILD_ITERATIONS})."
512                    )
513                }
514            },
515            "required": ["prompt"]
516        })
517    }
518
519    /// The route, the prompt's first line and the budget: enough to decide on. Written to
520    /// survive arguments of the wrong type, because it runs before they are checked.
521    fn describe_call(&self, args: &Value) -> String {
522        let route = match args.get("route") {
523            None | Some(Value::Null) => self.providers.default_route(),
524            Some(Value::String(s)) => s.clone(),
525            Some(_) => "(invalid route)".to_string(),
526        };
527        let prompt = args.get("prompt").and_then(Value::as_str).unwrap_or("");
528        let budget = match budget_arg(args) {
529            Ok(n) => n.to_string(),
530            Err(_) => "(invalid)".to_string(),
531        };
532        let custom = match args.get("system") {
533            Some(Value::String(s)) if !s.trim().is_empty() => ", with its own system prompt",
534            _ => "",
535        };
536        let (line, more) = first_line(prompt);
537        let more = match more {
538            0 => String::new(),
539            1 => " (+1 more line)".to_string(),
540            n => format!(" (+{n} more lines)"),
541        };
542        format!(
543            "delegate to a subagent on route `{route}`: \"{line}\"{more} \
544             (up to {budget} iterations{custom})"
545        )
546    }
547
548    async fn call(&self, _args: Value) -> Result<String, ToolError> {
549        Err(ToolError::Failed(
550            "`delegate` only runs inside an agent run".into(),
551        ))
552    }
553
554    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
555        let prompt = crate::tools::str_arg(&args, "prompt")?;
556        if prompt.trim().is_empty() {
557            return Err(ToolError::InvalidArgs("`prompt` is empty".into()));
558        }
559        let system = optional_string(&args, "system")?;
560        let budget = budget_arg(&args)?;
561        let route_name = self.resolve_route(&args)?;
562
563        if scope.run.children.reserve().is_none() {
564            return Err(ToolError::Failed(format!(
565                "this run has already started {MAX_CHILDREN_PER_RUN} subagents, which is the \
566                 most one run may start. Do the remaining work yourself, or put it in one \
567                 prompt to a subagent you already have the answer from."
568            )));
569        }
570
571        // The same child a flare is (`#171`), on the same code path: what differs is the origin
572        // string, the budget and whether `delegate`'s cap counted it.
573        let session_id = self.store.new_id();
574        let outcome = self
575            .run_child(
576                Arc::clone(&self.tools),
577                ChildJob {
578                    session_id: &session_id,
579                    prompt,
580                    system,
581                    route: &route_name,
582                    budget,
583                    origin: ChildOrigin::Subagent {
584                        parent: &scope.run.session,
585                        route: &route_name,
586                    },
587                },
588                scope.approver,
589                &scope.run.cancel,
590            )
591            .await;
592        scope.run.children.record(ChildRun {
593            route: outcome.route.clone(),
594            session_id: outcome.session_id.clone(),
595            prompt_tokens: outcome.prompt_tokens,
596            completion_tokens: outcome.completion_tokens,
597            iterations: outcome.iterations,
598            failed: outcome.failed(),
599        });
600        let footer = usage_line(
601            outcome.prompt_tokens,
602            outcome.completion_tokens,
603            outcome.iterations,
604        );
605        match outcome.answer {
606            Ok(reply) => {
607                // The answer is cut to leave room for the footer, which must survive.
608                let note = "\n[output truncated]".len();
609                let room = self
610                    .settings
611                    .max_output_bytes
612                    .saturating_sub(footer.len() + 2 + note);
613                Ok(format!("{}\n\n{footer}", truncate(reply, room)))
614            }
615            Err(reason) => Err(ToolError::Failed(format!(
616                "the subagent on route `{}` failed: {reason}\n\n{footer}",
617                outcome.route
618            ))),
619        }
620    }
621}
622
623impl DelegateTool {
624    /// The registry a flare runs with: the child registry with the write tools **removed**
625    /// (`#171`). Here rather than in `flares.rs` because this is the one place that knows what a
626    /// child gets, so it is the one place that should know what a flare does not.
627    pub(crate) fn flare_registry(&self) -> ToolRegistry {
628        self.tools.without(crate::flares::WRITE_TOOLS)
629    }
630
631    /// The route a child goes to when the call names none — a flare run needs the same answer a
632    /// `delegate` call gets, so it asks here rather than resolving it a second way.
633    pub(crate) fn default_route(&self) -> String {
634        self.providers.default_route()
635    }
636
637    /// The next child's session id, for a caller that has to name it before the child starts.
638    pub(crate) fn new_session_id(&self) -> String {
639        self.store.new_id()
640    }
641
642    /// Run one child to its final answer, on `tools` rather than necessarily this tool's own
643    /// registry (`#171`): a flare gets a registry with the write tools taken out.
644    ///
645    /// `delegate` and a flare run are the same engine with two callers — the child is an
646    /// [`Agent`], it gets its own session, its own route, the same hooks and the same turn-results
647    /// buffer, and only what it was told and what it may spend differ. Keeping that in one place
648    /// is the whole reason a flare run is not a second runtime.
649    pub(crate) async fn run_child(
650        &self,
651        tools: Arc<ToolRegistry>,
652        job: ChildJob<'_>,
653        approver: &dyn Approver,
654        cancel: &crate::cancel::Cancel,
655    ) -> ChildOutcome {
656        let session_id = job.session_id.to_string();
657        let mut outcome = ChildOutcome {
658            route: job.route.to_string(),
659            session_id: session_id.clone(),
660            answer: Err("the subagent could not start".to_string()),
661            prompt_tokens: None,
662            completion_tokens: None,
663            iterations: 0,
664        };
665        let route = match self.providers.provider(job.route) {
666            Ok(route) => route,
667            Err(reason) => {
668                outcome.answer = Err(format!("the subagent could not start: {reason}"));
669                return outcome;
670            }
671        };
672        outcome.route = route.name.clone();
673        let begun = match job.origin {
674            ChildOrigin::Subagent { parent, route } => {
675                self.store.begin_subagent(&session_id, parent, route)
676            }
677            ChildOrigin::Flare { run, n } => self.store.begin_flare(&session_id, run, n),
678        };
679        if let Err(e) = begun {
680            outcome.answer = Err(format!("the subagent could not start: {e}"));
681            return outcome;
682        }
683
684        let mut preamble = PREAMBLE.to_string();
685        if let Some(extra) = job.system.filter(|s| !s.trim().is_empty()) {
686            preamble.push_str("\n\n");
687            preamble.push_str(extra.trim());
688        }
689        let child = Agent::new(
690            route.provider,
691            tools,
692            self.store.clone(),
693            preamble,
694            job.budget,
695        )
696        .with_context_budget(route.context_budget_tokens)
697        .with_max_malformed_calls(self.settings.max_malformed_calls)
698        .with_tool_concurrency(self.settings.tool_concurrency)
699        .with_lock_wait(self.settings.lock_wait)
700        .with_hooks(self.hooks.clone())
701        .with_turn_results(Arc::clone(&self.turn_results));
702
703        let usage = Mutex::new(Usage::default());
704        let marked = ChildApprover {
705            inner: approver,
706            route: &route.name,
707        };
708        // The parent's flag, not a fresh one: a cancelled run has to stop the work it started, and
709        // a child agent keeps calling the model for minutes if nobody tells it.
710        let run = child
711            .run_cancellable(
712                Some(&session_id),
713                job.prompt,
714                &marked,
715                &|event| {
716                    if let AgentEvent::TurnStats { usage: turn, .. } = event {
717                        if let Ok(mut total) = usage.lock() {
718                            total.add(&turn);
719                        }
720                    }
721                },
722                cancel,
723            )
724            .await;
725        let usage = usage.into_inner().unwrap_or_default();
726        outcome.prompt_tokens = usage.prompt;
727        outcome.completion_tokens = usage.completion;
728        outcome.iterations = usage.iterations;
729        outcome.answer = match run {
730            Ok(done) if !done.reply.trim().is_empty() => Ok(done.reply),
731            Ok(_) => Err("it finished without any text to return".to_string()),
732            Err(Error::MaxIterations(n)) => Err(format!(
733                "it used all {n} of its iterations without a final answer; raise \
734                 `max_iterations` or split the job"
735            )),
736            Err(e) => Err(e.to_string()),
737        };
738        outcome
739    }
740}
741
742#[derive(Default)]
743struct Usage {
744    prompt: Option<u64>,
745    completion: Option<u64>,
746    iterations: usize,
747}
748
749impl Usage {
750    fn add(&mut self, turn: &crate::usage::TurnUsage) {
751        self.iterations += 1;
752        self.prompt = sum([self.prompt, turn.prompt_tokens].into_iter());
753        self.completion = sum([self.completion, turn.completion_tokens].into_iter());
754    }
755}
756
757#[cfg(test)]
758mod tests {
759    use super::*;
760    use crate::config::{Policy, ToolsConfig};
761    use crate::message::Message;
762    use crate::message::{FunctionCall, ToolCall};
763    use crate::tools::{AllowAll, DenyAll, ToolSpec};
764    use crate::usage::TurnUsage;
765
766    /// Answers from a script and keeps what it was sent, and what tools it was offered.
767    struct Recording {
768        replies: Mutex<Vec<crate::error::Result<Message>>>,
769        seen: Mutex<Vec<Vec<Message>>>,
770        offered: Mutex<Vec<Vec<String>>>,
771        usage: Mutex<Option<TurnUsage>>,
772        reported: Option<(u64, u64)>,
773    }
774
775    impl Recording {
776        fn new(
777            mut replies: Vec<crate::error::Result<Message>>,
778            reported: Option<(u64, u64)>,
779        ) -> Arc<Self> {
780            replies.reverse();
781            Arc::new(Self {
782                replies: Mutex::new(replies),
783                seen: Mutex::default(),
784                offered: Mutex::default(),
785                usage: Mutex::default(),
786                reported,
787            })
788        }
789        fn texts(&self) -> Vec<String> {
790            self.seen
791                .lock()
792                .unwrap()
793                .iter()
794                .flatten()
795                .filter_map(|m| m.content.clone())
796                .collect()
797        }
798    }
799
800    #[async_trait]
801    impl ChatProvider for Recording {
802        async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
803            self.seen.lock().unwrap().push(messages.to_vec());
804            self.offered
805                .lock()
806                .unwrap()
807                .push(tools.iter().map(|t| t.function.name.clone()).collect());
808            *self.usage.lock().unwrap() = self.reported.map(|(p, c)| TurnUsage {
809                prompt_tokens: Some(p),
810                completion_tokens: Some(c),
811                ..TurnUsage::default()
812            });
813            self.replies
814                .lock()
815                .unwrap()
816                .pop()
817                .unwrap_or_else(|| Err(Error::Provider("script exhausted".into())))
818        }
819        fn take_usage(&self) -> Option<TurnUsage> {
820            self.usage.lock().unwrap().take()
821        }
822    }
823
824    struct Fixed {
825        routes: Vec<(String, Arc<dyn ChatProvider>)>,
826        default: String,
827    }
828
829    impl ChildProviders for Fixed {
830        fn routes(&self) -> Vec<RouteInfo> {
831            self.routes
832                .iter()
833                .map(|(n, _)| RouteInfo {
834                    name: n.clone(),
835                    model: format!("{n}-model"),
836                    endpoint: String::new(),
837                })
838                .collect()
839        }
840        fn default_route(&self) -> String {
841            self.default.clone()
842        }
843        fn provider(&self, route: &str) -> Result<ChildRoute, String> {
844            let (name, provider) = self
845                .routes
846                .iter()
847                .find(|(n, _)| n == route)
848                .ok_or("no such route")?;
849            Ok(ChildRoute {
850                name: name.clone(),
851                provider: provider.clone(),
852                context_budget_tokens: 0,
853            })
854        }
855    }
856
857    fn tool_with(
858        routes: Vec<(&str, Arc<Recording>)>,
859        default: &str,
860        dir: &std::path::Path,
861    ) -> DelegateTool {
862        let routes = routes
863            .into_iter()
864            .map(|(name, provider)| (name, provider as Arc<dyn ChatProvider>))
865            .collect();
866        tool_with_providers(routes, default, dir)
867    }
868
869    fn tool_with_providers(
870        routes: Vec<(&str, Arc<dyn ChatProvider>)>,
871        default: &str,
872        dir: &std::path::Path,
873    ) -> DelegateTool {
874        let providers = Fixed {
875            routes: routes
876                .into_iter()
877                .map(|(n, p)| (n.to_string(), p))
878                .collect(),
879            default: default.to_string(),
880        };
881        let tools = ToolRegistry::from_config(&ToolsConfig::default(), dir.to_path_buf());
882        DelegateTool::new(
883            Arc::new(providers),
884            Arc::new(tools),
885            SessionStore::new(dir.join("sessions")),
886            DelegateSettings {
887                max_output_bytes: 4096,
888                max_malformed_calls: 3,
889                tool_concurrency: 1,
890                lock_wait: Duration::from_secs(1),
891            },
892        )
893    }
894
895    /// Runs `args` as the model of a parent run on session `parent` would.
896    async fn call(
897        tool: &DelegateTool,
898        run: &crate::tools::RunScope,
899        approver: &dyn Approver,
900        args: Value,
901    ) -> Result<String, ToolError> {
902        // `delegate` reads the approver and the run, never the registry: the empty one here is
903        // a placeholder for a tool that does not route.
904        let registry = crate::tools::ToolRegistry::new(4096);
905        tool.call_scoped(
906            args,
907            &CallScope {
908                approver,
909                run,
910                registry: &registry,
911                call_id: None,
912            },
913        )
914        .await
915    }
916
917    fn assistant_calling(tool: &str, args: &str) -> Message {
918        Message::assistant_tool_calls(
919            None,
920            vec![ToolCall {
921                id: "c1".into(),
922                kind: "function".into(),
923                function: FunctionCall {
924                    name: tool.into(),
925                    arguments: args.into(),
926                },
927            }],
928        )
929    }
930
931    #[tokio::test]
932    async fn the_childs_final_text_is_the_tool_result_with_its_own_usage_line() {
933        let dir = tempfile::tempdir().unwrap();
934        let big = Recording::new(vec![Ok(Message::assistant("the answer"))], Some((120, 7)));
935        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
936        let run = crate::tools::RunScope::new("parent1");
937        let out = call(&tool, &run, &DenyAll, json!({"prompt": "work it out"}))
938            .await
939            .unwrap();
940        assert_eq!(
941            out,
942            "the answer\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration"
943        );
944        let children = run.children.runs();
945        assert_eq!(children.len(), 1);
946        assert_eq!(children[0].route, "big");
947        assert_eq!(
948            (children[0].prompt_tokens, children[0].completion_tokens),
949            (Some(120), Some(7))
950        );
951        assert!(!children[0].failed);
952        // The child's own session holds its prompt and its answer, and says whose it is.
953        let child = tool.store.load(&children[0].session_id).unwrap();
954        assert_eq!(child.len(), 2);
955        assert_eq!(child[0].content.as_deref(), Some("work it out"));
956        let listed = tool.store.list().unwrap();
957        let info = listed
958            .iter()
959            .find(|s| s.id == children[0].session_id)
960            .unwrap();
961        let origin = info.subagent().unwrap();
962        assert_eq!((origin.parent, origin.route), ("parent1", "big"));
963    }
964
965    /// A provider that answers nothing until the process ends: the child is inside a model call
966    /// when the parent is cancelled, which is the case the flag has to reach.
967    #[derive(Default)]
968    struct Hanging {
969        asked: Arc<tokio::sync::Notify>,
970    }
971
972    #[async_trait]
973    impl ChatProvider for Hanging {
974        async fn chat(&self, _messages: &[Message], _tools: &[ToolSpec]) -> crate::Result<Message> {
975            // `notify_one`, not `notify_waiters`: a permit is then stored, so a watcher that
976            // registers after the request was made still learns about it.
977            self.asked.notify_one();
978            tokio::time::sleep(Duration::from_secs(60)).await;
979            Ok(Message::assistant("too late"))
980        }
981    }
982
983    #[tokio::test]
984    async fn a_cancelled_parent_stops_the_child_run() {
985        let dir = tempfile::tempdir().unwrap();
986        let slow = Arc::new(Hanging::default());
987        let tool = tool_with_providers(
988            vec![("slow", Arc::clone(&slow) as Arc<dyn ChatProvider>)],
989            "slow",
990            dir.path(),
991        );
992        let cancel = crate::cancel::Cancel::new();
993        let run = crate::tools::RunScope::new("p").cancellable(&cancel);
994
995        // The child must be inside its request before the flag is set, or this proves nothing: the
996        // flag would be seen at the run's first checkpoint and no request would be made at all.
997        let flag = cancel.clone();
998        let notifier = Arc::clone(&slow);
999        let canceller = tokio::spawn(async move {
1000            notifier.asked.notified().await;
1001            flag.cancel();
1002        });
1003        let started = std::time::Instant::now();
1004        let outcome = tokio::time::timeout(
1005            Duration::from_secs(10),
1006            call(&tool, &run, &DenyAll, json!({"prompt": "work it out"})),
1007        )
1008        .await
1009        .expect("the child stopped at the cancel, not at its own timeout");
1010        canceller.abort();
1011        assert!(
1012            started.elapsed() < Duration::from_secs(10),
1013            "the child kept working after the parent was cancelled"
1014        );
1015        // The failure is reported the way every child failure is, and it says which one.
1016        let err = outcome.expect_err("a cancelled child has no answer to give");
1017        assert!(
1018            err.to_string().contains("cancelled"),
1019            "the child's failure names the cancel: {err}"
1020        );
1021        // The child's session says it did not finish, so a later run resumes rather than trusts it.
1022        let children = run.children.runs();
1023        assert_eq!(children.len(), 1);
1024        assert!(children[0].failed);
1025    }
1026
1027    #[tokio::test]
1028    async fn a_subagents_answer_arrives_as_a_tool_result_with_its_own_usage() {
1029        let dir = tempfile::tempdir().unwrap();
1030        let child = Recording::new(vec![Ok(Message::assistant("CHILD ANSWER"))], Some((120, 7)));
1031        let tool = tool_with(vec![("big", child.clone())], "big", dir.path());
1032        let mut registry = ToolRegistry::new(4096);
1033        registry.register(Arc::new(tool), Policy::Ask);
1034        let parent_provider = Recording::new(
1035            vec![
1036                Ok(assistant_calling(
1037                    "delegate",
1038                    r#"{"prompt":"find the thing","route":"big"}"#,
1039                )),
1040                Ok(Message::assistant("PARENT FINAL")),
1041            ],
1042            Some((1000, 50)),
1043        );
1044        let store = SessionStore::new(dir.path().join("sessions"));
1045        let agent = Agent::new(
1046            parent_provider.clone(),
1047            Arc::new(registry),
1048            store.clone(),
1049            "parent system".into(),
1050            5,
1051        );
1052        let events = Mutex::new(Vec::new());
1053        let run = agent
1054            .run(None, "PARENT USER PROMPT", &AllowAll, &|e| {
1055                events.lock().unwrap().push(e)
1056            })
1057            .await
1058            .unwrap();
1059        let events = events.into_inner().unwrap();
1060
1061        // The child's final text is the tool result, with its usage beside it.
1062        let want = "CHILD ANSWER\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration";
1063        let result = events
1064            .iter()
1065            .find_map(|e| match e {
1066                AgentEvent::ToolResult {
1067                    name,
1068                    output,
1069                    is_error,
1070                    ..
1071                } if name == "delegate" => Some((output.clone(), *is_error)),
1072                _ => None,
1073            })
1074            .unwrap();
1075        assert_eq!(result, (want.to_string(), false));
1076        assert_eq!(run.reply, "PARENT FINAL");
1077
1078        // The usage is separate: the parent's own requests add up to the parent's numbers,
1079        // and the child's 120/7 are in `children`, in neither of them.
1080        let parent_prompt: u64 = events
1081            .iter()
1082            .filter_map(|e| match e {
1083                AgentEvent::TurnStats { usage, .. } => usage.prompt_tokens,
1084                _ => None,
1085            })
1086            .sum();
1087        assert_eq!(parent_prompt, 2000);
1088        assert_eq!(run.children.len(), 1);
1089        assert_eq!(
1090            (
1091                run.children[0].route.as_str(),
1092                run.children[0].prompt_tokens,
1093                run.children[0].completion_tokens,
1094                run.children[0].iterations,
1095            ),
1096            ("big", Some(120), Some(7), 1)
1097        );
1098
1099        // The parent's session holds the call and the answer, and nothing of the child.
1100        let parent = store.load(&run.session_id).unwrap();
1101        let roles: Vec<_> = parent.iter().map(|m| m.role).collect();
1102        assert_eq!(parent.len(), 4, "{roles:?}");
1103        let parent_text: String = parent
1104            .iter()
1105            .map(|m| m.content.clone().unwrap_or_default())
1106            .collect::<Vec<_>>()
1107            .join("\n");
1108        assert!(parent_text.contains(want), "{parent_text}");
1109        assert!(!parent_text.contains("You are a subagent"), "{parent_text}");
1110        // ...and the child never saw the parent's conversation.
1111        assert!(!child.texts().iter().any(|t| t.contains("PARENT")));
1112        assert!(child.texts().iter().any(|t| t == "find the thing"));
1113        // The child's session is its own row, marked as a child of this one.
1114        let child_row = store
1115            .list()
1116            .unwrap()
1117            .into_iter()
1118            .find(|s| s.id == run.children[0].session_id)
1119            .unwrap();
1120        assert_ne!(child_row.id, run.session_id);
1121        assert_eq!(child_row.subagent().unwrap().parent, run.session_id);
1122    }
1123
1124    /// A parent whose registry holds `tool`, asking `calls` of its own in the first turn.
1125    fn parent_calling(
1126        tool: DelegateTool,
1127        dir: &std::path::Path,
1128        calls: Vec<Message>,
1129        concurrency: usize,
1130    ) -> (Agent, Arc<Recording>) {
1131        let mut registry = ToolRegistry::new(4096);
1132        registry.register(Arc::new(tool), Policy::Ask);
1133        let mut replies = calls;
1134        replies.push(Message::assistant("PARENT FINAL"));
1135        let provider = Recording::new(replies.into_iter().map(Ok).collect(), None);
1136        let agent = Agent::new(
1137            provider.clone(),
1138            Arc::new(registry),
1139            SessionStore::new(dir.join("sessions")),
1140            "parent".into(),
1141            5,
1142        )
1143        .with_tool_concurrency(concurrency);
1144        (agent, provider)
1145    }
1146
1147    #[tokio::test]
1148    async fn a_child_that_fails_is_a_tool_result_and_the_parent_run_carries_on() {
1149        let dir = tempfile::tempdir().unwrap();
1150        let broken = Recording::new(vec![Err(Error::Provider("HTTP 503".into()))], None);
1151        let tool = tool_with(vec![("big", broken)], "big", dir.path());
1152        let (agent, parent) = parent_calling(
1153            tool,
1154            dir.path(),
1155            vec![assistant_calling("delegate", r#"{"prompt":"x"}"#)],
1156            1,
1157        );
1158        let events = Mutex::new(Vec::new());
1159        let run = agent
1160            .run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
1161            .await
1162            .expect("the parent run does not fail with its child");
1163        assert_eq!(run.reply, "PARENT FINAL");
1164        let result = events
1165            .into_inner()
1166            .unwrap()
1167            .into_iter()
1168            .find_map(|e| match e {
1169                AgentEvent::ToolResult {
1170                    output, is_error, ..
1171                } => Some((output, is_error)),
1172                _ => None,
1173            })
1174            .unwrap();
1175        assert!(result.1, "a failed child is an error result");
1176        assert!(
1177            result.0.contains("failed") && result.0.contains("HTTP 503"),
1178            "{}",
1179            result.0
1180        );
1181        assert!(
1182            parent.texts().iter().any(|t| t.contains("HTTP 503")),
1183            "the model read the reason"
1184        );
1185        assert!(run.children[0].failed);
1186    }
1187
1188    #[tokio::test]
1189    async fn a_parent_that_asks_for_more_children_than_the_cap_in_one_turn_gets_the_cap_not_a_fifth(
1190    ) {
1191        let dir = tempfile::tempdir().unwrap();
1192        let big = Recording::new(
1193            (0..MAX_CHILDREN_PER_RUN)
1194                .map(|_| Ok(Message::assistant("ok")))
1195                .collect(),
1196            None,
1197        );
1198        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1199        let many = Message::assistant_tool_calls(
1200            None,
1201            (0..MAX_CHILDREN_PER_RUN + 1)
1202                .map(|i| ToolCall {
1203                    id: format!("c{i}"),
1204                    kind: "function".into(),
1205                    function: FunctionCall {
1206                        name: "delegate".into(),
1207                        arguments: r#"{"prompt":"x"}"#.into(),
1208                    },
1209                })
1210                .collect(),
1211        );
1212        // Concurrent calls must not get past the cap together.
1213        let (agent, _) = parent_calling(tool, dir.path(), vec![many], MAX_CHILDREN_PER_RUN + 1);
1214        let events = Mutex::new(Vec::new());
1215        let run = agent
1216            .run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
1217            .await
1218            .unwrap();
1219        let results: Vec<bool> = events
1220            .into_inner()
1221            .unwrap()
1222            .into_iter()
1223            .filter_map(|e| match e {
1224                AgentEvent::ToolResult { is_error, .. } => Some(is_error),
1225                _ => None,
1226            })
1227            .collect();
1228        assert_eq!(results.iter().filter(|e| **e).count(), 1, "{results:?}");
1229        assert_eq!(run.children.len(), MAX_CHILDREN_PER_RUN);
1230        assert_eq!(big.seen.lock().unwrap().len(), MAX_CHILDREN_PER_RUN);
1231    }
1232
1233    #[tokio::test]
1234    async fn a_child_is_told_what_it_is_and_given_only_the_job_and_the_callers_instructions() {
1235        let dir = tempfile::tempdir().unwrap();
1236        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
1237        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1238        let run = crate::tools::RunScope::new("p");
1239        call(
1240            &tool,
1241            &run,
1242            &DenyAll,
1243            json!({"prompt": "JOB", "system": "ANSWER IN FRENCH"}),
1244        )
1245        .await
1246        .unwrap();
1247        let sent = big.seen.lock().unwrap()[0].clone();
1248        let system = sent[0].content.clone().unwrap();
1249        assert!(system.contains("You are a subagent"), "{system}");
1250        assert!(system.ends_with("ANSWER IN FRENCH"), "{system}");
1251        assert_eq!(
1252            sent.len(),
1253            2,
1254            "the preamble and the prompt, nothing of the parent"
1255        );
1256        assert_eq!(sent[1].content.as_deref(), Some("JOB"));
1257    }
1258
1259    #[tokio::test]
1260    async fn a_child_that_reports_no_usage_says_so_instead_of_counting_zero() {
1261        let dir = tempfile::tempdir().unwrap();
1262        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
1263        let tool = tool_with(vec![("big", big)], "big", dir.path());
1264        let out = call(
1265            &tool,
1266            &crate::tools::RunScope::new("p"),
1267            &DenyAll,
1268            json!({"prompt": "x"}),
1269        )
1270        .await
1271        .unwrap();
1272        assert!(
1273            out.ends_with("child usage: tokens not reported by the server, 1 iteration"),
1274            "{out}"
1275        );
1276    }
1277
1278    #[tokio::test]
1279    async fn an_unknown_route_is_a_tool_error_listing_the_routes_that_exist() {
1280        let dir = tempfile::tempdir().unwrap();
1281        let tool = tool_with(
1282            vec![
1283                ("big", Recording::new(vec![], None)),
1284                ("local", Recording::new(vec![], None)),
1285            ],
1286            "big",
1287            dir.path(),
1288        );
1289        let run = crate::tools::RunScope::new("p");
1290        let e = call(
1291            &tool,
1292            &run,
1293            &DenyAll,
1294            json!({"prompt": "x", "route": "ghost"}),
1295        )
1296        .await
1297        .unwrap_err();
1298        assert!(matches!(e, ToolError::Failed(_)), "{e:?}");
1299        let text = e.to_string();
1300        assert!(
1301            text.contains("unknown route `ghost`") && text.contains("big, local"),
1302            "{text}"
1303        );
1304        assert!(
1305            run.children.runs().is_empty(),
1306            "a refused call spends no place"
1307        );
1308    }
1309
1310    #[tokio::test]
1311    async fn the_n_plus_first_child_is_refused_with_a_reason_the_model_can_act_on() {
1312        let dir = tempfile::tempdir().unwrap();
1313        let replies = (0..MAX_CHILDREN_PER_RUN + 1)
1314            .map(|_| Ok(Message::assistant("ok")))
1315            .collect();
1316        let tool = tool_with(
1317            vec![("big", Recording::new(replies, None))],
1318            "big",
1319            dir.path(),
1320        );
1321        let run = crate::tools::RunScope::new("p");
1322        for _ in 0..MAX_CHILDREN_PER_RUN {
1323            call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
1324                .await
1325                .unwrap();
1326        }
1327        let e = call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
1328            .await
1329            .unwrap_err();
1330        let text = e.to_string();
1331        assert!(
1332            text.contains(&format!("already started {MAX_CHILDREN_PER_RUN} subagents"))
1333                && text.contains("yourself"),
1334            "{text}"
1335        );
1336        assert_eq!(run.children.runs().len(), MAX_CHILDREN_PER_RUN);
1337        // Another run has a cap of its own.
1338        call(
1339            &tool,
1340            &crate::tools::RunScope::new("other"),
1341            &DenyAll,
1342            json!({"prompt": "x"}),
1343        )
1344        .await
1345        .unwrap();
1346    }
1347
1348    #[tokio::test]
1349    async fn a_child_that_fails_comes_back_as_an_error_with_the_reason_and_its_cost() {
1350        let dir = tempfile::tempdir().unwrap();
1351        let big = Recording::new(
1352            vec![
1353                Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
1354                Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
1355            ],
1356            Some((10, 1)),
1357        );
1358        let tool = tool_with(vec![("big", big)], "big", dir.path());
1359        let run = crate::tools::RunScope::new("p");
1360        let e = call(
1361            &tool,
1362            &run,
1363            &DenyAll,
1364            json!({"prompt": "x", "max_iterations": 2}),
1365        )
1366        .await
1367        .unwrap_err();
1368        let text = e.to_string();
1369        assert!(
1370            text.contains("failed")
1371                && text.contains("used all 2 of its iterations")
1372                && text.ends_with("child usage: 20 prompt / 2 completion tokens, 2 iterations"),
1373            "{text}"
1374        );
1375        assert!(run.children.runs()[0].failed);
1376
1377        let broken = Recording::new(vec![Err(Error::Provider("HTTP 500".into()))], None);
1378        let tool = tool_with(vec![("big", broken)], "big", dir.path());
1379        let e = call(
1380            &tool,
1381            &crate::tools::RunScope::new("p"),
1382            &DenyAll,
1383            json!({"prompt": "x"}),
1384        )
1385        .await
1386        .unwrap_err();
1387        assert!(e.to_string().contains("HTTP 500"), "{e}");
1388    }
1389
1390    #[tokio::test]
1391    async fn a_child_is_offered_the_parents_tools_but_not_delegate() {
1392        let dir = tempfile::tempdir().unwrap();
1393        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
1394        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1395        call(
1396            &tool,
1397            &crate::tools::RunScope::new("p"),
1398            &DenyAll,
1399            json!({"prompt": "x"}),
1400        )
1401        .await
1402        .unwrap();
1403        let offered = big.offered.lock().unwrap()[0].clone();
1404        assert!(offered.contains(&"read_file".to_string()), "{offered:?}");
1405        assert!(!offered.contains(&"delegate".to_string()), "{offered:?}");
1406        assert!(!tool
1407            .tools
1408            .advertised_names()
1409            .contains(&"delegate".to_string()));
1410    }
1411
1412    const FAKE_KEY: &str = "sk-proj-ZmFrZWtleWZvcnRlc3RzMDEyMzQ1Njc4OQ";
1413
1414    /// A child that reads a file holding a key, run under `hooks`; returns what the child's
1415    /// model was sent on its second request and what its session stored.
1416    async fn child_reads_a_key(hooks: LoopHooks) -> (String, String, String) {
1417        let dir = tempfile::tempdir().unwrap();
1418        std::fs::write(
1419            dir.path().join("env.txt"),
1420            format!("key = {FAKE_KEY}\nplain\n"),
1421        )
1422        .unwrap();
1423        let big = Recording::new(
1424            vec![
1425                Ok(assistant_calling("read_file", r#"{"path":"env.txt"}"#)),
1426                Ok(Message::assistant("read it")),
1427            ],
1428            None,
1429        );
1430        let tool = tool_with(vec![("big", big.clone())], "big", dir.path()).with_hooks(hooks);
1431        let run = crate::tools::RunScope::new("parent");
1432        call(&tool, &run, &DenyAll, json!({"prompt": "read env.txt"}))
1433            .await
1434            .unwrap();
1435        let sent = big.seen.lock().unwrap()[1]
1436            .iter()
1437            .filter_map(|m| m.content.clone())
1438            .collect::<Vec<_>>()
1439            .join("\n");
1440        let id = run.children.runs()[0].session_id.clone();
1441        let stored = tool
1442            .store
1443            .load(&id)
1444            .unwrap()
1445            .iter()
1446            .filter_map(|m| m.content.clone())
1447            .collect::<Vec<_>>()
1448            .join("\n");
1449        (sent, stored, id)
1450    }
1451
1452    #[tokio::test]
1453    async fn a_childs_tool_output_is_redacted_when_the_parent_has_the_redact_hook() {
1454        // One hook named, so this proves the child inherited `redact-secrets` rather than
1455        // counting whatever the default order happens to be.
1456        let cfg = crate::config::Config::from_toml_str("[hooks]\norder = [\"redact-secrets\"]\n")
1457            .unwrap();
1458        let hooks = crate::hooks::from_config_reporting(
1459            &cfg,
1460            &crate::session::SessionStore::new(
1461                std::env::temp_dir().join(format!("eclipse-delegate-{}", std::process::id())),
1462            ),
1463            crate::hooks::Reporting::to(Arc::new(|_| {})),
1464        )
1465        .unwrap();
1466        assert_eq!(hooks.len(), 1);
1467        let (sent, stored, _) = child_reads_a_key(hooks).await;
1468        assert!(sent.contains("key = [redacted:api-key]"), "{sent}");
1469        assert!(!sent.contains(FAKE_KEY), "the child's model read the key");
1470        assert!(stored.contains("[redacted:api-key]"), "{stored}");
1471        assert!(
1472            !stored.contains(FAKE_KEY),
1473            "the child's session stored the key"
1474        );
1475    }
1476
1477    #[tokio::test]
1478    async fn a_child_with_no_hooks_reads_the_file_as_it_is() {
1479        let (sent, stored, _) = child_reads_a_key(LoopHooks::default()).await;
1480        assert!(sent.contains(FAKE_KEY), "{sent}");
1481        assert!(stored.contains(FAKE_KEY), "{stored}");
1482    }
1483
1484    #[derive(Default)]
1485    struct Recorder(Mutex<Vec<(String, String)>>);
1486
1487    #[async_trait]
1488    impl Approver for Recorder {
1489        async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
1490            self.0
1491                .lock()
1492                .unwrap()
1493                .push((call.tool.clone(), call.summary.clone()));
1494            crate::approvals::Decision::Deny("no".to_string())
1495        }
1496    }
1497
1498    #[tokio::test]
1499    async fn a_childs_own_approvals_reach_the_same_approver_marked_as_the_childs() {
1500        let dir = tempfile::tempdir().unwrap();
1501        let big = Recording::new(
1502            vec![
1503                // A command the shell is actually asked about: `echo hi` would simply run, and a
1504                // test that watched it reach the approver would be watching a prompt that no
1505                // longer exists.
1506                Ok(assistant_calling(
1507                    "shell",
1508                    r#"{"command":"rm -rf the-build"}"#,
1509                )),
1510                Ok(Message::assistant("it was declined")),
1511            ],
1512            None,
1513        );
1514        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1515        let approver = Recorder::default();
1516        let out = call(
1517            &tool,
1518            &crate::tools::RunScope::new("p"),
1519            &approver,
1520            json!({"prompt": "x"}),
1521        )
1522        .await
1523        .unwrap();
1524        assert!(out.starts_with("it was declined"), "{out}");
1525        let asked = approver.0.lock().unwrap().clone();
1526        assert_eq!(asked.len(), 1, "{asked:?}");
1527        assert_eq!(asked[0].0, "shell");
1528        assert!(
1529            asked[0].1.starts_with("[subagent on big] "),
1530            "{}",
1531            asked[0].1
1532        );
1533        assert!(
1534            big.texts().iter().any(|t| t.contains("declined")),
1535            "the child read the refusal as a tool result"
1536        );
1537    }
1538
1539    #[tokio::test]
1540    async fn wrong_typed_arguments_are_invalid_args_naming_the_key() {
1541        let dir = tempfile::tempdir().unwrap();
1542        let tool = tool_with(
1543            vec![("big", Recording::new(vec![], None))],
1544            "big",
1545            dir.path(),
1546        );
1547        let run = crate::tools::RunScope::new("p");
1548        for (args, key) in [
1549            (json!({}), "prompt"),
1550            (json!({"prompt": 3}), "prompt"),
1551            (json!({"prompt": "  "}), "prompt"),
1552            (json!({"prompt": "x", "route": 3}), "route"),
1553            (json!({"prompt": "x", "system": []}), "system"),
1554            (
1555                json!({"prompt": "x", "max_iterations": "8"}),
1556                "max_iterations",
1557            ),
1558            (
1559                json!({"prompt": "x", "max_iterations": 0}),
1560                "max_iterations",
1561            ),
1562            (
1563                json!({"prompt": "x", "max_iterations": 21}),
1564                "max_iterations",
1565            ),
1566            (
1567                json!({"prompt": "x", "max_iterations": 1.5}),
1568                "max_iterations",
1569            ),
1570        ] {
1571            let e = call(&tool, &run, &DenyAll, args.clone()).await.unwrap_err();
1572            assert!(
1573                matches!(e, ToolError::InvalidArgs(_)) && e.to_string().contains(key),
1574                "{args}: {e}"
1575            );
1576        }
1577        assert!(run.children.runs().is_empty());
1578    }
1579
1580    #[test]
1581    fn the_approval_summary_names_the_route_the_first_line_and_the_budget() {
1582        let dir = tempfile::tempdir().unwrap();
1583        let tool = tool_with(
1584            vec![
1585                ("big", Recording::new(vec![], None)),
1586                ("local", Recording::new(vec![], None)),
1587            ],
1588            "big",
1589            dir.path(),
1590        );
1591        let s =
1592            tool.describe_call(&json!({"prompt": "Audit the parser\nthen the lexer\nand more"}));
1593        assert_eq!(
1594            s,
1595            "delegate to a subagent on route `big`: \"Audit the parser\" (+2 more lines) \
1596             (up to 6 iterations)"
1597        );
1598        let s = tool.describe_call(
1599            &json!({"prompt": "x", "route": "local", "max_iterations": 3, "system": "be brief"}),
1600        );
1601        assert!(
1602            s.contains("route `local`")
1603                && s.contains("up to 3 iterations, with its own system prompt"),
1604            "{s}"
1605        );
1606        // It runs before the arguments are checked, so a bad one must not break it.
1607        let s = tool.describe_call(&json!({"prompt": 3, "route": 4, "max_iterations": "x"}));
1608        assert!(
1609            s.contains("(invalid route)") && s.contains("(invalid)"),
1610            "{s}"
1611        );
1612        let long = "x".repeat(500);
1613        assert!(tool.describe_call(&json!({ "prompt": long })).len() < 260);
1614    }
1615
1616    #[test]
1617    fn the_delegate_policy_defaults_to_ask() {
1618        assert_eq!(ToolsConfig::default().delegate, Policy::Ask);
1619    }
1620
1621    #[test]
1622    fn the_description_lists_the_routes_and_says_which_is_the_default() {
1623        let dir = tempfile::tempdir().unwrap();
1624        let tool = tool_with(
1625            vec![
1626                ("big", Recording::new(vec![], None)),
1627                ("local", Recording::new(vec![], None)),
1628            ],
1629            "local",
1630            dir.path(),
1631        );
1632        let d = tool.description();
1633        assert!(
1634            d.contains("`big` (big-model)") && d.contains("Default: `local`"),
1635            "{d}"
1636        );
1637    }
1638
1639    #[tokio::test]
1640    async fn an_answer_too_long_for_the_output_cap_is_cut_but_keeps_the_usage_line() {
1641        let dir = tempfile::tempdir().unwrap();
1642        let big = Recording::new(
1643            vec![Ok(Message::assistant("a".repeat(10_000)))],
1644            Some((5, 5)),
1645        );
1646        let tool = tool_with(vec![("big", big)], "big", dir.path());
1647        let out = call(
1648            &tool,
1649            &crate::tools::RunScope::new("p"),
1650            &AllowAll,
1651            json!({"prompt": "x"}),
1652        )
1653        .await
1654        .unwrap();
1655        assert!(out.len() <= 4096, "{}", out.len());
1656        assert!(out.contains("[output truncated]"));
1657        assert!(out.ends_with("child usage: 5 prompt / 5 completion tokens, 1 iteration"));
1658    }
1659
1660    #[test]
1661    fn the_readout_sums_the_children_and_says_how_many_failed() {
1662        assert_eq!(describe_children(&[]), None);
1663        let run = |route: &str, p, c, i, failed| ChildRun {
1664            route: route.into(),
1665            session_id: "s".into(),
1666            prompt_tokens: p,
1667            completion_tokens: c,
1668            iterations: i,
1669            failed,
1670        };
1671        let one = describe_children(&[run("big", Some(100), Some(10), 2, false)]).unwrap();
1672        assert_eq!(
1673            one,
1674            "delegated: 1 subagent (big) \u{2014} child usage: 100 prompt / 10 completion tokens, 2 iterations"
1675        );
1676        let two = describe_children(&[
1677            run("big", Some(100), Some(10), 2, false),
1678            run("local", None, None, 1, true),
1679        ])
1680        .unwrap();
1681        assert_eq!(
1682            two,
1683            "delegated: 2 subagents (big, local; 1 failed) \u{2014} child usage: 100 prompt / 10 completion tokens, 3 iterations"
1684        );
1685        let none = describe_children(&[run("big", None, None, 1, false)]).unwrap();
1686        assert!(none.contains("tokens not reported by the server"), "{none}");
1687    }
1688}