codive-core 0.1.0

Core types, traits, and utilities for Codive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! Agent - The core agent loop that orchestrates LLM interactions and tool execution
//!
//! The Agent is the heart of the system. It manages:
//! - Conversation history (via Session)
//! - LLM interactions (via Provider)
//! - Tool execution (via ToolRegistry)
//! - Event publishing (via EventBus)
//!
//! # Architecture
//!
//! ```text
//! User Input
//!     │
//!     ▼
//! ┌─────────┐
//! │  Agent  │◄──── Provider (LLM)
//! └─────────┘
//!     │  ▲
//!     │  │ Tool Results
//!     ▼  │
//! ┌─────────┐
//! │  Tools  │
//! └─────────┘
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use codive_core::{Agent, AgentConfig};
//! use codive_providers::AnthropicProvider;
//!
//! let provider = AnthropicProvider::new("sk-...")?;
//! let agent = Agent::new(provider, AgentConfig::default());
//!
//! // Run a single turn
//! let response = agent.run("Hello!").await?;
//! println!("{}", response);
//! ```

use codive_prompts::PromptStore;

use crate::config::AgentConfig;
use crate::event::{Event, EventBus};
use crate::message::{ContentPart, Message, ToolCall, ToolResult};
use crate::provider::{CompletionRequest, Provider, ProviderError, StopReason, StreamEvent};
use crate::session::Session;
use crate::tool::{ToolInfo, ToolRegistry};
use std::sync::Arc;
use tokio_stream::StreamExt;
use tracing::{debug, info, instrument, warn};

// Re-export CancellationToken for convenience
pub use tokio_util::sync::CancellationToken;

/// Errors that can occur during agent execution
#[derive(Debug, thiserror::Error)]
pub enum AgentRunError {
    /// Provider error during completion
    #[error("Provider error: {0}")]
    Provider(#[from] ProviderError),

    /// Tool execution error
    #[error("Tool error: {message}")]
    Tool { message: String },

    /// Maximum steps exceeded
    #[error("Maximum steps exceeded ({max_steps})")]
    MaxStepsExceeded { max_steps: u32 },

    /// Session error
    #[error("Session error: {message}")]
    Session { message: String },

    /// Operation was cancelled
    #[error("Operation cancelled")]
    Cancelled,
}

impl AgentRunError {
    /// Create a tool error
    pub fn tool(message: impl Into<String>) -> Self {
        Self::Tool {
            message: message.into(),
        }
    }

    /// Create a session error
    pub fn session(message: impl Into<String>) -> Self {
        Self::Session {
            message: message.into(),
        }
    }

    /// Check if the error is a cancellation
    pub fn is_cancelled(&self) -> bool {
        matches!(self, Self::Cancelled)
    }

}

/// Result of an agent turn
#[derive(Debug, Clone)]
pub struct TurnResult {
    /// The assistant's text response
    pub text: String,
    /// Tool calls made during this turn
    pub tool_calls: Vec<ToolCall>,
    /// Why the turn ended
    pub stop_reason: StopReason,
    /// Number of steps taken
    pub steps: u32,
}

impl TurnResult {
    /// Create a new turn result
    pub fn new(text: String, tool_calls: Vec<ToolCall>, stop_reason: StopReason, steps: u32) -> Self {
        Self {
            text,
            tool_calls,
            stop_reason,
            steps,
        }
    }
}

/// The Agent orchestrates conversations between users, LLMs, and tools
pub struct Agent {
    /// The LLM provider
    provider: Arc<dyn Provider>,
    /// Tool registry
    tools: ToolRegistry,
    /// Agent configuration
    config: AgentConfig,
    /// Prompt store for system prompts
    prompt_store: Arc<PromptStore>,
    /// Current session
    session: Session,
    /// Event bus for publishing events
    event_bus: EventBus,
}

impl Agent {
    /// Create a new agent with the given provider, configuration, and prompt store
    pub fn new(
        provider: Arc<dyn Provider>,
        config: AgentConfig,
        prompt_store: Arc<PromptStore>,
    ) -> Self {
        let session = Session::new();
        Self {
            provider,
            tools: ToolRegistry::new(),
            config,
            prompt_store,
            session,
            event_bus: EventBus::new(),
        }
    }

