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 narrowed to the readers (`#171`,
625    /// `#548`). 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 may hold.
627    ///
628    /// An allowlist, not a subtraction: `cronjob_manage`, `skill_manage` and every plugin and MCP
629    /// tool were in the child registry and stayed in a flare's, so a read-only fan-out could
630    /// schedule work and rewrite the skills directory.
631    pub(crate) fn flare_registry(&self) -> ToolRegistry {
632        self.tools.only(crate::flares::READ_TOOLS)
633    }
634
635    /// The route a child goes to when the call names none — a flare run needs the same answer a
636    /// `delegate` call gets, so it asks here rather than resolving it a second way.
637    pub(crate) fn default_route(&self) -> String {
638        self.providers.default_route()
639    }
640
641    /// The next child's session id, for a caller that has to name it before the child starts.
642    pub(crate) fn new_session_id(&self) -> String {
643        self.store.new_id()
644    }
645
646    /// Run one child to its final answer, on `tools` rather than necessarily this tool's own
647    /// registry (`#171`): a flare gets a registry with the write tools taken out.
648    ///
649    /// `delegate` and a flare run are the same engine with two callers — the child is an
650    /// [`Agent`], it gets its own session, its own route, the same hooks and the same turn-results
651    /// buffer, and only what it was told and what it may spend differ. Keeping that in one place
652    /// is the whole reason a flare run is not a second runtime.
653    pub(crate) async fn run_child(
654        &self,
655        tools: Arc<ToolRegistry>,
656        job: ChildJob<'_>,
657        approver: &dyn Approver,
658        cancel: &crate::cancel::Cancel,
659    ) -> ChildOutcome {
660        let session_id = job.session_id.to_string();
661        let mut outcome = ChildOutcome {
662            route: job.route.to_string(),
663            session_id: session_id.clone(),
664            answer: Err("the subagent could not start".to_string()),
665            prompt_tokens: None,
666            completion_tokens: None,
667            iterations: 0,
668        };
669        let route = match self.providers.provider(job.route) {
670            Ok(route) => route,
671            Err(reason) => {
672                outcome.answer = Err(format!("the subagent could not start: {reason}"));
673                return outcome;
674            }
675        };
676        outcome.route = route.name.clone();
677        let begun = match job.origin {
678            ChildOrigin::Subagent { parent, route } => {
679                self.store.begin_subagent(&session_id, parent, route)
680            }
681            ChildOrigin::Flare { run, n } => self.store.begin_flare(&session_id, run, n),
682        };
683        if let Err(e) = begun {
684            outcome.answer = Err(format!("the subagent could not start: {e}"));
685            return outcome;
686        }
687
688        let mut preamble = PREAMBLE.to_string();
689        if let Some(extra) = job.system.filter(|s| !s.trim().is_empty()) {
690            preamble.push_str("\n\n");
691            preamble.push_str(extra.trim());
692        }
693        let child = Agent::new(
694            route.provider,
695            tools,
696            self.store.clone(),
697            preamble,
698            job.budget,
699        )
700        .with_context_budget(route.context_budget_tokens)
701        .with_max_malformed_calls(self.settings.max_malformed_calls)
702        .with_tool_concurrency(self.settings.tool_concurrency)
703        .with_lock_wait(self.settings.lock_wait)
704        .with_hooks(self.hooks.clone())
705        .with_turn_results(Arc::clone(&self.turn_results));
706
707        let usage = Mutex::new(Usage::default());
708        let marked = ChildApprover {
709            inner: approver,
710            route: &route.name,
711        };
712        // The parent's flag, not a fresh one: a cancelled run has to stop the work it started, and
713        // a child agent keeps calling the model for minutes if nobody tells it.
714        let run = child
715            .run_cancellable(
716                Some(&session_id),
717                job.prompt,
718                &marked,
719                &|event| {
720                    if let AgentEvent::TurnStats { usage: turn, .. } = event {
721                        if let Ok(mut total) = usage.lock() {
722                            total.add(&turn);
723                        }
724                    }
725                },
726                cancel,
727            )
728            .await;
729        let usage = usage.into_inner().unwrap_or_default();
730        outcome.prompt_tokens = usage.prompt;
731        outcome.completion_tokens = usage.completion;
732        outcome.iterations = usage.iterations;
733        outcome.answer = match run {
734            Ok(done) if !done.reply.trim().is_empty() => Ok(done.reply),
735            Ok(_) => Err("it finished without any text to return".to_string()),
736            Err(Error::MaxIterations(n)) => Err(format!(
737                "it used all {n} of its iterations without a final answer; raise \
738                 `max_iterations` or split the job"
739            )),
740            Err(e) => Err(e.to_string()),
741        };
742        outcome
743    }
744}
745
746#[derive(Default)]
747struct Usage {
748    prompt: Option<u64>,
749    completion: Option<u64>,
750    iterations: usize,
751}
752
753impl Usage {
754    fn add(&mut self, turn: &crate::usage::TurnUsage) {
755        self.iterations += 1;
756        self.prompt = sum([self.prompt, turn.prompt_tokens].into_iter());
757        self.completion = sum([self.completion, turn.completion_tokens].into_iter());
758    }
759}
760
761#[cfg(test)]
762mod tests {
763    use super::*;
764    use crate::config::{Policy, ToolsConfig};
765    use crate::message::Message;
766    use crate::message::{FunctionCall, ToolCall};
767    use crate::tools::{AllowAll, DenyAll, ToolSpec};
768    use crate::usage::TurnUsage;
769
770    /// Answers from a script and keeps what it was sent, and what tools it was offered.
771    struct Recording {
772        replies: Mutex<Vec<crate::error::Result<Message>>>,
773        seen: Mutex<Vec<Vec<Message>>>,
774        offered: Mutex<Vec<Vec<String>>>,
775        usage: Mutex<Option<TurnUsage>>,
776        reported: Option<(u64, u64)>,
777    }
778
779    impl Recording {
780        fn new(
781            mut replies: Vec<crate::error::Result<Message>>,
782            reported: Option<(u64, u64)>,
783        ) -> Arc<Self> {
784            replies.reverse();
785            Arc::new(Self {
786                replies: Mutex::new(replies),
787                seen: Mutex::default(),
788                offered: Mutex::default(),
789                usage: Mutex::default(),
790                reported,
791            })
792        }
793        fn texts(&self) -> Vec<String> {
794            self.seen
795                .lock()
796                .unwrap()
797                .iter()
798                .flatten()
799                .filter_map(|m| m.content.clone())
800                .collect()
801        }
802    }
803
804    #[async_trait]
805    impl ChatProvider for Recording {
806        async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
807            self.seen.lock().unwrap().push(messages.to_vec());
808            self.offered
809                .lock()
810                .unwrap()
811                .push(tools.iter().map(|t| t.function.name.clone()).collect());
812            *self.usage.lock().unwrap() = self.reported.map(|(p, c)| TurnUsage {
813                prompt_tokens: Some(p),
814                completion_tokens: Some(c),
815                ..TurnUsage::default()
816            });
817            self.replies
818                .lock()
819                .unwrap()
820                .pop()
821                .unwrap_or_else(|| Err(Error::Provider("script exhausted".into())))
822        }
823        fn take_usage(&self) -> Option<TurnUsage> {
824            self.usage.lock().unwrap().take()
825        }
826    }
827
828    struct Fixed {
829        routes: Vec<(String, Arc<dyn ChatProvider>)>,
830        default: String,
831    }
832
833    impl ChildProviders for Fixed {
834        fn routes(&self) -> Vec<RouteInfo> {
835            self.routes
836                .iter()
837                .map(|(n, _)| RouteInfo {
838                    name: n.clone(),
839                    model: format!("{n}-model"),
840                    endpoint: String::new(),
841                })
842                .collect()
843        }
844        fn default_route(&self) -> String {
845            self.default.clone()
846        }
847        fn provider(&self, route: &str) -> Result<ChildRoute, String> {
848            let (name, provider) = self
849                .routes
850                .iter()
851                .find(|(n, _)| n == route)
852                .ok_or("no such route")?;
853            Ok(ChildRoute {
854                name: name.clone(),
855                provider: provider.clone(),
856                context_budget_tokens: 0,
857            })
858        }
859    }
860
861    fn tool_with(
862        routes: Vec<(&str, Arc<Recording>)>,
863        default: &str,
864        dir: &std::path::Path,
865    ) -> DelegateTool {
866        let routes = routes
867            .into_iter()
868            .map(|(name, provider)| (name, provider as Arc<dyn ChatProvider>))
869            .collect();
870        tool_with_providers(routes, default, dir)
871    }
872
873    fn tool_with_providers(
874        routes: Vec<(&str, Arc<dyn ChatProvider>)>,
875        default: &str,
876        dir: &std::path::Path,
877    ) -> DelegateTool {
878        let providers = Fixed {
879            routes: routes
880                .into_iter()
881                .map(|(n, p)| (n.to_string(), p))
882                .collect(),
883            default: default.to_string(),
884        };
885        let tools = ToolRegistry::from_config(&ToolsConfig::default(), dir.to_path_buf());
886        DelegateTool::new(
887            Arc::new(providers),
888            Arc::new(tools),
889            SessionStore::new(dir.join("sessions")),
890            DelegateSettings {
891                max_output_bytes: 4096,
892                max_malformed_calls: 3,
893                tool_concurrency: 1,
894                lock_wait: Duration::from_secs(1),
895            },
896        )
897    }
898
899    /// Runs `args` as the model of a parent run on session `parent` would.
900    async fn call(
901        tool: &DelegateTool,
902        run: &crate::tools::RunScope,
903        approver: &dyn Approver,
904        args: Value,
905    ) -> Result<String, ToolError> {
906        // `delegate` reads the approver and the run, never the registry: the empty one here is
907        // a placeholder for a tool that does not route.
908        let registry = crate::tools::ToolRegistry::new(4096);
909        tool.call_scoped(
910            args,
911            &CallScope {
912                approver,
913                run,
914                registry: &registry,
915                call_id: None,
916            },
917        )
918        .await
919    }
920
921    fn assistant_calling(tool: &str, args: &str) -> Message {
922        Message::assistant_tool_calls(
923            None,
924            vec![ToolCall {
925                id: "c1".into(),
926                kind: "function".into(),
927                function: FunctionCall {
928                    name: tool.into(),
929                    arguments: args.into(),
930                },
931            }],
932        )
933    }
934
935    #[tokio::test]
936    async fn the_childs_final_text_is_the_tool_result_with_its_own_usage_line() {
937        let dir = tempfile::tempdir().unwrap();
938        let big = Recording::new(vec![Ok(Message::assistant("the answer"))], Some((120, 7)));
939        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
940        let run = crate::tools::RunScope::new("parent1");
941        let out = call(&tool, &run, &DenyAll, json!({"prompt": "work it out"}))
942            .await
943            .unwrap();
944        assert_eq!(
945            out,
946            "the answer\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration"
947        );
948        let children = run.children.runs();
949        assert_eq!(children.len(), 1);
950        assert_eq!(children[0].route, "big");
951        assert_eq!(
952            (children[0].prompt_tokens, children[0].completion_tokens),
953            (Some(120), Some(7))
954        );
955        assert!(!children[0].failed);
956        // The child's own session holds its prompt and its answer, and says whose it is.
957        let child = tool.store.load(&children[0].session_id).unwrap();
958        assert_eq!(child.len(), 2);
959        assert_eq!(child[0].content.as_deref(), Some("work it out"));
960        let listed = tool.store.list().unwrap();
961        let info = listed
962            .iter()
963            .find(|s| s.id == children[0].session_id)
964            .unwrap();
965        let origin = info.subagent().unwrap();
966        assert_eq!((origin.parent, origin.route), ("parent1", "big"));
967    }
968
969    /// A provider that answers nothing until the process ends: the child is inside a model call
970    /// when the parent is cancelled, which is the case the flag has to reach.
971    #[derive(Default)]
972    struct Hanging {
973        asked: Arc<tokio::sync::Notify>,
974    }
975
976    #[async_trait]
977    impl ChatProvider for Hanging {
978        async fn chat(&self, _messages: &[Message], _tools: &[ToolSpec]) -> crate::Result<Message> {
979            // `notify_one`, not `notify_waiters`: a permit is then stored, so a watcher that
980            // registers after the request was made still learns about it.
981            self.asked.notify_one();
982            tokio::time::sleep(Duration::from_secs(60)).await;
983            Ok(Message::assistant("too late"))
984        }
985    }
986
987    #[tokio::test]
988    async fn a_cancelled_parent_stops_the_child_run() {
989        let dir = tempfile::tempdir().unwrap();
990        let slow = Arc::new(Hanging::default());
991        let tool = tool_with_providers(
992            vec![("slow", Arc::clone(&slow) as Arc<dyn ChatProvider>)],
993            "slow",
994            dir.path(),
995        );
996        let cancel = crate::cancel::Cancel::new();
997        let run = crate::tools::RunScope::new("p").cancellable(&cancel);
998
999        // The child must be inside its request before the flag is set, or this proves nothing: the
1000        // flag would be seen at the run's first checkpoint and no request would be made at all.
1001        let flag = cancel.clone();
1002        let notifier = Arc::clone(&slow);
1003        let canceller = tokio::spawn(async move {
1004            notifier.asked.notified().await;
1005            flag.cancel();
1006        });
1007        let started = std::time::Instant::now();
1008        let outcome = tokio::time::timeout(
1009            Duration::from_secs(10),
1010            call(&tool, &run, &DenyAll, json!({"prompt": "work it out"})),
1011        )
1012        .await
1013        .expect("the child stopped at the cancel, not at its own timeout");
1014        canceller.abort();
1015        assert!(
1016            started.elapsed() < Duration::from_secs(10),
1017            "the child kept working after the parent was cancelled"
1018        );
1019        // The failure is reported the way every child failure is, and it says which one.
1020        let err = outcome.expect_err("a cancelled child has no answer to give");
1021        assert!(
1022            err.to_string().contains("cancelled"),
1023            "the child's failure names the cancel: {err}"
1024        );
1025        // The child's session says it did not finish, so a later run resumes rather than trusts it.
1026        let children = run.children.runs();
1027        assert_eq!(children.len(), 1);
1028        assert!(children[0].failed);
1029    }
1030
1031    #[tokio::test]
1032    async fn a_subagents_answer_arrives_as_a_tool_result_with_its_own_usage() {
1033        let dir = tempfile::tempdir().unwrap();
1034        let child = Recording::new(vec![Ok(Message::assistant("CHILD ANSWER"))], Some((120, 7)));
1035        let tool = tool_with(vec![("big", child.clone())], "big", dir.path());
1036        let mut registry = ToolRegistry::new(4096);
1037        registry.register(Arc::new(tool), Policy::Ask);
1038        let parent_provider = Recording::new(
1039            vec![
1040                Ok(assistant_calling(
1041                    "delegate",
1042                    r#"{"prompt":"find the thing","route":"big"}"#,
1043                )),
1044                Ok(Message::assistant("PARENT FINAL")),
1045            ],
1046            Some((1000, 50)),
1047        );
1048        let store = SessionStore::new(dir.path().join("sessions"));
1049        let agent = Agent::new(
1050            parent_provider.clone(),
1051            Arc::new(registry),
1052            store.clone(),
1053            "parent system".into(),
1054            5,
1055        );
1056        let events = Mutex::new(Vec::new());
1057        let run = agent
1058            .run(None, "PARENT USER PROMPT", &AllowAll, &|e| {
1059                events.lock().unwrap().push(e)
1060            })
1061            .await
1062            .unwrap();
1063        let events = events.into_inner().unwrap();
1064
1065        // The child's final text is the tool result, with its usage beside it.
1066        let want = "CHILD ANSWER\n\nchild usage: 120 prompt / 7 completion tokens, 1 iteration";
1067        let result = events
1068            .iter()
1069            .find_map(|e| match e {
1070                AgentEvent::ToolResult {
1071                    name,
1072                    output,
1073                    is_error,
1074                    ..
1075                } if name == "delegate" => Some((output.clone(), *is_error)),
1076                _ => None,
1077            })
1078            .unwrap();
1079        assert_eq!(result, (want.to_string(), false));
1080        assert_eq!(run.reply, "PARENT FINAL");
1081
1082        // The usage is separate: the parent's own requests add up to the parent's numbers,
1083        // and the child's 120/7 are in `children`, in neither of them.
1084        let parent_prompt: u64 = events
1085            .iter()
1086            .filter_map(|e| match e {
1087                AgentEvent::TurnStats { usage, .. } => usage.prompt_tokens,
1088                _ => None,
1089            })
1090            .sum();
1091        assert_eq!(parent_prompt, 2000);
1092        assert_eq!(run.children.len(), 1);
1093        assert_eq!(
1094            (
1095                run.children[0].route.as_str(),
1096                run.children[0].prompt_tokens,
1097                run.children[0].completion_tokens,
1098                run.children[0].iterations,
1099            ),
1100            ("big", Some(120), Some(7), 1)
1101        );
1102
1103        // The parent's session holds the call and the answer, and nothing of the child.
1104        let parent = store.load(&run.session_id).unwrap();
1105        let roles: Vec<_> = parent.iter().map(|m| m.role).collect();
1106        assert_eq!(parent.len(), 4, "{roles:?}");
1107        let parent_text: String = parent
1108            .iter()
1109            .map(|m| m.content.clone().unwrap_or_default())
1110            .collect::<Vec<_>>()
1111            .join("\n");
1112        assert!(parent_text.contains(want), "{parent_text}");
1113        assert!(!parent_text.contains("You are a subagent"), "{parent_text}");
1114        // ...and the child never saw the parent's conversation.
1115        assert!(!child.texts().iter().any(|t| t.contains("PARENT")));
1116        assert!(child.texts().iter().any(|t| t == "find the thing"));
1117        // The child's session is its own row, marked as a child of this one.
1118        let child_row = store
1119            .list()
1120            .unwrap()
1121            .into_iter()
1122            .find(|s| s.id == run.children[0].session_id)
1123            .unwrap();
1124        assert_ne!(child_row.id, run.session_id);
1125        assert_eq!(child_row.subagent().unwrap().parent, run.session_id);
1126    }
1127
1128    /// A parent whose registry holds `tool`, asking `calls` of its own in the first turn.
1129    fn parent_calling(
1130        tool: DelegateTool,
1131        dir: &std::path::Path,
1132        calls: Vec<Message>,
1133        concurrency: usize,
1134    ) -> (Agent, Arc<Recording>) {
1135        let mut registry = ToolRegistry::new(4096);
1136        registry.register(Arc::new(tool), Policy::Ask);
1137        let mut replies = calls;
1138        replies.push(Message::assistant("PARENT FINAL"));
1139        let provider = Recording::new(replies.into_iter().map(Ok).collect(), None);
1140        let agent = Agent::new(
1141            provider.clone(),
1142            Arc::new(registry),
1143            SessionStore::new(dir.join("sessions")),
1144            "parent".into(),
1145            5,
1146        )
1147        .with_tool_concurrency(concurrency);
1148        (agent, provider)
1149    }
1150
1151    #[tokio::test]
1152    async fn a_child_that_fails_is_a_tool_result_and_the_parent_run_carries_on() {
1153        let dir = tempfile::tempdir().unwrap();
1154        let broken = Recording::new(vec![Err(Error::Provider("HTTP 503".into()))], None);
1155        let tool = tool_with(vec![("big", broken)], "big", dir.path());
1156        let (agent, parent) = parent_calling(
1157            tool,
1158            dir.path(),
1159            vec![assistant_calling("delegate", r#"{"prompt":"x"}"#)],
1160            1,
1161        );
1162        let events = Mutex::new(Vec::new());
1163        let run = agent
1164            .run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
1165            .await
1166            .expect("the parent run does not fail with its child");
1167        assert_eq!(run.reply, "PARENT FINAL");
1168        let result = events
1169            .into_inner()
1170            .unwrap()
1171            .into_iter()
1172            .find_map(|e| match e {
1173                AgentEvent::ToolResult {
1174                    output, is_error, ..
1175                } => Some((output, is_error)),
1176                _ => None,
1177            })
1178            .unwrap();
1179        assert!(result.1, "a failed child is an error result");
1180        assert!(
1181            result.0.contains("failed") && result.0.contains("HTTP 503"),
1182            "{}",
1183            result.0
1184        );
1185        assert!(
1186            parent.texts().iter().any(|t| t.contains("HTTP 503")),
1187            "the model read the reason"
1188        );
1189        assert!(run.children[0].failed);
1190    }
1191
1192    #[tokio::test]
1193    async fn a_parent_that_asks_for_more_children_than_the_cap_in_one_turn_gets_the_cap_not_a_fifth(
1194    ) {
1195        let dir = tempfile::tempdir().unwrap();
1196        let big = Recording::new(
1197            (0..MAX_CHILDREN_PER_RUN)
1198                .map(|_| Ok(Message::assistant("ok")))
1199                .collect(),
1200            None,
1201        );
1202        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1203        let many = Message::assistant_tool_calls(
1204            None,
1205            (0..MAX_CHILDREN_PER_RUN + 1)
1206                .map(|i| ToolCall {
1207                    id: format!("c{i}"),
1208                    kind: "function".into(),
1209                    function: FunctionCall {
1210                        name: "delegate".into(),
1211                        arguments: r#"{"prompt":"x"}"#.into(),
1212                    },
1213                })
1214                .collect(),
1215        );
1216        // Concurrent calls must not get past the cap together.
1217        let (agent, _) = parent_calling(tool, dir.path(), vec![many], MAX_CHILDREN_PER_RUN + 1);
1218        let events = Mutex::new(Vec::new());
1219        let run = agent
1220            .run(None, "go", &AllowAll, &|e| events.lock().unwrap().push(e))
1221            .await
1222            .unwrap();
1223        let results: Vec<bool> = events
1224            .into_inner()
1225            .unwrap()
1226            .into_iter()
1227            .filter_map(|e| match e {
1228                AgentEvent::ToolResult { is_error, .. } => Some(is_error),
1229                _ => None,
1230            })
1231            .collect();
1232        assert_eq!(results.iter().filter(|e| **e).count(), 1, "{results:?}");
1233        assert_eq!(run.children.len(), MAX_CHILDREN_PER_RUN);
1234        assert_eq!(big.seen.lock().unwrap().len(), MAX_CHILDREN_PER_RUN);
1235    }
1236
1237    #[tokio::test]
1238    async fn a_child_is_told_what_it_is_and_given_only_the_job_and_the_callers_instructions() {
1239        let dir = tempfile::tempdir().unwrap();
1240        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
1241        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1242        let run = crate::tools::RunScope::new("p");
1243        call(
1244            &tool,
1245            &run,
1246            &DenyAll,
1247            json!({"prompt": "JOB", "system": "ANSWER IN FRENCH"}),
1248        )
1249        .await
1250        .unwrap();
1251        let sent = big.seen.lock().unwrap()[0].clone();
1252        let system = sent[0].content.clone().unwrap();
1253        assert!(system.contains("You are a subagent"), "{system}");
1254        assert!(system.ends_with("ANSWER IN FRENCH"), "{system}");
1255        assert_eq!(
1256            sent.len(),
1257            2,
1258            "the preamble and the prompt, nothing of the parent"
1259        );
1260        assert_eq!(sent[1].content.as_deref(), Some("JOB"));
1261    }
1262
1263    #[tokio::test]
1264    async fn a_child_that_reports_no_usage_says_so_instead_of_counting_zero() {
1265        let dir = tempfile::tempdir().unwrap();
1266        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
1267        let tool = tool_with(vec![("big", big)], "big", dir.path());
1268        let out = call(
1269            &tool,
1270            &crate::tools::RunScope::new("p"),
1271            &DenyAll,
1272            json!({"prompt": "x"}),
1273        )
1274        .await
1275        .unwrap();
1276        assert!(
1277            out.ends_with("child usage: tokens not reported by the server, 1 iteration"),
1278            "{out}"
1279        );
1280    }
1281
1282    #[tokio::test]
1283    async fn an_unknown_route_is_a_tool_error_listing_the_routes_that_exist() {
1284        let dir = tempfile::tempdir().unwrap();
1285        let tool = tool_with(
1286            vec![
1287                ("big", Recording::new(vec![], None)),
1288                ("local", Recording::new(vec![], None)),
1289            ],
1290            "big",
1291            dir.path(),
1292        );
1293        let run = crate::tools::RunScope::new("p");
1294        let e = call(
1295            &tool,
1296            &run,
1297            &DenyAll,
1298            json!({"prompt": "x", "route": "ghost"}),
1299        )
1300        .await
1301        .unwrap_err();
1302        assert!(matches!(e, ToolError::Failed(_)), "{e:?}");
1303        let text = e.to_string();
1304        assert!(
1305            text.contains("unknown route `ghost`") && text.contains("big, local"),
1306            "{text}"
1307        );
1308        assert!(
1309            run.children.runs().is_empty(),
1310            "a refused call spends no place"
1311        );
1312    }
1313
1314    #[tokio::test]
1315    async fn the_n_plus_first_child_is_refused_with_a_reason_the_model_can_act_on() {
1316        let dir = tempfile::tempdir().unwrap();
1317        let replies = (0..MAX_CHILDREN_PER_RUN + 1)
1318            .map(|_| Ok(Message::assistant("ok")))
1319            .collect();
1320        let tool = tool_with(
1321            vec![("big", Recording::new(replies, None))],
1322            "big",
1323            dir.path(),
1324        );
1325        let run = crate::tools::RunScope::new("p");
1326        for _ in 0..MAX_CHILDREN_PER_RUN {
1327            call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
1328                .await
1329                .unwrap();
1330        }
1331        let e = call(&tool, &run, &DenyAll, json!({"prompt": "x"}))
1332            .await
1333            .unwrap_err();
1334        let text = e.to_string();
1335        assert!(
1336            text.contains(&format!("already started {MAX_CHILDREN_PER_RUN} subagents"))
1337                && text.contains("yourself"),
1338            "{text}"
1339        );
1340        assert_eq!(run.children.runs().len(), MAX_CHILDREN_PER_RUN);
1341        // Another run has a cap of its own.
1342        call(
1343            &tool,
1344            &crate::tools::RunScope::new("other"),
1345            &DenyAll,
1346            json!({"prompt": "x"}),
1347        )
1348        .await
1349        .unwrap();
1350    }
1351
1352    #[tokio::test]
1353    async fn a_child_that_fails_comes_back_as_an_error_with_the_reason_and_its_cost() {
1354        let dir = tempfile::tempdir().unwrap();
1355        let big = Recording::new(
1356            vec![
1357                Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
1358                Ok(assistant_calling("read_file", r#"{"path":"nope"}"#)),
1359            ],
1360            Some((10, 1)),
1361        );
1362        let tool = tool_with(vec![("big", big)], "big", dir.path());
1363        let run = crate::tools::RunScope::new("p");
1364        let e = call(
1365            &tool,
1366            &run,
1367            &DenyAll,
1368            json!({"prompt": "x", "max_iterations": 2}),
1369        )
1370        .await
1371        .unwrap_err();
1372        let text = e.to_string();
1373        assert!(
1374            text.contains("failed")
1375                && text.contains("used all 2 of its iterations")
1376                && text.ends_with("child usage: 20 prompt / 2 completion tokens, 2 iterations"),
1377            "{text}"
1378        );
1379        assert!(run.children.runs()[0].failed);
1380
1381        let broken = Recording::new(vec![Err(Error::Provider("HTTP 500".into()))], None);
1382        let tool = tool_with(vec![("big", broken)], "big", dir.path());
1383        let e = call(
1384            &tool,
1385            &crate::tools::RunScope::new("p"),
1386            &DenyAll,
1387            json!({"prompt": "x"}),
1388        )
1389        .await
1390        .unwrap_err();
1391        assert!(e.to_string().contains("HTTP 500"), "{e}");
1392    }
1393
1394    #[tokio::test]
1395    async fn a_child_is_offered_the_parents_tools_but_not_delegate() {
1396        let dir = tempfile::tempdir().unwrap();
1397        let big = Recording::new(vec![Ok(Message::assistant("ok"))], None);
1398        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1399        call(
1400            &tool,
1401            &crate::tools::RunScope::new("p"),
1402            &DenyAll,
1403            json!({"prompt": "x"}),
1404        )
1405        .await
1406        .unwrap();
1407        let offered = big.offered.lock().unwrap()[0].clone();
1408        assert!(offered.contains(&"read_file".to_string()), "{offered:?}");
1409        assert!(!offered.contains(&"delegate".to_string()), "{offered:?}");
1410        assert!(!tool
1411            .tools
1412            .advertised_names()
1413            .contains(&"delegate".to_string()));
1414    }
1415
1416    const FAKE_KEY: &str = "sk-proj-ZmFrZWtleWZvcnRlc3RzMDEyMzQ1Njc4OQ";
1417
1418    /// A child that reads a file holding a key, run under `hooks`; returns what the child's
1419    /// model was sent on its second request and what its session stored.
1420    async fn child_reads_a_key(hooks: LoopHooks) -> (String, String, String) {
1421        let dir = tempfile::tempdir().unwrap();
1422        std::fs::write(
1423            dir.path().join("env.txt"),
1424            format!("key = {FAKE_KEY}\nplain\n"),
1425        )
1426        .unwrap();
1427        let big = Recording::new(
1428            vec![
1429                Ok(assistant_calling("read_file", r#"{"path":"env.txt"}"#)),
1430                Ok(Message::assistant("read it")),
1431            ],
1432            None,
1433        );
1434        let tool = tool_with(vec![("big", big.clone())], "big", dir.path()).with_hooks(hooks);
1435        let run = crate::tools::RunScope::new("parent");
1436        call(&tool, &run, &DenyAll, json!({"prompt": "read env.txt"}))
1437            .await
1438            .unwrap();
1439        let sent = big.seen.lock().unwrap()[1]
1440            .iter()
1441            .filter_map(|m| m.content.clone())
1442            .collect::<Vec<_>>()
1443            .join("\n");
1444        let id = run.children.runs()[0].session_id.clone();
1445        let stored = tool
1446            .store
1447            .load(&id)
1448            .unwrap()
1449            .iter()
1450            .filter_map(|m| m.content.clone())
1451            .collect::<Vec<_>>()
1452            .join("\n");
1453        (sent, stored, id)
1454    }
1455
1456    #[tokio::test]
1457    async fn a_childs_tool_output_is_redacted_when_the_parent_has_the_redact_hook() {
1458        // One hook named, so this proves the child inherited `redact-secrets` rather than
1459        // counting whatever the default order happens to be.
1460        let cfg = crate::config::Config::from_toml_str("[hooks]\norder = [\"redact-secrets\"]\n")
1461            .unwrap();
1462        let hooks = crate::hooks::from_config_reporting(
1463            &cfg,
1464            &crate::session::SessionStore::new(
1465                std::env::temp_dir().join(format!("eclipse-delegate-{}", std::process::id())),
1466            ),
1467            crate::hooks::Reporting::to(Arc::new(|_| {})),
1468        )
1469        .unwrap();
1470        assert_eq!(hooks.len(), 1);
1471        let (sent, stored, _) = child_reads_a_key(hooks).await;
1472        assert!(sent.contains("key = [redacted:api-key]"), "{sent}");
1473        assert!(!sent.contains(FAKE_KEY), "the child's model read the key");
1474        assert!(stored.contains("[redacted:api-key]"), "{stored}");
1475        assert!(
1476            !stored.contains(FAKE_KEY),
1477            "the child's session stored the key"
1478        );
1479    }
1480
1481    #[tokio::test]
1482    async fn a_child_with_no_hooks_reads_the_file_as_it_is() {
1483        let (sent, stored, _) = child_reads_a_key(LoopHooks::default()).await;
1484        assert!(sent.contains(FAKE_KEY), "{sent}");
1485        assert!(stored.contains(FAKE_KEY), "{stored}");
1486    }
1487
1488    #[derive(Default)]
1489    struct Recorder(Mutex<Vec<(String, String)>>);
1490
1491    #[async_trait]
1492    impl Approver for Recorder {
1493        async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
1494            self.0
1495                .lock()
1496                .unwrap()
1497                .push((call.tool.clone(), call.summary.clone()));
1498            crate::approvals::Decision::Deny("no".to_string())
1499        }
1500    }
1501
1502    #[tokio::test]
1503    async fn a_childs_own_approvals_reach_the_same_approver_marked_as_the_childs() {
1504        let dir = tempfile::tempdir().unwrap();
1505        let big = Recording::new(
1506            vec![
1507                // A command the shell is actually asked about: `echo hi` would simply run, and a
1508                // test that watched it reach the approver would be watching a prompt that no
1509                // longer exists.
1510                Ok(assistant_calling(
1511                    "shell",
1512                    r#"{"command":"rm -rf the-build"}"#,
1513                )),
1514                Ok(Message::assistant("it was declined")),
1515            ],
1516            None,
1517        );
1518        let tool = tool_with(vec![("big", big.clone())], "big", dir.path());
1519        let approver = Recorder::default();
1520        let out = call(
1521            &tool,
1522            &crate::tools::RunScope::new("p"),
1523            &approver,
1524            json!({"prompt": "x"}),
1525        )
1526        .await
1527        .unwrap();
1528        assert!(out.starts_with("it was declined"), "{out}");
1529        let asked = approver.0.lock().unwrap().clone();
1530        assert_eq!(asked.len(), 1, "{asked:?}");
1531        assert_eq!(asked[0].0, "shell");
1532        assert!(
1533            asked[0].1.starts_with("[subagent on big] "),
1534            "{}",
1535            asked[0].1
1536        );
1537        assert!(
1538            big.texts().iter().any(|t| t.contains("declined")),
1539            "the child read the refusal as a tool result"
1540        );
1541    }
1542
1543    #[tokio::test]
1544    async fn wrong_typed_arguments_are_invalid_args_naming_the_key() {
1545        let dir = tempfile::tempdir().unwrap();
1546        let tool = tool_with(
1547            vec![("big", Recording::new(vec![], None))],
1548            "big",
1549            dir.path(),
1550        );
1551        let run = crate::tools::RunScope::new("p");
1552        for (args, key) in [
1553            (json!({}), "prompt"),
1554            (json!({"prompt": 3}), "prompt"),
1555            (json!({"prompt": "  "}), "prompt"),
1556            (json!({"prompt": "x", "route": 3}), "route"),
1557            (json!({"prompt": "x", "system": []}), "system"),
1558            (
1559                json!({"prompt": "x", "max_iterations": "8"}),
1560                "max_iterations",
1561            ),
1562            (
1563                json!({"prompt": "x", "max_iterations": 0}),
1564                "max_iterations",
1565            ),
1566            (
1567                json!({"prompt": "x", "max_iterations": 21}),
1568                "max_iterations",
1569            ),
1570            (
1571                json!({"prompt": "x", "max_iterations": 1.5}),
1572                "max_iterations",
1573            ),
1574        ] {
1575            let e = call(&tool, &run, &DenyAll, args.clone()).await.unwrap_err();
1576            assert!(
1577                matches!(e, ToolError::InvalidArgs(_)) && e.to_string().contains(key),
1578                "{args}: {e}"
1579            );
1580        }
1581        assert!(run.children.runs().is_empty());
1582    }
1583
1584    #[test]
1585    fn the_approval_summary_names_the_route_the_first_line_and_the_budget() {
1586        let dir = tempfile::tempdir().unwrap();
1587        let tool = tool_with(
1588            vec![
1589                ("big", Recording::new(vec![], None)),
1590                ("local", Recording::new(vec![], None)),
1591            ],
1592            "big",
1593            dir.path(),
1594        );
1595        let s =
1596            tool.describe_call(&json!({"prompt": "Audit the parser\nthen the lexer\nand more"}));
1597        assert_eq!(
1598            s,
1599            "delegate to a subagent on route `big`: \"Audit the parser\" (+2 more lines) \
1600             (up to 6 iterations)"
1601        );
1602        let s = tool.describe_call(
1603            &json!({"prompt": "x", "route": "local", "max_iterations": 3, "system": "be brief"}),
1604        );
1605        assert!(
1606            s.contains("route `local`")
1607                && s.contains("up to 3 iterations, with its own system prompt"),
1608            "{s}"
1609        );
1610        // It runs before the arguments are checked, so a bad one must not break it.
1611        let s = tool.describe_call(&json!({"prompt": 3, "route": 4, "max_iterations": "x"}));
1612        assert!(
1613            s.contains("(invalid route)") && s.contains("(invalid)"),
1614            "{s}"
1615        );
1616        let long = "x".repeat(500);
1617        assert!(tool.describe_call(&json!({ "prompt": long })).len() < 260);
1618    }
1619
1620    #[test]
1621    fn the_delegate_policy_defaults_to_ask() {
1622        assert_eq!(ToolsConfig::default().delegate, Policy::Ask);
1623    }
1624
1625    #[test]
1626    fn the_description_lists_the_routes_and_says_which_is_the_default() {
1627        let dir = tempfile::tempdir().unwrap();
1628        let tool = tool_with(
1629            vec![
1630                ("big", Recording::new(vec![], None)),
1631                ("local", Recording::new(vec![], None)),
1632            ],
1633            "local",
1634            dir.path(),
1635        );
1636        let d = tool.description();
1637        assert!(
1638            d.contains("`big` (big-model)") && d.contains("Default: `local`"),
1639            "{d}"
1640        );
1641    }
1642
1643    #[tokio::test]
1644    async fn an_answer_too_long_for_the_output_cap_is_cut_but_keeps_the_usage_line() {
1645        let dir = tempfile::tempdir().unwrap();
1646        let big = Recording::new(
1647            vec![Ok(Message::assistant("a".repeat(10_000)))],
1648            Some((5, 5)),
1649        );
1650        let tool = tool_with(vec![("big", big)], "big", dir.path());
1651        let out = call(
1652            &tool,
1653            &crate::tools::RunScope::new("p"),
1654            &AllowAll,
1655            json!({"prompt": "x"}),
1656        )
1657        .await
1658        .unwrap();
1659        assert!(out.len() <= 4096, "{}", out.len());
1660        assert!(out.contains("[output truncated]"));
1661        assert!(out.ends_with("child usage: 5 prompt / 5 completion tokens, 1 iteration"));
1662    }
1663
1664    #[test]
1665    fn the_readout_sums_the_children_and_says_how_many_failed() {
1666        assert_eq!(describe_children(&[]), None);
1667        let run = |route: &str, p, c, i, failed| ChildRun {
1668            route: route.into(),
1669            session_id: "s".into(),
1670            prompt_tokens: p,
1671            completion_tokens: c,
1672            iterations: i,
1673            failed,
1674        };
1675        let one = describe_children(&[run("big", Some(100), Some(10), 2, false)]).unwrap();
1676        assert_eq!(
1677            one,
1678            "delegated: 1 subagent (big) \u{2014} child usage: 100 prompt / 10 completion tokens, 2 iterations"
1679        );
1680        let two = describe_children(&[
1681            run("big", Some(100), Some(10), 2, false),
1682            run("local", None, None, 1, true),
1683        ])
1684        .unwrap();
1685        assert_eq!(
1686            two,
1687            "delegated: 2 subagents (big, local; 1 failed) \u{2014} child usage: 100 prompt / 10 completion tokens, 3 iterations"
1688        );
1689        let none = describe_children(&[run("big", None, None, 1, false)]).unwrap();
1690        assert!(none.contains("tokens not reported by the server"), "{none}");
1691    }
1692}