Skip to main content

strands/multiagent/
spec.rs

1//! Multi-agent specification and resolution.
2//!
3//! The model configures child agents at runtime; the developer sets one policy per axis that
4//! shapes the parameters the model sees and what it may supply:
5//!
6//! - [`Fixed`]: a developer-pinned value, hidden from the model;
7//! - [`Inherit`]: the parent agent's value, hidden from the model;
8//! - [`Open`]: a free-form value from the model;
9//! - [`Choice`]: a pick from a developer-supplied set.
10
11use std::fmt;
12use std::future::Future;
13use std::sync::Arc;
14
15use futures::future::BoxFuture;
16use indexmap::IndexMap;
17use serde_json::json;
18
19use crate::agent::Agent;
20use crate::error::{Error, Result};
21use crate::models::Model;
22use crate::types::{JsonObject, JsonValue};
23
24/// The model-facing description of each axis parameter (`AXIS_DESCRIPTIONS`).
25pub(crate) const AGENT_TYPE_DESCRIPTION: &str = "Role to assign this agent.";
26pub(crate) const INSTRUCTIONS_DESCRIPTION: &str = "A system prompt defining this agent's role.";
27pub(crate) const TOOLS_DESCRIPTION: &str = "Subset of tools to grant this agent. Fewer is safer; it cannot exceed your own. Omit to grant all inherited tools.";
28pub(crate) const MODEL_DESCRIPTION: &str = "Which model this agent runs on. Omit to inherit the parent's model.";
29
30/// A value an axis pins or a choice stands for.
31#[derive(Clone)]
32#[non_exhaustive]
33pub enum SpecValue {
34    /// Text: instructions, a tool name, a context mode, or a Bedrock model id.
35    Text(String),
36    /// A list of tool names.
37    List(Vec<String>),
38    /// A model instance.
39    Model(Arc<dyn Model>),
40}
41
42impl SpecValue {
43    fn as_text(&self) -> Option<&str> {
44        match self {
45            Self::Text(text) => Some(text),
46            _ => None,
47        }
48    }
49}
50
51impl From<&str> for SpecValue {
52    fn from(text: &str) -> Self {
53        Self::Text(text.to_owned())
54    }
55}
56
57impl From<String> for SpecValue {
58    fn from(text: String) -> Self {
59        Self::Text(text)
60    }
61}
62
63impl From<Vec<String>> for SpecValue {
64    fn from(list: Vec<String>) -> Self {
65        Self::List(list)
66    }
67}
68
69impl From<Vec<&str>> for SpecValue {
70    fn from(list: Vec<&str>) -> Self {
71        Self::List(list.into_iter().map(str::to_owned).collect())
72    }
73}
74
75impl From<Arc<dyn Model>> for SpecValue {
76    fn from(model: Arc<dyn Model>) -> Self {
77        Self::Model(model)
78    }
79}
80
81impl fmt::Debug for SpecValue {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::Text(text) => f.debug_tuple("Text").field(text).finish(),
85            Self::List(list) => f.debug_tuple("List").field(list).finish(),
86            Self::Model(model) => f.debug_tuple("Model").field(&model.model_id()).finish(),
87        }
88    }
89}
90
91impl PartialEq for SpecValue {
92    fn eq(&self, other: &Self) -> bool {
93        match (self, other) {
94            (Self::Text(a), Self::Text(b)) => a == b,
95            (Self::List(a), Self::List(b)) => a == b,
96            (Self::Model(a), Self::Model(b)) => Arc::ptr_eq(a, b),
97            _ => false,
98        }
99    }
100}
101
102/// The developer pins the value; the axis adds no model-facing parameter (`Fixed`).
103#[derive(Debug, Clone, Default, PartialEq)]
104#[non_exhaustive]
105pub struct Fixed {
106    /// The pinned value; `None` pins "unset".
107    pub value: Option<SpecValue>,
108}
109
110impl Fixed {
111    /// Pins `value`.
112    pub fn new(value: impl Into<SpecValue>) -> Self {
113        Self {
114            value: Some(value.into()),
115        }
116    }
117
118    /// Pins "unset".
119    #[must_use]
120    pub fn none() -> Self {
121        Self::default()
122    }
123}
124
125/// The child takes the parent's value; the axis adds no model-facing parameter (`Inherit`).
126#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
127#[non_exhaustive]
128pub struct Inherit;
129
130impl Inherit {
131    /// The inherit marker.
132    #[must_use]
133    pub fn new() -> Self {
134        Self
135    }
136}
137
138/// The model writes the value freely; the axis adds a string parameter (`Open`).
139#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
140#[non_exhaustive]
141pub struct Open;
142
143impl Open {
144    /// The open marker.
145    #[must_use]
146    pub fn new() -> Self {
147        Self
148    }
149}
150
151/// A selectable entry of a [`Choice`] (named to stay clear of the prelude's `Option`).
152#[derive(Debug, Clone, PartialEq)]
153#[non_exhaustive]
154pub struct ChoiceOption {
155    /// The name the model picks.
156    pub name: String,
157    /// The value behind the name; `None` stands for the name itself.
158    pub value: Option<SpecValue>,
159    /// Shown to the model next to the name.
160    pub description: String,
161}
162
163impl ChoiceOption {
164    /// An option standing for its own name.
165    pub fn new(name: impl Into<String>) -> Self {
166        Self {
167            name: name.into(),
168            value: None,
169            description: String::new(),
170        }
171    }
172
173    /// Sets the value behind the name.
174    #[must_use]
175    pub fn with_value(mut self, value: impl Into<SpecValue>) -> Self {
176        self.value = Some(value.into());
177        self
178    }
179
180    /// Sets the description shown to the model.
181    #[must_use]
182    pub fn with_description(mut self, description: impl Into<String>) -> Self {
183        self.description = description.into();
184        self
185    }
186
187    fn resolved_value(&self) -> SpecValue {
188        self.value.clone().unwrap_or_else(|| SpecValue::Text(self.name.clone()))
189    }
190}
191
192impl From<&str> for ChoiceOption {
193    fn from(name: &str) -> Self {
194        Self::new(name)
195    }
196}
197
198impl From<String> for ChoiceOption {
199    fn from(name: String) -> Self {
200        Self::new(name)
201    }
202}
203
204/// The model picks from a developer-supplied set (`Choice`); with `multiple`, more than one.
205///
206/// ```
207/// use strands::multiagent::{Choice, ChoiceOption};
208///
209/// let tools = Choice::new([ChoiceOption::new("readonly").with_value("read"), "shell".into()]).multiple(true);
210/// assert_eq!(tools.value_for("readonly"), "read".into());
211/// assert_eq!(tools.value_for("unknown"), "unknown".into());
212/// ```
213#[derive(Debug, Clone, PartialEq)]
214#[non_exhaustive]
215pub struct Choice {
216    /// The options, bare names or [`ChoiceOption`]s.
217    pub options: Vec<ChoiceOption>,
218    /// Whether the model may pick several, as an array.
219    pub multiple: bool,
220}
221
222impl Choice {
223    /// A single choice from `options`.
224    pub fn new(options: impl IntoIterator<Item = impl Into<ChoiceOption>>) -> Self {
225        Self {
226            options: options.into_iter().map(Into::into).collect(),
227            multiple: false,
228        }
229    }
230
231    /// Sets whether the model may pick several.
232    #[must_use]
233    pub fn multiple(mut self, multiple: bool) -> Self {
234        self.multiple = multiple;
235        self
236    }
237
238    /// The options with each value resolved: an unset value stands for the name (`normalized`).
239    #[must_use]
240    pub fn normalized(&self) -> Vec<ChoiceOption> {
241        self.options
242            .iter()
243            .map(|option| ChoiceOption {
244                value: Some(option.resolved_value()),
245                ..option.clone()
246            })
247            .collect()
248    }
249
250    /// The value behind `name`, or `name` itself when no option has it.
251    #[must_use]
252    pub fn value_for(&self, name: &str) -> SpecValue {
253        self.options
254            .iter()
255            .find(|option| option.name == name)
256            .map_or_else(|| SpecValue::Text(name.to_owned()), ChoiceOption::resolved_value)
257    }
258
259    fn has(&self, name: &str) -> bool {
260        self.options.iter().any(|option| option.name == name)
261    }
262}
263
264/// Any authority mode an axis can take (`Axis`).
265#[derive(Debug, Clone, PartialEq)]
266#[non_exhaustive]
267pub enum Axis {
268    /// [`Fixed`].
269    Fixed(Fixed),
270    /// [`Inherit`].
271    Inherit(Inherit),
272    /// [`Open`].
273    Open(Open),
274    /// [`Choice`].
275    Choice(Choice),
276}
277
278impl Axis {
279    /// The mode's name, for error messages.
280    pub(crate) fn kind(&self) -> &'static str {
281        match self {
282            Self::Fixed(_) => "Fixed",
283            Self::Inherit(_) => "Inherit",
284            Self::Open(_) => "Open",
285            Self::Choice(_) => "Choice",
286        }
287    }
288}
289
290impl From<Fixed> for Axis {
291    fn from(axis: Fixed) -> Self {
292        Self::Fixed(axis)
293    }
294}
295
296impl From<Inherit> for Axis {
297    fn from(axis: Inherit) -> Self {
298        Self::Inherit(axis)
299    }
300}
301
302impl From<Open> for Axis {
303    fn from(axis: Open) -> Self {
304        Self::Open(axis)
305    }
306}
307
308impl From<Choice> for Axis {
309    fn from(axis: Choice) -> Self {
310        Self::Choice(axis)
311    }
312}
313
314/// A named role, selected with `agent_type`: a partial child configuration (`Preset`).
315#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
316#[builder(on(String, into))]
317#[non_exhaustive]
318pub struct Preset {
319    /// The child's system prompt.
320    pub instructions: Option<String>,
321    /// The tool names granted to the child.
322    #[builder(with = |tools: impl IntoIterator<Item = impl Into<String>>| tools.into_iter().map(Into::into).collect())]
323    pub tools: Option<Vec<String>>,
324    /// The child's model: an instance ([`SpecValue::Model`]) or a Bedrock model id
325    /// ([`SpecValue::Text`]).
326    #[builder(into)]
327    pub model: Option<SpecValue>,
328    /// Shown to the model next to the preset's name.
329    #[builder(default)]
330    pub description: String,
331}
332
333/// The resolved configuration of one child agent, handed to the [`ChildAgentBuilder`]
334/// (`AgentSpec`). `None` fields inherit from the parent.
335#[derive(Debug, Clone, Default, PartialEq)]
336#[non_exhaustive]
337pub struct AgentSpec {
338    /// The child's name, which the default builder also uses as its id.
339    pub name: Option<String>,
340    /// The preset the child was built from.
341    pub agent_type: Option<String>,
342    /// The child's system prompt.
343    pub instructions: Option<String>,
344    /// The tool names granted to the child; `None` grants all of the parent's.
345    pub tools: Option<Vec<String>>,
346    /// The child's model; `None` inherits the parent's.
347    pub model: Option<SpecValue>,
348}
349
350/// Turns a resolved spec into a child agent, built the way the parent was (`AgentBuilder`). The
351/// builder may be async: the child is awaited before it runs.
352///
353/// ```
354/// use strands::Agent;
355/// use strands::multiagent::{AgentSpec, ChildAgentBuilder};
356/// use strands::testing::MockModel;
357///
358/// let from_async = ChildAgentBuilder::new(|spec: AgentSpec| async move {
359///     let _ = spec;
360///     Agent::builder().model(MockModel::new()).printer(false).build()
361/// });
362/// let from_sync = ChildAgentBuilder::sync(|_spec: &AgentSpec| {
363///     Agent::builder().model(MockModel::new()).printer(false).build()
364/// });
365/// # let _ = (from_async, from_sync);
366/// ```
367#[derive(Clone)]
368pub struct ChildAgentBuilder(Arc<dyn Fn(AgentSpec) -> BoxFuture<'static, Result<Agent>> + Send + Sync>);
369
370impl ChildAgentBuilder {
371    /// A builder from an async closure.
372    pub fn new<F, Fut>(build: F) -> Self
373    where
374        F: Fn(AgentSpec) -> Fut + Send + Sync + 'static,
375        Fut: Future<Output = Result<Agent>> + Send + 'static,
376    {
377        Self(Arc::new(move |spec| Box::pin(build(spec))))
378    }
379
380    /// A builder from a synchronous closure.
381    pub fn sync(build: impl Fn(&AgentSpec) -> Result<Agent> + Send + Sync + 'static) -> Self {
382        Self(Arc::new(move |spec| {
383            let child = build(&spec);
384            Box::pin(async move { child })
385        }))
386    }
387
388    /// Builds the child for `spec`.
389    pub fn build(&self, spec: AgentSpec) -> BoxFuture<'static, Result<Agent>> {
390        (self.0)(spec)
391    }
392}
393
394impl fmt::Debug for ChildAgentBuilder {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        f.write_str("ChildAgentBuilder(..)")
397    }
398}
399
400/// Describes a preset by its description plus the fields it sets.
401fn describe_preset(preset: &Preset) -> String {
402    let mut parts = Vec::new();
403    if preset.instructions.is_some() {
404        parts.push("instructions".to_owned());
405    }
406    if let Some(tools) = &preset.tools {
407        let names = if tools.is_empty() {
408            "none".to_owned()
409        } else {
410            tools.join(", ")
411        };
412        parts.push(format!("tools: {names}"));
413    }
414    match &preset.model {
415        Some(SpecValue::Text(model)) => parts.push(format!("model: {model}")),
416        Some(_) => parts.push("model".to_owned()),
417        None => {}
418    }
419    if parts.is_empty() {
420        return preset.description.clone();
421    }
422    let sets = format!("sets {}", parts.join("; "));
423    if preset.description.is_empty() {
424        sets
425    } else {
426        format!("{} ({sets})", preset.description)
427    }
428}
429
430/// The axes [`schema_properties`] and [`resolve_spec`] read.
431pub(crate) struct SpecAxes<'a> {
432    pub(crate) presets: &'a IndexMap<String, Preset>,
433    pub(crate) default_preset: Option<&'a str>,
434    pub(crate) instructions: &'a Axis,
435    pub(crate) tools: &'a Axis,
436    pub(crate) model: &'a Axis,
437}
438
439/// Renders each model-visible axis, plus an `agent_type` choice over the presets, as JSON Schema
440/// properties.
441pub(crate) fn schema_properties(axes: &SpecAxes<'_>) -> Result<JsonObject> {
442    let agent_type = (!axes.presets.is_empty()).then(|| {
443        Axis::Choice(Choice::new(axes.presets.iter().map(|(name, preset)| {
444            ChoiceOption::new(name).with_description(describe_preset(preset))
445        })))
446    });
447    let entries = [
448        ("agent_type", AGENT_TYPE_DESCRIPTION, agent_type.as_ref()),
449        ("instructions", INSTRUCTIONS_DESCRIPTION, Some(axes.instructions)),
450        ("tools", TOOLS_DESCRIPTION, Some(axes.tools)),
451        ("model", MODEL_DESCRIPTION, Some(axes.model)),
452    ];
453    let mut properties = JsonObject::new();
454    for (key, base, axis) in entries {
455        let mut description = base.to_owned();
456        if key == "agent_type"
457            && let Some(default) = axes.default_preset
458        {
459            description = format!("{description} Omit to use the default ('{default}').");
460        }
461        match axis {
462            Some(Axis::Open(_)) => {
463                properties.insert(key.to_owned(), json!({"type": "string", "description": description}));
464            }
465            Some(Axis::Choice(choice)) => {
466                properties.insert(key.to_owned(), choice_property(key, choice, description)?);
467            }
468            _ => {}
469        }
470    }
471    Ok(properties)
472}
473
474fn choice_property(key: &str, choice: &Choice, mut description: String) -> Result<JsonValue> {
475    if choice.options.is_empty() {
476        return Err(Error::other(format!(
477            "{key}: new Choice([]) offers no options; use new Fixed(...), or omit {key} to use its default."
478        )));
479    }
480    if key == "tools" && !choice.multiple {
481        return Err(Error::other(format!(
482            "{key}: new Choice(...) must set multiple to true; a child agent selects a subset of {key}."
483        )));
484    }
485    let values: Vec<&str> = choice.options.iter().map(|option| option.name.as_str()).collect();
486    let lines: Vec<String> = choice
487        .options
488        .iter()
489        .filter(|option| !option.description.is_empty())
490        .map(|option| format!("- {}: {}", option.name, option.description))
491        .collect();
492    if !lines.is_empty() {
493        description = format!("{description}\nOptions:\n{}", lines.join("\n"));
494    }
495    Ok(if choice.multiple {
496        json!({"type": "array", "items": {"type": "string", "enum": values}, "description": description})
497    } else {
498        json!({"type": "string", "enum": values, "description": description})
499    })
500}
501
502/// A scalar axis: the model's value, then the preset's, then the axis default.
503/// The model's value is the raw JSON, which an [`Open`] axis passes through.
504fn resolve_scalar(model_value: Option<&JsonValue>, axis: &Axis, preset_value: Option<SpecValue>) -> Option<Resolved> {
505    if let Some(value) = model_value {
506        if matches!(axis, Axis::Open(_)) {
507            return Some(Resolved::Raw(value.clone()));
508        }
509        if let (Axis::Choice(choice), Some(name)) = (axis, value.as_str())
510            && choice.has(name)
511        {
512            return Some(Resolved::Value(choice.value_for(name)));
513        }
514    }
515    if let Some(value) = preset_value {
516        return Some(Resolved::Value(value));
517    }
518    match axis {
519        Axis::Fixed(fixed) => fixed.value.clone().map(Resolved::Value),
520        _ => None,
521    }
522}
523
524enum Resolved {
525    Raw(JsonValue),
526    Value(SpecValue),
527}
528
529/// A list axis: the model's picks among the allowed options, then the preset's (clamped to the
530/// options), then every option of a multiple choice, then a fixed list.
531fn resolve_list(model_value: Option<&JsonValue>, axis: &Axis, preset_values: Option<&[String]>) -> Option<Vec<String>> {
532    let choice = match axis {
533        Axis::Choice(choice) => Some(choice),
534        _ => None,
535    };
536    let text_of = |choice: &Choice, name: &str| choice.value_for(name).as_text().map(str::to_owned);
537    if let (Some(value), Some(choice)) = (model_value, choice) {
538        let requested: Vec<&str> = match value {
539            JsonValue::String(name) => vec![name.as_str()],
540            JsonValue::Array(names) => names.iter().filter_map(JsonValue::as_str).collect(),
541            _ => Vec::new(),
542        };
543        return Some(
544            requested
545                .into_iter()
546                .filter(|name| choice.has(name))
547                .filter_map(|name| text_of(choice, name))
548                .collect(),
549        );
550    }
551    if let Some(preset_values) = preset_values {
552        let Some(choice) = choice else {
553            return Some(preset_values.to_vec());
554        };
555        let allowed: Vec<String> = choice
556            .options
557            .iter()
558            .filter_map(|option| text_of(choice, &option.name))
559            .collect();
560        return Some(
561            preset_values
562                .iter()
563                .filter(|tool| allowed.contains(tool))
564                .cloned()
565                .collect(),
566        );
567    }
568    match axis {
569        Axis::Choice(choice) if choice.multiple => Some(
570            choice
571                .options
572                .iter()
573                .filter_map(|option| text_of(choice, &option.name))
574                .collect(),
575        ),
576        Axis::Fixed(Fixed {
577            value: Some(SpecValue::List(list)),
578        }) => Some(list.clone()),
579        Axis::Fixed(Fixed {
580            value: Some(SpecValue::Text(name)),
581        }) => Some(vec![name.clone()]),
582        _ => None,
583    }
584}
585
586/// Why a model input could not be resolved into a spec.
587#[derive(Debug)]
588pub(crate) enum SpecError {
589    /// The input is invalid in a way the model can fix.
590    Invalid(String),
591    /// `instructions` resolved to something other than a string.
592    InstructionsNotText,
593}
594
595/// Combines one model input, named `name`, with the axis policies into a spec. A model-supplied
596/// value wins, then the preset's, then the axis default; an omitted `agent_type` selects the
597/// default preset unless the model wrote its own instructions.
598pub(crate) fn resolve_spec(
599    input: &JsonObject,
600    name: &str,
601    axes: &SpecAxes<'_>,
602) -> std::result::Result<AgentSpec, SpecError> {
603    let model_agent_type = input.get("agent_type").filter(|value| !value.is_null());
604    let known = model_agent_type
605        .and_then(JsonValue::as_str)
606        .filter(|agent_type| axes.presets.contains_key(*agent_type));
607    if model_agent_type.is_some() && known.is_none() {
608        let mut names: Vec<&str> = axes.presets.keys().map(String::as_str).collect();
609        names.sort_unstable();
610        let shown = model_agent_type.map(JsonValue::to_string).unwrap_or_default();
611        return Err(SpecError::Invalid(format!(
612            "Unknown agent_type {shown}; valid values: {}.",
613            names.join(", ")
614        )));
615    }
616    let overriding_instructions =
617        matches!(axes.instructions, Axis::Open(_) | Axis::Choice(_)) && input.contains_key("instructions");
618    let agent_type = match known {
619        Some(agent_type) => Some(agent_type.to_owned()),
620        None if !overriding_instructions => axes.default_preset.map(str::to_owned),
621        None => None,
622    };
623    let preset = agent_type.as_ref().and_then(|agent_type| axes.presets.get(agent_type));
624    let present = |key: &str| input.get(key).filter(|value| !value.is_null());
625
626    let instructions = match resolve_scalar(
627        present("instructions"),
628        axes.instructions,
629        preset
630            .and_then(|preset| preset.instructions.clone())
631            .map(SpecValue::Text),
632    ) {
633        None => None,
634        Some(Resolved::Raw(JsonValue::String(text)) | Resolved::Value(SpecValue::Text(text))) => Some(text),
635        Some(_) => return Err(SpecError::InstructionsNotText),
636    };
637    let tools = resolve_list(
638        present("tools"),
639        axes.tools,
640        preset.and_then(|preset| preset.tools.as_deref()),
641    );
642    let model = match resolve_scalar(
643        present("model"),
644        axes.model,
645        preset.and_then(|preset| preset.model.clone()),
646    ) {
647        Some(Resolved::Value(value)) => Some(value),
648        Some(Resolved::Raw(JsonValue::String(text))) => Some(SpecValue::Text(text)),
649        _ => None,
650    };
651    Ok(AgentSpec {
652        name: Some(name.to_owned()),
653        agent_type,
654        instructions,
655        tools,
656        model,
657    })
658}
659
660/// Choices, preset descriptions, schema properties and spec resolution, as the subagent tool uses
661/// them.
662#[cfg(test)]
663mod tests {
664    use super::*;
665
666    fn presets() -> IndexMap<String, Preset> {
667        IndexMap::from([
668            (
669                "researcher".to_owned(),
670                Preset::builder()
671                    .instructions("research")
672                    .tools(["read"])
673                    .description("finds facts")
674                    .build(),
675            ),
676            ("bare".to_owned(), Preset::default()),
677        ])
678    }
679
680    fn axes<'a>(
681        presets: &'a IndexMap<String, Preset>,
682        instructions: &'a Axis,
683        tools: &'a Axis,
684        model: &'a Axis,
685    ) -> SpecAxes<'a> {
686        SpecAxes {
687            presets,
688            default_preset: presets.keys().next().map(String::as_str),
689            instructions,
690            tools,
691            model,
692        }
693    }
694
695    #[test]
696    fn describes_presets_by_the_fields_they_set() {
697        let presets = presets();
698        assert_eq!(
699            describe_preset(&presets["researcher"]),
700            "finds facts (sets instructions; tools: read)"
701        );
702        assert_eq!(describe_preset(&presets["bare"]), "");
703        let model_only = Preset::builder().model("claude").build();
704        assert_eq!(describe_preset(&model_only), "sets model: claude");
705        let no_tools = Preset::builder().tools(Vec::<String>::new()).build();
706        assert_eq!(describe_preset(&no_tools), "sets tools: none");
707    }
708
709    #[test]
710    fn resolves_model_value_then_preset_then_axis_default() {
711        let presets = presets();
712        let (open, inherit) = (Axis::Open(Open), Axis::Inherit(Inherit));
713        let axes = axes(&presets, &open, &inherit, &inherit);
714        let input = json!({"task": "x"});
715        let spec = resolve_spec(input.as_object().unwrap(), "sub", &axes).unwrap();
716        assert_eq!(spec.agent_type.as_deref(), Some("researcher"));
717        assert_eq!(spec.instructions.as_deref(), Some("research"));
718        assert_eq!(spec.tools, Some(vec!["read".to_owned()]));
719        let input = json!({"instructions": "custom"});
720        let spec = resolve_spec(input.as_object().unwrap(), "sub", &axes).unwrap();
721        assert_eq!(spec.agent_type, None);
722        assert_eq!(spec.instructions.as_deref(), Some("custom"));
723        assert_eq!(spec.tools, None);
724    }
725
726    #[test]
727    fn rejects_an_unknown_agent_type() {
728        let presets = presets();
729        let (open, inherit) = (Axis::Open(Open), Axis::Inherit(Inherit));
730        let input = json!({"agent_type": "nope"});
731        let Err(SpecError::Invalid(message)) = resolve_spec(
732            input.as_object().unwrap(),
733            "sub",
734            &axes(&presets, &open, &inherit, &inherit),
735        ) else {
736            panic!("expected an invalid input");
737        };
738        assert_eq!(message, "Unknown agent_type \"nope\"; valid values: bare, researcher.");
739    }
740
741    #[test]
742    fn clamps_preset_tools_to_the_choice() {
743        let presets = presets();
744        let tools = Axis::Choice(Choice::new(["write"]).multiple(true));
745        let (fixed, inherit) = (Axis::Fixed(Fixed::none()), Axis::Inherit(Inherit));
746        let spec = resolve_spec(&JsonObject::new(), "sub", &axes(&presets, &fixed, &tools, &inherit)).unwrap();
747        assert_eq!(spec.tools, Some(Vec::new()));
748    }
749
750    #[test]
751    fn wraps_strings_and_fills_unset() {
752        let choice = Choice::new([
753            ChoiceOption::new("alias").with_value("real").with_description("d"),
754            ChoiceOption::new("bare"),
755            "raw".into(),
756        ]);
757        let options = choice.normalized();
758        assert_eq!(options.len(), 3);
759        assert_eq!(options[0].value, Some("real".into()));
760        assert_eq!(options[0].description, "d");
761        assert_eq!(options[1].value, Some("bare".into()));
762        assert_eq!(
763            (options[2].name.as_str(), options[2].value.clone()),
764            ("raw", Some("raw".into()))
765        );
766    }
767
768    #[test]
769    fn returns_mapped_value_for_known_option_and_passthrough_for_unknown() {
770        let choice = Choice::new([ChoiceOption::new("alias").with_value("real")]);
771        assert_eq!(choice.value_for("alias"), "real".into());
772        assert_eq!(choice.value_for("missing"), "missing".into());
773    }
774
775    #[test]
776    fn rejects_prototype_keys_null_and_non_string_agent_type_values() {
777        let presets = IndexMap::from([("g".to_owned(), Preset::default())]);
778        let (open, inherit) = (Axis::Open(Open), Axis::Inherit(Inherit));
779        let axes = axes(&presets, &open, &inherit, &inherit);
780        for bad in [
781            json!("constructor"),
782            json!("toString"),
783            json!("__proto__"),
784            json!(["g"]),
785        ] {
786            let input = json!({"task": "x", "agent_type": bad});
787            let Err(SpecError::Invalid(message)) = resolve_spec(input.as_object().unwrap(), "a", &axes) else {
788                panic!("expected an invalid input for {bad}");
789            };
790            assert!(message.starts_with("Unknown agent_type"), "{message}");
791        }
792        let input = json!({"task": "x", "agent_type": null});
793        let spec = resolve_spec(input.as_object().unwrap(), "a", &axes).unwrap();
794        assert_eq!(spec.agent_type.as_deref(), Some("g"));
795    }
796
797    #[test]
798    fn resolves_fixed_tools_list() {
799        let presets = IndexMap::new();
800        let (open, inherit) = (Axis::Open(Open), Axis::Inherit(Inherit));
801        let tools = Axis::Fixed(Fixed::new(vec!["a", "b"]));
802        let input = json!({"task": "x"});
803        let spec = resolve_spec(
804            input.as_object().unwrap(),
805            "a",
806            &axes(&presets, &open, &tools, &inherit),
807        )
808        .unwrap();
809        assert_eq!(spec.tools, Some(vec!["a".to_owned(), "b".to_owned()]));
810    }
811
812    #[test]
813    fn resolves_fixed_empty_to_empty_array_not_undefined() {
814        let presets = IndexMap::new();
815        let (open, inherit) = (Axis::Open(Open), Axis::Inherit(Inherit));
816        let tools = Axis::Fixed(Fixed::new(Vec::<String>::new()));
817        let input = json!({"task": "x"});
818        let spec = resolve_spec(
819            input.as_object().unwrap(),
820            "a",
821            &axes(&presets, &open, &tools, &inherit),
822        )
823        .unwrap();
824        assert_eq!(spec.tools, Some(Vec::new()));
825    }
826
827    #[test]
828    fn rejects_empty_choices_and_single_tool_choices() {
829        let presets = IndexMap::new();
830        let (open, inherit) = (Axis::Open(Open), Axis::Inherit(Inherit));
831        let empty = Axis::Choice(Choice::new(Vec::<String>::new()));
832        let error = schema_properties(&axes(&presets, &open, &inherit, &empty)).unwrap_err();
833        assert_eq!(
834            error.to_string(),
835            "model: new Choice([]) offers no options; use new Fixed(...), or omit model to use its default."
836        );
837        let error = schema_properties(&axes(&presets, &open, &empty, &inherit)).unwrap_err();
838        assert!(error.to_string().contains("offers no options"), "{error}");
839        let error = schema_properties(&axes(&presets, &empty, &inherit, &inherit)).unwrap_err();
840        assert!(error.to_string().contains("offers no options"), "{error}");
841        let single = Axis::Choice(Choice::new(["read", "shell"]));
842        let error = schema_properties(&axes(&presets, &open, &single, &inherit)).unwrap_err();
843        assert_eq!(
844            error.to_string(),
845            "tools: new Choice(...) must set multiple to true; a child agent selects a subset of tools."
846        );
847    }
848}