    /// Create an agent with an existing session
    pub fn with_session(
        provider: Arc<dyn Provider>,
        config: AgentConfig,
        prompt_store: Arc<PromptStore>,
        session: Session,
    ) -> Self {
        Self {
            provider,
            tools: ToolRegistry::new(),
            config,
            prompt_store,
            session,
            event_bus: EventBus::new(),
        }
    }

    /// Get a reference to the tool registry for registration
    pub fn tools_mut(&mut self) -> &mut ToolRegistry {
        &mut self.tools
    }

    /// Get a reference to the tool registry
    pub fn tools(&self) -> &ToolRegistry {
        &self.tools
    }

    /// Get a reference to the current session
    pub fn session(&self) -> &Session {
        &self.session
    }

    /// Get a mutable reference to the session
    pub fn session_mut(&mut self) -> &mut Session {
        &mut self.session
    }

    /// Get the event bus for subscribing to events
    pub fn event_bus(&self) -> &EventBus {
        &self.event_bus
    }

    /// Get the configuration
    pub fn config(&self) -> &AgentConfig {
        &self.config
    }

    /// Run a single conversation turn with the given user message
    ///
    /// This is the main entry point for interacting with the agent.
    /// It handles:
    /// 1. Adding the user message to the session
    /// 2. Calling the LLM for a response
    /// 3. Executing any tool calls
    /// 4. Repeating until the LLM stops or max steps is reached
    #[instrument(skip(self, user_message), fields(session_id = %self.session.id))]
    pub async fn run(&mut self, user_message: impl Into<String>) -> Result<TurnResult, AgentRunError> {
        self.run_with_cancellation(user_message, None).await
    }

    /// Run a single conversation turn with cancellation support
    ///
    /// Same as `run()` but can be cancelled via the provided `CancellationToken`.
    /// When cancelled, returns `AgentRunError::Cancelled`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use codive_core::{Agent, CancellationToken};
    ///
    /// let token = CancellationToken::new();
    /// let cancel_token = token.clone();
    ///
    /// // Cancel after 5 seconds
    /// tokio::spawn(async move {
    ///     tokio::time::sleep(Duration::from_secs(5)).await;
    ///     cancel_token.cancel();
    /// });
    ///
    /// match agent.run_with_cancellation("Hello", Some(token)).await {
    ///     Ok(result) => println!("Got response: {}", result.text),
    ///     Err(AgentRunError::Cancelled) => println!("Operation was cancelled"),
    ///     Err(e) => eprintln!("Error: {}", e),
    /// }
    /// ```
    #[instrument(skip(self, user_message, cancel_token), fields(session_id = %self.session.id))]
    pub async fn run_with_cancellation(
        &mut self,
        user_message: impl Into<String>,
        cancel_token: Option<CancellationToken>,
    ) -> Result<TurnResult, AgentRunError> {
        let user_message = user_message.into();
        info!(message = %user_message, "Starting agent turn");

        // Check for cancellation before starting
        if let Some(ref token) = cancel_token {
            if token.is_cancelled() {
                return Err(AgentRunError::Cancelled);
            }
        }

        // Add user message to session
        self.session.add_message(Message::user(&user_message));

        // Publish user message event
        self.event_bus.publish(Event::MessageCreated {
            session_id: self.session.id.clone(),
            message_id: format!("msg_{}", self.session.message_count()),
            role: "user".to_string(),
        });

        // Run the agent loop
        self.run_loop_internal(cancel_token).await
    }

    /// Continue the conversation without adding a new user message
    ///
    /// Useful after adding tool results or for multi-turn interactions
    pub async fn continue_turn(&mut self) -> Result<TurnResult, AgentRunError> {
        self.run_loop_internal(None).await
    }

    /// Continue the conversation with cancellation support
    pub async fn continue_turn_with_cancellation(
        &mut self,
        cancel_token: Option<CancellationToken>,
    ) -> Result<TurnResult, AgentRunError> {
        self.run_loop_internal(cancel_token).await
    }

