agents-runtime 0.0.30

Async runtime orchestration for Rust deep agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Configuration structs and types for Deep Agents
//!
//! This module contains all the configuration structures used to build Deep Agents,
//! including parameter structs that mirror the Python SDK API.

use crate::middleware::{token_tracking::TokenTrackingConfig, AgentMiddleware, HitlPolicy};
use crate::prompts::PromptFormat;
use agents_core::agent::PlannerHandle;
use agents_core::persistence::Checkpointer;
use agents_core::tools::ToolBox;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroUsize;
use std::sync::Arc;

/// Parameters for create_deep_agent() that mirror the Python API exactly
///
/// This struct matches the Python function signature:
/// ```python
/// def create_deep_agent(
///     tools: Sequence[Union[BaseTool, Callable, dict[str, Any]]] = [],
///     instructions: str = "",
///     middleware: Optional[list[AgentMiddleware]] = None,
///     model: Optional[Union[str, LanguageModelLike]] = None,
///     subagents: Optional[list[SubAgent | CustomSubAgent]] = None,
///     context_schema: Optional[Type[Any]] = None,
///     checkpointer: Optional[Checkpointer] = None,
///     tool_configs: Optional[dict[str, bool | ToolConfig]] = None,
/// )
/// ```
#[derive(Default)]
pub struct CreateDeepAgentParams {
    pub tools: Vec<ToolBox>,
    pub instructions: String,
    pub middleware: Vec<Arc<dyn AgentMiddleware>>,
    pub model: Option<Arc<dyn agents_core::llm::LanguageModel>>,
    pub subagents: Vec<SubAgentConfig>,
    pub context_schema: Option<String>,
    pub checkpointer: Option<Arc<dyn Checkpointer>>,
    pub tool_configs: HashMap<String, HitlPolicy>,
}

/// Configuration for building a deep agent instance.
///
/// This is the internal configuration used by the builder and runtime.
pub struct DeepAgentConfig {
    pub instructions: String,
    /// Optional custom system prompt that completely replaces the default Deep Agent prompt
    pub custom_system_prompt: Option<String>,
    /// Format for tool call examples in the system prompt (JSON or TOON)
    pub prompt_format: PromptFormat,
    pub planner: Arc<dyn PlannerHandle>,
    pub tools: Vec<ToolBox>,
    pub subagent_configs: Vec<SubAgentConfig>,
    pub summarization: Option<SummarizationConfig>,
    pub tool_interrupts: HashMap<String, HitlPolicy>,
    pub builtin_tools: Option<HashSet<String>>,
    pub auto_general_purpose: bool,
    pub enable_prompt_caching: bool,
    pub checkpointer: Option<Arc<dyn Checkpointer>>,
    pub event_dispatcher: Option<Arc<agents_core::events::EventDispatcher>>,
    pub enable_pii_sanitization: bool,
    pub token_tracking_config: Option<TokenTrackingConfig>,
    pub max_iterations: NonZeroUsize,
}

impl DeepAgentConfig {
    pub fn new(instructions: impl Into<String>, planner: Arc<dyn PlannerHandle>) -> Self {
        Self {
            instructions: instructions.into(),
            custom_system_prompt: None,
            prompt_format: PromptFormat::default(),
            planner,
            tools: Vec::new(),
            subagent_configs: Vec::new(),
            summarization: None,
            tool_interrupts: HashMap::new(),
            builtin_tools: None,
            auto_general_purpose: true,
            enable_prompt_caching: false,
            checkpointer: None,
            event_dispatcher: None,
            enable_pii_sanitization: true, // Enabled by default for security
            token_tracking_config: None,
            max_iterations: NonZeroUsize::new(10).unwrap(),
        }
    }

    /// Set a custom system prompt that completely replaces the default Deep Agent prompt.
    ///
    /// When set, the `instructions` field is ignored and this prompt is used directly.
    pub fn with_system_prompt(mut self, system_prompt: impl Into<String>) -> Self {
        self.custom_system_prompt = Some(system_prompt.into());
        self
    }

    /// Set the prompt format for tool call examples in the system prompt.
    ///
    /// - `PromptFormat::Json` (default): Uses JSON examples
    /// - `PromptFormat::Toon`: Uses TOON format for 30-60% token reduction
    ///
    /// See: <https://github.com/toon-format/toon>
    pub fn with_prompt_format(mut self, format: PromptFormat) -> Self {
        self.prompt_format = format;
        self
    }

    pub fn with_tool(mut self, tool: ToolBox) -> Self {
        self.tools.push(tool);
        self
    }

    /// Add a sub-agent configuration
    pub fn with_subagent_config(mut self, config: SubAgentConfig) -> Self {
        self.subagent_configs.push(config);
        self
    }

