Skip to main content

agent_base/engine/
builder.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use crate::llm::ReasoningConfig;
5use crate::tool::{Tool, ToolPolicy, ToolRegistry};
6use crate::types::{
7    AgentConfig, ConvertToLlmFn, ResponseFormat, RetryConfig, SessionIdGenerator,
8    shared_session_ids,
9};
10
11use super::AgentRuntime;
12use super::approval::ApprovalHandler;
13use super::context::{ContextCompaction, ContextWindowManager};
14use super::executor::{
15    ActionBackend, DEFAULT_INTERACT_TIMEOUT, FailClosedInteract, InteractionChannel,
16};
17use super::middleware::{Middleware, MiddlewareRef};
18use super::react_loop_guard::ReactLoopGuard;
19use super::recovery::{StopOnError, ToolErrorRecovery};
20use super::session_store::{InMemorySessionStore, SessionStore};
21
22pub struct AgentBuilder {
23    provider: Arc<dyn llm_trait::LlmProvider>,
24    config: AgentConfig,
25    tools: ToolRegistry,
26    approval_handler: Option<Arc<dyn ApprovalHandler>>,
27    tool_policy: Option<Arc<dyn ToolPolicy>>,
28    middlewares: Vec<MiddlewareRef>,
29    context_manager: Option<ContextWindowManager>,
30    session_store: Option<Arc<dyn SessionStore>>,
31    error_recovery: Option<Arc<dyn ToolErrorRecovery>>,
32    event_bus_capacity: usize,
33    session_id_generator: Option<Arc<dyn SessionIdGenerator>>,
34    convert_to_llm: Option<ConvertToLlmFn>,
35    guard: Option<Arc<dyn ReactLoopGuard>>,
36    context_compactor: Option<Arc<dyn ContextCompaction>>,
37    action_backend: Option<Box<dyn ActionBackend>>,
38    interact: Option<Arc<dyn InteractionChannel>>,
39    /// Outer `None` = unset (the default watchdog); inner `None` = explicitly
40    /// unbounded human time.
41    interact_timeout: Option<Option<Duration>>,
42    /// Which `Deferred` tools the model may open this session. A product that
43    /// registers [`crate::tool::ActivateTool`] MUST pass the same set it gave
44    /// that tool, or openings land in a set the engine never reads.
45    activation: crate::tool::ToolActivation,
46}
47
48impl AgentBuilder {
49    /// Create a new builder with an `LlmProvider`.
50    pub fn new(provider: Arc<dyn llm_trait::LlmProvider>) -> Self {
51        Self {
52            provider,
53            config: AgentConfig::default(),
54            tools: ToolRegistry::default(),
55            approval_handler: None,
56            tool_policy: None,
57            middlewares: Vec::new(),
58            context_manager: None,
59            session_store: None,
60            error_recovery: None,
61            event_bus_capacity: 2048,
62            session_id_generator: None,
63            convert_to_llm: None,
64            guard: None,
65            context_compactor: None,
66            action_backend: None,
67            interact: None,
68            interact_timeout: None,
69            activation: crate::tool::ToolActivation::new(),
70        }
71    }
72
73    /// Share the session's tool-activation set with the engine. See the field
74    /// docs: a product that registers [`crate::tool::ActivateTool`] must hand
75    /// that tool this same set.
76    pub fn with_tool_activation(mut self, activation: crate::tool::ToolActivation) -> Self {
77        self.activation = activation;
78        self
79    }
80
81    /// Re-wrap a registered tool as [`crate::tool::DeferredTool`]: it stays on
82    /// the roster and is callable once opened, but costs the request nothing
83    /// until then.
84    ///
85    /// Returns the tool's rendered wire definition, which is what
86    /// [`crate::tool::ActivateTool`] hands back when the model opens it. The
87    /// product needs that here because the tools worth deferring are built
88    /// inside the framework's own builder — it never holds the instances, so
89    /// it cannot render them itself. `None` when the name is not registered.
90    ///
91    /// Registration-time wrapping would be cleaner if every tool were built
92    /// where the product can see it. This moves the call to the product all the
93    /// same, which is the only layer that knows what its work actually needs.
94    pub fn defer_tool(&mut self, name: &str) -> Option<serde_json::Value> {
95        let inner = self.tools.get(name)?;
96        if inner.exposure() != crate::tool::ToolExposure::Deferred {
97            self.tools
98                .register_arc(Arc::new(crate::tool::DeferredTool::new(inner.clone())));
99        }
100        Some(crate::tool::render_tool_definition(inner.as_ref()))
101    }
102
103    pub fn event_bus_capacity(mut self, capacity: usize) -> Self {
104        self.event_bus_capacity = capacity;
105        self
106    }
107
108    pub fn session_id_generator(mut self, generator: Arc<dyn SessionIdGenerator>) -> Self {
109        self.session_id_generator = Some(generator);
110        self
111    }
112
113    /// Set a callback to transform messages before they are sent to the LLM.
114    ///
115    /// The default behavior (when `None`) is to filter out
116    /// `ChatMessage::Custom` variants, which most providers don't understand.
117    /// Override this to inject custom serialization logic for application-specific
118    /// message types.
119    pub fn convert_to_llm(mut self, cb: ConvertToLlmFn) -> Self {
120        self.convert_to_llm = Some(cb);
121        self
122    }
123
124    pub fn guard(mut self, guard: impl ReactLoopGuard + 'static) -> Self {
125        self.guard = Some(Arc::new(guard));
126        self
127    }
128
129    /// Set a guard from a pre-built `Arc<dyn ReactLoopGuard>`.
130    ///
131    /// Use this when you need to share the guard reference (e.g. for inspecting
132    /// recorded calls in tests).
133    pub fn guard_dyn(mut self, guard: Arc<dyn ReactLoopGuard>) -> Self {
134        self.guard = Some(guard);
135        self
136    }
137
138    /// Set an inline context compactor for the react loop.
139    ///
140    /// When set, the react loop will check token count after each tool turn
141    /// and compact the session if it exceeds the configured threshold.
142    pub fn context_compactor(mut self, compactor: Arc<dyn ContextCompaction>) -> Self {
143        self.context_compactor = Some(compactor);
144        self
145    }
146
147    /// Mount this runtime's action backend (T10c): text turns route to it,
148    /// tool-envelope turns keep the built-in tool-call backend. One backend
149    /// per runtime — build one runtime per session when the backend holds a
150    /// resident engine (the product's assembly-time choice, sdk-assembly
151    /// §3.4).
152    pub fn action_backend(mut self, backend: Box<dyn ActionBackend>) -> Self {
153        self.action_backend = Some(backend);
154        self
155    }
156
157    /// The product's interaction surface for the action backend's `ExecCtx`
158    /// (OV-6): consent and ask_user suspend through it. Without one, every
159    /// interaction fails closed (`FailClosedInteract`) — a cell reaching for
160    /// the human refuses, it never hangs or silently allows.
161    pub fn interaction(mut self, channel: Arc<dyn InteractionChannel>) -> Self {
162        self.interact = Some(channel);
163        self
164    }
165
166    /// Per-interaction deadline for the action backend's suspensions (`None`
167    /// = unbounded human time, the run's cancel token is the only guard —
168    /// phimint's TUI shape). Unset = [`DEFAULT_INTERACT_TIMEOUT`].
169    pub fn interaction_timeout(mut self, interact_timeout: Option<Duration>) -> Self {
170        self.interact_timeout = Some(interact_timeout);
171        self
172    }
173
174    /// Check if a guard has been set.
175    ///
176    /// Used by agent-works to inject a default guard if none was set.
177    pub fn get_guard(&self) -> Option<&Arc<dyn ReactLoopGuard>> {
178        self.guard.as_ref()
179    }
180
181    pub fn system_prompt(mut self, system_prompt: impl Into<String>) -> Self {
182        self.config.system_prompt = Some(system_prompt.into());
183        self
184    }
185
186    /// Set whether to include the reasoning content in LLM responses.
187    ///
188    /// Controls whether the `reasoning_content` field from the LLM is forwarded
189    /// to consumers (i.e., "show the thinking process").
190    /// See [`AgentConfig::enable_thought`] for the distinction from `enable_thinking()`.
191    pub fn enable_thought(mut self, enable: bool) -> Self {
192        self.config.enable_thought = enable;
193        self
194    }
195
196    pub fn reasoning(mut self, config: ReasoningConfig) -> Self {
197        self.config.reasoning = Some(config);
198        self
199    }
200
201    /// Set whether to enable the model's extended thinking / reasoning mode.
202    ///
203    /// Controls whether the model performs deep reasoning (i.e., "enable thinking mode").
204    /// See [`AgentConfig::enable_thought`] for the distinction from `enable_thought()`.
205    pub fn enable_thinking(mut self, enable: bool) -> Self {
206        let mut config = self.config.reasoning.take().unwrap_or_default();
207        config.enabled = Some(enable);
208        self.config.reasoning = Some(config);
209        self
210    }
211
212    pub fn thinking_budget(mut self, budget: u64) -> Self {
213        let mut config = self.config.reasoning.take().unwrap_or_default();
214        config.budget_tokens = Some(budget);
215        self.config.reasoning = Some(config);
216        self
217    }
218
219    pub fn tool_timeout(mut self, timeout_ms: u64) -> Self {
220        self.config.tool.tool_timeout_ms = Some(timeout_ms);
221        self
222    }
223
224    pub fn max_tool_output_chars(mut self, max_chars: usize) -> Self {
225        self.config.tool.max_tool_output_chars = Some(max_chars);
226        self
227    }
228
229    pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
230        self.tools.register(tool);
231        self
232    }
233
234    pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
235        self.tools.register_arc(tool);
236        self
237    }
238
239    pub fn approval_handler(mut self, handler: Arc<dyn ApprovalHandler>) -> Self {
240        self.approval_handler = Some(handler);
241        self
242    }
243
244    pub fn tool_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
245        self.tool_policy = Some(policy);
246        self
247    }
248
249    pub fn middleware(mut self, mw: impl Middleware + 'static) -> Self {
250        self.middlewares.push(Arc::new(mw));
251        self
252    }
253
254    pub fn context_window(mut self, max_tokens: usize) -> Self {
255        self.context_manager = Some(ContextWindowManager::new(max_tokens));
256        self
257    }
258
259    pub fn context_window_manager(mut self, manager: ContextWindowManager) -> Self {
260        self.context_manager = Some(manager);
261        self
262    }
263
264    pub fn response_format(mut self, format: ResponseFormat) -> Self {
265        self.config.llm.response_format = Some(format);
266        self
267    }
268
269    pub fn llm_retry(mut self, retry: RetryConfig) -> Self {
270        self.config.llm.llm_retry = Some(retry);
271        self
272    }
273
274    pub fn session_store(mut self, store: Arc<dyn SessionStore>) -> Self {
275        self.session_store = Some(store);
276        self
277    }
278
279    pub fn error_recovery(mut self, recovery: Arc<dyn ToolErrorRecovery>) -> Self {
280        self.error_recovery = Some(recovery);
281        self
282    }
283
284    pub fn max_sessions(mut self, max: usize) -> Self {
285        self.config.session.max_sessions = Some(max);
286        self
287    }
288
289    pub fn max_turns_per_session(mut self, max: usize) -> Self {
290        self.config.session.max_turns_per_session = Some(max);
291        self
292    }
293
294    /// Cap the number of react-loop iterations allowed for a *single* run (one user
295    /// input). Distinct from [`Self::max_turns_per_session`], which caps turns across
296    /// the whole session. When unset, falls back to `DEFAULT_MAX_TURNS` (50).
297    pub fn execution_max_turns(mut self, max: u32) -> Self {
298        self.config.execution.max_turns = Some(max);
299        self
300    }
301
302    pub fn max_message_tokens(mut self, max: usize) -> Self {
303        self.config.session.max_message_tokens = Some(max);
304        self
305    }
306
307    pub fn tool_error_retry_prompt(mut self, prompt: impl Into<String>) -> Self {
308        self.config.tool.tool_error_retry_prompt = Some(prompt.into());
309        self
310    }
311
312    pub fn language(mut self, language: crate::types::Language) -> Self {
313        self.config.language = language;
314        self
315    }
316
317    /// Conditionally chain a builder call: apply `f` only when `value` is `Some`.
318    ///
319    /// # Example
320    /// ```ignore
321    /// let builder = AgentBuilder::new(client)
322    ///     .apply_if(config.timeout, |b, t| b.tool_timeout(t))
323    ///     .apply_if(config.max_chars, |b, c| b.max_tool_output_chars(c));
324    /// ```
325    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
326        match value {
327            Some(v) => f(self, v),
328            None => self,
329        }
330    }
331
332    pub fn build(self) -> crate::types::AgentResult<AgentRuntime> {
333        self.config.validate()?;
334
335        tracing::info!(
336            tool_count = self.tools.len(),
337            middleware_count = self.middlewares.len(),
338            has_approval = self.approval_handler.is_some(),
339            has_context_window = self.context_manager.is_some(),
340            "building agent runtime"
341        );
342
343        let event_bus = super::runtime::EventBus::new(self.event_bus_capacity);
344
345        let session_store = self
346            .session_store
347            .unwrap_or_else(|| Arc::new(InMemorySessionStore::new()));
348        let error_recovery = self.error_recovery.unwrap_or_else(|| Arc::new(StopOnError));
349        // Default numbering is process-global: a host and its sub-agents are
350        // several engines in one process, and per-engine counters handed every
351        // one of them a "session 1".
352        let session_id_generator = self.session_id_generator.unwrap_or_else(shared_session_ids);
353
354        let session_manager = super::runtime::SessionManager::new(
355            session_id_generator,
356            session_store,
357            self.config.session.clone(),
358        );
359
360        let llm_engine = super::runtime::LlmEngine::new(self.provider.clone(), event_bus.clone());
361
362        let tool_engine = super::runtime::ToolEngine::new(
363            self.tools,
364            self.approval_handler,
365            self.tool_policy,
366            error_recovery,
367            event_bus.clone(),
368        );
369
370        // Interaction defaults: fail-closed when the product mounts no
371        // channel; the standard watchdog when it sets no deadline.
372        let interact = self
373            .interact
374            .unwrap_or_else(|| Arc::new(FailClosedInteract));
375        let interact_timeout = self
376            .interact_timeout
377            .unwrap_or(Some(DEFAULT_INTERACT_TIMEOUT));
378
379        let runner = Arc::new(super::runtime::RuntimeCore::new(
380            self.config,
381            llm_engine,
382            tool_engine,
383            session_manager,
384            event_bus,
385            self.context_manager,
386            self.middlewares,
387            self.convert_to_llm,
388            self.guard,
389            self.context_compactor,
390            self.action_backend,
391            interact,
392            interact_timeout,
393            self.activation,
394        ));
395
396        Ok(AgentRuntime { runner })
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use crate::engine::DenyAllApprovalHandler;
404    use crate::llm::ReasoningEffort;
405    use crate::tool::{Content, ToolActivation, ToolContext};
406    use crate::types::{AgentError, AgentResult, ApprovalRequest, Language, ResponseFormat};
407    use async_trait::async_trait;
408    use llm_trait::{Capabilities, ChatRequest, ChatResponse, ChatStream, LlmError, ProviderInfo};
409    use serde_json::Value;
410
411    struct DummyProvider;
412
413    #[async_trait]
414    impl llm_trait::LlmProvider for DummyProvider {
415        async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
416            Ok(ChatStream::new(Box::pin(futures_util::stream::empty())))
417        }
418
419        async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
420            Ok(ChatResponse {
421                content: String::new(),
422                reasoning_content: None,
423                tool_calls: vec![],
424                usage: Default::default(),
425                finish_reason: llm_trait::FinishReason::Stop,
426                raw: None,
427                thinking_signature: None,
428            })
429        }
430
431        fn capabilities(&self) -> Capabilities {
432            Capabilities::default()
433        }
434
435        fn info(&self) -> ProviderInfo {
436            ProviderInfo {
437                name: "dummy".to_string(),
438                model: "dummy".to_string(),
439                version: None,
440            }
441        }
442    }
443
444    #[test]
445    fn execution_max_turns_writes_per_run_config() {
446        let builder = AgentBuilder::new(Arc::new(DummyProvider)).execution_max_turns(200);
447        assert_eq!(builder.config.execution.max_turns, Some(200));
448    }
449
450    #[test]
451    fn execution_max_turns_defaults_to_none() {
452        let builder = AgentBuilder::new(Arc::new(DummyProvider));
453        assert_eq!(builder.config.execution.max_turns, None);
454    }
455
456    fn b() -> AgentBuilder {
457        AgentBuilder::new(Arc::new(DummyProvider))
458    }
459
460    struct NoopTool;
461
462    #[async_trait]
463    impl Tool for NoopTool {
464        fn name(&self) -> &'static str {
465            "noop"
466        }
467        fn description(&self) -> &'static str {
468            "noop tool"
469        }
470        fn schema(&self) -> Value {
471            serde_json::json!({"type": "object"})
472        }
473        async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
474            Ok(vec![Content::text("ok")])
475        }
476    }
477
478    struct AutoApprovePolicy;
479
480    #[async_trait]
481    impl ToolPolicy for AutoApprovePolicy {
482        async fn evaluate_approval(
483            &self,
484            _tool_name: &str,
485            _args: &Value,
486        ) -> Option<ApprovalRequest> {
487            None
488        }
489    }
490
491    struct NoopMiddleware;
492
493    impl Middleware for NoopMiddleware {}
494
495    #[test]
496    fn system_prompt_sets_config() {
497        assert_eq!(
498            b().system_prompt("be helpful")
499                .config
500                .system_prompt
501                .as_deref(),
502            Some("be helpful")
503        );
504    }
505
506    #[test]
507    fn enable_thought_sets_config() {
508        assert!(b().enable_thought(true).config.enable_thought);
509    }
510
511    #[test]
512    fn reasoning_sets_config() {
513        let rc = ReasoningConfig {
514            enabled: Some(true),
515            budget_tokens: Some(64),
516            effort: Some(ReasoningEffort::Medium),
517        };
518        let builder = b().reasoning(rc);
519        let got = builder.config.reasoning.as_ref().unwrap();
520        assert_eq!(got.enabled, Some(true));
521        assert_eq!(got.budget_tokens, Some(64));
522        assert!(matches!(got.effort.as_ref(), Some(ReasoningEffort::Medium)));
523    }
524
525    #[test]
526    fn enable_thinking_and_budget_set_reasoning() {
527        let builder = b().enable_thinking(true).thinking_budget(128);
528        let got = builder.config.reasoning.as_ref().unwrap();
529        assert_eq!(got.enabled, Some(true));
530        assert_eq!(got.budget_tokens, Some(128));
531    }
532
533    #[test]
534    fn tool_limits_set_config() {
535        let builder = b().tool_timeout(5_000).max_tool_output_chars(1_024);
536        assert_eq!(builder.config.tool.tool_timeout_ms, Some(5_000));
537        assert_eq!(builder.config.tool.max_tool_output_chars, Some(1_024));
538    }
539
540    #[test]
541    fn register_tool_adds_to_registry() {
542        assert_eq!(b().register_tool(NoopTool).tools.len(), 1);
543    }
544
545    #[test]
546    fn approval_handler_and_tool_policy_are_set() {
547        let builder = b()
548            .approval_handler(Arc::new(DenyAllApprovalHandler))
549            .tool_policy(Arc::new(AutoApprovePolicy));
550        assert!(builder.approval_handler.is_some());
551        assert!(builder.tool_policy.is_some());
552    }
553
554    #[test]
555    fn middleware_and_context_window_are_set() {
556        let builder = b().middleware(NoopMiddleware).context_window(8_000);
557        assert_eq!(builder.middlewares.len(), 1);
558        assert!(builder.context_manager.is_some());
559    }
560
561    #[test]
562    fn response_format_and_retry_set_config() {
563        let builder = b()
564            .response_format(ResponseFormat::JsonObject)
565            .llm_retry(RetryConfig::default().max_retries(5));
566        assert!(builder.config.llm.response_format.is_some());
567        assert_eq!(
568            builder.config.llm.llm_retry.as_ref().unwrap().max_retries,
569            5
570        );
571    }
572
573    #[test]
574    fn session_store_and_error_recovery_are_set() {
575        let builder = b()
576            .session_store(Arc::new(InMemorySessionStore::new()))
577            .error_recovery(Arc::new(StopOnError));
578        assert!(builder.session_store.is_some());
579        assert!(builder.error_recovery.is_some());
580    }
581
582    #[test]
583    fn session_limits_set_config() {
584        let builder = b()
585            .max_sessions(10)
586            .max_turns_per_session(20)
587            .max_message_tokens(30);
588        assert_eq!(builder.config.session.max_sessions, Some(10));
589        assert_eq!(builder.config.session.max_turns_per_session, Some(20));
590        assert_eq!(builder.config.session.max_message_tokens, Some(30));
591    }
592
593    #[test]
594    fn tool_error_retry_prompt_and_language_set_config() {
595        let builder = b()
596            .tool_error_retry_prompt("try again")
597            .language(Language::Zh);
598        assert_eq!(
599            builder.config.tool.tool_error_retry_prompt.as_deref(),
600            Some("try again")
601        );
602        assert_eq!(builder.config.language, Language::Zh);
603    }
604
605    #[test]
606    fn apply_if_applies_when_some_and_skips_when_none() {
607        let applied = b().apply_if(Some(3_000_u64), |b, t| b.tool_timeout(t));
608        assert_eq!(applied.config.tool.tool_timeout_ms, Some(3_000));
609
610        let skipped = b().apply_if(None, |b, t| b.tool_timeout(t));
611        assert_eq!(skipped.config.tool.tool_timeout_ms, None);
612    }
613
614    #[test]
615    fn build_ok_with_defaults() {
616        assert!(b().build().is_ok());
617    }
618
619    /// Value: protects=the one hand-off that makes opening a tool worth a turn —
620    /// the set `activate_tool` writes to must be the set the engine reads from,
621    /// or every open lands somewhere nobody looks and the roster silently does
622    /// nothing. fails_when=the builder keeps its own set instead of the one it
623    /// was handed. why_new=the field is new. seam=AgentBuilder -> RuntimeCore;
624    /// no_claim=that the turn loop reads it — that is one line, and covered
625    /// only by inspection.
626    #[test]
627    fn the_builder_hands_the_engine_the_activation_set_it_was_given() {
628        let activation = ToolActivation::new();
629        let runtime = b()
630            .with_tool_activation(activation.clone())
631            .build()
632            .expect("builds");
633        activation.activate("browser_navigate");
634        assert!(
635            runtime
636                .runner
637                .activation
638                .snapshot()
639                .contains(&"browser_navigate".to_string()),
640            "the engine must read the set the product's ActivateTool writes to"
641        );
642    }
643
644    /// Value: protects=the product's one lever over a tool the framework
645    /// registered — deferring must work by name at the builder, or a product
646    /// that cannot rebuild the framework's tools has no way to put the roster
647    /// to work; fails_when=the name is ignored or the tool is dropped instead
648    /// of re-wrapped. why_new=the method is new. seam=AgentBuilder -> registry;
649    /// no_claim=that these are the tools a given product should defer.
650    #[tokio::test]
651    async fn a_registered_tool_can_be_deferred_by_name() {
652        use crate::tool::Tool;
653
654        struct Probe;
655        #[async_trait]
656        impl Tool for Probe {
657            fn name(&self) -> &'static str {
658                "browser_navigate"
659            }
660            fn description(&self) -> &'static str {
661                "probe"
662            }
663            fn schema(&self) -> Value {
664                serde_json::json!({"type": "object"})
665            }
666            async fn call(
667                &self,
668                _args: &Value,
669                _ctx: &ToolContext,
670            ) -> crate::types::AgentResult<Vec<Content>> {
671                Ok(vec![])
672            }
673        }
674
675        let mut builder = b().register_tool(Probe);
676        let definition = builder
677            .defer_tool("browser_navigate")
678            .expect("a registered name is deferred and hands back its definition");
679        assert_eq!(
680            definition["function"]["name"], "browser_navigate",
681            "the definition is the tool's own — this is what ActivateTool serves"
682        );
683        assert!(
684            builder.defer_tool("no_such_tool").is_none(),
685            "and an unknown name is reported, not silently ignored"
686        );
687        assert!(
688            builder.defer_tool("browser_navigate").is_some(),
689            "twice is a no-op, but still returns what the roster needs"
690        );
691
692        let runtime = builder.build().expect("builds");
693        let ctx = crate::tool::ActivationContext {
694            session_id: crate::types::SessionId::new(0),
695            current_tools: vec![],
696            workspace: std::path::PathBuf::from("/tmp"),
697        };
698        let names: Vec<String> = runtime
699            .runner
700            .tool_engine
701            .definitions_filtered(&ctx)
702            .await
703            .iter()
704            .map(|d| d["function"]["name"].as_str().unwrap().to_string())
705            .collect();
706        assert!(
707            !names.contains(&"browser_navigate".to_string()),
708            "unopened, it costs the request nothing"
709        );
710
711        let mut opened = ctx.clone();
712        opened.current_tools = vec!["browser_navigate".to_string()];
713        let when_open: Vec<String> = runtime
714            .runner
715            .tool_engine
716            .definitions_filtered(&opened)
717            .await
718            .iter()
719            .map(|d| d["function"]["name"].as_str().unwrap().to_string())
720            .collect();
721        assert!(
722            when_open.contains(&"browser_navigate".to_string()),
723            "and once opened it is on the request like any other"
724        );
725    }
726
727    #[test]
728    fn build_err_on_invalid_config() {
729        assert!(matches!(
730            b().execution_max_turns(0).build(),
731            Err(AgentError::ConfigError(_))
732        ));
733    }
734}