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}
43
44impl AgentBuilder {
45    /// Create a new builder with an `LlmProvider`.
46    pub fn new(provider: Arc<dyn llm_trait::LlmProvider>) -> Self {
47        Self {
48            provider,
49            config: AgentConfig::default(),
50            tools: ToolRegistry::default(),
51            approval_handler: None,
52            tool_policy: None,
53            middlewares: Vec::new(),
54            context_manager: None,
55            session_store: None,
56            error_recovery: None,
57            event_bus_capacity: 2048,
58            session_id_generator: None,
59            convert_to_llm: None,
60            guard: None,
61            context_compactor: None,
62            action_backend: None,
63            interact: None,
64            interact_timeout: None,
65        }
66    }
67
68    pub fn event_bus_capacity(mut self, capacity: usize) -> Self {
69        self.event_bus_capacity = capacity;
70        self
71    }
72
73    pub fn session_id_generator(mut self, generator: Arc<dyn SessionIdGenerator>) -> Self {
74        self.session_id_generator = Some(generator);
75        self
76    }
77
78    /// Set a callback to transform messages before they are sent to the LLM.
79    ///
80    /// The default behavior (when `None`) is to filter out
81    /// `ChatMessage::Custom` variants, which most providers don't understand.
82    /// Override this to inject custom serialization logic for application-specific
83    /// message types.
84    pub fn convert_to_llm(mut self, cb: ConvertToLlmFn) -> Self {
85        self.convert_to_llm = Some(cb);
86        self
87    }
88
89    pub fn guard(mut self, guard: impl ReactLoopGuard + 'static) -> Self {
90        self.guard = Some(Arc::new(guard));
91        self
92    }
93
94    /// Set a guard from a pre-built `Arc<dyn ReactLoopGuard>`.
95    ///
96    /// Use this when you need to share the guard reference (e.g. for inspecting
97    /// recorded calls in tests).
98    pub fn guard_dyn(mut self, guard: Arc<dyn ReactLoopGuard>) -> Self {
99        self.guard = Some(guard);
100        self
101    }
102
103    /// Set an inline context compactor for the react loop.
104    ///
105    /// When set, the react loop will check token count after each tool turn
106    /// and compact the session if it exceeds the configured threshold.
107    pub fn context_compactor(mut self, compactor: Arc<dyn ContextCompaction>) -> Self {
108        self.context_compactor = Some(compactor);
109        self
110    }
111
112    /// Mount this runtime's action backend (T10c): text turns route to it,
113    /// tool-envelope turns keep the built-in tool-call backend. One backend
114    /// per runtime โ€” build one runtime per session when the backend holds a
115    /// resident engine (the product's assembly-time choice, sdk-assembly
116    /// ยง3.4).
117    pub fn action_backend(mut self, backend: Box<dyn ActionBackend>) -> Self {
118        self.action_backend = Some(backend);
119        self
120    }
121
122    /// The product's interaction surface for the action backend's `ExecCtx`
123    /// (OV-6): consent and ask_user suspend through it. Without one, every
124    /// interaction fails closed (`FailClosedInteract`) โ€” a cell reaching for
125    /// the human refuses, it never hangs or silently allows.
126    pub fn interaction(mut self, channel: Arc<dyn InteractionChannel>) -> Self {
127        self.interact = Some(channel);
128        self
129    }
130
131    /// Per-interaction deadline for the action backend's suspensions (`None`
132    /// = unbounded human time, the run's cancel token is the only guard โ€”
133    /// phimint's TUI shape). Unset = [`DEFAULT_INTERACT_TIMEOUT`].
134    pub fn interaction_timeout(mut self, interact_timeout: Option<Duration>) -> Self {
135        self.interact_timeout = Some(interact_timeout);
136        self
137    }
138
139    /// Check if a guard has been set.
140    ///
141    /// Used by agent-works to inject a default guard if none was set.
142    pub fn get_guard(&self) -> Option<&Arc<dyn ReactLoopGuard>> {
143        self.guard.as_ref()
144    }
145
146    pub fn system_prompt(mut self, system_prompt: impl Into<String>) -> Self {
147        self.config.system_prompt = Some(system_prompt.into());
148        self
149    }
150
151    /// Set whether to include the reasoning content in LLM responses.
152    ///
153    /// Controls whether the `reasoning_content` field from the LLM is forwarded
154    /// to consumers (i.e., "show the thinking process").
155    /// See [`AgentConfig::enable_thought`] for the distinction from `enable_thinking()`.
156    pub fn enable_thought(mut self, enable: bool) -> Self {
157        self.config.enable_thought = enable;
158        self
159    }
160
161    pub fn reasoning(mut self, config: ReasoningConfig) -> Self {
162        self.config.reasoning = Some(config);
163        self
164    }
165
166    /// Set whether to enable the model's extended thinking / reasoning mode.
167    ///
168    /// Controls whether the model performs deep reasoning (i.e., "enable thinking mode").
169    /// See [`AgentConfig::enable_thought`] for the distinction from `enable_thought()`.
170    pub fn enable_thinking(mut self, enable: bool) -> Self {
171        let mut config = self.config.reasoning.take().unwrap_or_default();
172        config.enabled = Some(enable);
173        self.config.reasoning = Some(config);
174        self
175    }
176
177    pub fn thinking_budget(mut self, budget: u64) -> Self {
178        let mut config = self.config.reasoning.take().unwrap_or_default();
179        config.budget_tokens = Some(budget);
180        self.config.reasoning = Some(config);
181        self
182    }
183
184    pub fn tool_timeout(mut self, timeout_ms: u64) -> Self {
185        self.config.tool.tool_timeout_ms = Some(timeout_ms);
186        self
187    }
188
189    pub fn max_tool_output_chars(mut self, max_chars: usize) -> Self {
190        self.config.tool.max_tool_output_chars = Some(max_chars);
191        self
192    }
193
194    pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
195        self.tools.register(tool);
196        self
197    }
198
199    pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
200        self.tools.register_arc(tool);
201        self
202    }
203
204    pub fn approval_handler(mut self, handler: Arc<dyn ApprovalHandler>) -> Self {
205        self.approval_handler = Some(handler);
206        self
207    }
208
209    pub fn tool_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
210        self.tool_policy = Some(policy);
211        self
212    }
213
214    pub fn middleware(mut self, mw: impl Middleware + 'static) -> Self {
215        self.middlewares.push(Arc::new(mw));
216        self
217    }
218
219    pub fn context_window(mut self, max_tokens: usize) -> Self {
220        self.context_manager = Some(ContextWindowManager::new(max_tokens));
221        self
222    }
223
224    pub fn context_window_manager(mut self, manager: ContextWindowManager) -> Self {
225        self.context_manager = Some(manager);
226        self
227    }
228
229    pub fn response_format(mut self, format: ResponseFormat) -> Self {
230        self.config.llm.response_format = Some(format);
231        self
232    }
233
234    pub fn llm_retry(mut self, retry: RetryConfig) -> Self {
235        self.config.llm.llm_retry = Some(retry);
236        self
237    }
238
239    pub fn session_store(mut self, store: Arc<dyn SessionStore>) -> Self {
240        self.session_store = Some(store);
241        self
242    }
243
244    pub fn error_recovery(mut self, recovery: Arc<dyn ToolErrorRecovery>) -> Self {
245        self.error_recovery = Some(recovery);
246        self
247    }
248
249    pub fn max_sessions(mut self, max: usize) -> Self {
250        self.config.session.max_sessions = Some(max);
251        self
252    }
253
254    pub fn max_turns_per_session(mut self, max: usize) -> Self {
255        self.config.session.max_turns_per_session = Some(max);
256        self
257    }
258
259    /// Cap the number of react-loop iterations allowed for a *single* run (one user
260    /// input). Distinct from [`Self::max_turns_per_session`], which caps turns across
261    /// the whole session. When unset, falls back to `DEFAULT_MAX_TURNS` (50).
262    pub fn execution_max_turns(mut self, max: u32) -> Self {
263        self.config.execution.max_turns = Some(max);
264        self
265    }
266
267    pub fn max_message_tokens(mut self, max: usize) -> Self {
268        self.config.session.max_message_tokens = Some(max);
269        self
270    }
271
272    pub fn tool_error_retry_prompt(mut self, prompt: impl Into<String>) -> Self {
273        self.config.tool.tool_error_retry_prompt = Some(prompt.into());
274        self
275    }
276
277    pub fn language(mut self, language: crate::types::Language) -> Self {
278        self.config.language = language;
279        self
280    }
281
282    /// Conditionally chain a builder call: apply `f` only when `value` is `Some`.
283    ///
284    /// # Example
285    /// ```ignore
286    /// let builder = AgentBuilder::new(client)
287    ///     .apply_if(config.timeout, |b, t| b.tool_timeout(t))
288    ///     .apply_if(config.max_chars, |b, c| b.max_tool_output_chars(c));
289    /// ```
290    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
291        match value {
292            Some(v) => f(self, v),
293            None => self,
294        }
295    }
296
297    pub fn build(self) -> crate::types::AgentResult<AgentRuntime> {
298        self.config.validate()?;
299
300        tracing::info!(
301            tool_count = self.tools.len(),
302            middleware_count = self.middlewares.len(),
303            has_approval = self.approval_handler.is_some(),
304            has_context_window = self.context_manager.is_some(),
305            "building agent runtime"
306        );
307
308        let event_bus = super::runtime::EventBus::new(self.event_bus_capacity);
309
310        let session_store = self
311            .session_store
312            .unwrap_or_else(|| Arc::new(InMemorySessionStore::new()));
313        let error_recovery = self.error_recovery.unwrap_or_else(|| Arc::new(StopOnError));
314        // Default numbering is process-global: a host and its sub-agents are
315        // several engines in one process, and per-engine counters handed every
316        // one of them a "session 1".
317        let session_id_generator = self.session_id_generator.unwrap_or_else(shared_session_ids);
318
319        let session_manager = super::runtime::SessionManager::new(
320            session_id_generator,
321            session_store,
322            self.config.session.clone(),
323        );
324
325        let llm_engine = super::runtime::LlmEngine::new(self.provider.clone(), event_bus.clone());
326
327        let tool_engine = super::runtime::ToolEngine::new(
328            self.tools,
329            self.approval_handler,
330            self.tool_policy,
331            error_recovery,
332            event_bus.clone(),
333        );
334
335        // Interaction defaults: fail-closed when the product mounts no
336        // channel; the standard watchdog when it sets no deadline.
337        let interact = self
338            .interact
339            .unwrap_or_else(|| Arc::new(FailClosedInteract));
340        let interact_timeout = self
341            .interact_timeout
342            .unwrap_or(Some(DEFAULT_INTERACT_TIMEOUT));
343
344        let runner = Arc::new(super::runtime::RuntimeCore::new(
345            self.config,
346            llm_engine,
347            tool_engine,
348            session_manager,
349            event_bus,
350            self.context_manager,
351            self.middlewares,
352            self.convert_to_llm,
353            self.guard,
354            self.context_compactor,
355            self.action_backend,
356            interact,
357            interact_timeout,
358        ));
359
360        Ok(AgentRuntime { runner })
361    }
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367    use crate::engine::DenyAllApprovalHandler;
368    use crate::llm::ReasoningEffort;
369    use crate::tool::{Content, ToolContext};
370    use crate::types::{AgentError, AgentResult, ApprovalRequest, Language, ResponseFormat};
371    use async_trait::async_trait;
372    use llm_trait::{Capabilities, ChatRequest, ChatResponse, ChatStream, LlmError, ProviderInfo};
373    use serde_json::Value;
374
375    struct DummyProvider;
376
377    #[async_trait]
378    impl llm_trait::LlmProvider for DummyProvider {
379        async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
380            Ok(ChatStream::new(Box::pin(futures_util::stream::empty())))
381        }
382
383        async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
384            Ok(ChatResponse {
385                content: String::new(),
386                reasoning_content: None,
387                tool_calls: vec![],
388                usage: Default::default(),
389                finish_reason: llm_trait::FinishReason::Stop,
390                raw: None,
391                thinking_signature: None,
392            })
393        }
394
395        fn capabilities(&self) -> Capabilities {
396            Capabilities::default()
397        }
398
399        fn info(&self) -> ProviderInfo {
400            ProviderInfo {
401                name: "dummy".to_string(),
402                model: "dummy".to_string(),
403                version: None,
404            }
405        }
406    }
407
408    #[test]
409    fn execution_max_turns_writes_per_run_config() {
410        let builder = AgentBuilder::new(Arc::new(DummyProvider)).execution_max_turns(200);
411        assert_eq!(builder.config.execution.max_turns, Some(200));
412    }
413
414    #[test]
415    fn execution_max_turns_defaults_to_none() {
416        let builder = AgentBuilder::new(Arc::new(DummyProvider));
417        assert_eq!(builder.config.execution.max_turns, None);
418    }
419
420    fn b() -> AgentBuilder {
421        AgentBuilder::new(Arc::new(DummyProvider))
422    }
423
424    struct NoopTool;
425
426    #[async_trait]
427    impl Tool for NoopTool {
428        fn name(&self) -> &'static str {
429            "noop"
430        }
431        fn description(&self) -> &'static str {
432            "noop tool"
433        }
434        fn schema(&self) -> Value {
435            serde_json::json!({"type": "object"})
436        }
437        async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
438            Ok(vec![Content::text("ok")])
439        }
440    }
441
442    struct AutoApprovePolicy;
443
444    #[async_trait]
445    impl ToolPolicy for AutoApprovePolicy {
446        async fn evaluate_approval(
447            &self,
448            _tool_name: &str,
449            _args: &Value,
450        ) -> Option<ApprovalRequest> {
451            None
452        }
453    }
454
455    struct NoopMiddleware;
456
457    impl Middleware for NoopMiddleware {}
458
459    #[test]
460    fn system_prompt_sets_config() {
461        assert_eq!(
462            b().system_prompt("be helpful")
463                .config
464                .system_prompt
465                .as_deref(),
466            Some("be helpful")
467        );
468    }
469
470    #[test]
471    fn enable_thought_sets_config() {
472        assert!(b().enable_thought(true).config.enable_thought);
473    }
474
475    #[test]
476    fn reasoning_sets_config() {
477        let rc = ReasoningConfig {
478            enabled: Some(true),
479            budget_tokens: Some(64),
480            effort: Some(ReasoningEffort::Medium),
481        };
482        let builder = b().reasoning(rc);
483        let got = builder.config.reasoning.as_ref().unwrap();
484        assert_eq!(got.enabled, Some(true));
485        assert_eq!(got.budget_tokens, Some(64));
486        assert!(matches!(got.effort.as_ref(), Some(ReasoningEffort::Medium)));
487    }
488
489    #[test]
490    fn enable_thinking_and_budget_set_reasoning() {
491        let builder = b().enable_thinking(true).thinking_budget(128);
492        let got = builder.config.reasoning.as_ref().unwrap();
493        assert_eq!(got.enabled, Some(true));
494        assert_eq!(got.budget_tokens, Some(128));
495    }
496
497    #[test]
498    fn tool_limits_set_config() {
499        let builder = b().tool_timeout(5_000).max_tool_output_chars(1_024);
500        assert_eq!(builder.config.tool.tool_timeout_ms, Some(5_000));
501        assert_eq!(builder.config.tool.max_tool_output_chars, Some(1_024));
502    }
503
504    #[test]
505    fn register_tool_adds_to_registry() {
506        assert_eq!(b().register_tool(NoopTool).tools.len(), 1);
507    }
508
509    #[test]
510    fn approval_handler_and_tool_policy_are_set() {
511        let builder = b()
512            .approval_handler(Arc::new(DenyAllApprovalHandler))
513            .tool_policy(Arc::new(AutoApprovePolicy));
514        assert!(builder.approval_handler.is_some());
515        assert!(builder.tool_policy.is_some());
516    }
517
518    #[test]
519    fn middleware_and_context_window_are_set() {
520        let builder = b().middleware(NoopMiddleware).context_window(8_000);
521        assert_eq!(builder.middlewares.len(), 1);
522        assert!(builder.context_manager.is_some());
523    }
524
525    #[test]
526    fn response_format_and_retry_set_config() {
527        let builder = b()
528            .response_format(ResponseFormat::JsonObject)
529            .llm_retry(RetryConfig::default().max_retries(5));
530        assert!(builder.config.llm.response_format.is_some());
531        assert_eq!(
532            builder.config.llm.llm_retry.as_ref().unwrap().max_retries,
533            5
534        );
535    }
536
537    #[test]
538    fn session_store_and_error_recovery_are_set() {
539        let builder = b()
540            .session_store(Arc::new(InMemorySessionStore::new()))
541            .error_recovery(Arc::new(StopOnError));
542        assert!(builder.session_store.is_some());
543        assert!(builder.error_recovery.is_some());
544    }
545
546    #[test]
547    fn session_limits_set_config() {
548        let builder = b()
549            .max_sessions(10)
550            .max_turns_per_session(20)
551            .max_message_tokens(30);
552        assert_eq!(builder.config.session.max_sessions, Some(10));
553        assert_eq!(builder.config.session.max_turns_per_session, Some(20));
554        assert_eq!(builder.config.session.max_message_tokens, Some(30));
555    }
556
557    #[test]
558    fn tool_error_retry_prompt_and_language_set_config() {
559        let builder = b()
560            .tool_error_retry_prompt("try again")
561            .language(Language::Zh);
562        assert_eq!(
563            builder.config.tool.tool_error_retry_prompt.as_deref(),
564            Some("try again")
565        );
566        assert_eq!(builder.config.language, Language::Zh);
567    }
568
569    #[test]
570    fn apply_if_applies_when_some_and_skips_when_none() {
571        let applied = b().apply_if(Some(3_000_u64), |b, t| b.tool_timeout(t));
572        assert_eq!(applied.config.tool.tool_timeout_ms, Some(3_000));
573
574        let skipped = b().apply_if(None, |b, t| b.tool_timeout(t));
575        assert_eq!(skipped.config.tool.tool_timeout_ms, None);
576    }
577
578    #[test]
579    fn build_ok_with_defaults() {
580        assert!(b().build().is_ok());
581    }
582
583    #[test]
584    fn build_err_on_invalid_config() {
585        assert!(matches!(
586            b().execution_max_turns(0).build(),
587            Err(AgentError::ConfigError(_))
588        ));
589    }
590}