    /// Add multiple sub-agent configurations
    pub fn with_subagent_configs<I>(mut self, configs: I) -> Self
    where
        I: IntoIterator<Item = SubAgentConfig>,
    {
        self.subagent_configs.extend(configs);
        self
    }

    pub fn with_summarization(mut self, config: SummarizationConfig) -> Self {
        self.summarization = Some(config);
        self
    }

    pub fn with_tool_interrupt(mut self, tool_name: impl Into<String>, policy: HitlPolicy) -> Self {
        self.tool_interrupts.insert(tool_name.into(), policy);
        self
    }

    /// Limit which built-in tools are exposed. When omitted, all built-ins are available.
    /// Built-ins: write_todos, ls, read_file, write_file, edit_file.
    /// The `task` tool (for subagents) is always available when subagents are registered.
    pub fn with_builtin_tools<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let set: HashSet<String> = names.into_iter().map(|s| s.into()).collect();
        self.builtin_tools = Some(set);
        self
    }

    /// Enable or disable automatic registration of a "general-purpose" subagent.
    /// Enabled by default; set to false to opt out.
    pub fn with_auto_general_purpose(mut self, enabled: bool) -> Self {
        self.auto_general_purpose = enabled;
        self
    }

    /// Enable or disable Anthropic prompt caching middleware.
    /// Disabled by default; set to true to enable caching for better performance.
    pub fn with_prompt_caching(mut self, enabled: bool) -> Self {
        self.enable_prompt_caching = enabled;
        self
    }

    /// Set the checkpointer for persisting agent state between runs.
    pub fn with_checkpointer(mut self, checkpointer: Arc<dyn Checkpointer>) -> Self {
        self.checkpointer = Some(checkpointer);
        self
    }

    /// Add an event broadcaster to the agent's event dispatcher.
    pub fn with_event_broadcaster(
        mut self,
        broadcaster: Arc<dyn agents_core::events::EventBroadcaster>,
    ) -> Self {
        if self.event_dispatcher.is_none() {
            self.event_dispatcher = Some(Arc::new(agents_core::events::EventDispatcher::new()));
        }
        if let Some(dispatcher) = Arc::get_mut(self.event_dispatcher.as_mut().unwrap()) {
            dispatcher.add_broadcaster(broadcaster);
        }
        self
    }

    /// Set the event dispatcher directly.
    pub fn with_event_dispatcher(
        mut self,
        dispatcher: Arc<agents_core::events::EventDispatcher>,
    ) -> Self {
        self.event_dispatcher = Some(dispatcher);
        self
    }

    /// Enable or disable PII sanitization in event data.
    /// Enabled by default for security. Disable only if you need raw data
    /// and have other security measures in place.
    ///
    /// When enabled:
    /// - Message previews are truncated to 100 characters
    /// - Sensitive fields (passwords, tokens, etc.) are redacted
    /// - PII patterns (emails, phones, credit cards) are removed
    pub fn with_pii_sanitization(mut self, enabled: bool) -> Self {
        self.enable_pii_sanitization = enabled;
        self
    }

    /// Configure token tracking for monitoring LLM usage and costs.
    pub fn with_token_tracking_config(mut self, config: TokenTrackingConfig) -> Self {
        self.token_tracking_config = Some(config);
        self
    }

    /// Set the maximum number of ReAct loop iterations before stopping.
    ///
    /// **Note**: `max_iterations` must be greater than 0. Passing 0 will result in a panic.
    ///
    /// # Panics
    ///
    /// Panics if `max_iterations` is 0.
    ///
    /// # Default
    ///
    /// Defaults to 10 if not specified.
    pub fn with_max_iterations(mut self, max_iterations: usize) -> Self {
        self.max_iterations =
            NonZeroUsize::new(max_iterations).expect("max_iterations must be greater than 0");
        self
    }
}

/// Configuration for creating and registering a subagent using a simple, Python-like shape.
///
/// Configuration for a sub-agent - a full AI agent with its own LLM, tools, and memory.
///
/// A sub-agent is just like the main agent: it has its own system instructions,
/// tools, LLM, and can maintain its own conversation history. The main agent
/// delegates tasks to sub-agents via the `task` tool.
///
/// ## Required Fields:
/// - `name`: Unique identifier for this sub-agent
/// - `description`: What this sub-agent specializes in (shown to main agent)
/// - `instructions`: System prompt for this sub-agent
///
/// ## Optional Fields:
/// - `model`: LLM to use (defaults to parent agent's model if not specified)
/// - `tools`: Tools available to this sub-agent (defaults to empty)
/// - `builtin_tools`: Built-in tools to enable (filesystem, todos, etc.)
/// - `enable_prompt_caching`: Whether to cache prompts for efficiency
pub struct SubAgentConfig {
    // Required fields
    pub name: String,
    pub description: String,
    pub instructions: String,

