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