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