    /// The main agent loop with optional cancellation support
    async fn run_loop_internal(
        &mut self,
        cancel_token: Option<CancellationToken>,
    ) -> Result<TurnResult, AgentRunError> {
        let mut steps = 0u32;
        let mut accumulated_text = String::new();
        let mut all_tool_calls = Vec::new();
        let mut final_stop_reason: StopReason;

        loop {
            steps += 1;

            // Check for cancellation at the start of each step
            if let Some(ref token) = cancel_token {
                if token.is_cancelled() {
                    info!(steps, "Agent run cancelled");
                    return Err(AgentRunError::Cancelled);
                }
            }

            // Check max steps
            if steps > self.config.max_steps {
                warn!(steps, max = self.config.max_steps, "Maximum steps exceeded");
                return Err(AgentRunError::MaxStepsExceeded {
                    max_steps: self.config.max_steps,
                });
            }

            debug!(step = steps, "Running agent step");

            // Build the completion request
            let request = self.build_request();

            // Call the provider (with cancellation check)
            let stream_result = if let Some(ref token) = cancel_token {
                tokio::select! {
                    _ = token.cancelled() => {
                        info!(steps, "Agent run cancelled during provider call");
                        return Err(AgentRunError::Cancelled);
                    }
                    result = self.provider.complete(request) => result
                }
            } else {
                self.provider.complete(request).await
            };

            let mut stream = stream_result?;

            // Process the stream
            let (text, tool_calls, stop_reason) = self.process_stream(&mut stream).await?;

            // Accumulate results
            accumulated_text.push_str(&text);
            all_tool_calls.extend(tool_calls.clone());
            final_stop_reason = stop_reason;

            // Build the assistant message
            let mut content_parts = Vec::new();
            if !text.is_empty() {
                content_parts.push(ContentPart::text(&text));
            }
            for call in &tool_calls {
                content_parts.push(ContentPart::ToolCall(call.clone()));
            }

            if !content_parts.is_empty() {
                self.session.add_message(Message::assistant(content_parts));
            }

            // Publish assistant message completion event
            if !text.is_empty() {
                self.event_bus.publish(Event::MessageComplete {
                    session_id: self.session.id.clone(),
                    message_id: format!("msg_{}", self.session.message_count()),
                });
            }

            // If there are tool calls, execute them
            if !tool_calls.is_empty() {
                // Check for cancellation before tool execution
                if let Some(ref token) = cancel_token {
                    if token.is_cancelled() {
                        info!(steps, "Agent run cancelled before tool execution");
                        return Err(AgentRunError::Cancelled);
                    }
                }

                let results = self.execute_tools(&tool_calls).await;

                // Add tool results to session
                self.session.add_message(Message::tool_results(results));

                // Continue the loop to get the next response
                continue;
            }

            // No tool calls - we're done
            break;
        }

        info!(
            steps,
            text_len = accumulated_text.len(),
            tool_calls = all_tool_calls.len(),
            "Agent turn complete"
        );

        Ok(TurnResult::new(
            accumulated_text,
            all_tool_calls,
            final_stop_reason,
            steps,
        ))
    }

    /// Build a completion request from the current session state
    fn build_request(&self) -> CompletionRequest {
        let system_prompt = self.config.build_system_prompt(&self.prompt_store);

        let mut request = CompletionRequest::new(system_prompt)
            .with_messages(self.session.messages.iter().cloned());

        // Add tools if any are registered
        let tool_infos: Vec<ToolInfo> = self.tools.tool_infos_with_store(&self.prompt_store);
        if !tool_infos.is_empty() {
            request = request.with_tools(tool_infos);
        }

        request
    }

    /// Process a completion stream and extract text, tool calls, and stop reason
    async fn process_stream(
        &self,
        stream: &mut crate::provider::CompletionStream,
    ) -> Result<(String, Vec<ToolCall>, StopReason), AgentRunError> {
        let mut text = String::new();
        let mut tool_calls: Vec<ToolCallBuilder> = Vec::new();
        let mut stop_reason = StopReason::EndTurn;

        while let Some(event) = stream.next().await {
            match event {
                StreamEvent::MessageStart { message_id } => {
                    debug!(message_id, "Stream started");
                }
                StreamEvent::TextDelta { text: delta } => {
                    text.push_str(&delta);
                    // Publish streaming event
                    self.event_bus.publish(Event::MessageDelta {
                        session_id: self.session.id.clone(),
                        message_id: "streaming".to_string(),
                        delta,
                    });
                }
                StreamEvent::ToolCallStart { index, id, name } => {
                    // Ensure we have enough builders
                    while tool_calls.len() <= index {
                        tool_calls.push(ToolCallBuilder::default());
                    }
                    tool_calls[index].id = id;
                    tool_calls[index].name = name;
                }
                StreamEvent::ToolCallDelta {
                    index,
                    arguments_delta,
                } => {
                    if index < tool_calls.len() {
                        tool_calls[index].arguments.push_str(&arguments_delta);
                    }
                }
                StreamEvent::ToolCallEnd { index: _ } => {
                    // Tool call complete - nothing special needed
                }
                StreamEvent::MessageEnd {
                    stop_reason: reason,
                    usage: _,
                } => {
                    stop_reason = reason;
                }
                StreamEvent::Error { message, code } => {
                    warn!(message, ?code, "Stream error");
                    return Err(AgentRunError::Provider(ProviderError::ProviderError {
                        message,
                    }));
                }
            }
        }

        // Convert builders to ToolCall
        let completed_tool_calls: Vec<ToolCall> = tool_calls
            .into_iter()
            .filter(|b| !b.id.is_empty() && !b.name.is_empty())
            .map(|b| {
                let arguments = serde_json::from_str(&b.arguments).unwrap_or(serde_json::json!({}));
                ToolCall::new(b.id, b.name, arguments)
            })
            .collect();

        Ok((text, completed_tool_calls, stop_reason))
    }

