1#[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#[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 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 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 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 pub const fn tier(mut self, tier: ModelTier) -> Self {
187 self.tier = tier;
188 self
189 }
190
191 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 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 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 pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
260 self.config.system_prompt = Some(prompt.into());
261 self
262 }
263
264 pub const fn max_iterations(mut self, limit: usize) -> Self {
268 self.config.max_iterations = limit;
269 self
270 }
271
272 pub const fn context_strategy(mut self, strategy: ContextStrategy) -> Self {
274 self.config.context = strategy;
275 self
276 }
277
278 pub fn persona_prompt(mut self, prompt: impl Into<String>) -> Self {
280 self.config.persona_prompt = Some(prompt.into());
281 self
282 }
283
284 pub const fn agent_kind(mut self, kind: AgentKind) -> Self {
286 self.config.agent_kind = kind;
287 self
288 }
289
290 pub fn transcript_path(mut self, path: impl Into<String>) -> Self {
292 self.config.transcript_path = Some(path.into());
293 self
294 }
295
296 pub fn transcript(mut self, path: impl Into<std::path::PathBuf>) -> Self {
298 self.transcript = Some(Transcript::new(path));
299 self
300 }
301
302 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 #[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 pub fn system<T: serde::Serialize>(mut self, value: T) -> Self {
317 self.context.insert_system(&value);
318 self
319 }
320
321 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 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 #[cfg(feature = "mcp")]
384 pub fn mcp(mut self, conn: McpConnection) -> Self {
385 self.tools.register_mcp(conn);
386 self
387 }
388
389 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 pub fn config(mut self, config: AgentConfig) -> Self {
444 self.config = config;
445 self
446 }
447
448 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 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 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 #[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 #[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 struct MockTool;
583
584 #[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 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 }
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 }
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}