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