    /// Execute tool calls and return results
    async fn execute_tools(&self, tool_calls: &[ToolCall]) -> Vec<ToolResult> {
        let mut results = Vec::with_capacity(tool_calls.len());

        for call in tool_calls {
            debug!(tool = %call.name, id = %call.id, "Executing tool");

            // Publish tool execution event
            self.event_bus.publish(Event::ToolCallStarted {
                session_id: self.session.id.clone(),
                tool_name: call.name.clone(),
                tool_call_id: call.id.clone(),
                arguments: Some(call.arguments.clone()),
            });

            let (result, file_change) = if let Some(tool) = self.tools.get(&call.name) {
                let output = tool.execute(call.arguments.clone()).await;
                let file_change = output.file_change.clone();

                let result = if output.is_error {
                    ToolResult::failure(&call.id, &output.content)
                } else {
                    ToolResult::success(&call.id, &output.content)
                };
                (result, file_change)
            } else {
                warn!(tool = %call.name, "Tool not found");
                (ToolResult::failure(&call.id, format!("Tool '{}' not found", call.name)), None)
            };

            // Publish tool completion event
            self.event_bus.publish(Event::ToolCallCompleted {
                session_id: self.session.id.clone(),
                tool_call_id: call.id.clone(),
                success: result.is_success(),
                file_change,
            });

            results.push(result);
        }

        results
    }
}

/// Helper for building tool calls from streamed data
#[derive(Default)]
struct ToolCallBuilder {
    id: String,
    name: String,
    arguments: String,
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tool::{Tool, ToolOutput};
    use async_trait::async_trait;

    /// Create a default PromptStore for testing
    fn test_prompt_store() -> Arc<PromptStore> {
        Arc::new(PromptStore::default())
    }

    /// A mock provider for testing
    struct MockProvider {
        responses: Vec<Vec<StreamEvent>>,
        call_count: std::sync::atomic::AtomicUsize,
    }

    impl MockProvider {
        fn new(responses: Vec<Vec<StreamEvent>>) -> Self {
            Self {
                responses,
                call_count: std::sync::atomic::AtomicUsize::new(0),
            }
        }

        fn single_response(text: &str) -> Self {
            Self::new(vec![vec![
                StreamEvent::message_start("msg_1"),
                StreamEvent::text_delta(text),
                StreamEvent::message_end(StopReason::EndTurn),
            ]])
        }
    }

    #[async_trait]
    impl Provider for MockProvider {
        fn name(&self) -> &str {
            "mock"
        }

        fn model(&self) -> &str {
            "mock-model"
        }

        async fn complete(
            &self,
            _request: CompletionRequest,
        ) -> Result<crate::provider::CompletionStream, ProviderError> {
            let idx = self
                .call_count
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let events = self.responses.get(idx).cloned().unwrap_or_default();
            Ok(Box::pin(tokio_stream::iter(events)))
        }
    }

    /// A simple echo tool for testing
    struct EchoTool;

    #[async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &str {
            "echo"
        }

