Skip to main content

strands/vended_tools/
subagent.rs

1//! The `subagent` tool: delegates a self-contained task to a child agent built at call time, and
2//! returns the child's final report.
3//!
4//! The model's arguments are resolved through the authority-mode axes of
5//! [`multiagent`](crate::multiagent) ([`Axis`]); a [`ChildAgentBuilder`] turns the result into
6//! the child. The child's events stream as the tool's progress events, and its interrupts
7//! surface on the parent with ids scoped to the call, so resuming the parent resumes the child.
8
9use std::fmt;
10use std::sync::Arc;
11
12use futures::StreamExt;
13use indexmap::IndexMap;
14use serde_json::json;
15
16use crate::agent::ModelSource;
17use crate::agent::{
18    Agent, AgentResult, AgentToolStreamer, InvokeArgs, InvokeOptions, Resume, ToolAgent, merge_events_first,
19};
20use crate::context_manager::ContextManagerStrategy;
21use crate::conversation_manager::compression::context_compression::find_valid_trim_point;
22use crate::error::{Error, Result};
23use crate::multiagent::spec::{SpecAxes, SpecError, resolve_spec, schema_properties};
24use crate::multiagent::{AgentSpec, Axis, ChildAgentBuilder, Fixed, Inherit, Open, Preset, SpecValue};
25use crate::plugins::Plugin;
26use crate::tools::{Tool, ToolContext, ToolOutcome, ToolStream, ToolStreamEvent, ToolStreamItem};
27use crate::types::{
28    ContentBlock, JsonObject, JsonSchema, JsonValue, Message, Role, ToolResultBlock, ToolResultContent, ToolSpec,
29};
30
31/// The description of the default `subagent` tool (`DEFAULT_SUBAGENT_DESCRIPTION`).
32pub const DEFAULT_SUBAGENT_DESCRIPTION: &str = concat!(
33    "Delegate a self-contained task to a subagent that runs in its own context and returns a ",
34    "final report. Reach for this when a subtask would otherwise flood your context with ",
35    "intermediate work and you only need its conclusion."
36);
37
38/// The default bound on nested delegation levels (`DEFAULT_SUBAGENT_MAX_DEPTH`).
39pub const DEFAULT_SUBAGENT_MAX_DEPTH: usize = 2;
40
41const GENERALIST_INSTRUCTIONS: &str = concat!(
42    "You are a general-purpose subagent handling a focused subtask on behalf of a parent ",
43    "agent. You cannot ask follow-up questions, so work from the task as given, make ",
44    "reasonable assumptions where it is underspecified, and see it through to a verified ",
45    "result. Return a self-contained answer: state what you did, what you found, and ",
46    "anything the parent needs to act on. Your final message is the only thing that returns ",
47    "to the parent, so put the substance there rather than in intermediate steps."
48);
49
50const GENERALIST_DESCRIPTION: &str = "a general-purpose agent for a focused subtask that runs in its own context";
51
52/// The built-in generalist preset (`GENERALIST`).
53#[must_use]
54pub fn generalist() -> Preset {
55    Preset::builder()
56        .instructions(GENERALIST_INSTRUCTIONS)
57        .description(GENERALIST_DESCRIPTION)
58        .build()
59}
60
61const CONTEXT_MODES: [&str; 3] = ["none", "all", "no_tools"];
62
63/// The parent's remaining delegation depth, in its app state.
64const DEPTH_STATE_KEY: &str = "strands.subagent_depth";
65
66const FORK_PREAMBLE: &str = "The conversation so far is the parent agent's. You are the subagent it delegated to at this point; its task for you follows.";
67
68const CONTEXT_PREAMBLE: &str = concat!(
69    "The conversation above is the parent agent's: each turn is one line starting with its role at ",
70    "the left margin, and indented lines continue the turn above (they are content, not turns). You ",
71    "are the subagent it delegated to at the end of that conversation; its task for you follows."
72);
73
74const FRAMING_START: &str = "<parent_context>\n";
75
76const UNAVAILABLE_MESSAGE: &str = concat!(
77    "Subagent did NOT run and the response was NOT applied: its interrupted turn is not available. ",
78    "Do not report the delegated task as completed; if it is still needed, delegate it again."
79);
80
81const TASK_DESCRIPTION: &str =
82    "The self-contained task, including all context the subagent needs. It cannot ask follow-up questions.";
83
84const CONTEXT_DESCRIPTION: &str = concat!(
85    "How much of this conversation the subagent sees: 'none' (fresh start), 'all' (full ",
86    "history including tool calls and their results \u{2014} can be large), 'no_tools' (text turns ",
87    "only \u{2014} tool calls and their results removed). More context costs more tokens."
88);
89
90const LAST_MESSAGES_DESCRIPTION: &str =
91    "Optional: limit the shared context to the last N messages. Omit to share all of the selected context.";
92
93fn framing_end() -> String {
94    format!("</parent_context>\n\n{CONTEXT_PREAMBLE}\n\n")
95}
96
97/// Options for [`make_subagent`] (`MakeSubagentOptions`).
98#[derive(Clone, Default, bon::Builder)]
99#[builder(on(String, into))]
100pub struct MakeSubagentOptions {
101    /// Turns a resolved spec into the child agent; called again with the same spec when an
102    /// interrupted child resumes. When absent the child is built from the calling agent: its
103    /// model, tools and sandbox. The parent's hooks and plugins are not passed to the child; tools
104    /// a plugin added to the parent are inherited like any other tool but run without the plugin's
105    /// hooks. Pass a builder for a child that needs them.
106    #[builder(into)]
107    pub builder: Option<ChildAgentBuilder>,
108    /// Named roles the model selects with `agent_type`, in the order the schema lists them; a
109    /// repeated name replaces the earlier preset in its place. The [`generalist`] when absent.
110    #[builder(with = |presets: impl IntoIterator<Item = (impl Into<String>, Preset)>| {
111        presets.into_iter().map(|(name, preset)| (name.into(), preset)).collect()
112    })]
113    pub presets: Option<Vec<(String, Preset)>>,
114    /// The preset used when the model omits `agent_type`; the first preset when absent.
115    pub default_preset: Option<String>,
116    /// The policy for the child's system prompt: [`Open`], [`Choice`](crate::multiagent::Choice) or [`Fixed`]; `Open` when
117    /// absent.
118    pub instructions: Option<Axis>,
119    /// The policy for the child's tools: [`Choice`](crate::multiagent::Choice) (with `multiple`), [`Fixed`] or [`Inherit`];
120    /// `Inherit` when absent.
121    pub tools: Option<Axis>,
122    /// The policy for the child's model: [`Inherit`], [`Choice`](crate::multiagent::Choice) or [`Fixed`]; `Inherit` when
123    /// absent.
124    pub model: Option<Axis>,
125    /// How much of the parent's conversation the child sees: [`Fixed`] or [`Choice`](crate::multiagent::Choice) over
126    /// `none`, `all` and `no_tools`; `Fixed("none")` when absent.
127    pub context: Option<Axis>,
128    /// The most nested delegation levels; [`DEFAULT_SUBAGENT_MAX_DEPTH`] when absent.
129    pub max_depth: Option<usize>,
130    /// The tool name; `subagent` when absent.
131    pub name: Option<String>,
132    /// The tool description; [`DEFAULT_SUBAGENT_DESCRIPTION`] when absent.
133    pub description: Option<String>,
134}
135
136impl fmt::Debug for MakeSubagentOptions {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        f.debug_struct("MakeSubagentOptions")
139            .field("builder", &self.builder.is_some())
140            .field("presets", &self.presets)
141            .field("default_preset", &self.default_preset)
142            .field("instructions", &self.instructions)
143            .field("tools", &self.tools)
144            .field("model", &self.model)
145            .field("context", &self.context)
146            .field("max_depth", &self.max_depth)
147            .field("name", &self.name)
148            .finish_non_exhaustive()
149    }
150}
151
152fn check_axis(key: &str, axis: &Axis, allowed: &[&str]) -> Result<()> {
153    if allowed.contains(&axis.kind()) {
154        return Ok(());
155    }
156    Err(Error::other(format!(
157        "{key}: {} is not supported; use {}.",
158        axis.kind(),
159        allowed.join(", ")
160    )))
161}
162
163/// The default `subagent` tool: the generalist preset and every axis at its default
164/// (`subagent`).
165#[must_use]
166pub fn subagent() -> SubagentTool {
167    make_subagent(MakeSubagentOptions::default()).unwrap_or_else(|error| {
168        tracing::error!("error=<{error}> | default subagent options were rejected, using a task-only schema");
169        let schema = json!({
170            "type": "object",
171            "properties": {"task": {"type": "string", "description": TASK_DESCRIPTION}},
172            "required": ["task"]
173        });
174        SubagentTool {
175            inner: Arc::new(Inner {
176                name: "subagent".to_owned(),
177                spec: ToolSpec::new("subagent", DEFAULT_SUBAGENT_DESCRIPTION).with_input_schema(schema),
178                presets: IndexMap::from([("generalist".to_owned(), generalist())]),
179                default_preset: Some("generalist".to_owned()),
180                instructions: Axis::Open(Open),
181                tools: Axis::Inherit(Inherit),
182                model: Axis::Inherit(Inherit),
183                context: Axis::Fixed(Fixed::new("none")),
184                builder: None,
185                max_depth: DEFAULT_SUBAGENT_MAX_DEPTH,
186            }),
187        }
188    })
189}
190
191/// Creates a subagent tool whose input schema follows the axis policies and presets.
192///
193/// ```
194/// use strands::multiagent::{Choice, Preset};
195/// use strands::vended_tools::subagent::{MakeSubagentOptions, make_subagent};
196///
197/// let researcher = make_subagent(MakeSubagentOptions {
198///     presets: Some(vec![(
199///         "researcher".to_owned(),
200///         Preset::builder().instructions("You research topics.").description("research").build(),
201///     )]),
202///     context: Some(Choice::new(["none", "all"]).into()),
203///     ..MakeSubagentOptions::default()
204/// })?;
205/// let agent = strands::Agent::builder().tools([researcher]).printer(false).build()?;
206/// assert!(agent.tool_registry().get("subagent").is_some());
207/// # Ok::<(), strands::Error>(())
208/// ```
209///
210/// # Errors
211///
212/// When `max_depth` is 0, `name` or `description` is empty, `default_preset` is not a preset,
213/// an axis has a mode it does not support, a [`Choice`](crate::multiagent::Choice) has no options or (for tools) is not
214/// `multiple`, or a context mode is not `none`, `all` or `no_tools`.
215pub fn make_subagent(options: MakeSubagentOptions) -> Result<SubagentTool> {
216    let name = options.name.unwrap_or_else(|| "subagent".to_owned());
217    let description = options
218        .description
219        .unwrap_or_else(|| DEFAULT_SUBAGENT_DESCRIPTION.to_owned());
220    let max_depth = options.max_depth.unwrap_or(DEFAULT_SUBAGENT_MAX_DEPTH);
221    if name.is_empty() {
222        return Err(Error::other("name must be a non-empty string."));
223    }
224    if description.is_empty() {
225        return Err(Error::other("description must be a non-empty string."));
226    }
227    if max_depth < 1 {
228        return Err(Error::other("maxDepth must be a positive integer (>= 1)."));
229    }
230    let presets: IndexMap<String, Preset> = options.presets.map_or_else(
231        || IndexMap::from([("generalist".to_owned(), generalist())]),
232        |presets| presets.into_iter().collect(),
233    );
234    let instructions = options.instructions.unwrap_or(Axis::Open(Open));
235    let tools = options.tools.unwrap_or(Axis::Inherit(Inherit));
236    let model = options.model.unwrap_or(Axis::Inherit(Inherit));
237    let context = options.context.unwrap_or_else(|| Axis::Fixed(Fixed::new("none")));
238    check_axis("instructions", &instructions, &["Open", "Choice", "Fixed"])?;
239    check_axis("tools", &tools, &["Choice", "Fixed", "Inherit"])?;
240    check_axis("model", &model, &["Inherit", "Choice", "Fixed"])?;
241    check_axis("context", &context, &["Fixed", "Choice"])?;
242    let default_preset = options.default_preset.or_else(|| presets.keys().next().cloned());
243    if let Some(default_preset) = &default_preset
244        && !presets.contains_key(default_preset)
245    {
246        let names: Vec<&str> = presets.keys().map(String::as_str).collect();
247        return Err(Error::other(format!(
248            "defaultPreset '{default_preset}' is not one of the presets: {}.",
249            names.join(", ")
250        )));
251    }
252    for mode in context_modes(&context) {
253        if !mode.as_ref().is_some_and(|mode| CONTEXT_MODES.contains(&mode.as_str())) {
254            let shown = mode.map_or_else(|| "undefined".to_owned(), |mode| JsonValue::String(mode).to_string());
255            return Err(Error::other(format!(
256                "context mode {shown} must be one of: {}.",
257                CONTEXT_MODES.join(", ")
258            )));
259        }
260    }
261    let axes = SpecAxes {
262        presets: &presets,
263        default_preset: default_preset.as_deref(),
264        instructions: &instructions,
265        tools: &tools,
266        model: &model,
267    };
268    let schema = build_schema(&axes, &context)?;
269    let spec = ToolSpec::new(&name, &description).with_input_schema(schema);
270    Ok(SubagentTool {
271        inner: Arc::new(Inner {
272            name,
273            spec,
274            presets,
275            default_preset,
276            instructions,
277            tools,
278            model,
279            context,
280            builder: options.builder,
281            max_depth,
282        }),
283    })
284}
285
286/// The context mode each option of the context axis stands for.
287fn context_modes(context: &Axis) -> Vec<Option<String>> {
288    let text = |value: Option<SpecValue>| match value {
289        Some(SpecValue::Text(text)) => Some(text),
290        _ => None,
291    };
292    match context {
293        Axis::Choice(choice) => choice
294            .normalized()
295            .into_iter()
296            .map(|option| text(option.value))
297            .collect(),
298        Axis::Fixed(fixed) => vec![text(fixed.value.clone())],
299        _ => Vec::new(),
300    }
301}
302
303/// The input schema.
304fn build_schema(axes: &SpecAxes<'_>, context: &Axis) -> Result<JsonSchema> {
305    let mut properties = JsonObject::new();
306    properties.insert(
307        "task".to_owned(),
308        json!({"type": "string", "description": TASK_DESCRIPTION}),
309    );
310    properties.extend(schema_properties(axes)?);
311    if let Axis::Choice(choice) = context {
312        let options = choice.normalized();
313        let lines: Vec<String> = options
314            .iter()
315            .filter(|option| !option.description.is_empty())
316            .map(|option| format!("- {}: {}", option.name, option.description))
317            .collect();
318        let mut description = CONTEXT_DESCRIPTION.to_owned();
319        if !lines.is_empty() {
320            description = format!("{description}\nOptions:\n{}", lines.join("\n"));
321        }
322        let names: Vec<&str> = options.iter().map(|option| option.name.as_str()).collect();
323        properties.insert(
324            "context".to_owned(),
325            json!({"type": "string", "enum": names, "description": description}),
326        );
327        let shares = options
328            .iter()
329            .any(|option| option.value != Some(SpecValue::Text("none".to_owned())));
330        if shares {
331            properties.insert(
332                "last_messages".to_owned(),
333                json!({"type": "integer", "description": LAST_MESSAGES_DESCRIPTION}),
334            );
335        }
336    }
337    Ok(json!({"type": "object", "properties": properties, "required": ["task"]}))
338}
339
340/// The `subagent` tool: builds a fresh child per call and streams it (`SubagentTool`).
341#[derive(Clone)]
342pub struct SubagentTool {
343    inner: Arc<Inner>,
344}
345
346struct Inner {
347    name: String,
348    spec: ToolSpec,
349    presets: IndexMap<String, Preset>,
350    default_preset: Option<String>,
351    instructions: Axis,
352    tools: Axis,
353    model: Axis,
354    context: Axis,
355    builder: Option<ChildAgentBuilder>,
356    max_depth: usize,
357}
358
359impl fmt::Debug for SubagentTool {
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        f.debug_struct("SubagentTool")
362            .field("name", &self.inner.name)
363            .field("max_depth", &self.inner.max_depth)
364            .finish_non_exhaustive()
365    }
366}
367
368impl Tool for SubagentTool {
369    fn name(&self) -> &str {
370        &self.inner.name
371    }
372
373    fn description(&self) -> &str {
374        &self.inner.spec.description
375    }
376
377    fn tool_spec(&self) -> ToolSpec {
378        self.inner.spec.clone()
379    }
380
381    fn stream(&self, context: ToolContext) -> ToolStream {
382        let (sender, receiver) = futures::channel::mpsc::channel(0);
383        let run = self.inner.clone().run(context, sender);
384        let outcome = futures::stream::once(run).map(ToolStreamItem::Outcome);
385        ToolStream::new(merge_events_first(receiver.map(ToolStreamItem::Event), outcome))
386    }
387}
388
389/// A prepared call: the child and its prompt, or the outcome when the call ends early.
390enum Prepared {
391    Run(Box<Agent>, InvokeArgs),
392    Done(ToolOutcome),
393}
394
395fn error_result(tool_use_id: &str, text: impl Into<String>) -> ToolOutcome {
396    ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(text)]).into()
397}
398
399impl Inner {
400    fn axes(&self) -> SpecAxes<'_> {
401        SpecAxes {
402            presets: &self.presets,
403            default_preset: self.default_preset.as_deref(),
404            instructions: &self.instructions,
405            tools: &self.tools,
406            model: &self.model,
407        }
408    }
409
410    async fn build(&self, spec: &AgentSpec, parent: &ToolAgent) -> Result<Agent> {
411        match &self.builder {
412            Some(builder) => builder.build(spec.clone()).await,
413            None => default_builder(spec, parent),
414        }
415    }
416
417    fn fail(&self, tool_use_id: &str, message: &str) -> ToolOutcome {
418        tracing::warn!(
419            "tool_name=<{}>, tool_use_id=<{tool_use_id}>, error=<{message}> | subagent failed",
420            self.name
421        );
422        error_result(tool_use_id, format!("Subagent error: {message}"))
423    }
424
425    async fn run(
426        self: Arc<Self>,
427        context: ToolContext,
428        mut events: futures::channel::mpsc::Sender<ToolStreamEvent>,
429    ) -> ToolOutcome {
430        let tool_use_id = context.tool_use().tool_use_id.clone();
431        let raw = context.tool_use().input.as_object().cloned().unwrap_or_default();
432        let parent = context.agent();
433        let mut streamer = AgentToolStreamer::new(
434            parent.interrupt_state().clone(),
435            &tool_use_id,
436            "subagent",
437            true,
438            "Subagent".to_owned(),
439        );
440        let (mut child, prompt) = match self.prepare(&tool_use_id, &raw, parent, &mut streamer).await {
441            Prepared::Run(child, prompt) => (child, prompt),
442            Prepared::Done(outcome) => return outcome,
443        };
444        let options = InvokeOptions {
445            invocation_state: Some(context.invocation_state().copy()),
446            cancel_signal: Some(context.cancel_signal().clone()),
447            invocation_context: context.invocation_context().cloned(),
448            ..InvokeOptions::default()
449        };
450        if let Err(error) = streamer
451            .stream(&mut child, prompt, options, &self.name, &mut events)
452            .await
453        {
454            return self.fail(&tool_use_id, &error.to_string());
455        }
456        streamer.terminal_tool_result(|result: &AgentResult| vec![ToolResultContent::text(result.to_string())])
457    }
458
459    async fn prepare(
460        &self,
461        tool_use_id: &str,
462        raw: &JsonObject,
463        parent: &ToolAgent,
464        streamer: &mut AgentToolStreamer,
465    ) -> Prepared {
466        if streamer.is_resuming() {
467            return self.prepare_resume(tool_use_id, raw, parent, streamer).await;
468        }
469        let depth = parent
470            .app_state()
471            .get_value(DEPTH_STATE_KEY)
472            .and_then(|depth| depth.as_u64())
473            .map_or(self.max_depth, |depth| usize::try_from(depth).unwrap_or(usize::MAX));
474        if depth == 0 {
475            return Prepared::Done(error_result(
476                tool_use_id,
477                format!(
478                    "Delegation depth limit reached ({} levels); you cannot delegate further. Complete this task yourself instead of calling {} again.",
479                    self.max_depth, self.name
480                ),
481            ));
482        }
483        let Some(task) = raw
484            .get("task")
485            .and_then(JsonValue::as_str)
486            .filter(|task| !task.trim().is_empty())
487        else {
488            return Prepared::Done(error_result(
489                tool_use_id,
490                "Missing required parameter 'task': describe the task to delegate.",
491            ));
492        };
493        let spec = match resolve_spec(raw, &self.name, &self.axes()) {
494            Ok(spec) => spec,
495            Err(SpecError::Invalid(message)) => return Prepared::Done(self.fail(tool_use_id, &message)),
496            Err(SpecError::InstructionsNotText) => {
497                return Prepared::Done(error_result(tool_use_id, "Parameter 'instructions' must be a string."));
498            }
499        };
500        let child = match self.build(&spec, parent).await {
501            Ok(child) => child,
502            Err(error) => return Prepared::Done(self.fail(tool_use_id, &error.to_string())),
503        };
504        if let Err(error) = child.app_state().set(DEPTH_STATE_KEY, depth - 1) {
505            return Prepared::Done(self.fail(tool_use_id, &error.to_string()));
506        }
507        let prompt = self.prompt(task, raw, parent);
508        Prepared::Run(Box::new(child), prompt)
509    }
510
511    /// Rebuilds the interrupted child from the same input and restores its stored turn.
512    async fn prepare_resume(
513        &self,
514        tool_use_id: &str,
515        raw: &JsonObject,
516        parent: &ToolAgent,
517        streamer: &mut AgentToolStreamer,
518    ) -> Prepared {
519        let spec = match resolve_spec(raw, &self.name, &self.axes()) {
520            Ok(spec) => spec,
521            Err(SpecError::Invalid(message)) => return Prepared::Done(self.fail(tool_use_id, &message)),
522            Err(SpecError::InstructionsNotText) => {
523                return Prepared::Done(self.fail(tool_use_id, "Parameter 'instructions' must be a string."));
524            }
525        };
526        let mut child = match self.build(&spec, parent).await {
527            Ok(child) => Some(child),
528            Err(error) => {
529                tracing::warn!(
530                    "tool_name=<{}>, tool_use_id=<{tool_use_id}>, error=<{error}> | failed to rebuild interrupted subagent",
531                    self.name
532                );
533                None
534            }
535        };
536        match streamer.resume(child.as_mut(), UNAVAILABLE_MESSAGE).await {
537            Resume::Responses(responses) => match child {
538                Some(child) => Prepared::Run(Box::new(child), InvokeArgs::InterruptResponses(responses)),
539                None => Prepared::Done(error_result(tool_use_id, UNAVAILABLE_MESSAGE)),
540            },
541            Resume::Raise(interrupts) if interrupts.is_empty() => {
542                Prepared::Done(error_result(tool_use_id, "Subagent interrupted without any interrupts"))
543            }
544            Resume::Raise(interrupts) => Prepared::Done(ToolOutcome::Interrupt(crate::interrupt::InterruptError::new(
545                interrupts,
546            ))),
547            Resume::Stop => Prepared::Done(
548                streamer.terminal_tool_result(|result: &AgentResult| vec![ToolResultContent::text(result.to_string())]),
549            ),
550        }
551    }
552
553    /// The context mode and the positive `last_messages` limit from the model's input.
554    fn resolve_context(&self, raw: &JsonObject) -> (String, Option<usize>) {
555        let mode = match &self.context {
556            Axis::Choice(choice) => raw
557                .get("context")
558                .and_then(|value| match value {
559                    JsonValue::String(name) => Some(name.clone()),
560                    JsonValue::Null => None,
561                    other => Some(other.to_string()),
562                })
563                .filter(|name| choice.options.iter().any(|option| &option.name == name))
564                .and_then(|name| match choice.value_for(&name) {
565                    SpecValue::Text(mode) => Some(mode),
566                    _ => None,
567                }),
568            Axis::Fixed(Fixed {
569                value: Some(SpecValue::Text(mode)),
570            }) => Some(mode.clone()),
571            _ => None,
572        };
573        let last = match raw.get("last_messages") {
574            Some(JsonValue::Number(number)) => number.as_f64(),
575            Some(JsonValue::String(text)) => text.trim().parse::<f64>().ok(),
576            _ => None,
577        };
578        #[allow(
579            clippy::cast_possible_truncation,
580            clippy::cast_sign_loss,
581            reason = "checked to be at least 1"
582        )]
583        let last = last
584            .map(f64::trunc)
585            .filter(|count| count.is_finite() && *count >= 1.0)
586            .map(|count| count as usize);
587        (mode.unwrap_or_else(|| "none".to_owned()), last)
588    }
589
590    fn prompt(&self, task: &str, raw: &JsonObject, parent: &ToolAgent) -> InvokeArgs {
591        let (mode, last_messages) = self.resolve_context(raw);
592        match mode.as_str() {
593            "all" => {
594                let mut messages = fork_messages(parent.messages(), last_messages);
595                let framed = ContentBlock::text(format!("{FORK_PREAMBLE}\n\n{task}"));
596                match messages.last_mut() {
597                    None => InvokeArgs::Text(task.to_owned()),
598                    Some(last) if last.role == Role::User => {
599                        last.content.push(framed);
600                        InvokeArgs::Messages(messages)
601                    }
602                    Some(_) => {
603                        messages.push(Message::new(Role::User, vec![framed]));
604                        InvokeArgs::Messages(messages)
605                    }
606                }
607            }
608            "no_tools" => {
609                let block = render_context(parent.messages(), last_messages);
610                if block.is_empty() {
611                    InvokeArgs::Text(task.to_owned())
612                } else {
613                    InvokeArgs::Text(format!("{FRAMING_START}{block}\n{}{task}", framing_end()))
614                }
615            }
616            _ => InvokeArgs::Text(task.to_owned()),
617        }
618    }
619}
620
621/// The child the default builder makes: the parent's model, sandbox, printer
622/// setting, trace attributes, intervention handlers and tools (all, or those `spec.tools` names
623/// that the parent has, never its context manager's), named after the spec, with an `auto`
624/// context manager unless its model is stateful. The parent's hooks and plugins stay behind.
625fn default_builder(spec: &AgentSpec, parent: &ToolAgent) -> Result<Agent> {
626    let inheritance = parent.inheritance();
627    let managed: Vec<String> = inheritance
628        .context_manager
629        .as_ref()
630        .map(|manager| {
631            manager
632                .get_tools()
633                .into_iter()
634                .flat_map(|source| source.into_parts().tools)
635                .map(|tool| tool.name().to_owned())
636                .collect()
637        })
638        .unwrap_or_default();
639    let parent_tools: Vec<Arc<dyn Tool>> = parent
640        .tool_registry()
641        .list()
642        .into_iter()
643        .filter(|tool| !managed.iter().any(|name| name == tool.name()))
644        .collect();
645    let find = |name: &str| parent_tools.iter().find(|tool| tool.name() == name).cloned();
646    let tools: Vec<Arc<dyn Tool>> = match &spec.tools {
647        None => parent_tools.clone(),
648        Some(names) => names
649            .iter()
650            .filter_map(|name| {
651                let tool = find(name);
652                if tool.is_none() {
653                    tracing::warn!("tool_name=<{name}> | subagent requested tool but parent does not own it, skipping");
654                }
655                tool
656            })
657            .collect(),
658    };
659    let model = match &spec.model {
660        Some(SpecValue::Model(model)) => ModelSource::Model(model.clone()),
661        Some(SpecValue::Text(model_id)) => ModelSource::Id(model_id.clone()),
662        _ => ModelSource::Model(parent.model().clone()),
663    };
664    let stateful = matches!(&model, ModelSource::Model(model) if model.stateful());
665    let trace_attributes = inheritance
666        .tracer
667        .as_ref()
668        .map(|tracer| tracer.trace_attributes())
669        .unwrap_or_default();
670    Agent::builder()
671        .maybe_context_manager((!stateful).then_some(ContextManagerStrategy::Auto))
672        .trace_attributes(trace_attributes)
673        .interventions(inheritance.interventions.iter().cloned())
674        .system_prompt(spec.instructions.clone().unwrap_or_default())
675        .tools(tools)
676        .model(model)
677        .maybe_name(spec.name.clone())
678        .maybe_id(spec.name.clone())
679        .sandbox(parent.sandbox().clone())
680        .printer(parent.printer())
681        .build()
682}
683
684/// Copies the parent's messages without reasoning, injected context or unanswered tool calls,
685/// merging consecutive messages of one role, and widens a `last_messages` window so it never
686/// starts inside a tool pair.
687fn fork_messages(messages: &[Message], last_messages: Option<usize>) -> Vec<Message> {
688    let answered: Vec<&str> = messages
689        .iter()
690        .flat_map(|message| &message.content)
691        .filter_map(|block| match block {
692            ContentBlock::ToolResult(result) => Some(result.tool_use_id.as_str()),
693            _ => None,
694        })
695        .collect();
696    let mut forked: Vec<Message> = Vec::new();
697    for message in messages {
698        let content: Vec<ContentBlock> = message
699            .content
700            .iter()
701            .filter(|block| match block {
702                ContentBlock::Reasoning(_) | ContentBlock::Injected(_) => false,
703                ContentBlock::ToolUse(tool_use) => answered.contains(&tool_use.tool_use_id.as_str()),
704                _ => true,
705            })
706            .cloned()
707            .collect();
708        if content.is_empty() {
709            continue;
710        }
711        match forked.last_mut() {
712            Some(previous) if previous.role == message.role => previous.content.extend(content),
713            _ => forked.push(Message::new(message.role, content)),
714        }
715    }
716    let Some(last) = last_messages else {
717        return forked;
718    };
719    let mut start = forked.len().saturating_sub(last);
720    while start > 0 && find_valid_trim_point(&forked[start..(start + 2).min(forked.len())], 0) != 0 {
721        start -= 1;
722    }
723    forked.split_off(start)
724}
725
726/// Renders the parent's text turns as a plain-text block.
727fn render_context(messages: &[Message], last_messages: Option<usize>) -> String {
728    let messages = match last_messages {
729        Some(last) => &messages[messages.len().saturating_sub(last)..],
730        None => messages,
731    };
732    let framing_end = framing_end();
733    let lines: Vec<String> = messages
734        .iter()
735        .filter_map(|message| {
736            let text: Vec<&str> = message
737                .content
738                .iter()
739                .filter_map(|block| match block {
740                    ContentBlock::Text(text) => Some(text.text.as_str()),
741                    _ => None,
742                })
743                .collect();
744            let mut text = text.join(" ").trim().to_owned();
745            if text.starts_with(FRAMING_START)
746                && let Some(end) = text.find(&framing_end)
747            {
748                text = text[end + framing_end.len()..].to_owned();
749            }
750            (!text.is_empty()).then(|| format!("{}: {text}", role_name(message.role)).replace('\n', "\n  "))
751        })
752        .collect();
753    lines
754        .join("\n")
755        .replace("<parent_context>", "<\\parent_context>")
756        .replace("</parent_context>", "<\\/parent_context>")
757}
758
759fn role_name(role: Role) -> &'static str {
760    match role {
761        Role::User => "user",
762        _ => "assistant",
763    }
764}
765
766#[cfg(test)]
767mod tests;