Skip to main content

strands_harness/
agent.rs

1//! The harness factory: a preconfigured Strands [`Agent`] in one call.
2
3use std::collections::{BTreeMap, HashSet};
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use futures::future::BoxFuture;
9use strands::background_tasks::BackgroundTasksConfig;
10use strands::context_manager::ContextManagerStrategy;
11use strands::conversation_manager::ConversationManager;
12use strands::hooks::InitializedEvent;
13use strands::interventions::InterventionHandler;
14use strands::memory::{MemoryManager, MemoryManagerSource};
15use strands::plugins::Plugin;
16use strands::retry::RetryStrategy;
17use strands::sandbox::Sandbox;
18use strands::session::{SaveLatestStrategy, SessionManager, SessionManagerConfig};
19use strands::storage::{LocalFileStorage, Storage};
20use strands::telemetry::AttributeValue;
21use strands::tools::{Tool, ToolExecutorStrategy, ToolSource};
22use strands::types::{JsonObject, JsonSchema, Message, SystemPrompt, Toggle};
23use strands::vended_plugins::skills::{AgentSkills, AgentSkillsConfig, SkillSource};
24use strands::{Agent, AgentConfig, ModelSource};
25
26use crate::builtin_tools::{
27    WebSearchMode, build_builtin_tools, resolve_builtin_tools, web_search_explicit, web_search_mode,
28};
29use crate::config::BuiltinPluginName;
30use crate::defaults::{DEFAULT_BUILTIN_PLUGINS, DEFAULT_MODEL, DEFAULT_SESSION_DIR, DEFAULT_SKILLS_DIR};
31use crate::env::Env;
32use crate::factory::{BUILTIN_TOOL_FACTORY, BuiltinToolFactory, ENVIRONMENT_PLUGIN_NAME};
33use crate::interventions::{InterventionsOption, resolve_interventions};
34use crate::memory::{ResolveMemoryOptions, resolve_memory};
35use crate::models::{ModelPlan, ModelRequest, resolve_model};
36use crate::prompt::build_system_prompt;
37use crate::telemetry::setup_telemetry;
38use crate::types::{
39    BuiltinToolsConfig, BuiltinToolsOption, ContextManagerOption, Effort, McpServersOption, MemoryConfig, SessionConfig,
40};
41
42/// The name the SDK's skills plugin registers under.
43const AGENT_SKILLS_NAME: &str = "strands:agent-skills";
44
45/// The delegation tool always runs in the background: its calls are long-running subtasks whose
46/// intermediate work should stay out of the parent's turn.
47const ALWAYS_BACKGROUND_TOOL_NAMES: [&str; 1] = ["subagent"];
48
49/// What `session` accepts.
50#[derive(Clone)]
51#[non_exhaustive]
52pub enum SessionOption {
53    /// No persistence (`false`, `null`): the conversation and offloaded artifacts stay in memory.
54    Off,
55    /// File-backed persistence under the config's directory and id (`true` is the empty config).
56    On(SessionConfig),
57    /// A session manager, used as is. Pass [`storage`](HarnessAgentOptions::storage) with it, or
58    /// offloaded artifacts are embedded in its snapshots.
59    Manager(SessionManager),
60}
61
62impl From<bool> for SessionOption {
63    fn from(enabled: bool) -> Self {
64        if enabled {
65            Self::On(SessionConfig::default())
66        } else {
67            Self::Off
68        }
69    }
70}
71
72impl From<SessionConfig> for SessionOption {
73    fn from(config: SessionConfig) -> Self {
74        Self::On(config)
75    }
76}
77
78impl From<SessionManager> for SessionOption {
79    fn from(manager: SessionManager) -> Self {
80        Self::Manager(manager)
81    }
82}
83
84impl fmt::Debug for SessionOption {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::Off => f.write_str("Off"),
88            Self::On(config) => f.debug_tuple("On").field(config).finish(),
89            Self::Manager(manager) => f.debug_tuple("Manager").field(&manager.session_id()).finish(),
90        }
91    }
92}
93
94/// What `skills` accepts.
95#[derive(Debug, Clone)]
96#[non_exhaustive]
97pub enum SkillsOption {
98    /// No skills (`false`, `null`).
99    Off,
100    /// Scans `./.agent/skills` when it exists (`true`, the default).
101    Default,
102    /// These sources, passed to the SDK's `AgentSkills` plugin unfiltered: the plugin reads them
103    /// through the agent's sandbox and warns on a missing one. An empty list is off.
104    Sources(Vec<SkillSource>),
105    /// A plugin instance, used as is.
106    Plugin(AgentSkills),
107}
108
109impl From<bool> for SkillsOption {
110    fn from(enabled: bool) -> Self {
111        if enabled { Self::Default } else { Self::Off }
112    }
113}
114
115impl From<SkillSource> for SkillsOption {
116    fn from(source: SkillSource) -> Self {
117        Self::Sources(vec![source])
118    }
119}
120
121impl From<&str> for SkillsOption {
122    fn from(source: &str) -> Self {
123        Self::Sources(vec![source.into()])
124    }
125}
126
127impl From<String> for SkillsOption {
128    fn from(source: String) -> Self {
129        Self::Sources(vec![source.into()])
130    }
131}
132
133impl From<PathBuf> for SkillsOption {
134    fn from(source: PathBuf) -> Self {
135        Self::Sources(vec![source.into()])
136    }
137}
138
139impl From<&Path> for SkillsOption {
140    fn from(source: &Path) -> Self {
141        Self::Sources(vec![source.into()])
142    }
143}
144
145impl<T: Into<SkillSource>> From<Vec<T>> for SkillsOption {
146    fn from(sources: Vec<T>) -> Self {
147        Self::Sources(sources.into_iter().map(Into::into).collect())
148    }
149}
150
151impl<T: Into<SkillSource>, const N: usize> From<[T; N]> for SkillsOption {
152    fn from(sources: [T; N]) -> Self {
153        Self::Sources(sources.into_iter().map(Into::into).collect())
154    }
155}
156
157impl From<AgentSkills> for SkillsOption {
158    fn from(plugin: AgentSkills) -> Self {
159        Self::Plugin(plugin)
160    }
161}
162
163/// What `memory` accepts.
164#[derive(Clone)]
165#[non_exhaustive]
166pub enum MemoryOption {
167    /// No long-term memory (`false`, `null`).
168    Off,
169    /// The harness's file-based memory (`true` is the empty config).
170    On(MemoryConfig),
171    /// A memory manager, used as is.
172    Manager(MemoryManager),
173}
174
175impl From<bool> for MemoryOption {
176    fn from(enabled: bool) -> Self {
177        if enabled {
178            Self::On(MemoryConfig::default())
179        } else {
180            Self::Off
181        }
182    }
183}
184
185impl From<MemoryConfig> for MemoryOption {
186    fn from(config: MemoryConfig) -> Self {
187        Self::On(config)
188    }
189}
190
191impl From<MemoryManager> for MemoryOption {
192    fn from(manager: MemoryManager) -> Self {
193        Self::Manager(manager)
194    }
195}
196
197impl fmt::Debug for MemoryOption {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        match self {
200            Self::Off => f.write_str("Off"),
201            Self::On(config) => f.debug_tuple("On").field(config).finish(),
202            Self::Manager(_) => f.write_str("Manager(..)"),
203        }
204    }
205}
206
207/// Options for [`create_harness`] (`HarnessAgentOptions`). Every field is optional.
208///
209/// The fields after `interventions` are the SDK's [`AgentConfig`] fields the harness does not
210/// own, forwarded verbatim; an explicit value always wins over the harness default it
211/// corresponds to.
212///
213/// ```
214/// use strands_harness::{BuiltinToolName, Effort, HarnessAgentOptions};
215///
216/// let options = HarnessAgentOptions::builder()
217///     .model("anthropic/claude-opus-5")
218///     .effort(Effort::High)
219///     .instructions("You are a migration assistant.")
220///     .builtin_tools([BuiltinToolName::Read, BuiltinToolName::Shell])
221///     .session(false)
222///     .build();
223/// assert_eq!(options.effort, Effort::High);
224/// ```
225#[derive(Default, bon::Builder)]
226#[builder(builder_type(name = HarnessAgentOptionsBuilder, vis = "pub", doc {
227    /// Builds [`HarnessAgentOptions`]; the setters are its fields.
228}))]
229pub struct HarnessAgentOptions {
230    /// Consumer tools, added alongside the built-in tools. A tool name must be unique across all
231    /// sources (built-in tools, `tools`, plugins); a collision fails at construction. To replace
232    /// a built-in, drop it first through `builtin_tools`. Named consumer tools also join the
233    /// `subagent` tool's narrowable set, and every MCP client is handed to each delegate. Set them
234    /// with the builder's `tools(..)`.
235    #[builder(field)]
236    pub tools: Vec<ToolSource>,
237    /// Consumer plugins, registered before the harness's. An `AgentSkills` plugin here replaces
238    /// the one the harness would add, and a plugin named like a built-in plugin
239    /// (`strands:environment`) replaces it. A `subagent` child inherits these.
240    /// Set them with the builder's `plugins(..)`.
241    #[builder(field)]
242    pub plugins: Vec<Arc<dyn Plugin>>,
243    /// A model or router, a `"provider/name"` string (such as `"anthropic/claude-fable-5"`), a
244    /// bare Bedrock model id, or `None` for the harness default (Bedrock Opus 5.5).
245    #[builder(into)]
246    pub model: Option<ModelSource>,
247    /// Reasoning effort applied to the resolved model, mapped to each provider's request fields:
248    /// [`Effort::Auto`] (the default) uses the model vendor's default level (what Claude Code,
249    /// Codex or Gemini CLI run it at; the provider's `high` otherwise), [`Effort::Off`]
250    /// turns reasoning off, and a named level sets it; a level the provider does not support
251    /// fails. Ignored for a model instance or router.
252    #[builder(default)]
253    pub effort: Effort,
254    /// A domain block appended after the harness contract. Ignored when `system_prompt` is set.
255    #[builder(into)]
256    pub instructions: Option<String>,
257    /// MCP servers to connect: a path to a JSON file (a flat `{ name: {..} }` map, or that map
258    /// under `mcpServers`) or the map itself. A server that fails to start yields no tools unless
259    /// it sets `continueOnError: false`; each server's tools are prefixed with its name unless
260    /// it sets its own `prefix` (`""` opts out). Needs the `mcp` feature: without it, setting
261    /// servers fails at [`create_harness`].
262    #[builder(into)]
263    pub mcp_servers: Option<McpServersOption>,
264    /// Which built-in tools to enable: a list pins exactly those (an empty list disables them
265    /// all), a [`BuiltinToolsConfig`] edits the defaults. `web_search` turns on the provider's
266    /// native search (OpenAI, Anthropic, and the GPT-5, GPT-6 and Daybreak models on Bedrock
267    /// Mantle), or a tool backed by Amazon Bedrock AgentCore web search on other Bedrock models;
268    /// elsewhere it is off, and naming it there fails.
269    /// [`WebSearchSetting::Exa`](crate::WebSearchSetting::Exa) (`"exa"` in a config) uses Exa's
270    /// hosted search on any model instead (needs the `mcp` feature). A `subagent` child inherits
271    /// this.
272    #[builder(into)]
273    pub builtin_tools: Option<BuiltinToolsOption>,
274    /// SDK Background Tasks. The `subagent` tool always runs in the background; by default the
275    /// model may choose background execution for any other compatible tool. `false` disables
276    /// Background Tasks; a config controls the other tools, concurrency, completion and timeouts.
277    #[builder(into)]
278    pub background_tasks: Option<Toggle<BackgroundTasksConfig>>,
279    /// Prompt caching where the provider supports it; on by default. `Some(true)` is an explicit
280    /// request, which fails on a model that cannot cache; `Some(false)` turns off what the harness
281    /// configures. Not applied to a model instance or router (an explicit request warns).
282    pub caching: Option<bool>,
283    /// SDK context management: [`ContextManagerStrategy::Auto`] (the default) or `Agentic`
284    /// selects an SDK strategy, an instance is used as is, and `Disabled` turns it off.
285    #[builder(into)]
286    pub context_manager: Option<ContextManagerOption>,
287    /// File-backed conversation persistence, on by default: a fresh random 8-hex id under
288    /// `./.agent/sessions`, with offloaded artifacts kept there too. Ignored when
289    /// `session_manager` is set.
290    #[builder(into)]
291    pub session: Option<SessionOption>,
292    /// Agent Skills through the SDK's `AgentSkills` plugin; by default `./.agent/skills` when it
293    /// exists. Ignored when an `AgentSkills` plugin is in `plugins`.
294    #[builder(into)]
295    pub skills: Option<SkillsOption>,
296    /// File-based long-term memory, on by default: durable facts distilled into markdown under
297    /// `./.agent/memory`, searched before each user turn. Ignored when `memory_manager` is set.
298    /// Extraction runs in the background, so call [`Agent::shutdown`] to persist what is pending.
299    #[builder(into)]
300    pub memory: Option<MemoryOption>,
301    /// The built-in feature plugins to enable; `environment` by default, which injects the
302    /// platform, date, working directory and the project's `AGENTS.md` before each user turn. For
303    /// a task list, pass the SDK's `strands::vended_plugins::todos::Todos` in `plugins`.
304    #[builder(with = |names: impl IntoIterator<Item = BuiltinPluginName>| names.into_iter().collect())]
305    pub builtin_plugins: Option<Vec<BuiltinPluginName>>,
306    /// Gates tool calls behind approval or a policy; off by default. A preset (`"ask"`,
307    /// `"smart"`), a natural-language policy, a `.cedar` policy file, a handler, or a list. A
308    /// `subagent` child inherits the policy, so a delegate cannot bypass it.
309    #[builder(into)]
310    pub interventions: Option<InterventionsOption>,
311    /// See [`AgentConfig::aux_model`].
312    #[builder(into)]
313    pub aux_model: Option<ModelSource>,
314    /// See [`AgentConfig::messages`].
315    #[builder(default)]
316    pub messages: Vec<Message>,
317    /// See [`AgentConfig::system_prompt`]. Replaces the harness prompt and `instructions`.
318    #[builder(into)]
319    pub system_prompt: Option<SystemPrompt>,
320    /// See [`AgentConfig::app_state`].
321    pub app_state: Option<JsonObject>,
322    /// See [`AgentConfig::model_state`].
323    pub model_state: Option<JsonObject>,
324    /// See [`AgentConfig::printer`].
325    pub printer: Option<bool>,
326    /// See [`AgentConfig::retry_strategy`].
327    pub retry_strategy: Option<Vec<RetryStrategy>>,
328    /// See [`AgentConfig::structured_output_schema`].
329    pub structured_output_schema: Option<JsonSchema>,
330    /// See [`AgentConfig::name`].
331    #[builder(into)]
332    pub name: Option<String>,
333    /// See [`AgentConfig::description`].
334    #[builder(into)]
335    pub description: Option<String>,
336    /// See [`AgentConfig::id`].
337    #[builder(into)]
338    pub id: Option<String>,
339    /// See [`AgentConfig::tool_executor`].
340    #[builder(into)]
341    pub tool_executor: Option<ToolExecutorStrategy>,
342    /// See [`AgentConfig::sort_tools`].
343    pub sort_tools: Option<bool>,
344    /// See [`AgentConfig::conversation_manager`].
345    pub conversation_manager: Option<Arc<dyn ConversationManager>>,
346    /// See [`AgentConfig::trace_attributes`].
347    pub trace_attributes: Option<BTreeMap<String, AttributeValue>>,
348    /// See [`AgentConfig::baggage_attributes`].
349    pub baggage_attributes: Option<BTreeMap<String, String>>,
350    /// See [`AgentConfig::sandbox`]. The harness's built-ins route through it, so the tools the
351    /// sandbox vends are dropped once the agent initializes.
352    pub sandbox: Option<Arc<dyn Sandbox>>,
353    /// See [`AgentConfig::storage`]. Backs the context manager's archive; defaults to the
354    /// session's own folder when the harness builds the session.
355    pub storage: Option<Arc<dyn Storage>>,
356    /// See [`AgentConfig::session_manager`]. Wins over `session`.
357    pub session_manager: Option<SessionManager>,
358    /// See [`AgentConfig::memory_manager`]. Wins over `memory`.
359    #[builder(into)]
360    pub memory_manager: Option<MemoryManagerSource>,
361}
362
363impl<S: harness_agent_options_builder::State> HarnessAgentOptionsBuilder<S> {
364    /// Adds consumer tools: any iterator of tools, `Arc<dyn Tool>`s, MCP clients or nested lists.
365    pub fn tools(mut self, tools: impl IntoIterator<Item = impl Into<ToolSource>>) -> Self {
366        self.tools.extend(tools.into_iter().map(Into::into));
367        self
368    }
369
370    /// Adds consumer plugins, by value or as `Arc`s.
371    pub fn plugins(mut self, plugins: impl IntoIterator<Item = impl Plugin>) -> Self {
372        self.plugins
373            .extend(plugins.into_iter().map(|plugin| Arc::new(plugin) as Arc<dyn Plugin>));
374        self
375    }
376}
377
378impl fmt::Debug for HarnessAgentOptions {
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        f.debug_struct("HarnessAgentOptions")
381            .field("model", &self.model)
382            .field("effort", &self.effort)
383            .field("instructions", &self.instructions)
384            .field("tools", &self.tools)
385            .field("builtin_tools", &self.builtin_tools)
386            .field("session", &self.session)
387            .field("memory", &self.memory)
388            .field("skills", &self.skills)
389            .finish_non_exhaustive()
390    }
391}
392
393/// The parent config a `subagent` child is rebuilt from: the harness options the child
394/// inherits, with sessions forced off so a throwaway delegate never persists its own state.
395#[derive(Clone)]
396pub(crate) struct ParentConfig {
397    pub(crate) model: Option<ModelSource>,
398    pub(crate) effort: Effort,
399    pub(crate) context_manager: Option<ContextManagerOption>,
400    pub(crate) skills: Option<SkillsOption>,
401    /// `None` is the default (on); a memory instance is forwarded as off.
402    pub(crate) memory: Option<MemoryOption>,
403    /// The parent's consumer tools, MCP clients included.
404    pub(crate) tools: Vec<ToolSource>,
405    /// The parent's resolved record, with `web_search` adjusted for the child's model.
406    pub(crate) builtin_tools: BuiltinToolsConfig,
407    pub(crate) caching: Option<bool>,
408    pub(crate) builtin_plugins: Option<Vec<BuiltinPluginName>>,
409    pub(crate) plugins: Vec<Arc<dyn Plugin>>,
410    pub(crate) interventions: Option<InterventionsOption>,
411    pub(crate) background_tasks: Option<Toggle<BackgroundTasksConfig>>,
412    pub(crate) sandbox: Option<Arc<dyn Sandbox>>,
413}
414
415impl ParentConfig {
416    pub(crate) fn to_options(&self) -> HarnessAgentOptions {
417        HarnessAgentOptions {
418            tools: self.tools.clone(),
419            plugins: self.plugins.clone(),
420            model: self.model.clone(),
421            effort: self.effort,
422            builtin_tools: Some(BuiltinToolsOption::Mapping(self.builtin_tools.clone())),
423            background_tasks: self.background_tasks.clone(),
424            caching: self.caching,
425            context_manager: self.context_manager.clone(),
426            session: Some(SessionOption::Off),
427            skills: self.skills.clone(),
428            memory: self.memory.clone(),
429            builtin_plugins: self.builtin_plugins.clone(),
430            interventions: self.interventions.clone(),
431            sandbox: self.sandbox.clone(),
432            ..Default::default()
433        }
434    }
435}
436
437/// Sanitizes a session id to `[a-z0-9_-]`.
438pub(crate) fn sanitize_session_id(session_id: &str) -> String {
439    let sanitized: String = session_id
440        .trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}')
441        .to_lowercase()
442        .chars()
443        .map(|c| {
444            if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-' {
445                c
446            } else {
447                '-'
448            }
449        })
450        .collect();
451    if sanitized.is_empty() {
452        "default".to_owned()
453    } else {
454        sanitized
455    }
456}
457
458fn random_session_id() -> String {
459    format!("{:08x}", rand::random::<u32>())
460}
461
462/// Resolves `skills` into an `AgentSkills` plugin, or `None` when nothing was requested. The
463/// default is best-effort: it loads `./.agent/skills` only when it exists locally.
464fn skills_plugin(skills: SkillsOption) -> Option<Arc<dyn Plugin>> {
465    let sources = match skills {
466        SkillsOption::Plugin(plugin) => return Some(Arc::new(plugin)),
467        SkillsOption::Default if Path::new(DEFAULT_SKILLS_DIR).is_dir() => vec![DEFAULT_SKILLS_DIR.into()],
468        SkillsOption::Sources(sources) if !sources.is_empty() => sources,
469        _ => return None,
470    };
471    Some(Arc::new(AgentSkills::new(AgentSkillsConfig {
472        skills: sources,
473        ..Default::default()
474    })))
475}
476
477fn builtin_plugin_name(name: BuiltinPluginName) -> &'static str {
478    match name {
479        BuiltinPluginName::Environment => ENVIRONMENT_PLUGIN_NAME,
480    }
481}
482
483/// The built-in plugins to add: each named one, unless a plugin with its name is already registered.
484fn select_builtin_plugins(
485    names: &[BuiltinPluginName],
486    existing: &[Arc<dyn Plugin>],
487    factory: &BuiltinToolFactory,
488) -> Vec<Arc<dyn Plugin>> {
489    names
490        .iter()
491        .filter(|name| {
492            !existing
493                .iter()
494                .any(|plugin| plugin.name() == builtin_plugin_name(**name))
495        })
496        .map(|name| match name {
497            BuiltinPluginName::Environment => (factory.environment)(),
498        })
499        .collect()
500}
501
502/// The tools a list of sources names up front: top-level tools only, since nested lists, agents
503/// and MCP clients resolve later.
504fn named_tools(sources: &[ToolSource]) -> Vec<&Arc<dyn Tool>> {
505    sources
506        .iter()
507        .filter_map(|source| match source {
508            ToolSource::Tool(tool) => Some(tool),
509            _ => None,
510        })
511        .collect()
512}
513
514/// The tools each plugin vends (such as `todo_write`), via [`Plugin::get_tools`].
515fn plugin_tools(plugins: &[Arc<dyn Plugin>]) -> Vec<ToolSource> {
516    plugins.iter().flat_map(|plugin| plugin.get_tools()).collect()
517}
518
519/// One source of tool names for the collision check.
520struct NamedSource<'a> {
521    label: &'static str,
522    builtin: bool,
523    tools: Vec<&'a Arc<dyn Tool>>,
524}
525
526/// Fails if two tools would register under the same name, naming the losing source, rather than
527/// one tool silently disappearing. Names differing only by `-` and `_`
528/// collide, as in the SDK registry.
529fn check_name_collisions(sources: &[NamedSource<'_>]) -> strands::Result<()> {
530    let mut seen: Vec<(String, &'static str, bool)> = Vec::new();
531    for source in sources {
532        for tool in &source.tools {
533            let key = tool.name().replace('-', "_");
534            if let Some((_, label, builtin)) = seen.iter().find(|(known, ..)| *known == key) {
535                let place = if *label == source.label {
536                    source.label.to_owned()
537                } else {
538                    format!("{label} and {}", source.label)
539                };
540                let remedy = if source.builtin || *builtin {
541                    "Rename the tool you passed, or drop the built-in via builtinTools / builtinPlugins."
542                } else {
543                    "Rename one so each tool has a unique name."
544                };
545                return Err(strands::Error::other(format!(
546                    "Tool name {} is registered more than once (from {place}). {remedy}",
547                    crate::types::json_string(tool.name())
548                )));
549            }
550            seen.push((key, source.label, source.builtin));
551        }
552    }
553    Ok(())
554}
555
556/// The Background Tasks policy: unset or `true` lets the model
557/// background any tool; the always-background tools are moved to `always` in every policy.
558pub(crate) fn resolve_background_tasks(
559    configured: Option<Toggle<BackgroundTasksConfig>>,
560    forced: &[String],
561) -> Toggle<BackgroundTasksConfig> {
562    let policy = match configured {
563        Some(Toggle::Off) => return Toggle::Off,
564        Some(Toggle::On(config)) if config != BackgroundTasksConfig::default() => config,
565        _ => BackgroundTasksConfig {
566            agentic: Some(vec!["*".to_owned()]),
567            ..Default::default()
568        },
569    };
570    let omit_forced = |selectors: Vec<String>| -> Vec<String> {
571        selectors
572            .into_iter()
573            .filter(|selector| selector == "*" || !forced.contains(selector))
574            .collect()
575    };
576    let explicit_always = policy.always.is_some();
577    let mut always = omit_forced(policy.always.clone().unwrap_or_default());
578    always.extend(forced.iter().cloned());
579    Toggle::On(BackgroundTasksConfig {
580        agentic: policy.agentic.clone().map(omit_forced),
581        always: (!always.is_empty() || explicit_always).then_some(always),
582        never: policy.never.clone().map(omit_forced),
583        ..policy
584    })
585}
586
587/// A harness agent's configuration before the agent is built, kept apart so tests can inspect
588/// what `create_harness` resolved.
589#[cfg_attr(not(test), allow(dead_code, reason = "inspected by tests"))]
590pub(crate) struct Assembly {
591    pub(crate) config: AgentConfig,
592    /// The config a `subagent` child is rebuilt from.
593    pub(crate) parent: Arc<ParentConfig>,
594    pub(crate) model_plan: Option<ModelPlan>,
595    /// Tool names the harness registers itself, which the sandbox-tool cleanup must keep.
596    pub(crate) known_tool_names: HashSet<String>,
597}
598
599/// Builds a preconfigured Strands agent with the harness defaults.
600///
601/// Every default is overridable through [`HarnessAgentOptions`], and the result is a plain
602/// [`Agent`] that can be changed further. Resolution is async because MCP servers are connected
603/// here.
604///
605/// ```no_run
606/// use strands_harness::{HarnessAgentOptions, create_harness};
607///
608/// # async fn run() -> strands::Result<()> {
609/// let mut agent = create_harness(
610///     HarnessAgentOptions::builder()
611///         .model("anthropic/claude-opus-5")
612///         .interventions("ask")
613///         .build(),
614/// )
615/// .await?;
616/// let result = agent.invoke("Fix the failing test in src/lib.rs").await?;
617/// println!("{result}");
618/// agent.shutdown().await?;
619/// # Ok(())
620/// # }
621/// ```
622///
623/// # Errors
624///
625/// An invalid option (an unknown model provider, an unsupported effort level, a tool name
626/// registered twice, an empty session id, ...), a provider whose cargo feature is disabled, an
627/// MCP config that cannot be loaded, or an agent the SDK rejects.
628pub async fn create_harness(options: HarnessAgentOptions) -> strands::Result<Agent> {
629    create_harness_boxed(options, Env::process()).await
630}
631
632/// [`create_harness`] with an explicit environment, boxed so the `subagent` builder can recurse.
633pub(crate) fn create_harness_boxed(
634    options: HarnessAgentOptions,
635    env: Env,
636) -> BoxFuture<'static, strands::Result<Agent>> {
637    Box::pin(async move {
638        let has_sandbox = options.sandbox.is_some();
639        let assembly = assemble(options, &env).await?;
640        let agent = Agent::new(assembly.config)?;
641        if has_sandbox {
642            drop_sandbox_tools(&agent, assembly.known_tool_names);
643        }
644        Ok(agent)
645    })
646}
647
648/// Drops the tools the sandbox vends (such as `sandbox_bash`) once the SDK registers them at
649/// initialization: the harness's built-ins already route through the sandbox. A name the
650/// harness registered itself is kept.
651fn drop_sandbox_tools(agent: &Agent, known: HashSet<String>) {
652    let _cleanup = agent.add_hook(move |event: &mut InitializedEvent<'_>| {
653        let vended: Vec<String> = event
654            .agent()
655            .sandbox()
656            .get_tools()
657            .iter()
658            .map(|tool| tool.name().to_owned())
659            .filter(|name| !known.contains(name))
660            .collect();
661        for name in vended {
662            event.agent_mut().tool_registry_mut().remove(&name);
663        }
664    });
665}
666
667#[cfg(feature = "mcp")]
668async fn with_mcp_servers(
669    mut tools: Vec<ToolSource>,
670    servers: Option<McpServersOption>,
671) -> strands::Result<Vec<ToolSource>> {
672    tools.extend(load_mcp_servers(servers.map(McpServersOption::into_source)).await?);
673    Ok(tools)
674}
675
676#[cfg(not(feature = "mcp"))]
677async fn with_mcp_servers(
678    tools: Vec<ToolSource>,
679    servers: Option<McpServersOption>,
680) -> strands::Result<Vec<ToolSource>> {
681    if servers.is_some() {
682        return Err(strands::Error::other(
683            "mcp_servers needs the strands-harness feature \"mcp\"; enable it to connect MCP servers.",
684        ));
685    }
686    Ok(tools)
687}
688
689#[cfg(feature = "mcp")]
690async fn load_mcp_servers(servers: Option<strands::mcp::McpServersSource>) -> strands::Result<Vec<ToolSource>> {
691    use strands::mcp::{McpClient, McpClientOptions, McpLoadServersOptions};
692
693    let Some(servers) = servers else {
694        return Ok(Vec::new());
695    };
696    let defaults = McpClientOptions {
697        continue_on_error: true,
698        ..Default::default()
699    };
700    let options = McpLoadServersOptions {
701        prefix_with_server_name: true,
702    };
703    let clients = McpClient::load_servers(servers, defaults, options).await?;
704    Ok(clients.into_iter().map(ToolSource::McpClient).collect())
705}
706
707/// A harness-built session manager and the archive storage in its folder.
708type SessionParts = (SessionManager, Option<Arc<dyn Storage>>);
709
710fn session_parts(session: Option<SessionOption>) -> strands::Result<Option<SessionParts>> {
711    let config = match session.unwrap_or(SessionOption::On(SessionConfig::default())) {
712        SessionOption::Off => return Ok(None),
713        SessionOption::Manager(manager) => return Ok(Some((manager, None))),
714        SessionOption::On(config) => config,
715    };
716    if config.id.as_deref().is_some_and(|id| id.trim().is_empty()) {
717        return Err(strands::Error::other("session.id must be a non-empty string."));
718    }
719    let dir = config.dir.unwrap_or_else(|| PathBuf::from(DEFAULT_SESSION_DIR));
720    let session_id = config.id.as_deref().map_or_else(random_session_id, sanitize_session_id);
721    let manager = SessionManager::new(SessionManagerConfig {
722        storage: Some(Arc::new(LocalFileStorage::new(&dir).namespace("")?)),
723        session_id: Some(session_id.clone()),
724        save_latest_on: Some(SaveLatestStrategy::Message),
725        ..Default::default()
726    })?;
727    // The archive goes to files, not into the snapshot rewritten on every message. It lives in the
728    // session's own folder because each folder under the session dir is read as a session.
729    let archive: Arc<dyn Storage> = Arc::new(LocalFileStorage::new(dir.join(&session_id)));
730    Ok(Some((manager, Some(archive))))
731}
732
733/// Resolves every harness option into the SDK agent configuration.
734pub(crate) async fn assemble(options: HarnessAgentOptions, env: &Env) -> strands::Result<Assembly> {
735    assemble_with(options, env, &BUILTIN_TOOL_FACTORY).await
736}
737
738/// [`assemble`] with the constructors the built-ins are made with.
739#[allow(
740    clippy::too_many_lines,
741    reason = "one pass over the options, in the order they resolve"
742)]
743pub(crate) async fn assemble_with(
744    options: HarnessAgentOptions,
745    env: &Env,
746    factory: &BuiltinToolFactory,
747) -> strands::Result<Assembly> {
748    let HarnessAgentOptions {
749        tools,
750        plugins: consumer_plugins,
751        model,
752        effort,
753        instructions,
754        mcp_servers,
755        builtin_tools,
756        background_tasks,
757        caching,
758        context_manager,
759        session,
760        skills,
761        memory,
762        builtin_plugins,
763        interventions,
764        aux_model,
765        messages,
766        system_prompt,
767        app_state,
768        model_state,
769        printer,
770        retry_strategy,
771        structured_output_schema,
772        name,
773        description,
774        id,
775        tool_executor,
776        sort_tools,
777        conversation_manager,
778        trace_attributes,
779        baggage_attributes,
780        sandbox,
781        storage,
782        session_manager,
783        memory_manager,
784    } = options;
785
786    setup_telemetry(env)?;
787
788    let resolved = resolve_builtin_tools(builtin_tools.as_ref());
789    let explicit_search = web_search_explicit(builtin_tools.as_ref());
790    let web_search = web_search_mode(resolved.web_search, explicit_search, model.as_ref())?;
791
792    // Not passing `caching` uses the default (on) and warns on an unsupported model; passing it
793    // is an explicit request, which fails there instead.
794    let request = ModelRequest {
795        effort,
796        web_search: web_search == Some(WebSearchMode::Native),
797        caching: caching.unwrap_or(true),
798        caching_explicit: caching.is_some(),
799    };
800    let resolved_model = resolve_model(model.as_ref(), DEFAULT_MODEL, request, env)?;
801    let system_prompt = system_prompt.or_else(|| Some(build_system_prompt(instructions.as_deref(), &[]).into()));
802
803    let consumer = with_mcp_servers(tools, mcp_servers).await?;
804
805    let memory_instance = matches!(memory, Some(MemoryOption::Manager(_))) || memory_manager.is_some();
806    let mut forwarded = resolved.to_config();
807    if web_search.is_none() {
808        // Off, or on by default but unavailable here: forward it off so a child on the same model
809        // stays quiet.
810        forwarded.web_search = Some(false.into());
811    } else if !explicit_search {
812        // Forward the default as a default, so a child without native search logs, not fails.
813        forwarded.web_search = None;
814    }
815    let parent = Arc::new(ParentConfig {
816        model,
817        effort,
818        context_manager: context_manager.clone(),
819        skills: skills.clone(),
820        memory: if memory_instance {
821            Some(MemoryOption::Off)
822        } else {
823            memory.clone()
824        },
825        tools: consumer.clone(),
826        builtin_tools: forwarded,
827        caching,
828        builtin_plugins: builtin_plugins.clone(),
829        plugins: consumer_plugins.clone(),
830        interventions: interventions.clone(),
831        background_tasks: background_tasks.clone(),
832        sandbox: sandbox.clone(),
833    });
834    let builtin = build_builtin_tools(&resolved, web_search, &parent, env, factory)?;
835
836    // Consumer plugins stay first so the tail is the harness's own.
837    let mut plugins = consumer_plugins.clone();
838    let has_skills = plugins.iter().any(|plugin| plugin.name() == AGENT_SKILLS_NAME);
839    if let Some(plugin) = skills_plugin(skills.unwrap_or(SkillsOption::Default)).filter(|_| !has_skills) {
840        plugins.push(plugin);
841    }
842    let builtin_plugin_names = builtin_plugins.unwrap_or_else(|| DEFAULT_BUILTIN_PLUGINS.to_vec());
843    let selected_plugins = select_builtin_plugins(&builtin_plugin_names, &plugins, factory);
844    plugins.extend(selected_plugins);
845    let harness_plugins = &plugins[consumer_plugins.len()..];
846
847    let (session_manager, storage) = match session_manager {
848        Some(manager) => (Some(manager), storage),
849        None => match session_parts(session)? {
850            Some((manager, archive)) => (Some(manager), storage.or(archive)),
851            None => (None, storage),
852        },
853    };
854
855    let memory_manager = match memory_manager {
856        Some(source) => Some(source),
857        None => match memory.unwrap_or(MemoryOption::On(MemoryConfig::default())) {
858            MemoryOption::Off => None,
859            MemoryOption::Manager(manager) => Some(manager.into()),
860            MemoryOption::On(config) => Some(
861                resolve_memory(
862                    ResolveMemoryOptions {
863                        stores: config.stores,
864                        model: parent.model.clone(),
865                        dir: config.dir,
866                        web_fetch_model: resolved.web_fetch_config().and_then(|config| config.model),
867                        read_only: false,
868                    },
869                    env,
870                )?
871                .into(),
872            ),
873        },
874    };
875    // A manager carries its resolved tools (`search_memory` by default); a config does not, so
876    // only a manager can be checked for name collisions here.
877    let memory_tools = match &memory_manager {
878        Some(MemoryManagerSource::Manager(manager)) => manager.get_tools(),
879        _ => Vec::new(),
880    };
881
882    let builtin_sources: Vec<ToolSource> = builtin.iter().map(|tool| ToolSource::Tool(Arc::clone(tool))).collect();
883    let harness_plugin_tools = plugin_tools(harness_plugins);
884    let consumer_plugin_tools = plugin_tools(&consumer_plugins);
885    let sources = [
886        NamedSource {
887            label: "a built-in tool",
888            builtin: true,
889            tools: named_tools(&builtin_sources),
890        },
891        NamedSource {
892            label: "tools",
893            builtin: false,
894            tools: named_tools(&consumer),
895        },
896        NamedSource {
897            label: "a built-in plugin",
898            builtin: true,
899            tools: named_tools(&harness_plugin_tools),
900        },
901        NamedSource {
902            label: "plugins",
903            builtin: false,
904            tools: named_tools(&consumer_plugin_tools),
905        },
906        NamedSource {
907            label: "memory",
908            builtin: true,
909            tools: named_tools(&memory_tools),
910        },
911    ];
912    check_name_collisions(&sources)?;
913    let known_tool_names = sources
914        .iter()
915        .flat_map(|source| source.tools.iter().map(|tool| tool.name().to_owned()))
916        .collect();
917
918    let handlers: Vec<Arc<dyn InterventionHandler>> = resolve_interventions(interventions.as_ref(), None)?;
919    let forced: Vec<String> = builtin_sources
920        .iter()
921        .chain(consumer.iter())
922        .filter_map(|source| match source {
923            ToolSource::Tool(tool) if ALWAYS_BACKGROUND_TOOL_NAMES.contains(&tool.name()) => {
924                Some(tool.name().to_owned())
925            }
926            _ => None,
927        })
928        .collect();
929    let background_tasks = resolve_background_tasks(background_tasks, &forced);
930
931    let mut agent_tools = builtin_sources;
932    agent_tools.extend(consumer);
933    let config = AgentConfig {
934        tools: agent_tools,
935        plugins,
936        interventions: handlers,
937        model: Some(resolved_model.source),
938        aux_model,
939        messages,
940        system_prompt,
941        app_state,
942        model_state,
943        printer,
944        retry_strategy,
945        structured_output_schema,
946        name,
947        description,
948        id,
949        tool_executor,
950        sort_tools,
951        conversation_manager,
952        context_manager: Some(context_manager.unwrap_or(ContextManagerStrategy::Auto)),
953        background_tasks: Some(background_tasks),
954        trace_attributes,
955        baggage_attributes,
956        sandbox,
957        storage,
958        session_manager,
959        memory_manager,
960    };
961    Ok(Assembly {
962        config,
963        parent,
964        model_plan: resolved_model.plan,
965        known_tool_names,
966    })
967}
968
969#[cfg(test)]
970mod tests;