1use std::marker::PhantomData;
7#[cfg(feature = "skills")]
8use std::sync::Arc;
9
10use aither_core::{
11 LanguageModel,
12 llm::{
13 Tool,
14 model::Parameters,
15 tool::{AnyApprover, Approver, ToolDefinition},
16 },
17};
18#[cfg(feature = "skills")]
19use aither_skills::SkillRegistry;
20
21use crate::{
22 agent::Agent,
23 config::AgentConfig,
24 context::{
25 AnyContextSource, AnyFileReferences, AnyLiveSource, Context, ContextPolicy, ContextSource,
26 ExternalContent, ExternalSlot, FileReferences, HandoffDocument, HandoffSchema,
27 InstructionSlot, LiveSource, SystemLayout,
28 },
29 hook::Hooks,
30 request_parameters::WithParameters,
31 tools::AgentTools,
32};
33
34#[cfg(feature = "mcp")]
35use aither_mcp::McpConnection;
36
37#[must_use]
57pub struct AgentBuilder<M, H = (), C = M, Schema = HandoffDocument> {
58 model: M,
59 compaction_model: Option<WithParameters<C>>,
62 hooks: H,
63 parameters: Parameters,
64 config: AgentConfig,
65 context: Context,
66 prompt_cache: crate::context::PromptCache,
67 clock: crate::AnyClock,
68 context_sources: Vec<AnyContextSource>,
69 live_sources: Vec<AnyLiveSource>,
70 approver: Option<AnyApprover>,
71 subagents: Option<crate::SubagentRuns>,
72 fork_source: Option<crate::fork::ForkSource>,
73 identity: aither_core::llm::AgentIdentity,
74 tools: AgentTools,
75 connectivity: crate::connectivity::Watch,
76 restore_dir: Option<std::path::PathBuf>,
77 file_references: Option<AnyFileReferences>,
78 inherited: Option<Inherited>,
80 #[cfg(feature = "skills")]
81 skill_registry: Option<Arc<SkillRegistry>>,
82 handoff_schema: PhantomData<fn() -> Schema>,
84}
85
86#[derive(Clone)]
88struct Inherited {
89 budget: crate::context::ContextBudget,
90 profile: aither_core::llm::model::Profile,
91 effort: crate::effort::EffortAnchor,
92 definitions: Vec<ToolDefinition>,
93}
94
95impl<M, H, C, Schema> std::fmt::Debug for AgentBuilder<M, H, C, Schema> {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 f.debug_struct("AgentBuilder")
98 .field("config", &self.config)
99 .finish_non_exhaustive()
100 }
101}
102
103impl<M: LanguageModel> AgentBuilder<M> {
104 pub fn new(model: M) -> Self {
106 Self {
107 model,
108 compaction_model: None,
109 hooks: (),
110 parameters: Parameters::default(),
111 config: AgentConfig::default(),
112 context: Context::default(),
113 prompt_cache: crate::context::PromptCache::new(uuid::Uuid::new_v4().to_string()),
114 clock: crate::AnyClock::default(),
115 context_sources: Vec::new(),
116 live_sources: Vec::new(),
117 approver: None,
118 subagents: None,
119 fork_source: None,
120 identity: aither_core::llm::AgentIdentity::Main,
121 tools: AgentTools::new(),
122 connectivity: crate::connectivity::Watch::default(),
123 restore_dir: None,
124 file_references: None,
125 inherited: None,
126 #[cfg(feature = "skills")]
127 skill_registry: None,
128 handoff_schema: PhantomData,
129 }
130 }
131}
132
133impl<M, H, C, Schema> AgentBuilder<M, H, C, Schema>
134where
135 M: LanguageModel + 'static,
136 C: LanguageModel + 'static,
137 H: Hooks,
138 Schema: HandoffSchema,
139{
140 pub fn identity(mut self, identity: aither_core::llm::AgentIdentity) -> Self {
144 self.identity = identity;
145 self
146 }
147
148 pub fn fork_source(mut self, source: crate::fork::ForkSource) -> Self {
151 self.fork_source = Some(source);
152 self
153 }
154
155 pub const fn max_iterations(mut self, limit: usize) -> Self {
159 self.config.max_iterations = limit;
160 self
161 }
162
163 pub const fn context_policy(mut self, policy: ContextPolicy) -> Self {
166 self.config.context_policy = policy;
167 self
168 }
169
170 pub const fn config(mut self, config: AgentConfig) -> Self {
172 self.config = config;
173 self
174 }
175
176 pub fn context_source<S: ContextSource>(mut self, source: S) -> Self {
181 self.context_sources.push(AnyContextSource::new(source));
182 self
183 }
184
185 pub fn live_source<S: LiveSource>(mut self, source: S) -> Self {
199 assert!(
200 self.live_sources
201 .iter()
202 .all(|registered| registered.tag() != S::TAG),
203 "live source `{}` is registered twice",
204 S::TAG
205 );
206 self.live_sources.push(AnyLiveSource::new(source));
207 self
208 }
209
210 pub fn subagents(mut self, runs: crate::SubagentRuns) -> Self {
213 self.subagents = Some(runs);
214 self
215 }
216
217 pub fn approver(mut self, approver: impl Approver) -> Self {
225 self.approver = Some(AnyApprover::new(approver));
226 self
227 }
228
229 #[cfg(feature = "skills")]
231 pub fn skill_registry(mut self, registry: Arc<SkillRegistry>) -> Self {
232 self.skill_registry = Some(registry);
233 self
234 }
235
236 pub fn instruction(mut self, content: impl Into<String>) -> Self {
239 let instructions = self.context.instructions_mut();
240 let slot = InstructionSlot::owned(format!("instruction-{}", instructions.len()));
241 instructions.place(slot.clone());
242 instructions.insert(&slot, content);
243 self
244 }
245
246 pub fn tagged_instruction(mut self, tag: &'static str, content: &str) -> Self {
248 let instructions = self.context.instructions_mut();
249 let slot = InstructionSlot::new(tag);
250 instructions.place(slot.clone());
251 instructions.insert_tagged(&slot, content);
252 self
253 }
254
255 pub fn external_content(mut self, name: &'static str, content: ExternalContent) -> Self {
259 let external = self.context.external_mut();
260 let slot = ExternalSlot::new(name);
261 external.place(slot.clone());
262 external.insert(&slot, content);
263 self
264 }
265
266 pub fn system_layout(mut self, layout: SystemLayout) -> Self {
273 self.context.set_layout(layout);
274 self
275 }
276
277 pub fn request_parameters(mut self, parameters: Parameters) -> Self {
286 self.parameters = parameters;
287 self
288 }
289
290 pub fn prompt_cache(mut self, cache: crate::context::PromptCache) -> Self {
298 self.prompt_cache = cache;
299 self
300 }
301
302 pub fn claude_cache_ttl(mut self, ttl: aither_core::llm::model::ClaudePromptCacheTtl) -> Self {
305 self.prompt_cache = self.prompt_cache.with_ttl(ttl);
306 self
307 }
308
309 pub fn cache_lifetime(mut self, lifetime: crate::context::CacheLifetime) -> Self {
312 self.prompt_cache = self.prompt_cache.with_lifetime(lifetime);
313 self
314 }
315
316 pub fn clock(mut self, clock: impl crate::Clock) -> Self {
319 self.clock = crate::AnyClock::new(clock);
320 self
321 }
322
323 pub fn restore_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
325 self.restore_dir = Some(path.into());
326 self
327 }
328
329 pub fn file_references(mut self, references: impl FileReferences) -> Self {
331 self.file_references = Some(AnyFileReferences::new(references));
332 self
333 }
334
335 pub fn handoff<S2: HandoffSchema>(self) -> AgentBuilder<M, H, C, S2> {
342 AgentBuilder {
343 model: self.model,
344 compaction_model: self.compaction_model,
345 hooks: self.hooks,
346 parameters: self.parameters,
347 config: self.config,
348 context: self.context,
349 prompt_cache: self.prompt_cache,
350 clock: self.clock,
351 context_sources: self.context_sources,
352 live_sources: self.live_sources,
353 approver: self.approver,
354 subagents: self.subagents,
355 fork_source: self.fork_source,
356 identity: self.identity,
357 tools: self.tools,
358 connectivity: self.connectivity,
359 restore_dir: self.restore_dir,
360 file_references: self.file_references,
361 inherited: self.inherited,
362 #[cfg(feature = "skills")]
363 skill_registry: self.skill_registry,
364 handoff_schema: PhantomData,
365 }
366 }
367
368 pub fn compaction_model<C2: LanguageModel>(
381 self,
382 model: C2,
383 parameters: Parameters,
384 ) -> AgentBuilder<M, H, C2, Schema> {
385 AgentBuilder {
386 model: self.model,
387 compaction_model: Some(WithParameters {
388 model,
389 parameters: Box::new(parameters),
390 }),
391 hooks: self.hooks,
392 parameters: self.parameters,
393 config: self.config,
394 context: self.context,
395 prompt_cache: self.prompt_cache,
396 clock: self.clock,
397 context_sources: self.context_sources,
398 live_sources: self.live_sources,
399 approver: self.approver,
400 subagents: self.subagents,
401 fork_source: self.fork_source,
402 identity: self.identity,
403 tools: self.tools,
404 connectivity: self.connectivity,
405 restore_dir: self.restore_dir,
406 file_references: self.file_references,
407 inherited: self.inherited,
408 #[cfg(feature = "skills")]
409 skill_registry: self.skill_registry,
410 handoff_schema: PhantomData,
411 }
412 }
413
414 pub fn hooks<NH: Hooks>(self, hooks: NH) -> AgentBuilder<M, NH, C, Schema> {
417 AgentBuilder {
418 model: self.model,
419 compaction_model: self.compaction_model,
420 hooks,
421 parameters: self.parameters,
422 config: self.config,
423 context: self.context,
424 prompt_cache: self.prompt_cache,
425 clock: self.clock,
426 context_sources: self.context_sources,
427 live_sources: self.live_sources,
428 approver: self.approver,
429 subagents: self.subagents,
430 fork_source: self.fork_source,
431 identity: self.identity,
432 tools: self.tools,
433 connectivity: self.connectivity,
434 restore_dir: self.restore_dir,
435 file_references: self.file_references,
436 inherited: self.inherited,
437 #[cfg(feature = "skills")]
438 skill_registry: self.skill_registry,
439 handoff_schema: PhantomData,
440 }
441 }
442
443 pub fn tool<T: Tool + 'static>(mut self, tool: T) -> Self {
451 self.tools
452 .register(tool)
453 .expect("tool registration must succeed: duplicate name or missing description");
454 self
455 }
456
457 pub fn forked_from(mut self, fork: &crate::fork::ForkSnapshot) -> Self {
471 self.context = fork.context.clone();
472 self.prompt_cache = fork.prompt_cache.clone();
473 self.parameters = fork.request_parameters.clone();
474 self.config.context_policy = fork.context_policy;
475 self.inherited = Some(Inherited {
476 budget: fork.budget,
477 profile: fork.profile.clone(),
478 effort: fork.effort,
479 definitions: fork.definitions.clone(),
480 });
481 self
482 }
483
484 #[cfg(feature = "mcp")]
489 pub fn mcp(mut self, conn: McpConnection) -> Self {
490 self.tools.register_mcp(conn);
491 self
492 }
493
494 #[cfg(feature = "connectivity")]
503 pub fn connectivity(mut self, connectivity: aither_connectivity::Connectivity) -> Self {
504 self.connectivity = crate::connectivity::Watch::new(connectivity);
505 self
506 }
507
508 #[must_use]
513 pub fn tool_definitions(&self) -> Vec<ToolDefinition> {
514 self.tools.active_definitions()
515 }
516
517 pub fn build(self) -> Agent<M, H, C, Schema> {
524 let inherited = self.inherited.as_ref();
525 if let Some(inherited) = inherited {
526 assert_eq!(
527 self.tools.active_definitions(),
528 inherited.definitions,
529 "a fork's tools must present the definitions of the request it starts from"
530 );
531 }
532 let initialized = inherited.is_some();
534 let (budget, effort, profile) = inherited.map_or_else(Default::default, |inherited| {
535 (
536 inherited.budget,
537 inherited.effort,
538 Some(inherited.profile.clone()),
539 )
540 });
541 Agent {
542 warmth: crate::CacheWarmth::new(self.prompt_cache.lifetime(), self.clock),
543 model: std::sync::Arc::new(self.model),
544 compaction_model: self.compaction_model.map(|compactor| WithParameters {
545 model: std::sync::Arc::new(compactor.model),
546 parameters: compactor.parameters,
547 }),
548 parameters: Box::new(self.parameters),
549 effort,
550 idle_compacted: false,
551 tools: self.tools,
552 hooks: self.hooks,
553 config: self.config,
554 context: self.context,
555 budget,
556 prompt_cache: self.prompt_cache,
557 context_sources: self.context_sources,
558 live_sources: self.live_sources,
559 approver: self.approver,
560 subagents: self.subagents,
561 pauses: std::sync::Arc::default(),
562 last_tail: Vec::new(),
563 reassembled: false,
564 prefix_rewrites: crate::context::PrefixRewrites::default(),
565 requests_sent: 0,
566 request_ids: 0,
567 compaction: crate::compaction_state::CompactionState::default(),
568 compaction_failure: None,
569 compaction_announced: false,
570 tool_results: std::collections::VecDeque::new(),
571 profile,
572 compaction_profile: None,
573 initialized,
574 connectivity: self.connectivity,
575 restore_dir: self.restore_dir,
576 file_references: self.file_references,
577 last_request: None,
578 delivering: None,
579 fork_source: self.fork_source,
580 identity: self.identity,
581 cache_stats: crate::CacheStats::new(),
582 #[cfg(feature = "skills")]
583 skill_registry: self.skill_registry,
584 handoff_schema: PhantomData,
585 }
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592 use std::borrow::Cow;
593
594 use schemars::JsonSchema;
595 use serde::Deserialize;
596
597 use futures_core::Stream;
598
599 #[derive(Debug)]
601 struct MockError;
602
603 impl std::fmt::Display for MockError {
604 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
605 write!(f, "mock error")
606 }
607 }
608
609 impl std::error::Error for MockError {}
610
611 impl aither_core::llm::Classify for MockError {
612 fn failure(&self) -> aither_core::llm::Failure {
613 aither_core::llm::Failure::permanent()
614 }
615 }
616
617 #[derive(Clone)]
619 struct MockLlm;
620
621 impl LanguageModel for MockLlm {
622 type Error = MockError;
623
624 fn respond(
625 &self,
626 _request: aither_core::llm::LLMRequest,
627 ) -> impl Stream<Item = Result<aither_core::llm::Event, Self::Error>> + Send {
628 futures_lite::stream::empty()
629 }
630
631 fn profile(
632 &self,
633 ) -> impl std::future::Future<
634 Output = Result<aither_core::llm::model::Profile, Self::Error>,
635 > + Send {
636 std::future::ready(Ok(aither_core::llm::model::Profile::new(
637 "mock",
638 "test",
639 "mock-model",
640 "A mock model for testing",
641 100_000,
642 )))
643 }
644 }
645
646 struct MockTool;
648
649 #[derive(Debug, JsonSchema, Deserialize)]
651 struct MockArgs;
652
653 impl Tool for MockTool {
654 fn name(&self) -> Cow<'static, str> {
655 "mock_tool".into()
656 }
657
658 type Arguments = MockArgs;
659 type Res = aither_core::llm::ToolResult;
660
661 fn call(
662 &self,
663 _args: Self::Arguments,
664 _cx: aither_core::llm::ToolContext,
665 ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
666 std::future::ready(Ok(aither_core::llm::ToolResult::text("ok")))
667 }
668 }
669
670 struct MockHook;
672
673 impl Hooks for MockHook {}
674
675 #[test]
676 fn test_builder_basic() {
677 let agent = AgentBuilder::new(MockLlm).build();
678 assert_eq!(agent.tools.definitions(), []);
679 }
680
681 #[test]
682 fn test_builder_with_tool() {
683 let agent = AgentBuilder::new(MockLlm).tool(MockTool).build();
684 assert_eq!(agent.tools.definitions().len(), 1);
685 }
686
687 #[test]
688 fn instructions_render_in_the_order_they_were_added() {
689 let agent = AgentBuilder::new(MockLlm)
690 .instruction("first")
691 .tagged_instruction("second", "two")
692 .instruction("third")
693 .build();
694 let rendered: Vec<String> = agent
695 .context
696 .build_request(&[])
697 .iter()
698 .map(|message| message.content().to_string())
699 .collect();
700 let joined = rendered.join("\n");
701 let first = joined.find("first").expect("first instruction renders");
702 let second = joined.find("two").expect("second instruction renders");
703 let third = joined.find("third").expect("third instruction renders");
704 assert!(first < second && second < third);
705 }
706
707 #[test]
708 fn the_agent_holds_no_instruction_the_embedder_did_not_add() {
709 let agent = AgentBuilder::new(MockLlm).build();
710 assert!(agent.context.instructions().is_empty());
711 assert!(agent.context.external().is_empty());
712 }
713
714 #[test]
715 fn test_builder_with_hook() {
716 let _agent = AgentBuilder::new(MockLlm).hooks(MockHook).build();
717 }
718
719 #[test]
721 fn options_survive_the_steps_that_change_the_builders_type() {
722 let policy = ContextPolicy {
723 handoff_reserve: 1_234,
724 ..ContextPolicy::default()
725 };
726 let agent = AgentBuilder::new(MockLlm)
727 .context_policy(policy)
728 .max_iterations(7)
729 .hooks(MockHook)
730 .compaction_model(MockLlm, Parameters::default())
731 .build();
732 assert_eq!(agent.config.context_policy, policy);
733 assert_eq!(agent.config.max_iterations, 7);
734 }
735
736 #[test]
737 fn test_builder_default_config() {
738 let agent = AgentBuilder::new(MockLlm).build();
739 assert_eq!(
740 agent.config.max_iterations,
741 AgentConfig::default().max_iterations
742 );
743 }
744}