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
6use 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/// Builder for constructing agents with custom configuration.
38///
39/// # Type Parameters
40///
41/// - `M`: the conversation model
42/// - `H`: the composed hooks
43/// - `C`: the model compaction runs on, when [`compaction_model`](Self::compaction_model)
44///   sets one
45/// - `Schema`: the handoff schema, see [`handoff`](Self::handoff)
46///
47/// # Example
48///
49/// ```rust,ignore
50/// let agent = Agent::builder(claude)
51///     .request_parameters(parameters)
52///     .instruction("You are a helpful assistant.")
53///     .tool(FileSystemTool::read_only("."))
54///     .build();
55/// ```
56#[must_use]
57pub struct AgentBuilder<M, H = (), C = M, Schema = HandoffDocument> {
58    model: M,
59    /// The model compaction runs on instead of the session's own, with the
60    /// parameters of its requests.
61    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    /// The window state a fork inherits, which replaces initialization.
79    inherited: Option<Inherited>,
80    #[cfg(feature = "skills")]
81    skill_registry: Option<Arc<SkillRegistry>>,
82    /// The handoff schema compactions ask for; no value is held.
83    handoff_schema: PhantomData<fn() -> Schema>,
84}
85
86/// What a fork carries over from the main agent besides its context.
87#[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    /// Creates a new agent builder with default configuration.
105    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    /// Sets the identity every tool call of the built agent carries as the
141    /// agent making it. An agent is the main agent unless an embedder builds
142    /// it as a subagent.
143    pub fn identity(mut self, identity: aither_core::llm::AgentIdentity) -> Self {
144        self.identity = identity;
145        self
146    }
147
148    /// Publishes every request the built agent sends to `source`, which is
149    /// where a fork starts from.
150    pub fn fork_source(mut self, source: crate::fork::ForkSource) -> Self {
151        self.fork_source = Some(source);
152        self
153    }
154
155    /// Sets the maximum number of iterations (turns).
156    ///
157    /// The agent will stop and return an error if this limit is exceeded.
158    pub const fn max_iterations(mut self, limit: usize) -> Self {
159        self.config.max_iterations = limit;
160        self
161    }
162
163    /// Sets the context management policy: when compaction starts, where the
164    /// window pauses, and the budgets compaction and recovery work within.
165    pub const fn context_policy(mut self, policy: ContextPolicy) -> Self {
166        self.config.context_policy = policy;
167        self
168    }
169
170    /// Sets the full agent configuration.
171    pub const fn config(mut self, config: AgentConfig) -> Self {
172        self.config = config;
173        self
174    }
175
176    /// Registers a source rendered into the tail of every request.
177    ///
178    /// Sources are rendered in registration order, and each is told when the
179    /// request it contributed to was sent.
180    pub fn context_source<S: ContextSource>(mut self, source: S) -> Self {
181        self.context_sources.push(AnyContextSource::new(source));
182        self
183    }
184
185    /// Registers live content: a source rendered into the cacheable prefix,
186    /// after the system prompt and before the handoff, for content too large
187    /// to resend uncached in every request's tail.
188    ///
189    /// Blocks render in registration order. A change after a request carried
190    /// the block reaches the model as the diff alert the source writes for
191    /// it, and the new block replaces the old one at the next reassembly or
192    /// compaction (see [`LiveSource`]).
193    ///
194    /// # Panics
195    ///
196    /// Panics if a live source with the same [`TAG`](LiveSource::TAG) is
197    /// already registered.
198    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    /// Sets the registry of children the agent's tools run, whose events
211    /// join the agent's stream (see [`SubagentRuns`](crate::SubagentRuns)).
212    pub fn subagents(mut self, runs: crate::SubagentRuns) -> Self {
213        self.subagents = Some(runs);
214        self
215    }
216
217    /// Sets who answers the approval requests of tool calls: a
218    /// [`ToolDecision::Ask`](crate::ToolDecision::Ask) from a hook, and the
219    /// requests tools make of their own.
220    ///
221    /// Without one, a request fails the run with
222    /// [`AgentError::Approval`](crate::AgentError::Approval). The run emits
223    /// [`Paused`](crate::AgentEvent::Paused) while an approval is pending.
224    pub fn approver(mut self, approver: impl Approver) -> Self {
225        self.approver = Some(AnyApprover::new(approver));
226        self
227    }
228
229    /// Sets the skill registry used for the skill catalog compaction offers.
230    #[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    /// Appends an instruction to the system prompt, verbatim. Instructions
237    /// render in the order they are added; aither supplies none of its own.
238    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    /// Appends an instruction to the system prompt wrapped in a `tag` tag.
247    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    /// Appends the external-content block `name`: memory, a repository's
256    /// instructions, a fetched page or a file, rendered after every
257    /// instruction inside a boundary it cannot close.
258    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    /// Lays the system prompt out in `layout`'s order, for a prompt whose
267    /// blocks are placed by name instead of by the order they are added in.
268    ///
269    /// # Panics
270    ///
271    /// Panics if a block already added has no slot in `layout`.
272    pub fn system_layout(mut self, layout: SystemLayout) -> Self {
273        self.context.set_layout(layout);
274        self
275    }
276
277    /// Sets the parameters of every request aither sends the conversation
278    /// model: the agent's turns, its compactions on that model, its cache
279    /// keep-alives and the first request of a fork.
280    ///
281    /// aither sets the fields it owns per request over them — the prompt-
282    /// cache controls, structured output on a compaction, and the token cap
283    /// of a keep-alive — and sends every other field as given here. The
284    /// [`compaction_model`](Self::compaction_model) takes its own.
285    pub fn request_parameters(mut self, parameters: Parameters) -> Self {
286        self.parameters = parameters;
287        self
288    }
289
290    /// Overrides the session's prompt-cache controller.
291    ///
292    /// The default derives a fresh session key per agent, so every rebuild
293    /// asks for a new cache shard; a host that rebuilds its agent supplies
294    /// the session's identity (and the replaced agent's epoch, through
295    /// [`PromptCache::with_epoch`](crate::context::PromptCache::with_epoch))
296    /// so the key stays the same across rebuilds.
297    pub fn prompt_cache(mut self, cache: crate::context::PromptCache) -> Self {
298        self.prompt_cache = cache;
299        self
300    }
301
302    /// Sets the Claude cache retention of the session's prompt cache,
303    /// keeping its session key; the cache lifetime follows the retention.
304    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    /// Sets the conversation's cache lifetime, keeping the rest of its
310    /// prompt cache. Idle compaction and idle reassembly follow it.
311    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    /// Sets the time source idle compaction, idle reassembly and cache
317    /// warmth read; the system clock by default.
318    pub fn clock(mut self, clock: impl crate::Clock) -> Self {
319        self.clock = crate::AnyClock::new(clock);
320        self
321    }
322
323    /// Sets the directory files are restored from after a compaction.
324    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    /// Sets how a compaction's file index finds the files tool results name.
330    pub fn file_references(mut self, references: impl FileReferences) -> Self {
331        self.file_references = Some(AnyFileReferences::new(references));
332        self
333    }
334
335    /// Sets the handoff schema every compaction asks the model for, in place
336    /// of [`HandoffDocument`].
337    ///
338    /// The schema's type is the structured output the model fills; its
339    /// [`HandoffSchema`] implementation gives the instruction, the retry,
340    /// the validation and the text the conversation reads after the handoff.
341    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    /// Sets the model compaction runs on, instead of the session's own.
369    ///
370    /// Without one, compaction reads the conversation's prompt cache on the
371    /// session's model, and an idle session is compacted shortly before the
372    /// cache expires ([`Agent::compact_when_idle`]). A different model cannot
373    /// read that cache, so with one set compaction requests go to it, idle
374    /// compaction never runs, and an idle gap past the cache lifetime
375    /// reassembles the window instead.
376    ///
377    /// Compaction requests to it carry `parameters`, the model's own, in
378    /// place of the session model's, under the cache controls and structured
379    /// output aither sets on every compaction.
380    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    /// Sets the embedder's decisions at the loop's control points, in place
415    /// of any set before (see [`Hooks`]).
416    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    /// Registers a tool.
444    ///
445    /// # Panics
446    ///
447    /// Panics if the tool cannot be registered: another tool already uses
448    /// its name, or it carries no description for the model to read. Both
449    /// are mistakes in the calling program.
450    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    /// Makes the built agent a fork of the main agent that sent `fork`.
458    ///
459    /// The agent starts from the main agent's request: its window, with the
460    /// live tail as the last message, its request parameters and its
461    /// prompt-cache identity, so its first request is the main agent's
462    /// followed by the prompt it is given and reads the main agent's cache.
463    /// Nothing is initialized on top of that, since initialization would
464    /// rewrite the window.
465    ///
466    /// The tools registered on this builder must present exactly
467    /// [`ForkSnapshot::definitions`](crate::ForkSnapshot::definitions), or
468    /// the first request would diverge from the cached prefix at the tool
469    /// definitions.
470    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    /// Registers an MCP connection.
485    ///
486    /// All tools from the MCP server will be available for the agent to use.
487    /// You can call this method multiple times to register multiple MCP servers.
488    #[cfg(feature = "mcp")]
489    pub fn mcp(mut self, conn: McpConnection) -> Self {
490        self.tools.register_mcp(conn);
491        self
492    }
493
494    /// Ends a provider response stream in flight when the machine wakes from
495    /// sleep or loses its network.
496    ///
497    /// The attempt fails with an [`AgentError::Llm`](crate::AgentError::Llm)
498    /// whose failure is
499    /// [`FailureKind::Network`](aither_core::llm::FailureKind::Network), so the
500    /// caller retries instead of sitting on a dead socket. Nothing about the
501    /// change reaches the agent's context.
502    #[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    /// Returns the definitions of the tools registered on this builder so far.
509    ///
510    /// These are the definitions the built agent sends to the model, in the
511    /// order the tool registry holds them.
512    #[must_use]
513    pub fn tool_definitions(&self) -> Vec<ToolDefinition> {
514        self.tools.active_definitions()
515    }
516
517    /// Builds the agent.
518    ///
519    /// # Panics
520    ///
521    /// Panics when the agent is a fork and its tools do not present the
522    /// definitions the main agent's request carried.
523    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        // A fork starts initialized, from what the main agent carried over.
533        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    // Mock error type for testing
600    #[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    // Mock LLM for testing
618    #[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    // Mock tool
647    struct MockTool;
648
649    /// Does nothing, for tests that only care that a tool was registered.
650    #[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    // Mock hook
671    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    /// Options set before a step that changes the builder's type survive it.
720    #[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}