Skip to main content

strands_harness/
types.rs

1//! Option types for [`create_harness`](crate::create_harness).
2//!
3//! `*Config` is a data shape, `*Option` the set of forms the like-named option accepts, and
4//! [`HarnessAgentOptions`](crate::HarnessAgentOptions) the config plus runtime-only fields.
5
6use std::fmt;
7use std::path::PathBuf;
8use std::str::FromStr;
9use std::sync::Arc;
10
11use serde::{Deserialize, Serialize, Serializer};
12use strands::context_manager::ContextManagerStrategy;
13use strands::memory::MemoryStore;
14
15use crate::config::BuiltinToolName;
16pub(crate) use crate::tools::programmatic_tool_caller::ProgrammaticToolCallerConfig;
17pub(crate) use crate::tools::web_fetch::{WebFetchConfig, WebFetchTransport};
18pub(crate) use crate::tools::web_search::WebSearchSetting;
19
20/// Reasoning effort applied to the resolved model (`Effort`); see
21/// [`HarnessAgentOptions::effort`](crate::HarnessAgentOptions::effort).
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
23#[serde(rename_all = "lowercase")]
24#[non_exhaustive]
25pub enum Effort {
26    /// The model vendor's default level, else the provider's recommended one (`'auto'`, the default).
27    #[default]
28    Auto,
29    /// Reasoning off: the provider's `none` level where it has one, otherwise no reasoning field.
30    Off,
31    /// `'minimal'`.
32    Minimal,
33    /// `'low'`.
34    Low,
35    /// `'medium'`.
36    Medium,
37    /// `'high'`.
38    High,
39    /// `'xhigh'`.
40    Xhigh,
41    /// `'max'`.
42    Max,
43}
44
45impl Effort {
46    /// Every effort, in the order error messages list them.
47    pub(crate) const ALL: [Self; 8] = [
48        Self::Auto,
49        Self::Off,
50        Self::Minimal,
51        Self::Low,
52        Self::Medium,
53        Self::High,
54        Self::Xhigh,
55        Self::Max,
56    ];
57
58    /// The config spelling, such as `"xhigh"`.
59    #[must_use]
60    pub fn as_str(self) -> &'static str {
61        match self {
62            Self::Auto => "auto",
63            Self::Off => "off",
64            Self::Minimal => "minimal",
65            Self::Low => "low",
66            Self::Medium => "medium",
67            Self::High => "high",
68            Self::Xhigh => "xhigh",
69            Self::Max => "max",
70        }
71    }
72
73    pub(crate) fn names() -> String {
74        Self::ALL.map(Self::as_str).join(", ")
75    }
76}
77
78impl fmt::Display for Effort {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.write_str(self.as_str())
81    }
82}
83
84impl FromStr for Effort {
85    type Err = strands::Error;
86
87    /// Parses the config spelling; anything else fails listing the supported efforts.
88    fn from_str(value: &str) -> strands::Result<Self> {
89        Self::ALL
90            .into_iter()
91            .find(|effort| effort.as_str() == value)
92            .ok_or_else(|| {
93                strands::Error::other(format!(
94                    "Effort {} is not valid. Supported: {}.",
95                    json_string(value),
96                    Self::names()
97                ))
98            })
99    }
100}
101
102/// A setting that is a boolean or a config object, such as a built-in tool's entry in
103/// [`BuiltinToolsConfig`]: on, off, or on with a config.
104#[derive(Debug, Clone, PartialEq)]
105#[non_exhaustive]
106pub enum Setting<C> {
107    /// `true` enables with the defaults; `false` disables.
108    Enabled(bool),
109    /// Enables and configures.
110    Config(C),
111}
112
113impl<C> Setting<C> {
114    /// Whether the setting enables what it configures.
115    #[must_use]
116    pub fn is_enabled(&self) -> bool {
117        !matches!(self, Self::Enabled(false))
118    }
119}
120
121impl<C> From<bool> for Setting<C> {
122    fn from(enabled: bool) -> Self {
123        Self::Enabled(enabled)
124    }
125}
126
127impl<C: Serialize> Serialize for Setting<C> {
128    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
129        match self {
130            Self::Enabled(enabled) => serializer.serialize_bool(*enabled),
131            Self::Config(config) => config.serialize(serializer),
132        }
133    }
134}
135
136macro_rules! setting_from {
137    ($($config:ty),* $(,)?) => {$(
138        impl From<$config> for Setting<$config> {
139            fn from(config: $config) -> Self {
140                Self::Config(config)
141            }
142        }
143    )*};
144}
145
146setting_from!(
147    ReadConfig,
148    ShellConfig,
149    WebFetchConfig,
150    ProgrammaticToolCallerConfig,
151    SubagentConfig,
152    SessionConfig,
153    MemoryConfig,
154    crate::config::HarnessConfigWebFetch,
155    crate::config::HarnessConfigMemory,
156);
157
158/// Per-tool config for the `subagent` built-in (`SubagentConfig`).
159#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
160#[serde(rename_all = "camelCase", deny_unknown_fields)]
161pub struct SubagentConfig {
162    /// How many levels of delegation a child may itself open; `0` removes the tool. 2 when
163    /// absent.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub max_depth: Option<usize>,
166}
167
168/// Per-tool config for the `read` built-in (`ReadConfig`).
169#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, bon::Builder)]
170pub struct ReadConfig {
171    /// Return images and binary documents as viewable media. Defaults to whether the model
172    /// accepts them.
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub media: Option<bool>,
175}
176
177/// Per-tool config for the `shell` built-in (`ShellConfig`).
178#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, bon::Builder)]
179pub struct ShellConfig {
180    /// Tool description shown to the model; `None` for the SDK's default.
181    #[builder(into)]
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub description: Option<String>,
184}
185
186/// Edits to the default built-in tool set (`BuiltinToolsConfig`). `false` disables a tool,
187/// `true` enables it, and a per-tool config enables and configures it (`web_search` takes
188/// [`WebSearchSetting::Exa`] instead). `all` is the portable config's `"*"` key (default `true`):
189/// it includes the harness defaults; set it to `false` to start from nothing and enable tools one by one.
190///
191/// ```
192/// use strands_harness::{BuiltinToolsConfig, ShellConfig};
193///
194/// let edits = BuiltinToolsConfig::builder()
195///     .subagent(false)
196///     .shell(ShellConfig::builder().description("Run a command.").build())
197///     .build();
198/// assert!(edits.all.is_none());
199/// ```
200#[derive(Debug, Clone, Default, bon::Builder)]
201pub struct BuiltinToolsConfig {
202    /// Whether the harness defaults are the baseline (`"*"`); `true` when `None`.
203    pub all: Option<bool>,
204    /// `shell`.
205    #[builder(into)]
206    pub shell: Option<Setting<ShellConfig>>,
207    /// `read`.
208    #[builder(into)]
209    pub read: Option<Setting<ReadConfig>>,
210    /// `write`; takes no config.
211    pub write: Option<bool>,
212    /// `edit`; takes no config.
213    pub edit: Option<bool>,
214    /// `web_fetch`.
215    #[builder(into)]
216    pub web_fetch: Option<Setting<WebFetchConfig>>,
217    /// `web_search`.
218    #[builder(into)]
219    pub web_search: Option<WebSearchSetting>,
220    /// `programmatic_tool_caller`.
221    #[builder(into)]
222    pub programmatic_tool_caller: Option<Setting<ProgrammaticToolCallerConfig>>,
223    /// `subagent`.
224    #[builder(into)]
225    pub subagent: Option<Setting<SubagentConfig>>,
226}
227
228/// What `builtin_tools` accepts: a list pins exactly those tools (an empty list disables them
229/// all), a mapping edits the defaults.
230#[derive(Debug, Clone)]
231#[non_exhaustive]
232pub enum BuiltinToolsOption {
233    /// Exactly these tools.
234    List(Vec<BuiltinToolName>),
235    /// Edits to the defaults.
236    Mapping(BuiltinToolsConfig),
237}
238
239impl From<Vec<BuiltinToolName>> for BuiltinToolsOption {
240    fn from(names: Vec<BuiltinToolName>) -> Self {
241        Self::List(names)
242    }
243}
244
245impl From<&[BuiltinToolName]> for BuiltinToolsOption {
246    fn from(names: &[BuiltinToolName]) -> Self {
247        Self::List(names.to_vec())
248    }
249}
250
251impl<const N: usize> From<[BuiltinToolName; N]> for BuiltinToolsOption {
252    fn from(names: [BuiltinToolName; N]) -> Self {
253        Self::List(names.to_vec())
254    }
255}
256
257impl From<BuiltinToolsConfig> for BuiltinToolsOption {
258    fn from(config: BuiltinToolsConfig) -> Self {
259        Self::Mapping(config)
260    }
261}
262
263/// Session persistence (`SessionConfig`); the empty config selects the defaults.
264#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, bon::Builder)]
265pub struct SessionConfig {
266    /// Identifier for the session's stored state, sanitized to `[a-z0-9_-]`. Defaults to a fresh
267    /// random 8-hex id each run; pass a previous run's [`Agent::session_id`](strands::Agent::session_id)
268    /// to resume it.
269    #[builder(into)]
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub id: Option<String>,
272    /// Root directory for session state and offloaded artifacts. Defaults to `./.agent/sessions`.
273    #[builder(into)]
274    #[serde(skip_serializing_if = "Option::is_none")]
275    pub dir: Option<PathBuf>,
276}
277
278/// The harness's default long-term memory (`MemoryConfig`); the empty config selects the
279/// defaults. For a different policy pass the SDK's
280/// [`memory_manager`](crate::HarnessAgentOptions::memory_manager) instead.
281#[derive(Clone, Default, bon::Builder)]
282pub struct MemoryConfig {
283    /// Directory the default file store's files live in. Defaults to `./.agent/memory`.
284    #[builder(into)]
285    pub dir: Option<PathBuf>,
286    /// Replaces the default file store while keeping the harness's memory policy (injection on,
287    /// `search_memory` on, no `add_memory` tool). Unlike a full memory manager, the `subagent`
288    /// delegate shares these stores read-only. Empty selects the default store.
289    #[builder(default)]
290    pub stores: Vec<Arc<dyn MemoryStore>>,
291}
292
293impl fmt::Debug for MemoryConfig {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        f.debug_struct("MemoryConfig")
296            .field("dir", &self.dir)
297            .field(
298                "stores",
299                &self.stores.iter().map(|store| store.name()).collect::<Vec<_>>(),
300            )
301            .finish()
302    }
303}
304
305/// What `context_manager` accepts (`ContextManagerOption`): exactly the SDK's
306/// [`ContextManagerStrategy`], whose [`Disabled`](ContextManagerStrategy::Disabled) stands for
307/// both `false` and `null`.
308pub type ContextManagerOption = ContextManagerStrategy;
309
310/// A string as `JSON.stringify` writes it, for error messages that quote values.
311pub(crate) fn json_string(value: &str) -> String {
312    serde_json::Value::String(value.to_owned()).to_string()
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    #[test]
320    fn rejects_an_effort_outside_the_enum_by_name() {
321        let error = "bogus".parse::<Effort>().unwrap_err();
322        assert_eq!(
323            error.to_string(),
324            "Effort \"bogus\" is not valid. Supported: auto, off, minimal, low, medium, high, xhigh, max."
325        );
326        assert_eq!("xhigh".parse::<Effort>().unwrap(), Effort::Xhigh);
327    }
328}
329
330/// Where `mcp_servers` come from. The type exists with or without the `mcp` feature; without it,
331/// [`create_harness`](crate::create_harness) fails when servers are set.
332///
333/// ```
334/// use strands_harness::McpServersOption;
335///
336/// assert!(matches!(McpServersOption::from("./mcp.json"), McpServersOption::Path(_)));
337/// ```
338#[derive(Debug, Clone)]
339#[non_exhaustive]
340pub enum McpServersOption {
341    /// A JSON config file: a flat `{ name: {..} }` map, or that map under `mcpServers`.
342    Path(PathBuf),
343    /// Server entries by name, as JSON.
344    Json(strands::types::JsonObject),
345    /// An SDK source, typed server configs included.
346    #[cfg(feature = "mcp")]
347    Source(strands::mcp::McpServersSource),
348}
349
350impl From<&str> for McpServersOption {
351    fn from(path: &str) -> Self {
352        Self::Path(PathBuf::from(path))
353    }
354}
355
356impl From<String> for McpServersOption {
357    fn from(path: String) -> Self {
358        Self::Path(PathBuf::from(path))
359    }
360}
361
362impl From<PathBuf> for McpServersOption {
363    fn from(path: PathBuf) -> Self {
364        Self::Path(path)
365    }
366}
367
368impl From<strands::types::JsonObject> for McpServersOption {
369    fn from(servers: strands::types::JsonObject) -> Self {
370        Self::Json(servers)
371    }
372}
373
374#[cfg(feature = "mcp")]
375impl From<strands::mcp::McpServersSource> for McpServersOption {
376    fn from(source: strands::mcp::McpServersSource) -> Self {
377        Self::Source(source)
378    }
379}
380
381#[cfg(feature = "mcp")]
382impl McpServersOption {
383    pub(crate) fn into_source(self) -> strands::mcp::McpServersSource {
384        match self {
385            Self::Path(path) => strands::mcp::McpServersSource::Path(path),
386            Self::Json(servers) => strands::mcp::McpServersSource::Json(servers),
387            Self::Source(source) => source,
388        }
389    }
390}