Skip to main content

aither_agent/
builder.rs

1//! Builder for constructing agents with custom configuration.
2//!
3//! The builder pattern allows fluent configuration of agents with
4//! tools, hooks, and various settings.
5
6#[cfg(feature = "skills")]
7use std::sync::Arc;
8
9use aither_core::{LanguageModel, llm::Tool};
10use aither_sandbox::{BackgroundTaskReceiver, JobRegistry, PermissionEventReceiver};
11#[cfg(feature = "skills")]
12use aither_skills::SkillRegistry;
13
14use crate::{
15    agent::Agent,
16    compression::ContextStrategy,
17    config::{AgentConfig, AgentKind},
18    context::Context,
19    hook::{HCons, Hook},
20    model_group::ModelTier,
21    todo::{TodoList, TodoTool},
22    tools::AgentTools,
23    transcript::Transcript,
24};
25
26#[cfg(feature = "mcp")]
27use aither_mcp::McpConnection;
28
29/// Builder for constructing agents with custom configuration.
30///
31/// Supports tiered LLM configuration:
32/// - Advanced: Primary model for main reasoning (most capable)
33/// - Balanced: Model for moderate tasks like subagents (defaults to advanced)
34/// - Fast: Model for quick tasks like compaction (defaults to balanced)
35///
36/// # Example
37///
38/// ```rust,ignore
39/// // Simple: all tiers use the same model
40/// let agent = Agent::builder(claude).build();
41///
42/// // Tiered: different models for different tasks
43/// let agent = Agent::builder(opus)      // Advanced
44///     .balanced_model(sonnet)           // Balanced
45///     .fast_model(haiku)                // Fast
46///     .system_prompt("You are a helpful assistant.")
47///     .tool(FileSystemTool::read_only("."))
48///     .build();
49/// ```
50#[must_use]
51pub struct AgentBuilder<Advanced, Balanced = Advanced, Fast = Balanced, H = ()> {
52    advanced: Advanced,
53    balanced: Balanced,
54    fast: Fast,
55    tier: ModelTier,
56    tools: AgentTools,
57    hooks: H,
58    config: AgentConfig,
59    context: Context,
60    todo_list: Option<TodoList>,
61    background_receiver: Option<BackgroundTaskReceiver>,
62    permission_receiver: Option<PermissionEventReceiver>,
63    job_registry: Option<JobRegistry>,
64    transcript: Option<Transcript>,
65    sandbox_dir: Option<std::path::PathBuf>,
66    #[cfg(feature = "skills")]
67    skill_registry: Option<Arc<SkillRegistry>>,
68}
69
70impl<Advanced, Balanced, Fast, H> std::fmt::Debug for AgentBuilder<Advanced, Balanced, Fast, H> {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("AgentBuilder")
73            .field("tier", &self.tier)
74            .field("config", &self.config)
75            .field("todo_enabled", &self.todo_list.is_some())
76            .finish_non_exhaustive()
77    }
78}
79
80impl<LLM: LanguageModel + Clone> AgentBuilder<LLM, LLM, LLM, ()> {
81    /// Creates a new agent builder with default configuration.
82    ///
83    /// All model tiers (advanced/balanced/fast) use the same model.
84    pub fn new(llm: LLM) -> Self {
85        Self {
86            advanced: llm.clone(),
87            balanced: llm.clone(),
88            fast: llm,
89            tier: ModelTier::default(),
90            tools: AgentTools::new(),
91            hooks: (),
92            config: AgentConfig::default(),
93            context: Context::default(),
94            todo_list: None,
95            background_receiver: None,
96            permission_receiver: None,
97            job_registry: None,
98            transcript: None,
99            sandbox_dir: None,
100            #[cfg(feature = "skills")]
101            skill_registry: None,
102        }
103    }
104}
105
106impl<Advanced, Balanced, Fast, H> AgentBuilder<Advanced, Balanced, Fast, H>
107where
108    Advanced: LanguageModel,
109    Balanced: LanguageModel,
110    Fast: LanguageModel,
111    H: Hook,
112{
113    /// Sets the balanced model for moderate tasks (e.g., subagents).
114    ///
115    /// This model is used when spawning subagents that don't need
116    /// the full capabilities of the advanced model.
117    pub fn balanced_model<B2: LanguageModel>(
118        self,
119        model: B2,
120    ) -> AgentBuilder<Advanced, B2, Fast, H> {
121        AgentBuilder {
122            advanced: self.advanced,
123            balanced: model,
124            fast: self.fast,
125            tier: self.tier,
126            tools: self.tools,
127            hooks: self.hooks,
128            config: self.config,
129            context: self.context,
130            todo_list: self.todo_list,
131            background_receiver: self.background_receiver,
132            permission_receiver: self.permission_receiver,
133            job_registry: self.job_registry,
134            transcript: self.transcript,
135            sandbox_dir: self.sandbox_dir,
136            #[cfg(feature = "skills")]
137            skill_registry: self.skill_registry,
138        }
139    }
140
141    /// Sets the fast model for quick tasks (e.g., compaction, ask command).
142    ///
143    /// This model is used for tasks where speed and cost matter more
144    /// than capability, such as context compression.
145    pub fn fast_model<F2: LanguageModel>(
146        self,
147        model: F2,
148    ) -> AgentBuilder<Advanced, Balanced, F2, H> {
149        AgentBuilder {
150            advanced: self.advanced,
151            balanced: self.balanced,
152            fast: model,
153            tier: self.tier,
154            tools: self.tools,
155            hooks: self.hooks,
156            config: self.config,
157            context: self.context,
158            todo_list: self.todo_list,
159            background_receiver: self.background_receiver,
160            permission_receiver: self.permission_receiver,
161            job_registry: self.job_registry,
162            transcript: self.transcript,
163            sandbox_dir: self.sandbox_dir,
164            #[cfg(feature = "skills")]
165            skill_registry: self.skill_registry,
166        }
167    }
168
169    /// Sets which model tier to use for the agent's main reasoning loop.
170    ///
171    /// This allows creating subagents that use different capability levels:
172    /// - `ModelTier::Advanced`: Use the most capable model (default)
173    /// - `ModelTier::Balanced`: Use the balanced model (good for subagents)
174    /// - `ModelTier::Fast`: Use the fast model (for quick tasks)
175    ///
176    /// # Example
177    ///
178    /// ```rust,ignore
179    /// // Create an explore subagent using the balanced model
180    /// let explore_agent = Agent::builder(opus)
181    ///     .balanced_model(sonnet)
182    ///     .fast_model(haiku)
183    ///     .tier(ModelTier::Balanced)  // Use sonnet for reasoning
184    ///     .build();
185    /// ```
186    pub const fn tier(mut self, tier: ModelTier) -> Self {
187        self.tier = tier;
188        self
189    }
190
191    /// Registers an eager (always-loaded) tool.
192    ///
193    /// Eager tools are included in every LLM request.
194    ///
195    /// # Panics
196    ///
197    /// Panics if the tool cannot be registered: another tool already uses
198    /// its name, or it carries no description for the model to read. Both
199    /// are mistakes in the calling program.
200    pub fn tool<T: Tool + 'static>(mut self, tool: T) -> Self {
201        self.tools
202            .register(tool)
203            .expect("tool registration must succeed: duplicate name or missing description");
204        self
205    }
206
207    /// Registers a dynamic terminal tool (type-erased).
208    ///
209    /// This is used for child terminal capability bundles in subagents where the
210    /// concrete terminal type is not known at compile time.
211    pub fn dyn_terminal(mut self, dyn_tool: aither_sandbox::DynTerminalTool) -> Self {
212        self.background_receiver = Some(dyn_tool.background_receiver());
213        self.permission_receiver = Some(dyn_tool.permission_receiver());
214        self.job_registry = Some(dyn_tool.job_registry());
215        self.sandbox_dir = Some(dyn_tool.working_dir().clone());
216        self.tools.register_dyn_terminal(dyn_tool);
217        self
218    }
219
220    /// Adds a hook to intercept agent operations.
221    ///
222    /// Hooks are composed using the `HCons` pattern, allowing multiple
223    /// hooks to be chained at compile time.
224    ///
225    /// # Example
226    ///
227    /// ```rust,ignore
228    /// let agent = Agent::builder(llm)
229    ///     .hook(LoggingHook)
230    ///     .hook(ConfirmationHook)
231    ///     .build();
232    /// // Type: Agent<LLM, HCons<ConfirmationHook, HCons<LoggingHook, ()>>>
233    /// ```
234    pub fn hook<NH: Hook>(self, hook: NH) -> AgentBuilder<Advanced, Balanced, Fast, HCons<NH, H>> {
235        AgentBuilder {
236            advanced: self.advanced,
237            balanced: self.balanced,
238            fast: self.fast,
239            tier: self.tier,
240            tools: self.tools,
241            hooks: HCons::new(hook, self.hooks),
242            config: self.config,
243            context: self.context,
244            todo_list: self.todo_list,
245            background_receiver: self.background_receiver,
246            permission_receiver: self.permission_receiver,
247            job_registry: self.job_registry,
248            transcript: self.transcript,
249            sandbox_dir: self.sandbox_dir,
250            #[cfg(feature = "skills")]
251            skill_registry: self.skill_registry,
252        }
253    }
254
255    /// Sets the system prompt.
256    ///
257    /// The system prompt is prepended to every conversation and
258    /// remains stable for prompt caching.
259    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
260        self.config.system_prompt = Some(prompt.into());
261        self
262    }
263
264    /// Sets the maximum number of iterations (turns).
265    ///
266    /// The agent will stop and return an error if this limit is exceeded.
267    pub const fn max_iterations(mut self, limit: usize) -> Self {
268        self.config.max_iterations = limit;
269        self
270    }
271
272    /// Sets the context compression strategy.
273    pub const fn context_strategy(mut self, strategy: ContextStrategy) -> Self {
274        self.config.context = strategy;
275        self
276    }
277
278    /// Sets an optional persona overlay prompt.
279    pub fn persona_prompt(mut self, prompt: impl Into<String>) -> Self {
280        self.config.persona_prompt = Some(prompt.into());
281        self
282    }
283
284    /// Sets agent kind (coding or chatbot).
285    pub const fn agent_kind(mut self, kind: AgentKind) -> Self {
286        self.config.agent_kind = kind;
287        self
288    }
289
290    /// Sets transcript path for long-memory recovery guidance.
291    pub fn transcript_path(mut self, path: impl Into<String>) -> Self {
292        self.config.transcript_path = Some(path.into());
293        self
294    }
295
296    /// Enables writing a readable transcript to the given path.
297    pub fn transcript(mut self, path: impl Into<std::path::PathBuf>) -> Self {
298        self.transcript = Some(Transcript::new(path));
299        self
300    }
301
302    /// Sets sandbox directory for working document supervision.
303    pub fn sandbox_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
304        self.sandbox_dir = Some(path.into());
305        self
306    }
307
308    /// Sets the skill registry used for runtime skill matching and activation.
309    #[cfg(feature = "skills")]
310    pub fn skill_registry(mut self, registry: Arc<SkillRegistry>) -> Self {
311        self.skill_registry = Some(registry);
312        self
313    }
314
315    /// Inserts or replaces a typed persistent system block.
316    pub fn system<T: serde::Serialize>(mut self, value: T) -> Self {
317        self.context.insert_system(&value);
318        self
319    }
320
321    /// Inserts or replaces a persistent system block with an explicit tag.
322    pub fn system_named(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
323        self.context.insert_system_named(tag, content);
324        self
325    }
326
327    /// Inserts or replaces a persistent system block with raw text.
328    ///
329    /// Unlike [`system`](Self::system) and [`system_named`](Self::system_named),
330    /// the `content` is stored verbatim without any XML wrapping. This is the
331    /// preferred entry point for prose system blocks (workspace descriptions,
332    /// runtime metadata, environment hints) where XML structure adds tokens
333    /// without providing semantic value.
334    pub fn system_text(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
335        self.context.insert_system_text(tag, content);
336        self
337    }
338
339    /// Registers an MCP connection.
340    ///
341    /// All tools from the MCP server will be available for the agent to use.
342    /// You can call this method multiple times to register multiple MCP servers.
343    ///
344    /// # Example
345    ///
346    /// ```rust,ignore
347    /// use aither_mcp::McpConnection;
348    ///
349    /// // Connect to an MCP server
350    /// let conn = McpConnection::spawn("npx", &["-y", "@modelcontextprotocol/server-filesystem", "/"]).await?;
351    ///
352    /// let agent = Agent::builder(llm)
353    ///     .mcp(conn)
354    ///     .build();
355    /// ```
356    ///
357    /// # Multiple Servers
358    ///
359    /// ```rust,ignore
360    /// let filesystem = McpConnection::spawn("npx", &["-y", "@modelcontextprotocol/server-filesystem", "/"]).await?;
361    /// let github = McpConnection::spawn("npx", &["-y", "@modelcontextprotocol/server-github"]).await?;
362    ///
363    /// let agent = Agent::builder(llm)
364    ///     .mcp(filesystem)
365    ///     .mcp(github)
366    ///     .build();
367    /// ```
368    ///
369    /// # Loading from Configuration
370    ///
371    /// ```rust,ignore
372    /// use aither_mcp::{McpConnection, McpServersConfig};
373    ///
374    /// let config: McpServersConfig = serde_json::from_str(&config_json)?;
375    /// let connections = McpConnection::from_configs(&config).await?;
376    ///
377    /// let mut builder = Agent::builder(llm);
378    /// for (_name, conn) in connections {
379    ///     builder = builder.mcp(conn);
380    /// }
381    /// let agent = builder.build();
382    /// ```
383    #[cfg(feature = "mcp")]
384    pub fn mcp(mut self, conn: McpConnection) -> Self {
385        self.tools.register_mcp(conn);
386        self
387    }
388
389    /// Registers the terminal tool for command execution in a sandbox.
390    ///
391    /// The terminal tool enables command execution with configurable permission modes
392    /// (sandboxed, network, unsafe). It creates its own working directory with
393    /// four random words and manages output storage internally.
394    ///
395    /// This also captures the background task receiver for polling completed
396    /// background tasks during the agent loop.
397    ///
398    /// # Example
399    ///
400    /// ```rust,ignore
401    /// use aither_sandbox::{TerminalTool, ToolRegistryBuilder, permission::DenyUnsafe};
402    /// use std::sync::Arc;
403    ///
404    /// // Create terminal tool (creates random working dir like amber-forest-thunder-pearl/)
405    /// let terminal_tool = TerminalTool::new_in(parent, DenyUnsafe, executor).await?;
406    /// let registry = Arc::new(ToolRegistryBuilder::new().build(terminal_tool.outputs_dir()));
407    /// let terminal_tool = terminal_tool.with_registry(registry);
408    ///
409    /// let agent = Agent::builder(llm)
410    ///     .terminal(terminal_tool)
411    ///     .build();
412    /// ```
413    ///
414    /// # Panics
415    ///
416    /// Panics if the tool cannot be registered: another tool already uses
417    /// its name, or it carries no description for the model to read. Both
418    /// are mistakes in the calling program.
419    pub fn terminal<P, E, State>(
420        mut self,
421        terminal_tool: aither_sandbox::TerminalTool<P, E, State>,
422    ) -> Self
423    where
424        P: aither_sandbox::PermissionHandler + 'static,
425        E: executor_core::Executor + Clone + 'static,
426        State: Clone + 'static,
427        aither_sandbox::TerminalTool<P, E, State>: Tool + 'static,
428    {
429        let background_receiver = terminal_tool.background_receiver();
430        let permission_receiver = terminal_tool.permission_receiver();
431        let job_registry = terminal_tool.job_registry();
432        self.sandbox_dir = Some(terminal_tool.working_dir().clone());
433        self.tools
434            .register(terminal_tool)
435            .expect("tool registration must succeed: duplicate name or missing description");
436        self.background_receiver = Some(background_receiver);
437        self.permission_receiver = Some(permission_receiver);
438        self.job_registry = Some(job_registry);
439        self
440    }
441
442    /// Sets the full agent configuration.
443    pub fn config(mut self, config: AgentConfig) -> Self {
444        self.config = config;
445        self
446    }
447
448    /// Enables todo list tracking for managing long tasks.
449    ///
450    /// When enabled, the agent will:
451    /// - Inject the current todo list into the context before each LLM request
452    /// - Generate system reminders when tasks are completed
453    ///
454    /// # Example
455    ///
456    /// ```rust,ignore
457    /// let agent = Agent::builder(llm)
458    ///     .todo()
459    ///     .build();
460    /// ```
461    ///
462    /// # Panics
463    ///
464    /// Panics if the tool cannot be registered: another tool already uses
465    /// its name, or it carries no description for the model to read. Both
466    /// are mistakes in the calling program.
467    pub fn todo(mut self) -> Self {
468        let list = TodoList::new();
469        let tool = TodoTool::with_list(list.clone());
470        self.tools
471            .register(tool)
472            .expect("tool registration must succeed: duplicate name or missing description");
473        self.todo_list = Some(list);
474        self
475    }
476
477    /// Enables todo list tracking with a shared list.
478    ///
479    /// Use this when you want to share a todo list between multiple agents
480    /// or access the list externally.
481    ///
482    /// # Panics
483    ///
484    /// Panics if the tool cannot be registered: another tool already uses
485    /// its name, or it carries no description for the model to read. Both
486    /// are mistakes in the calling program.
487    pub fn todo_with_list(mut self, list: TodoList) -> Self {
488        let tool = TodoTool::with_list(list.clone());
489        self.tools
490            .register(tool)
491            .expect("tool registration must succeed: duplicate name or missing description");
492        self.todo_list = Some(list);
493        self
494    }
495
496    /// Builds the agent.
497    pub fn build(self) -> Agent<Advanced, Balanced, Fast, H> {
498        Agent {
499            advanced: self.advanced,
500            balanced: self.balanced,
501            fast: self.fast,
502            tier: self.tier,
503            tools: self.tools,
504            hooks: self.hooks,
505            config: self.config,
506            context: self.context,
507            profile: None,
508            fast_profile: None,
509            initialized: false,
510            todo_list: self.todo_list,
511            background_receiver: self.background_receiver,
512            permission_receiver: self.permission_receiver,
513            job_registry: self.job_registry,
514            transcript: self.transcript,
515            sandbox_dir: self.sandbox_dir,
516            last_working_docs: None,
517            last_request_started_at: None,
518            transient_system_messages: Vec::new(),
519            cache_stats: crate::CacheStats::new(),
520            #[cfg(feature = "skills")]
521            skill_registry: self.skill_registry,
522            #[cfg(feature = "skills")]
523            active_skills: Vec::new(),
524            #[cfg(feature = "skills")]
525            active_allowed_tools: None,
526        }
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use std::borrow::Cow;
534
535    #[cfg(feature = "skills")]
536    use aither_skills::{Skill, SkillRegistry};
537    use schemars::JsonSchema;
538    use serde::Deserialize;
539
540    use futures_core::Stream;
541
542    // Mock error type for testing
543    #[derive(Debug)]
544    struct MockError;
545
546    impl std::fmt::Display for MockError {
547        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548            write!(f, "mock error")
549        }
550    }
551
552    impl std::error::Error for MockError {}
553
554    // Mock LLM for testing
555    #[derive(Clone)]
556    struct MockLlm;
557
558    impl LanguageModel for MockLlm {
559        type Error = MockError;
560
561        fn respond(
562            &self,
563            _request: aither_core::llm::LLMRequest,
564        ) -> impl Stream<Item = Result<aither_core::llm::Event, Self::Error>> + Send {
565            futures_lite::stream::empty()
566        }
567
568        fn profile(
569            &self,
570        ) -> impl std::future::Future<Output = aither_core::llm::model::Profile> + Send {
571            std::future::ready(aither_core::llm::model::Profile::new(
572                "mock",
573                "test",
574                "mock-model",
575                "A mock model for testing",
576                100_000,
577            ))
578        }
579    }
580
581    // Mock tool
582    struct MockTool;
583
584    /// Does nothing, for tests that only care that a tool was registered.
585    #[derive(Debug, JsonSchema, Deserialize)]
586    struct MockArgs;
587
588    impl Tool for MockTool {
589        fn name(&self) -> Cow<'static, str> {
590            "mock_tool".into()
591        }
592
593        type Arguments = MockArgs;
594        type Res = aither_core::llm::ToolResult;
595
596        fn call(
597            &self,
598            _args: Self::Arguments,
599        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
600            std::future::ready(Ok(aither_core::llm::ToolResult::text("ok")))
601        }
602    }
603
604    // Mock hook
605    struct MockHook;
606
607    impl Hook for MockHook {}
608
609    #[test]
610    fn test_builder_basic() {
611        let agent = AgentBuilder::new(MockLlm).build();
612        assert!(agent.tools.definitions().is_empty());
613    }
614
615    #[test]
616    fn public_model_tier_configures_agent_builder() {
617        let agent = AgentBuilder::new(MockLlm)
618            .tier(crate::ModelTier::Balanced)
619            .build();
620        assert_eq!(agent.tier, crate::ModelTier::Balanced);
621    }
622
623    #[test]
624    fn test_builder_with_tool() {
625        let agent = AgentBuilder::new(MockLlm).tool(MockTool).build();
626        assert_eq!(agent.tools.definitions().len(), 1);
627    }
628
629    #[test]
630    fn test_builder_with_system_prompt() {
631        let agent = AgentBuilder::new(MockLlm)
632            .system_prompt("You are helpful.")
633            .build();
634        assert_eq!(
635            agent.config.system_prompt,
636            Some("You are helpful.".to_string())
637        );
638    }
639
640    #[test]
641    fn test_builder_with_hook() {
642        let _agent = AgentBuilder::new(MockLlm).hook(MockHook).build();
643        // Type check: agent has HCons<MockHook, ()> as hook type
644    }
645
646    #[test]
647    fn test_builder_with_multiple_hooks() {
648        let _agent = AgentBuilder::new(MockLlm)
649            .hook(MockHook)
650            .hook(MockHook)
651            .build();
652        // Type check: agent has HCons<MockHook, HCons<MockHook, ()>>
653    }
654
655    #[test]
656    fn test_builder_max_iterations() {
657        let agent = AgentBuilder::new(MockLlm).max_iterations(100).build();
658        assert_eq!(agent.config.max_iterations, 100);
659    }
660
661    #[test]
662    fn test_builder_default_config() {
663        let agent = AgentBuilder::new(MockLlm).build();
664        assert_eq!(
665            agent.config.max_iterations,
666            AgentConfig::default().max_iterations
667        );
668    }
669
670    #[cfg(feature = "skills")]
671    #[test]
672    fn test_builder_preserves_skill_registry() {
673        let mut registry = SkillRegistry::new();
674        registry.register(Skill {
675            name: "code-review".to_string(),
676            description: "Review code carefully".to_string(),
677            instructions: "Use a review checklist.".to_string(),
678            allowed_tools: Some(vec!["mock_tool".to_string()]),
679            resources: std::collections::HashMap::new(),
680        });
681
682        let agent = AgentBuilder::new(MockLlm)
683            .skill_registry(Arc::new(registry))
684            .build();
685        assert!(agent.skill_registry.is_some());
686    }
687
688    #[cfg(feature = "skills")]
689    #[test]
690    fn test_runtime_skill_activation_is_disabled() {
691        let mut registry = SkillRegistry::new();
692        registry.register(Skill {
693            name: "code-review".to_string(),
694            description: "Review code carefully".to_string(),
695            instructions: "Use a review checklist.".to_string(),
696            allowed_tools: Some(vec!["mock_tool".to_string()]),
697            resources: std::collections::HashMap::new(),
698        });
699
700        let mut agent = AgentBuilder::new(MockLlm)
701            .skill_registry(Arc::new(registry))
702            .build();
703        let events = agent.activate_skills_for_prompt("please review this patch");
704
705        assert!(events.is_empty());
706        assert!(agent.active_skills.is_empty());
707        assert!(agent.active_allowed_tools.is_none());
708    }
709}