Skip to main content

mojentic/agents/
simple_recursive_agent.rs

1//! Simple recursive agent using event-driven architecture.
2//!
3//! This module provides a declarative, event-driven agent that recursively attempts
4//! to solve problems using available tools. The agent continues iterating until it
5//! succeeds, fails explicitly, or reaches the maximum number of iterations.
6//!
7//! # Architecture
8//!
9//! The agent uses three main components:
10//!
11//! 1. **GoalState** - Tracks the problem-solving state through iterations
12//! 2. **EventEmitter** - Manages event subscriptions and async dispatch
13//! 3. **SimpleRecursiveAgent** - Orchestrates the problem-solving process
14//!
15//! # Events
16//!
17//! The agent emits the following events during problem-solving:
18//!
19//! - `GoalSubmittedEvent` - When a problem is submitted
20//! - `IterationCompletedEvent` - After each iteration completes
21//! - `GoalAchievedEvent` - When the goal is successfully achieved
22//! - `GoalFailedEvent` - When the goal explicitly fails
23//! - `TimeoutEvent` - When the process times out
24//!
25//! # Examples
26//!
27//! ```ignore
28//! use mojentic::agents::SimpleRecursiveAgent;
29//! use mojentic::llm::{LlmBroker, LlmGateway};
30//! use mojentic::llm::gateways::OllamaGateway;
31//! use mojentic::llm::tools::simple_date_tool::SimpleDateTool;
32//! use std::sync::Arc;
33//!
34//! #[tokio::main]
35//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
36//!     let gateway = Arc::new(OllamaGateway::default());
37//!     let broker = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
38//!
39//!     let tools: Vec<Box<dyn LlmTool>> = vec![Box::new(SimpleDateTool)];
40//!
41//!     let agent = SimpleRecursiveAgent::builder(broker)
42//!         .tools(tools)
43//!         .max_iterations(5)
44//!         .build();
45//!
46//!     // Subscribe to events
47//!     agent.emitter.subscribe(|event: IterationCompletedEvent| {
48//!         println!("Iteration {}: {}", event.state.iteration, event.response);
49//!     });
50//!
51//!     let result = agent.solve("What's the date next Friday?").await?;
52//!     println!("Result: {}", result);
53//!
54//!     Ok(())
55//! }
56//! ```
57//!
58//! # Completion Indicators
59//!
60//! The agent monitors responses for exact matches (trimmed, case-insensitive):
61//! the response must be exactly `DONE` or `FAIL` (trimmed, case-insensitive)
62//! - "DONE" - Task completed successfully
63//! - "FAIL" - Task cannot be completed
64
65use crate::error::{MojenticError, Result};
66use crate::llm::chat_session::ChatSession;
67use crate::llm::tools::LlmTool;
68use crate::llm::LlmBroker;
69use std::future::Future;
70use std::pin::Pin;
71use std::sync::Arc;
72use tokio::sync::{mpsc, Mutex};
73use tokio::time::{timeout, Duration};
74use tracing::warn;
75
76/// Represents the state of a problem-solving process.
77#[derive(Debug, Clone)]
78pub struct GoalState {
79    /// The problem or goal to solve
80    pub goal: String,
81    /// Current iteration count
82    pub iteration: usize,
83    /// Maximum allowed iterations
84    pub max_iterations: usize,
85    /// The solution, if found
86    pub solution: Option<String>,
87    /// Whether the problem-solving process is complete
88    pub is_complete: bool,
89}
90
91impl GoalState {
92    /// Create a new goal state
93    pub fn new(goal: impl Into<String>, max_iterations: usize) -> Self {
94        Self {
95            goal: goal.into(),
96            iteration: 0,
97            max_iterations,
98            solution: None,
99            is_complete: false,
100        }
101    }
102}
103
104/// Base trait for solver events.
105pub trait SolverEvent: Send + Sync + std::fmt::Debug {
106    /// Get the current state
107    fn state(&self) -> &GoalState;
108}
109
110/// Event triggered when a goal is submitted for solving.
111#[derive(Debug, Clone)]
112pub struct GoalSubmittedEvent {
113    pub state: GoalState,
114}
115
116impl SolverEvent for GoalSubmittedEvent {
117    fn state(&self) -> &GoalState {
118        &self.state
119    }
120}
121
122/// Event triggered when an iteration of the problem-solving process is completed.
123#[derive(Debug, Clone)]
124pub struct IterationCompletedEvent {
125    pub state: GoalState,
126    /// The response from the LLM for this iteration
127    pub response: String,
128}
129
130impl SolverEvent for IterationCompletedEvent {
131    fn state(&self) -> &GoalState {
132        &self.state
133    }
134}
135
136/// Event triggered when a goal is successfully achieved.
137#[derive(Debug, Clone)]
138pub struct GoalAchievedEvent {
139    pub state: GoalState,
140}
141
142impl SolverEvent for GoalAchievedEvent {
143    fn state(&self) -> &GoalState {
144        &self.state
145    }
146}
147
148/// Event triggered when a goal cannot be solved.
149#[derive(Debug, Clone)]
150pub struct GoalFailedEvent {
151    pub state: GoalState,
152}
153
154impl SolverEvent for GoalFailedEvent {
155    fn state(&self) -> &GoalState {
156        &self.state
157    }
158}
159
160/// Event triggered when the problem-solving process times out.
161#[derive(Debug, Clone)]
162pub struct TimeoutEvent {
163    pub state: GoalState,
164}
165
166impl SolverEvent for TimeoutEvent {
167    fn state(&self) -> &GoalState {
168        &self.state
169    }
170}
171
172/// Union type of all solver events
173#[derive(Debug, Clone)]
174pub enum AnySolverEvent {
175    GoalSubmitted(GoalSubmittedEvent),
176    IterationCompleted(IterationCompletedEvent),
177    GoalAchieved(GoalAchievedEvent),
178    GoalFailed(GoalFailedEvent),
179    Timeout(TimeoutEvent),
180}
181
182impl AnySolverEvent {
183    /// Get the state from any event variant
184    pub fn state(&self) -> &GoalState {
185        match self {
186            AnySolverEvent::GoalSubmitted(e) => &e.state,
187            AnySolverEvent::IterationCompleted(e) => &e.state,
188            AnySolverEvent::GoalAchieved(e) => &e.state,
189            AnySolverEvent::GoalFailed(e) => &e.state,
190            AnySolverEvent::Timeout(e) => &e.state,
191        }
192    }
193}
194
195/// Event handler callback type
196type EventCallback = Arc<dyn Fn(AnySolverEvent) + Send + Sync>;
197
198/// A simple event emitter that allows subscribing to and emitting events.
199///
200/// This implementation uses async channels to dispatch events to subscribers
201/// asynchronously without blocking the emitter. Handler panics or errors are
202/// routed back to any registered error sink so that callers can observe them.
203pub struct EventEmitter {
204    subscribers: Arc<Mutex<Vec<EventCallback>>>,
205    /// Optional channel to forward handler errors (e.g. panics) to the solve future.
206    error_tx: Arc<Mutex<Option<mpsc::Sender<MojenticError>>>>,
207}
208
209impl EventEmitter {
210    /// Create a new event emitter
211    pub fn new() -> Self {
212        Self {
213            subscribers: Arc::new(Mutex::new(Vec::new())),
214            error_tx: Arc::new(Mutex::new(None)),
215        }
216    }
217
218    /// Register a channel to receive handler errors.
219    ///
220    /// When a subscriber callback panics, the panic message is forwarded as a
221    /// [`MojenticError::HandlerError`] on this sender.
222    pub async fn set_error_sink(&self, tx: mpsc::Sender<MojenticError>) {
223        let mut guard = self.error_tx.lock().await;
224        *guard = Some(tx);
225    }
226
227    /// Subscribe to events with a callback function.
228    ///
229    /// # Examples
230    ///
231    /// ```ignore
232    /// emitter.subscribe(|event: AnySolverEvent| {
233    ///     println!("Event received: {:?}", event);
234    /// });
235    /// ```
236    pub async fn subscribe<F>(&self, callback: F)
237    where
238        F: Fn(AnySolverEvent) + Send + Sync + 'static,
239    {
240        let mut subscribers = self.subscribers.lock().await;
241        subscribers.push(Arc::new(callback));
242    }
243
244    /// Emit an event to all subscribers asynchronously.
245    ///
246    /// Events are dispatched to subscribers without blocking the emitter.
247    /// If a subscriber panics, the panic is caught and forwarded as a
248    /// [`MojenticError::HandlerError`] to the registered error sink (if any).
249    pub async fn emit(&self, event: AnySolverEvent) {
250        let subscribers = self.subscribers.lock().await.clone();
251        let error_tx = self.error_tx.lock().await.clone();
252
253        for callback in subscribers {
254            let event = event.clone();
255            let callback = callback.clone();
256            let error_tx = error_tx.clone();
257
258            // Spawn a task to call the callback asynchronously and catch panics.
259            let handle = tokio::spawn(async move {
260                callback(event);
261            });
262
263            // If we have an error sink, watch for panics from the spawned task.
264            if let Some(tx) = error_tx.clone() {
265                tokio::spawn(async move {
266                    if let Err(join_err) = handle.await {
267                        if join_err.is_panic() {
268                            let msg = join_err
269                                .into_panic()
270                                .downcast::<&str>()
271                                .map(|s| s.to_string())
272                                .unwrap_or_else(|_| "handler panicked".to_string());
273                            let _ = tx.send(MojenticError::HandlerError(msg)).await;
274                        }
275                    }
276                });
277            }
278        }
279    }
280}
281
282impl Default for EventEmitter {
283    fn default() -> Self {
284        Self::new()
285    }
286}
287
288/// An agent that recursively attempts to solve a problem using available tools.
289///
290/// This agent uses an event-driven approach to manage the problem-solving process.
291/// It will continue attempting to solve the problem until it either succeeds,
292/// fails explicitly, or reaches the maximum number of iterations.
293pub struct SimpleRecursiveAgent {
294    broker: Arc<LlmBroker>,
295    tools: Vec<Box<dyn LlmTool>>,
296    max_iterations: usize,
297    system_prompt: String,
298    /// The event emitter used to manage events
299    pub emitter: Arc<EventEmitter>,
300}
301
302impl SimpleRecursiveAgent {
303    /// Create a new SimpleRecursiveAgent with default settings.
304    ///
305    /// # Arguments
306    ///
307    /// * `broker` - The LLM broker to use for generating responses
308    ///
309    /// # Examples
310    ///
311    /// ```ignore
312    /// use mojentic::agents::SimpleRecursiveAgent;
313    /// use mojentic::llm::LlmBroker;
314    /// use std::sync::Arc;
315    ///
316    /// let broker = Arc::new(LlmBroker::new("qwen3:32b", gateway, None));
317    /// let agent = SimpleRecursiveAgent::new(broker);
318    /// ```
319    pub fn new(broker: Arc<LlmBroker>) -> Self {
320        Self::builder(broker).build()
321    }
322
323    /// Create a SimpleRecursiveAgent builder for custom configuration.
324    ///
325    /// # Arguments
326    ///
327    /// * `broker` - The LLM broker to use for generating responses
328    ///
329    /// # Examples
330    ///
331    /// ```ignore
332    /// use mojentic::agents::SimpleRecursiveAgent;
333    ///
334    /// let agent = SimpleRecursiveAgent::builder(broker)
335    ///     .max_iterations(10)
336    ///     .system_prompt("You are a specialized assistant.")
337    ///     .tools(vec![Box::new(SimpleDateTool)])
338    ///     .build();
339    /// ```
340    pub fn builder(broker: Arc<LlmBroker>) -> SimpleRecursiveAgentBuilder {
341        SimpleRecursiveAgentBuilder::new(broker)
342    }
343
344    /// Solve a problem asynchronously.
345    ///
346    /// This method runs the event-driven problem-solving process with a 300-second timeout.
347    /// The agent will continue iterating until:
348    /// - The task is completed successfully ("DONE")
349    /// - The task fails explicitly ("FAIL")
350    /// - The maximum number of iterations is reached
351    /// - The process times out (300 seconds)
352    ///
353    /// # Arguments
354    ///
355    /// * `problem` - The problem or request to be solved
356    ///
357    /// # Returns
358    ///
359    /// The solution to the problem
360    ///
361    /// # Examples
362    ///
363    /// ```ignore
364    /// let solution = agent.solve("Calculate the factorial of 5").await?;
365    /// println!("Solution: {}", solution);
366    /// ```
367    pub async fn solve(&self, problem: impl Into<String>) -> Result<String> {
368        let problem = problem.into();
369
370        // Create a channel to receive the solution
371        let (solution_tx, mut solution_rx) = mpsc::channel::<String>(1);
372
373        // Create an error channel so handler panics surface to this future
374        let (error_tx, mut error_rx) = mpsc::channel::<MojenticError>(8);
375        self.emitter.set_error_sink(error_tx).await;
376
377        // Create the initial goal state
378        let state = GoalState::new(problem.clone(), self.max_iterations);
379
380        // Clone what we need for the async task
381        let solution_tx_clone = solution_tx.clone();
382
383        // Subscribe to completion events
384        let emitter = self.emitter.clone();
385        emitter
386            .subscribe(move |event: AnySolverEvent| match &event {
387                AnySolverEvent::GoalAchieved(_)
388                | AnySolverEvent::GoalFailed(_)
389                | AnySolverEvent::Timeout(_) => {
390                    if let Some(solution) = &event.state().solution {
391                        let _ = solution_tx_clone.try_send(solution.clone());
392                    }
393                }
394                _ => {}
395            })
396            .await;
397
398        // Start the solving process
399        self.emitter
400            .emit(AnySolverEvent::GoalSubmitted(GoalSubmittedEvent {
401                state: state.clone(),
402            }))
403            .await;
404
405        // Spawn a task to handle the problem submission
406        let agent = self.clone_for_handler();
407        tokio::spawn(async move {
408            agent.handle_goal_submitted(state).await;
409        });
410
411        // Wait for solution, handler error, or timeout (300 seconds)
412        match timeout(Duration::from_secs(300), async {
413            tokio::select! {
414                solution = solution_rx.recv() => {
415                    Ok(solution)
416                }
417                Some(err) = error_rx.recv() => {
418                    Err(err)
419                }
420            }
421        })
422        .await
423        {
424            Ok(Ok(Some(solution))) => Ok(solution),
425            Ok(Err(handler_err)) => Err(handler_err),
426            Ok(Ok(None)) | Err(_) => {
427                let timeout_message =
428                    "Timeout: Could not solve the problem within 300 seconds.".to_string();
429                let mut timeout_state = GoalState::new(problem, self.max_iterations);
430                timeout_state.solution = Some(timeout_message.clone());
431                timeout_state.is_complete = true;
432
433                self.emitter
434                    .emit(AnySolverEvent::Timeout(TimeoutEvent {
435                        state: timeout_state,
436                    }))
437                    .await;
438
439                Ok(timeout_message)
440            }
441        }
442    }
443
444    /// Handle a goal submitted event
445    fn handle_goal_submitted(
446        &self,
447        state: GoalState,
448    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
449        Box::pin(async move {
450            self.process_iteration(state).await;
451        })
452    }
453
454    /// Handle an iteration completed event
455    fn handle_iteration_completed(
456        &self,
457        mut state: GoalState,
458        response: String,
459    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
460        Box::pin(async move {
461            let normalized = response.trim().to_uppercase();
462
463            // Check if the task failed
464            if normalized == "FAIL" {
465                state.solution = Some(format!(
466                    "Failed to solve after {} iterations:\n{}",
467                    state.iteration, response
468                ));
469                state.is_complete = true;
470
471                self.emitter.emit(AnySolverEvent::GoalFailed(GoalFailedEvent { state })).await;
472                return;
473            }
474
475            // Check if the task succeeded
476            if normalized == "DONE" {
477                state.solution = Some(response);
478                state.is_complete = true;
479
480                self.emitter
481                    .emit(AnySolverEvent::GoalAchieved(GoalAchievedEvent { state }))
482                    .await;
483                return;
484            }
485
486            // Check if we've reached max iterations
487            if state.iteration >= state.max_iterations {
488                state.solution = Some(format!(
489                    "Best solution after {} iterations:\n{}",
490                    state.max_iterations, response
491                ));
492                state.is_complete = true;
493
494                self.emitter
495                    .emit(AnySolverEvent::GoalAchieved(GoalAchievedEvent { state }))
496                    .await;
497                return;
498            }
499
500            // Continue with next iteration
501            self.process_iteration(state).await;
502        })
503    }
504
505    /// Process a single iteration of the problem-solving process
506    fn process_iteration(
507        &self,
508        mut state: GoalState,
509    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
510        Box::pin(async move {
511            // Increment iteration counter
512            state.iteration += 1;
513
514            // Generate prompt for this iteration
515            let prompt = format!(
516                "Given the user request:\n\
517             {}\n\
518             \n\
519             Use the tools at your disposal to act on their request.\n\
520             You may wish to create a step-by-step plan for more complicated requests.\n\
521             \n\
522             If you cannot provide an answer, say only \"FAIL\".\n\
523             If you have the answer, say only \"DONE\".",
524                state.goal
525            );
526
527            // Generate response asynchronously
528            match self.generate_response(&prompt).await {
529                Ok(response) => {
530                    self.emitter
531                        .emit(AnySolverEvent::IterationCompleted(IterationCompletedEvent {
532                            state: state.clone(),
533                            response: response.clone(),
534                        }))
535                        .await;
536
537                    // Handle the completed iteration
538                    self.handle_iteration_completed(state, response).await;
539                }
540                Err(e) => {
541                    warn!("Error generating response: {}", e);
542                    let mut error_state = state;
543                    error_state.solution = Some(format!("Error: {}", e));
544                    error_state.is_complete = true;
545
546                    self.emitter
547                        .emit(AnySolverEvent::GoalFailed(GoalFailedEvent { state: error_state }))
548                        .await;
549                }
550            }
551        })
552    }
553
554    /// Generate a response using a ChatSession
555    async fn generate_response(&self, prompt: &str) -> Result<String> {
556        // Create a chat session for this request
557        let broker = Arc::clone(&self.broker);
558        let mut chat = ChatSession::builder((*broker).clone())
559            .system_prompt(&self.system_prompt)
560            .tools(self.tools.iter().map(|t| t.clone_box()).collect())
561            .build();
562
563        chat.send(prompt).await
564    }
565
566    /// Clone the agent for use in async handlers
567    ///
568    /// This creates a shallow clone suitable for spawned tasks
569    fn clone_for_handler(&self) -> Self {
570        Self {
571            broker: self.broker.clone(),
572            tools: self.tools.iter().map(|t| t.clone_box()).collect(),
573            max_iterations: self.max_iterations,
574            system_prompt: self.system_prompt.clone(),
575            emitter: self.emitter.clone(),
576        }
577    }
578}
579
580/// Builder for constructing a `SimpleRecursiveAgent` with custom configuration.
581pub struct SimpleRecursiveAgentBuilder {
582    broker: Arc<LlmBroker>,
583    tools: Vec<Box<dyn LlmTool>>,
584    max_iterations: usize,
585    system_prompt: Option<String>,
586}
587
588impl SimpleRecursiveAgentBuilder {
589    /// Create a new builder
590    fn new(broker: Arc<LlmBroker>) -> Self {
591        Self {
592            broker,
593            tools: Vec::new(),
594            max_iterations: 5,
595            system_prompt: None,
596        }
597    }
598
599    /// Set the tools available to the agent
600    pub fn tools(mut self, tools: Vec<Box<dyn LlmTool>>) -> Self {
601        self.tools = tools;
602        self
603    }
604
605    /// Set the maximum number of iterations (default: 5)
606    pub fn max_iterations(mut self, max_iterations: usize) -> Self {
607        self.max_iterations = max_iterations;
608        self
609    }
610
611    /// Set a custom system prompt
612    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
613        self.system_prompt = Some(prompt.into());
614        self
615    }
616
617    /// Build the agent
618    pub fn build(self) -> SimpleRecursiveAgent {
619        let system_prompt = self.system_prompt.unwrap_or_else(|| {
620            "You are a problem-solving assistant that can solve complex problems step by step. \
621             You analyze problems, break them down into smaller parts, and solve them systematically. \
622             If you cannot solve a problem completely in one step, you make progress and identify what to do next."
623                .to_string()
624        });
625
626        SimpleRecursiveAgent {
627            broker: self.broker,
628            tools: self.tools,
629            max_iterations: self.max_iterations,
630            system_prompt,
631            emitter: Arc::new(EventEmitter::new()),
632        }
633    }
634}
635
636#[cfg(test)]
637mod tests {
638    use super::*;
639    use crate::llm::gateway::{CompletionConfig, LlmGateway, StreamChunk};
640    use crate::llm::models::{LlmGatewayResponse, LlmMessage};
641    use crate::llm::tools::{FunctionDescriptor, ToolDescriptor};
642    use async_trait::async_trait;
643    use futures::stream::{self, Stream};
644    use serde_json::{json, Value};
645    use std::collections::HashMap;
646    use std::pin::Pin;
647    use std::sync::atomic::{AtomicUsize, Ordering};
648
649    // Mock gateway for testing
650    struct MockGateway {
651        responses: Vec<String>,
652        call_count: Arc<AtomicUsize>,
653    }
654
655    impl MockGateway {
656        fn new(responses: Vec<String>) -> Self {
657            Self {
658                responses,
659                call_count: Arc::new(AtomicUsize::new(0)),
660            }
661        }
662    }
663
664    #[async_trait::async_trait]
665    impl LlmGateway for MockGateway {
666        async fn complete(
667            &self,
668            _model: &str,
669            _messages: &[LlmMessage],
670            _tools: Option<&[Box<dyn LlmTool>]>,
671            _config: &CompletionConfig,
672        ) -> Result<LlmGatewayResponse> {
673            let idx = self.call_count.fetch_add(1, Ordering::SeqCst);
674
675            let content = if idx < self.responses.len() {
676                self.responses[idx].clone()
677            } else {
678                "default response".to_string()
679            };
680
681            Ok(LlmGatewayResponse {
682                content: Some(content),
683                object: None,
684                tool_calls: vec![],
685                thinking: None,
686                ..Default::default()
687            })
688        }
689
690        async fn complete_json(
691            &self,
692            _model: &str,
693            _messages: &[LlmMessage],
694            _schema: Value,
695            _config: &CompletionConfig,
696        ) -> Result<Value> {
697            Ok(json!({}))
698        }
699
700        async fn get_available_models(&self) -> Result<Vec<String>> {
701            Ok(vec!["test-model".to_string()])
702        }
703
704        async fn calculate_embeddings(
705            &self,
706            _text: &str,
707            _model: Option<&str>,
708        ) -> Result<Vec<f32>> {
709            Ok(vec![0.1, 0.2, 0.3])
710        }
711
712        fn complete_stream<'a>(
713            &'a self,
714            _model: &'a str,
715            _messages: &'a [LlmMessage],
716            _tools: Option<&'a [Box<dyn LlmTool>]>,
717            _config: &'a CompletionConfig,
718        ) -> Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> {
719            Box::pin(stream::iter(vec![Ok(StreamChunk::Content("test".to_string()))]))
720        }
721    }
722
723    // Mock tool for testing
724    #[derive(Clone)]
725    struct MockTool {
726        name: String,
727    }
728
729    #[async_trait]
730
731    impl LlmTool for MockTool {
732        async fn run(
733            &self,
734            _args: &HashMap<String, Value>,
735            _ctx: &crate::llm::tools::ToolRunCtx,
736        ) -> Result<Value> {
737            Ok(json!({"result": "success"}))
738        }
739
740        fn descriptor(&self) -> ToolDescriptor {
741            ToolDescriptor {
742                r#type: "function".to_string(),
743                function: FunctionDescriptor {
744                    name: self.name.clone(),
745                    description: "A mock tool".to_string(),
746                    parameters: json!({}),
747                },
748            }
749        }
750
751        fn clone_box(&self) -> Box<dyn LlmTool> {
752            Box::new(self.clone())
753        }
754    }
755
756    #[tokio::test]
757    async fn test_goal_state_creation() {
758        let state = GoalState::new("Test problem", 5);
759
760        assert_eq!(state.goal, "Test problem");
761        assert_eq!(state.iteration, 0);
762        assert_eq!(state.max_iterations, 5);
763        assert_eq!(state.solution, None);
764        assert!(!state.is_complete);
765    }
766
767    #[tokio::test]
768    async fn test_event_emitter_subscribe_and_emit() {
769        let emitter = EventEmitter::new();
770        let received = Arc::new(Mutex::new(false));
771        let received_clone = received.clone();
772
773        emitter
774            .subscribe(move |_event: AnySolverEvent| {
775                let received = received_clone.clone();
776                tokio::spawn(async move {
777                    *received.lock().await = true;
778                });
779            })
780            .await;
781
782        let state = GoalState::new("Test", 5);
783        emitter.emit(AnySolverEvent::GoalSubmitted(GoalSubmittedEvent { state })).await;
784
785        // Give the async task time to execute
786        tokio::time::sleep(Duration::from_millis(50)).await;
787
788        assert!(*received.lock().await);
789    }
790
791    #[tokio::test]
792    async fn test_builder_default_settings() {
793        let gateway = Arc::new(MockGateway::new(vec![]));
794        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
795        let agent = SimpleRecursiveAgent::new(broker);
796
797        assert_eq!(agent.max_iterations, 5);
798        assert_eq!(agent.tools.len(), 0);
799    }
800
801    #[tokio::test]
802    async fn test_builder_custom_max_iterations() {
803        let gateway = Arc::new(MockGateway::new(vec![]));
804        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
805        let agent = SimpleRecursiveAgent::builder(broker).max_iterations(10).build();
806
807        assert_eq!(agent.max_iterations, 10);
808    }
809
810    #[tokio::test]
811    async fn test_builder_with_tools() {
812        let gateway = Arc::new(MockGateway::new(vec![]));
813        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
814
815        let tools: Vec<Box<dyn LlmTool>> = vec![Box::new(MockTool {
816            name: "test_tool".to_string(),
817        })];
818
819        let agent = SimpleRecursiveAgent::builder(broker).tools(tools).build();
820
821        assert_eq!(agent.tools.len(), 1);
822    }
823
824    #[tokio::test]
825    async fn test_builder_custom_system_prompt() {
826        let gateway = Arc::new(MockGateway::new(vec![]));
827        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
828        let agent = SimpleRecursiveAgent::builder(broker).system_prompt("Custom prompt").build();
829
830        assert_eq!(agent.system_prompt, "Custom prompt");
831    }
832
833    #[tokio::test]
834    async fn test_solve_completes_with_done() {
835        let gateway = Arc::new(MockGateway::new(vec!["DONE".to_string()]));
836        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
837        let agent = SimpleRecursiveAgent::new(broker);
838
839        let result = agent.solve("Test problem").await.unwrap();
840
841        assert_eq!(result, "DONE");
842    }
843
844    #[tokio::test]
845    async fn test_solve_fails_with_fail() {
846        let gateway = Arc::new(MockGateway::new(vec!["FAIL".to_string()]));
847        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
848        let agent = SimpleRecursiveAgent::new(broker);
849
850        let result = agent.solve("Impossible problem").await.unwrap();
851
852        assert!(result.contains("Failed to solve after 1 iterations"));
853        assert!(result.contains("FAIL"));
854    }
855
856    #[tokio::test]
857    async fn test_solve_case_insensitive_done() {
858        let gateway = Arc::new(MockGateway::new(vec!["done".to_string()]));
859        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
860        let agent = SimpleRecursiveAgent::new(broker);
861
862        let result = agent.solve("Test problem").await.unwrap();
863
864        assert_eq!(result, "done");
865    }
866
867    #[tokio::test]
868    async fn test_solve_case_insensitive_fail() {
869        let gateway = Arc::new(MockGateway::new(vec!["fail".to_string()]));
870        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
871        let agent = SimpleRecursiveAgent::new(broker);
872
873        let result = agent.solve("Test problem").await.unwrap();
874
875        assert!(result.contains("Failed to solve"));
876        assert!(result.contains("fail"));
877    }
878
879    #[tokio::test]
880    async fn test_solve_word_boundary_done() {
881        // "I'm DONE with this task" is NOT a strict match — should not trigger completion.
882        // The agent will exhaust max_iterations (default 5) using the single response.
883        let gateway = Arc::new(MockGateway::new(vec!["I'm DONE with this task".to_string()]));
884        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
885        let agent = SimpleRecursiveAgent::builder(broker).max_iterations(1).build();
886
887        let result = agent.solve("Test problem").await.unwrap();
888
889        // Strict match: substring "DONE" does NOT trigger GoalAchieved
890        assert!(result.contains("Best solution after 1 iterations"));
891        assert!(result.contains("I'm DONE with this task"));
892    }
893
894    #[tokio::test]
895    async fn test_solve_word_boundary_fail() {
896        // "This will FAIL" is NOT a strict match — should not trigger GoalFailed.
897        // The agent will exhaust max_iterations (default 5) using the single response.
898        let gateway = Arc::new(MockGateway::new(vec!["This will FAIL".to_string()]));
899        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
900        let agent = SimpleRecursiveAgent::builder(broker).max_iterations(1).build();
901
902        let result = agent.solve("Test problem").await.unwrap();
903
904        // Strict match: substring "FAIL" does NOT trigger GoalFailed
905        assert!(result.contains("Best solution after 1 iterations"));
906        assert!(result.contains("This will FAIL"));
907    }
908
909    #[tokio::test]
910    async fn test_solve_stops_at_max_iterations() {
911        let gateway = Arc::new(MockGateway::new(vec![
912            "Step 1".to_string(),
913            "Step 2".to_string(),
914            "Step 3".to_string(),
915        ]));
916        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
917        let agent = SimpleRecursiveAgent::builder(broker).max_iterations(3).build();
918
919        let result = agent.solve("Long problem").await.unwrap();
920
921        assert!(result.contains("Best solution after 3 iterations"));
922        assert!(result.contains("Step 3"));
923    }
924
925    #[tokio::test]
926    async fn test_solve_multiple_iterations_before_done() {
927        let gateway = Arc::new(MockGateway::new(vec![
928            "Working...".to_string(),
929            "Still working...".to_string(),
930            "DONE".to_string(),
931        ]));
932        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
933        let agent = SimpleRecursiveAgent::builder(broker).max_iterations(5).build();
934
935        let result = agent.solve("Complex problem").await.unwrap();
936
937        assert_eq!(result, "DONE");
938    }
939
940    #[tokio::test]
941    async fn test_event_emission_during_solve() {
942        let gateway = Arc::new(MockGateway::new(vec!["DONE".to_string()]));
943        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
944        let agent = SimpleRecursiveAgent::new(broker);
945
946        let goal_submitted = Arc::new(Mutex::new(false));
947        let iteration_completed = Arc::new(Mutex::new(false));
948        let goal_achieved = Arc::new(Mutex::new(false));
949
950        let goal_submitted_clone = goal_submitted.clone();
951        let iteration_completed_clone = iteration_completed.clone();
952        let goal_achieved_clone = goal_achieved.clone();
953
954        agent
955            .emitter
956            .subscribe(move |event: AnySolverEvent| {
957                let gs = goal_submitted_clone.clone();
958                let ic = iteration_completed_clone.clone();
959                let ga = goal_achieved_clone.clone();
960
961                tokio::spawn(async move {
962                    match event {
963                        AnySolverEvent::GoalSubmitted(_) => *gs.lock().await = true,
964                        AnySolverEvent::IterationCompleted(_) => *ic.lock().await = true,
965                        AnySolverEvent::GoalAchieved(_) => *ga.lock().await = true,
966                        _ => {}
967                    }
968                });
969            })
970            .await;
971
972        let _result = agent.solve("Test problem").await.unwrap();
973
974        // Give async tasks time to complete
975        tokio::time::sleep(Duration::from_millis(100)).await;
976
977        assert!(*goal_submitted.lock().await, "GoalSubmitted event not fired");
978        assert!(*iteration_completed.lock().await, "IterationCompleted event not fired");
979        assert!(*goal_achieved.lock().await, "GoalAchieved event not fired");
980    }
981
982    #[tokio::test]
983    async fn test_event_emission_on_failure() {
984        let gateway = Arc::new(MockGateway::new(vec!["FAIL".to_string()]));
985        let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
986        let agent = SimpleRecursiveAgent::new(broker);
987
988        let goal_failed = Arc::new(Mutex::new(false));
989        let goal_failed_clone = goal_failed.clone();
990
991        agent
992            .emitter
993            .subscribe(move |event: AnySolverEvent| {
994                let gf = goal_failed_clone.clone();
995                tokio::spawn(async move {
996                    if matches!(event, AnySolverEvent::GoalFailed(_)) {
997                        *gf.lock().await = true;
998                    }
999                });
1000            })
1001            .await;
1002
1003        let _result = agent.solve("Test problem").await.unwrap();
1004
1005        // Give async tasks time to complete
1006        tokio::time::sleep(Duration::from_millis(100)).await;
1007
1008        assert!(*goal_failed.lock().await, "GoalFailed event not fired");
1009    }
1010
1011    #[tokio::test]
1012    async fn test_handler_panic_surfaces_as_error() {
1013        let emitter = EventEmitter::new();
1014
1015        // Subscribe a callback that panics
1016        emitter
1017            .subscribe(|_event: AnySolverEvent| {
1018                panic!("intentional test panic");
1019            })
1020            .await;
1021
1022        let (error_tx, mut error_rx) = mpsc::channel::<MojenticError>(8);
1023        emitter.set_error_sink(error_tx).await;
1024
1025        let state = GoalState::new("Test", 5);
1026        emitter.emit(AnySolverEvent::GoalSubmitted(GoalSubmittedEvent { state })).await;
1027
1028        // Give the spawned tasks time to run and forward the panic
1029        let err = tokio::time::timeout(Duration::from_secs(2), error_rx.recv())
1030            .await
1031            .expect("timed out waiting for handler error")
1032            .expect("channel closed without error");
1033
1034        match err {
1035            MojenticError::HandlerError(msg) => {
1036                assert!(msg.contains("intentional test panic"), "unexpected error message: {msg}");
1037            }
1038            other => panic!("Expected HandlerError, got: {:?}", other),
1039        }
1040    }
1041}