1use std::sync::Arc;
2
3use crate::llm::{ReasoningConfig, StreamClient};
4use crate::tool::{Tool, ToolPolicy, ToolRegistry};
5use crate::types::{
6 AgentConfig, AtomicU64SessionIdGenerator, ConvertToLlmFn, ResponseFormat, RetryConfig,
7 SessionIdGenerator,
8};
9
10use super::AgentRuntime;
11use super::approval::ApprovalHandler;
12use super::context::ContextWindowManager;
13use super::middleware::{Middleware, MiddlewareRef};
14use super::recovery::{StopOnError, ToolErrorRecovery};
15use super::session_store::{InMemorySessionStore, SessionStore};
16
17pub struct AgentBuilder {
18 client: Arc<dyn StreamClient>,
19 config: AgentConfig,
20 tools: ToolRegistry,
21 approval_handler: Option<Arc<dyn ApprovalHandler>>,
22 tool_policy: Option<Arc<dyn ToolPolicy>>,
23 middlewares: Vec<MiddlewareRef>,
24 context_manager: Option<ContextWindowManager>,
25 session_store: Option<Arc<dyn SessionStore>>,
26 error_recovery: Option<Arc<dyn ToolErrorRecovery>>,
27 event_bus_capacity: usize,
28 session_id_generator: Option<Arc<dyn SessionIdGenerator>>,
29 convert_to_llm: Option<ConvertToLlmFn>,
30}
31
32impl AgentBuilder {
33 pub fn new(client: Arc<dyn StreamClient>) -> Self {
34 Self {
35 client,
36 config: AgentConfig::default(),
37 tools: ToolRegistry::default(),
38 approval_handler: None,
39 tool_policy: None,
40 middlewares: Vec::new(),
41 context_manager: None,
42 session_store: None,
43 error_recovery: None,
44 event_bus_capacity: 2048,
45 session_id_generator: None,
46 convert_to_llm: None,
47 }
48 }
49
50 pub fn event_bus_capacity(mut self, capacity: usize) -> Self {
51 self.event_bus_capacity = capacity;
52 self
53 }
54
55 pub fn session_id_generator(mut self, generator: Arc<dyn SessionIdGenerator>) -> Self {
56 self.session_id_generator = Some(generator);
57 self
58 }
59
60 pub fn convert_to_llm(mut self, cb: ConvertToLlmFn) -> Self {
67 self.convert_to_llm = Some(cb);
68 self
69 }
70
71 pub fn system_prompt(mut self, system_prompt: impl Into<String>) -> Self {
72 self.config.system_prompt = Some(system_prompt.into());
73 self
74 }
75
76 pub fn enable_thought(mut self, enable: bool) -> Self {
82 self.config.enable_thought = enable;
83 self
84 }
85
86 pub fn reasoning(mut self, config: ReasoningConfig) -> Self {
87 self.config.reasoning = Some(config);
88 self
89 }
90
91 pub fn enable_thinking(mut self, enable: bool) -> Self {
96 let mut config = self.config.reasoning.take().unwrap_or_default();
97 config.enabled = Some(enable);
98 self.config.reasoning = Some(config);
99 self
100 }
101
102 pub fn thinking_budget(mut self, budget: u64) -> Self {
103 let mut config = self.config.reasoning.take().unwrap_or_default();
104 config.budget_tokens = Some(budget);
105 self.config.reasoning = Some(config);
106 self
107 }
108
109 pub fn tool_timeout(mut self, timeout_ms: u64) -> Self {
110 self.config.tool.tool_timeout_ms = Some(timeout_ms);
111 self
112 }
113
114 pub fn max_tool_output_chars(mut self, max_chars: usize) -> Self {
115 self.config.tool.max_tool_output_chars = Some(max_chars);
116 self
117 }
118
119 pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
120 self.tools.register(tool);
121 self
122 }
123
124 pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
125 self.tools.register_arc(tool);
126 self
127 }
128
129 pub fn approval_handler(mut self, handler: Arc<dyn ApprovalHandler>) -> Self {
130 self.approval_handler = Some(handler);
131 self
132 }
133
134 pub fn tool_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
135 self.tool_policy = Some(policy);
136 self
137 }
138
139 pub fn middleware(mut self, mw: impl Middleware + 'static) -> Self {
140 self.middlewares.push(Arc::new(mw));
141 self
142 }
143
144 pub fn context_window(mut self, max_tokens: usize) -> Self {
145 self.context_manager = Some(ContextWindowManager::new(max_tokens));
146 self
147 }
148
149 pub fn context_window_manager(mut self, manager: ContextWindowManager) -> Self {
150 self.context_manager = Some(manager);
151 self
152 }
153
154 pub fn response_format(mut self, format: ResponseFormat) -> Self {
155 self.config.llm.response_format = Some(format);
156 self
157 }
158
159 pub fn llm_retry(mut self, retry: RetryConfig) -> Self {
160 self.config.llm.llm_retry = Some(retry);
161 self
162 }
163
164 pub fn session_store(mut self, store: Arc<dyn SessionStore>) -> Self {
165 self.session_store = Some(store);
166 self
167 }
168
169 pub fn error_recovery(mut self, recovery: Arc<dyn ToolErrorRecovery>) -> Self {
170 self.error_recovery = Some(recovery);
171 self
172 }
173
174 pub fn max_sessions(mut self, max: usize) -> Self {
175 self.config.session.max_sessions = Some(max);
176 self
177 }
178
179 pub fn max_turns_per_session(mut self, max: usize) -> Self {
180 self.config.session.max_turns_per_session = Some(max);
181 self
182 }
183
184 pub fn execution_max_turns(mut self, max: u32) -> Self {
188 self.config.execution.max_turns = Some(max);
189 self
190 }
191
192 pub fn max_message_tokens(mut self, max: usize) -> Self {
193 self.config.session.max_message_tokens = Some(max);
194 self
195 }
196
197 pub fn tool_error_retry_prompt(mut self, prompt: impl Into<String>) -> Self {
198 self.config.tool.tool_error_retry_prompt = Some(prompt.into());
199 self
200 }
201
202 pub fn language(mut self, language: crate::types::Language) -> Self {
203 self.config.language = language;
204 self
205 }
206
207 pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
216 match value {
217 Some(v) => f(self, v),
218 None => self,
219 }
220 }
221
222 pub fn build(self) -> crate::types::AgentResult<AgentRuntime> {
223 self.config.validate()?;
224
225 tracing::info!(
226 tool_count = self.tools.len(),
227 middleware_count = self.middlewares.len(),
228 has_approval = self.approval_handler.is_some(),
229 has_context_window = self.context_manager.is_some(),
230 "building agent runtime"
231 );
232
233 let event_bus = super::runtime::EventBus::new(self.event_bus_capacity);
234
235 self.tools.inject_event_bus(&event_bus);
238
239 let session_store = self
240 .session_store
241 .unwrap_or_else(|| Arc::new(InMemorySessionStore::new()));
242 let error_recovery = self.error_recovery.unwrap_or_else(|| Arc::new(StopOnError));
243 let session_id_generator = self
244 .session_id_generator
245 .unwrap_or_else(|| Arc::new(AtomicU64SessionIdGenerator::default()));
246
247 let session_manager = super::runtime::SessionManager::new(
248 session_id_generator,
249 session_store,
250 self.config.session.clone(),
251 );
252
253 let llm_engine = super::runtime::LlmEngine::new(self.client.clone(), event_bus.clone());
254
255 let tool_engine = super::runtime::ToolEngine::new(
256 self.tools,
257 self.approval_handler,
258 self.tool_policy,
259 error_recovery,
260 event_bus.clone(),
261 );
262
263 let runner = Arc::new(super::runtime::RuntimeCore::new(
264 self.config,
265 llm_engine,
266 tool_engine,
267 session_manager,
268 event_bus,
269 self.context_manager,
270 self.middlewares,
271 self.convert_to_llm,
272 ));
273
274 Ok(AgentRuntime { runner })
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use crate::llm::LlmClient;
282 use crate::llm::StreamChunk;
283 use crate::types::{AgentResult, ChatMessage, ResponseFormat};
284 use async_trait::async_trait;
285 use futures_core::Stream;
286 use serde_json::Value;
287 use std::pin::Pin;
288
289 struct DummyClient;
290
291 #[async_trait]
292 impl LlmClient for DummyClient {
293 async fn chat(
294 &self,
295 _messages: &[ChatMessage],
296 _tools: &[Value],
297 _reasoning: Option<&ReasoningConfig>,
298 _response_format: Option<&ResponseFormat>,
299 ) -> AgentResult<Value> {
300 Ok(Value::Null)
301 }
302
303 async fn chat_stream(
304 &self,
305 _messages: &[ChatMessage],
306 _tools: &[Value],
307 _reasoning: Option<&ReasoningConfig>,
308 _response_format: Option<&ResponseFormat>,
309 ) -> AgentResult<Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>> {
310 unimplemented!("not used in builder tests")
311 }
312
313 fn capabilities(&self) -> crate::llm::LlmCapabilities {
314 crate::llm::LlmCapabilities::default()
315 }
316 }
317
318 #[test]
319 fn execution_max_turns_writes_per_run_config() {
320 let client = crate::llm::adapt(Arc::new(DummyClient));
321 let builder = AgentBuilder::new(client).execution_max_turns(200);
322 assert_eq!(builder.config.execution.max_turns, Some(200));
324 }
325
326 #[test]
327 fn execution_max_turns_defaults_to_none() {
328 let client = crate::llm::adapt(Arc::new(DummyClient));
329 let builder = AgentBuilder::new(client);
330 assert_eq!(builder.config.execution.max_turns, None);
331 }
332}