        fn description(&self) -> &str {
            "Echoes back the input"
        }

        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "message": { "type": "string" }
                },
                "required": ["message"]
            })
        }

        async fn execute(&self, params: serde_json::Value) -> ToolOutput {
            let message = params["message"].as_str().unwrap_or("no message");
            ToolOutput::success(format!("Echo: {}", message))
        }
    }

    #[test]
    fn test_agent_creation() {
        let provider = Arc::new(MockProvider::single_response("Hello"));
        let config = AgentConfig::default();
        let agent = Agent::new(provider, config, test_prompt_store());

        assert!(agent.tools().is_empty());
        assert!(agent.session().messages.is_empty());
    }

    #[test]
    fn test_agent_with_session() {
        let provider = Arc::new(MockProvider::single_response("Hello"));
        let config = AgentConfig::default();
        let mut session = Session::new();
        session.add_message(Message::user("Previous message"));

        let agent = Agent::with_session(provider, config, test_prompt_store(), session);
        assert_eq!(agent.session().messages.len(), 1);
    }

    #[test]
    fn test_register_tool() {
        let provider = Arc::new(MockProvider::single_response("Hello"));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());

        agent.tools_mut().register(Arc::new(EchoTool));
        assert!(agent.tools().get("echo").is_some());
    }

    #[tokio::test]
    async fn test_simple_run() {
        let provider = Arc::new(MockProvider::single_response("Hello, I'm Claude!"));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());

        let result = agent.run("Hello!").await.unwrap();

        assert_eq!(result.text, "Hello, I'm Claude!");
        assert!(result.tool_calls.is_empty());
        assert_eq!(result.stop_reason, StopReason::EndTurn);
        assert_eq!(result.steps, 1);
    }

    #[tokio::test]
    async fn test_run_updates_session() {
        let provider = Arc::new(MockProvider::single_response("Response"));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());

        agent.run("User input").await.unwrap();

        // Should have user message + assistant response
        let messages = &agent.session().messages;
        assert_eq!(messages.len(), 2);
        assert!(messages[0].is_user());
        assert!(messages[1].is_assistant());
    }

    #[tokio::test]
    async fn test_max_steps_exceeded() {
        // Provider that always requests tool use
        let responses = (0..100)
            .map(|_| {
                vec![
                    StreamEvent::message_start("msg"),
                    StreamEvent::ToolCallStart {
                        index: 0,
                        id: "call_1".to_string(),
                        name: "echo".to_string(),
                    },
                    StreamEvent::ToolCallDelta {
                        index: 0,
                        arguments_delta: r#"{"message":"test"}"#.to_string(),
                    },
                    StreamEvent::ToolCallEnd { index: 0 },
                    StreamEvent::MessageEnd {
                        stop_reason: StopReason::ToolUse,
                        usage: None,
                    },
                ]
            })
            .collect();

        let provider = Arc::new(MockProvider::new(responses));
        let config = AgentConfig::default().with_max_steps(3);
        let mut agent = Agent::new(provider, config, test_prompt_store());
        agent.tools_mut().register(Arc::new(EchoTool));

        let result = agent.run("Hello").await;
        assert!(matches!(result, Err(AgentRunError::MaxStepsExceeded { max_steps: 3 })));
    }

    #[tokio::test]
    async fn test_tool_execution() {
        // First response requests a tool, second gives final answer
        let responses = vec![
            vec![
                StreamEvent::message_start("msg_1"),
                StreamEvent::text_delta("Let me echo that."),
                StreamEvent::ToolCallStart {
                    index: 0,
                    id: "call_1".to_string(),
                    name: "echo".to_string(),
                },
                StreamEvent::ToolCallDelta {
                    index: 0,
                    arguments_delta: r#"{"message":"hello"}"#.to_string(),
                },
                StreamEvent::ToolCallEnd { index: 0 },
                StreamEvent::MessageEnd {
                    stop_reason: StopReason::ToolUse,
                    usage: None,
                },
            ],
            vec![
                StreamEvent::message_start("msg_2"),
                StreamEvent::text_delta("The echo returned: Echo: hello"),
                StreamEvent::MessageEnd {
                    stop_reason: StopReason::EndTurn,
                    usage: None,
                },
            ],
        ];

        let provider = Arc::new(MockProvider::new(responses));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());
        agent.tools_mut().register(Arc::new(EchoTool));

        let result = agent.run("Echo hello").await.unwrap();

        assert!(result.text.contains("echo"));
        assert_eq!(result.tool_calls.len(), 1);
        assert_eq!(result.tool_calls[0].name, "echo");
        assert_eq!(result.steps, 2);
    }

    #[tokio::test]
    async fn test_tool_not_found() {
        let responses = vec![
            vec![
                StreamEvent::message_start("msg_1"),
                StreamEvent::ToolCallStart {
                    index: 0,
                    id: "call_1".to_string(),
                    name: "nonexistent_tool".to_string(),
                },
                StreamEvent::ToolCallDelta {
                    index: 0,
                    arguments_delta: "{}".to_string(),
                },
                StreamEvent::ToolCallEnd { index: 0 },
                StreamEvent::MessageEnd {
                    stop_reason: StopReason::ToolUse,
                    usage: None,
                },
            ],
            vec![
                StreamEvent::message_start("msg_2"),
                StreamEvent::text_delta("Tool not found"),
                StreamEvent::MessageEnd {
                    stop_reason: StopReason::EndTurn,
                    usage: None,
                },
            ],
        ];

        let provider = Arc::new(MockProvider::new(responses));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());

        let _result = agent.run("Use unknown tool").await.unwrap();

        // Should complete but session should have error result
        let messages = &agent.session().messages;
        // User + Assistant (tool call) + User (tool result) + Assistant (response)
        assert_eq!(messages.len(), 4);
    }

    #[test]
    fn test_turn_result() {
        let result = TurnResult::new(
            "Hello".to_string(),
            vec![],
            StopReason::EndTurn,
            1,
        );

        assert_eq!(result.text, "Hello");
        assert!(result.tool_calls.is_empty());
        assert_eq!(result.stop_reason, StopReason::EndTurn);
        assert_eq!(result.steps, 1);
    }

    #[test]
    fn test_agent_run_error_display() {
        let err = AgentRunError::tool("Tool failed");
        assert!(err.to_string().contains("Tool failed"));

        let err = AgentRunError::MaxStepsExceeded { max_steps: 10 };
        assert!(err.to_string().contains("10"));
    }

    #[test]
    fn test_cancellation_error() {
        let err = AgentRunError::Cancelled;
        assert!(err.is_cancelled());
        assert!(err.to_string().contains("cancelled"));

        let err = AgentRunError::tool("some error");
        assert!(!err.is_cancelled());
    }

    #[tokio::test]
    async fn test_run_with_already_cancelled_token() {
        let provider = Arc::new(MockProvider::single_response("Hello"));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());

        // Create an already-cancelled token
        let token = CancellationToken::new();
        token.cancel();

        let result = agent.run_with_cancellation("Hello", Some(token)).await;
        assert!(matches!(result, Err(AgentRunError::Cancelled)));
    }

    #[tokio::test]
    async fn test_run_with_no_cancellation() {
        let provider = Arc::new(MockProvider::single_response("Hello, I'm Claude!"));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());

        // Token that's never cancelled
        let token = CancellationToken::new();

        let result = agent.run_with_cancellation("Hello!", Some(token)).await.unwrap();
        assert_eq!(result.text, "Hello, I'm Claude!");
    }

    #[tokio::test]
    async fn test_run_without_token_works() {
        let provider = Arc::new(MockProvider::single_response("Response"));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());

        // Pass None for token
        let result = agent.run_with_cancellation("Hello", None).await.unwrap();
        assert_eq!(result.text, "Response");
    }

    #[tokio::test]
    async fn test_cancellation_during_tool_loop() {
        // Provider that requests a tool, but we cancel before execution
        let responses = vec![
            vec![
                StreamEvent::message_start("msg_1"),
                StreamEvent::ToolCallStart {
                    index: 0,
                    id: "call_1".to_string(),
                    name: "echo".to_string(),
                },
                StreamEvent::ToolCallDelta {
                    index: 0,
                    arguments_delta: r#"{"message":"test"}"#.to_string(),
                },
                StreamEvent::ToolCallEnd { index: 0 },
                StreamEvent::MessageEnd {
                    stop_reason: StopReason::ToolUse,
                    usage: None,
                },
            ],
        ];

        let provider = Arc::new(MockProvider::new(responses));
        let config = AgentConfig::default();
        let mut agent = Agent::new(provider, config, test_prompt_store());
        agent.tools_mut().register(Arc::new(EchoTool));

        let token = CancellationToken::new();
        let cancel_token = token.clone();

        // Spawn a task to cancel immediately after the provider returns
        // but before tool execution
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            cancel_token.cancel();
        });

        // Give it a moment to set up
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;

        // This should either complete before cancel or get cancelled
        // We mainly want to ensure no panic and correct behavior
        let result = agent.run_with_cancellation("Use tool", Some(token)).await;

        // Result should be either success (completed before cancel) or cancelled
        assert!(result.is_ok() || matches!(result, Err(AgentRunError::Cancelled)));
    }
}