    // Optional fields - agent configuration
    pub model: Option<Arc<dyn agents_core::llm::LanguageModel>>,
    pub tools: Option<Vec<ToolBox>>,
    pub builtin_tools: Option<HashSet<String>>,
    pub enable_prompt_caching: bool,
}

impl SubAgentConfig {
    /// Create a new sub-agent configuration with required fields only
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        instructions: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            instructions: instructions.into(),
            model: None,
            tools: None,
            builtin_tools: None,
            enable_prompt_caching: false,
        }
    }

    /// Set the LLM model for this sub-agent
    pub fn with_model(mut self, model: Arc<dyn agents_core::llm::LanguageModel>) -> Self {
        self.model = Some(model);
        self
    }

    /// Set the tools for this sub-agent
    pub fn with_tools(mut self, tools: Vec<ToolBox>) -> Self {
        self.tools = Some(tools);
        self
    }

    /// Enable specific built-in tools (filesystem, todos, etc.)
    pub fn with_builtin_tools(mut self, tools: HashSet<String>) -> Self {
        self.builtin_tools = Some(tools);
        self
    }

    /// Enable prompt caching for this sub-agent
    pub fn with_prompt_caching(mut self, enabled: bool) -> Self {
        self.enable_prompt_caching = enabled;
        self
    }
}

impl IntoIterator for SubAgentConfig {
    type Item = SubAgentConfig;
    type IntoIter = std::iter::Once<SubAgentConfig>;

    fn into_iter(self) -> Self::IntoIter {
        std::iter::once(self)
    }
}

/// Configuration for summarization middleware
#[derive(Clone)]
pub struct SummarizationConfig {
    pub messages_to_keep: usize,
    pub summary_note: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::planner::LlmBackedPlanner;
    use std::sync::Arc;

    // Mock planner for testing
    fn create_mock_planner() -> Arc<dyn PlannerHandle> {
        // This is a simplified mock - in real tests you'd use a proper mock
        // For now, we'll just test the config builder API
        use crate::providers::{OpenAiChatModel, OpenAiConfig};
        use agents_core::llm::LanguageModel;

        // Create a dummy config - tests won't actually call the LLM
        let config = OpenAiConfig {
            api_key: "test-key".to_string(),
            model: "gpt-4o-mini".to_string(),
            api_url: None,
            custom_headers: Vec::new(),
        };

        let model: Arc<dyn LanguageModel> =
            Arc::new(OpenAiChatModel::new(config).expect("Failed to create test model"));
        Arc::new(LlmBackedPlanner::new(model))
    }

    #[test]
    fn test_config_default_max_iterations() {
        let planner = create_mock_planner();
        let config = DeepAgentConfig::new("test instructions", planner);
        assert_eq!(config.max_iterations.get(), 10);
    }

    #[test]
    fn test_config_custom_max_iterations() {
        let planner = create_mock_planner();
        let config = DeepAgentConfig::new("test instructions", planner).with_max_iterations(25);
        assert_eq!(config.max_iterations.get(), 25);
    }

    #[test]
    fn test_config_chaining_with_max_iterations() {
        let planner = create_mock_planner();
        let config = DeepAgentConfig::new("test instructions", planner)
            .with_max_iterations(30)
            .with_auto_general_purpose(false)
            .with_prompt_caching(true)
            .with_pii_sanitization(false);

        assert_eq!(config.max_iterations.get(), 30);
        assert!(!config.auto_general_purpose);
        assert!(config.enable_prompt_caching);
        assert!(!config.enable_pii_sanitization);
    }

    #[test]
    fn test_config_max_iterations_persists() {
        let planner = create_mock_planner();
        let config = DeepAgentConfig::new("test instructions", planner).with_max_iterations(42);

        // Verify the value is actually stored
        assert_eq!(config.max_iterations.get(), 42);
    }

    #[test]
    #[should_panic(expected = "max_iterations must be greater than 0")]
    fn test_config_zero_max_iterations_panics() {
        let planner = create_mock_planner();
        let _config = DeepAgentConfig::new("test instructions", planner).with_max_iterations(0);
    }

    #[test]
    fn test_config_max_iterations_with_other_options() {
        let planner = create_mock_planner();

        // Test that max_iterations works with various combinations
        let config =
            DeepAgentConfig::new("test instructions", planner.clone()).with_max_iterations(5);
        assert_eq!(config.max_iterations.get(), 5);

        let config2 = DeepAgentConfig::new("test instructions", planner.clone())
            .with_prompt_caching(true)
            .with_max_iterations(15);
        assert_eq!(config2.max_iterations.get(), 15);
        assert!(config2.enable_prompt_caching);

        let config3 = DeepAgentConfig::new("test instructions", planner)
            .with_auto_general_purpose(false)
            .with_max_iterations(100)
            .with_pii_sanitization(true);
        assert_eq!(config3.max_iterations.get(), 100);
        assert!(!config3.auto_general_purpose);
        assert!(config3.enable_pii_sanitization);
    }
}