1use codive_prompts::PromptStore;
41
42use crate::config::AgentConfig;
43use crate::event::{Event, EventBus};
44use crate::message::{ContentPart, Message, ToolCall, ToolResult};
45use crate::provider::{CompletionRequest, Provider, ProviderError, StopReason, StreamEvent};
46use crate::session::Session;
47use crate::tool::{ToolInfo, ToolRegistry};
48use std::sync::Arc;
49use tokio_stream::StreamExt;
50use tracing::{debug, info, instrument, warn};
51
52pub use tokio_util::sync::CancellationToken;
54
55#[derive(Debug, thiserror::Error)]
57pub enum AgentRunError {
58 #[error("Provider error: {0}")]
60 Provider(#[from] ProviderError),
61
62 #[error("Tool error: {message}")]
64 Tool { message: String },
65
66 #[error("Maximum steps exceeded ({max_steps})")]
68 MaxStepsExceeded { max_steps: u32 },
69
70 #[error("Session error: {message}")]
72 Session { message: String },
73
74 #[error("Operation cancelled")]
76 Cancelled,
77}
78
79impl AgentRunError {
80 pub fn tool(message: impl Into<String>) -> Self {
82 Self::Tool {
83 message: message.into(),
84 }
85 }
86
87 pub fn session(message: impl Into<String>) -> Self {
89 Self::Session {
90 message: message.into(),
91 }
92 }
93
94 pub fn is_cancelled(&self) -> bool {
96 matches!(self, Self::Cancelled)
97 }
98
99}
100
101#[derive(Debug, Clone)]
103pub struct TurnResult {
104 pub text: String,
106 pub tool_calls: Vec<ToolCall>,
108 pub stop_reason: StopReason,
110 pub steps: u32,
112}
113
114impl TurnResult {
115 pub fn new(text: String, tool_calls: Vec<ToolCall>, stop_reason: StopReason, steps: u32) -> Self {
117 Self {
118 text,
119 tool_calls,
120 stop_reason,
121 steps,
122 }
123 }
124}
125
126pub struct Agent {
128 provider: Arc<dyn Provider>,
130 tools: ToolRegistry,
132 config: AgentConfig,
134 prompt_store: Arc<PromptStore>,
136 session: Session,
138 event_bus: EventBus,
140}
141
142impl Agent {
143 pub fn new(
145 provider: Arc<dyn Provider>,
146 config: AgentConfig,
147 prompt_store: Arc<PromptStore>,
148 ) -> Self {
149 let session = Session::new();
150 Self {
151 provider,
152 tools: ToolRegistry::new(),
153 config,
154 prompt_store,
155 session,
156 event_bus: EventBus::new(),
157 }
158 }
159
160 pub fn with_session(
162 provider: Arc<dyn Provider>,
163 config: AgentConfig,
164 prompt_store: Arc<PromptStore>,
165 session: Session,
166 ) -> Self {
167 Self {
168 provider,
169 tools: ToolRegistry::new(),
170 config,
171 prompt_store,
172 session,
173 event_bus: EventBus::new(),
174 }
175 }
176
177 pub fn tools_mut(&mut self) -> &mut ToolRegistry {
179 &mut self.tools
180 }
181
182 pub fn tools(&self) -> &ToolRegistry {
184 &self.tools
185 }
186
187 pub fn session(&self) -> &Session {
189 &self.session
190 }
191
192 pub fn session_mut(&mut self) -> &mut Session {
194 &mut self.session
195 }
196
197 pub fn event_bus(&self) -> &EventBus {
199 &self.event_bus
200 }
201
202 pub fn config(&self) -> &AgentConfig {
204 &self.config
205 }
206
207 #[instrument(skip(self, user_message), fields(session_id = %self.session.id))]
216 pub async fn run(&mut self, user_message: impl Into<String>) -> Result<TurnResult, AgentRunError> {
217 self.run_with_cancellation(user_message, None).await
218 }
219
220 #[instrument(skip(self, user_message, cancel_token), fields(session_id = %self.session.id))]
246 pub async fn run_with_cancellation(
247 &mut self,
248 user_message: impl Into<String>,
249 cancel_token: Option<CancellationToken>,
250 ) -> Result<TurnResult, AgentRunError> {
251 let user_message = user_message.into();
252 info!(message = %user_message, "Starting agent turn");
253
254 if let Some(ref token) = cancel_token {
256 if token.is_cancelled() {
257 return Err(AgentRunError::Cancelled);
258 }
259 }
260
261 self.session.add_message(Message::user(&user_message));
263
264 self.event_bus.publish(Event::MessageCreated {
266 session_id: self.session.id.clone(),
267 message_id: format!("msg_{}", self.session.message_count()),
268 role: "user".to_string(),
269 });
270
271 self.run_loop_internal(cancel_token).await
273 }
274
275 pub async fn continue_turn(&mut self) -> Result<TurnResult, AgentRunError> {
279 self.run_loop_internal(None).await
280 }
281
282 pub async fn continue_turn_with_cancellation(
284 &mut self,
285 cancel_token: Option<CancellationToken>,
286 ) -> Result<TurnResult, AgentRunError> {
287 self.run_loop_internal(cancel_token).await
288 }
289
290 async fn run_loop_internal(
292 &mut self,
293 cancel_token: Option<CancellationToken>,
294 ) -> Result<TurnResult, AgentRunError> {
295 let mut steps = 0u32;
296 let mut accumulated_text = String::new();
297 let mut all_tool_calls = Vec::new();
298 let mut final_stop_reason: StopReason;
299
300 loop {
301 steps += 1;
302
303 if let Some(ref token) = cancel_token {
305 if token.is_cancelled() {
306 info!(steps, "Agent run cancelled");
307 return Err(AgentRunError::Cancelled);
308 }
309 }
310
311 if steps > self.config.max_steps {
313 warn!(steps, max = self.config.max_steps, "Maximum steps exceeded");
314 return Err(AgentRunError::MaxStepsExceeded {
315 max_steps: self.config.max_steps,
316 });
317 }
318
319 debug!(step = steps, "Running agent step");
320
321 let request = self.build_request();
323
324 let stream_result = if let Some(ref token) = cancel_token {
326 tokio::select! {
327 _ = token.cancelled() => {
328 info!(steps, "Agent run cancelled during provider call");
329 return Err(AgentRunError::Cancelled);
330 }
331 result = self.provider.complete(request) => result
332 }
333 } else {
334 self.provider.complete(request).await
335 };
336
337 let mut stream = stream_result?;
338
339 let (text, tool_calls, stop_reason) = self.process_stream(&mut stream).await?;
341
342 accumulated_text.push_str(&text);
344 all_tool_calls.extend(tool_calls.clone());
345 final_stop_reason = stop_reason;
346
347 let mut content_parts = Vec::new();
349 if !text.is_empty() {
350 content_parts.push(ContentPart::text(&text));
351 }
352 for call in &tool_calls {
353 content_parts.push(ContentPart::ToolCall(call.clone()));
354 }
355
356 if !content_parts.is_empty() {
357 self.session.add_message(Message::assistant(content_parts));
358 }
359
360 if !text.is_empty() {
362 self.event_bus.publish(Event::MessageComplete {
363 session_id: self.session.id.clone(),
364 message_id: format!("msg_{}", self.session.message_count()),
365 });
366 }
367
368 if !tool_calls.is_empty() {
370 if let Some(ref token) = cancel_token {
372 if token.is_cancelled() {
373 info!(steps, "Agent run cancelled before tool execution");
374 return Err(AgentRunError::Cancelled);
375 }
376 }
377
378 let results = self.execute_tools(&tool_calls).await;
379
380 self.session.add_message(Message::tool_results(results));
382
383 continue;
385 }
386
387 break;
389 }
390
391 info!(
392 steps,
393 text_len = accumulated_text.len(),
394 tool_calls = all_tool_calls.len(),
395 "Agent turn complete"
396 );
397
398 Ok(TurnResult::new(
399 accumulated_text,
400 all_tool_calls,
401 final_stop_reason,
402 steps,
403 ))
404 }
405
406 fn build_request(&self) -> CompletionRequest {
408 let system_prompt = self.config.build_system_prompt(&self.prompt_store);
409
410 let mut request = CompletionRequest::new(system_prompt)
411 .with_messages(self.session.messages.iter().cloned());
412
413 let tool_infos: Vec<ToolInfo> = self.tools.tool_infos_with_store(&self.prompt_store);
415 if !tool_infos.is_empty() {
416 request = request.with_tools(tool_infos);
417 }
418
419 request
420 }
421
422 async fn process_stream(
424 &self,
425 stream: &mut crate::provider::CompletionStream,
426 ) -> Result<(String, Vec<ToolCall>, StopReason), AgentRunError> {
427 let mut text = String::new();
428 let mut tool_calls: Vec<ToolCallBuilder> = Vec::new();
429 let mut stop_reason = StopReason::EndTurn;
430
431 while let Some(event) = stream.next().await {
432 match event {
433 StreamEvent::MessageStart { message_id } => {
434 debug!(message_id, "Stream started");
435 }
436 StreamEvent::TextDelta { text: delta } => {
437 text.push_str(&delta);
438 self.event_bus.publish(Event::MessageDelta {
440 session_id: self.session.id.clone(),
441 message_id: "streaming".to_string(),
442 delta,
443 });
444 }
445 StreamEvent::ToolCallStart { index, id, name } => {
446 while tool_calls.len() <= index {
448 tool_calls.push(ToolCallBuilder::default());
449 }
450 tool_calls[index].id = id;
451 tool_calls[index].name = name;
452 }
453 StreamEvent::ToolCallDelta {
454 index,
455 arguments_delta,
456 } => {
457 if index < tool_calls.len() {
458 tool_calls[index].arguments.push_str(&arguments_delta);
459 }
460 }
461 StreamEvent::ToolCallEnd { index: _ } => {
462 }
464 StreamEvent::MessageEnd {
465 stop_reason: reason,
466 usage: _,
467 } => {
468 stop_reason = reason;
469 }
470 StreamEvent::Error { message, code } => {
471 warn!(message, ?code, "Stream error");
472 return Err(AgentRunError::Provider(ProviderError::ProviderError {
473 message,
474 }));
475 }
476 }
477 }
478
479 let completed_tool_calls: Vec<ToolCall> = tool_calls
481 .into_iter()
482 .filter(|b| !b.id.is_empty() && !b.name.is_empty())
483 .map(|b| {
484 let arguments = serde_json::from_str(&b.arguments).unwrap_or(serde_json::json!({}));
485 ToolCall::new(b.id, b.name, arguments)
486 })
487 .collect();
488
489 Ok((text, completed_tool_calls, stop_reason))
490 }
491
492 async fn execute_tools(&self, tool_calls: &[ToolCall]) -> Vec<ToolResult> {
494 let mut results = Vec::with_capacity(tool_calls.len());
495
496 for call in tool_calls {
497 debug!(tool = %call.name, id = %call.id, "Executing tool");
498
499 self.event_bus.publish(Event::ToolCallStarted {
501 session_id: self.session.id.clone(),
502 tool_name: call.name.clone(),
503 tool_call_id: call.id.clone(),
504 arguments: Some(call.arguments.clone()),
505 });
506
507 let (result, file_change) = if let Some(tool) = self.tools.get(&call.name) {
508 let output = tool.execute(call.arguments.clone()).await;
509 let file_change = output.file_change.clone();
510
511 let result = if output.is_error {
512 ToolResult::failure(&call.id, &output.content)
513 } else {
514 ToolResult::success(&call.id, &output.content)
515 };
516 (result, file_change)
517 } else {
518 warn!(tool = %call.name, "Tool not found");
519 (ToolResult::failure(&call.id, format!("Tool '{}' not found", call.name)), None)
520 };
521
522 self.event_bus.publish(Event::ToolCallCompleted {
524 session_id: self.session.id.clone(),
525 tool_call_id: call.id.clone(),
526 success: result.is_success(),
527 file_change,
528 });
529
530 results.push(result);
531 }
532
533 results
534 }
535}
536
537#[derive(Default)]
539struct ToolCallBuilder {
540 id: String,
541 name: String,
542 arguments: String,
543}
544
545#[cfg(test)]
550mod tests {
551 use super::*;
552 use crate::tool::{Tool, ToolOutput};
553 use async_trait::async_trait;
554
555 fn test_prompt_store() -> Arc<PromptStore> {
557 Arc::new(PromptStore::default())
558 }
559
560 struct MockProvider {
562 responses: Vec<Vec<StreamEvent>>,
563 call_count: std::sync::atomic::AtomicUsize,
564 }
565
566 impl MockProvider {
567 fn new(responses: Vec<Vec<StreamEvent>>) -> Self {
568 Self {
569 responses,
570 call_count: std::sync::atomic::AtomicUsize::new(0),
571 }
572 }
573
574 fn single_response(text: &str) -> Self {
575 Self::new(vec![vec![
576 StreamEvent::message_start("msg_1"),
577 StreamEvent::text_delta(text),
578 StreamEvent::message_end(StopReason::EndTurn),
579 ]])
580 }
581 }
582
583 #[async_trait]
584 impl Provider for MockProvider {
585 fn name(&self) -> &str {
586 "mock"
587 }
588
589 fn model(&self) -> &str {
590 "mock-model"
591 }
592
593 async fn complete(
594 &self,
595 _request: CompletionRequest,
596 ) -> Result<crate::provider::CompletionStream, ProviderError> {
597 let idx = self
598 .call_count
599 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
600 let events = self.responses.get(idx).cloned().unwrap_or_default();
601 Ok(Box::pin(tokio_stream::iter(events)))
602 }
603 }
604
605 struct EchoTool;
607
608 #[async_trait]
609 impl Tool for EchoTool {
610 fn name(&self) -> &str {
611 "echo"
612 }
613
614 fn description(&self) -> &str {
615 "Echoes back the input"
616 }
617
618 fn parameters_schema(&self) -> serde_json::Value {
619 serde_json::json!({
620 "type": "object",
621 "properties": {
622 "message": { "type": "string" }
623 },
624 "required": ["message"]
625 })
626 }
627
628 async fn execute(&self, params: serde_json::Value) -> ToolOutput {
629 let message = params["message"].as_str().unwrap_or("no message");
630 ToolOutput::success(format!("Echo: {}", message))
631 }
632 }
633
634 #[test]
635 fn test_agent_creation() {
636 let provider = Arc::new(MockProvider::single_response("Hello"));
637 let config = AgentConfig::default();
638 let agent = Agent::new(provider, config, test_prompt_store());
639
640 assert!(agent.tools().is_empty());
641 assert!(agent.session().messages.is_empty());
642 }
643
644 #[test]
645 fn test_agent_with_session() {
646 let provider = Arc::new(MockProvider::single_response("Hello"));
647 let config = AgentConfig::default();
648 let mut session = Session::new();
649 session.add_message(Message::user("Previous message"));
650
651 let agent = Agent::with_session(provider, config, test_prompt_store(), session);
652 assert_eq!(agent.session().messages.len(), 1);
653 }
654
655 #[test]
656 fn test_register_tool() {
657 let provider = Arc::new(MockProvider::single_response("Hello"));
658 let config = AgentConfig::default();
659 let mut agent = Agent::new(provider, config, test_prompt_store());
660
661 agent.tools_mut().register(Arc::new(EchoTool));
662 assert!(agent.tools().get("echo").is_some());
663 }
664
665 #[tokio::test]
666 async fn test_simple_run() {
667 let provider = Arc::new(MockProvider::single_response("Hello, I'm Claude!"));
668 let config = AgentConfig::default();
669 let mut agent = Agent::new(provider, config, test_prompt_store());
670
671 let result = agent.run("Hello!").await.unwrap();
672
673 assert_eq!(result.text, "Hello, I'm Claude!");
674 assert!(result.tool_calls.is_empty());
675 assert_eq!(result.stop_reason, StopReason::EndTurn);
676 assert_eq!(result.steps, 1);
677 }
678
679 #[tokio::test]
680 async fn test_run_updates_session() {
681 let provider = Arc::new(MockProvider::single_response("Response"));
682 let config = AgentConfig::default();
683 let mut agent = Agent::new(provider, config, test_prompt_store());
684
685 agent.run("User input").await.unwrap();
686
687 let messages = &agent.session().messages;
689 assert_eq!(messages.len(), 2);
690 assert!(messages[0].is_user());
691 assert!(messages[1].is_assistant());
692 }
693
694 #[tokio::test]
695 async fn test_max_steps_exceeded() {
696 let responses = (0..100)
698 .map(|_| {
699 vec![
700 StreamEvent::message_start("msg"),
701 StreamEvent::ToolCallStart {
702 index: 0,
703 id: "call_1".to_string(),
704 name: "echo".to_string(),
705 },
706 StreamEvent::ToolCallDelta {
707 index: 0,
708 arguments_delta: r#"{"message":"test"}"#.to_string(),
709 },
710 StreamEvent::ToolCallEnd { index: 0 },
711 StreamEvent::MessageEnd {
712 stop_reason: StopReason::ToolUse,
713 usage: None,
714 },
715 ]
716 })
717 .collect();
718
719 let provider = Arc::new(MockProvider::new(responses));
720 let config = AgentConfig::default().with_max_steps(3);
721 let mut agent = Agent::new(provider, config, test_prompt_store());
722 agent.tools_mut().register(Arc::new(EchoTool));
723
724 let result = agent.run("Hello").await;
725 assert!(matches!(result, Err(AgentRunError::MaxStepsExceeded { max_steps: 3 })));
726 }
727
728 #[tokio::test]
729 async fn test_tool_execution() {
730 let responses = vec![
732 vec![
733 StreamEvent::message_start("msg_1"),
734 StreamEvent::text_delta("Let me echo that."),
735 StreamEvent::ToolCallStart {
736 index: 0,
737 id: "call_1".to_string(),
738 name: "echo".to_string(),
739 },
740 StreamEvent::ToolCallDelta {
741 index: 0,
742 arguments_delta: r#"{"message":"hello"}"#.to_string(),
743 },
744 StreamEvent::ToolCallEnd { index: 0 },
745 StreamEvent::MessageEnd {
746 stop_reason: StopReason::ToolUse,
747 usage: None,
748 },
749 ],
750 vec![
751 StreamEvent::message_start("msg_2"),
752 StreamEvent::text_delta("The echo returned: Echo: hello"),
753 StreamEvent::MessageEnd {
754 stop_reason: StopReason::EndTurn,
755 usage: None,
756 },
757 ],
758 ];
759
760 let provider = Arc::new(MockProvider::new(responses));
761 let config = AgentConfig::default();
762 let mut agent = Agent::new(provider, config, test_prompt_store());
763 agent.tools_mut().register(Arc::new(EchoTool));
764
765 let result = agent.run("Echo hello").await.unwrap();
766
767 assert!(result.text.contains("echo"));
768 assert_eq!(result.tool_calls.len(), 1);
769 assert_eq!(result.tool_calls[0].name, "echo");
770 assert_eq!(result.steps, 2);
771 }
772
773 #[tokio::test]
774 async fn test_tool_not_found() {
775 let responses = vec![
776 vec![
777 StreamEvent::message_start("msg_1"),
778 StreamEvent::ToolCallStart {
779 index: 0,
780 id: "call_1".to_string(),
781 name: "nonexistent_tool".to_string(),
782 },
783 StreamEvent::ToolCallDelta {
784 index: 0,
785 arguments_delta: "{}".to_string(),
786 },
787 StreamEvent::ToolCallEnd { index: 0 },
788 StreamEvent::MessageEnd {
789 stop_reason: StopReason::ToolUse,
790 usage: None,
791 },
792 ],
793 vec![
794 StreamEvent::message_start("msg_2"),
795 StreamEvent::text_delta("Tool not found"),
796 StreamEvent::MessageEnd {
797 stop_reason: StopReason::EndTurn,
798 usage: None,
799 },
800 ],
801 ];
802
803 let provider = Arc::new(MockProvider::new(responses));
804 let config = AgentConfig::default();
805 let mut agent = Agent::new(provider, config, test_prompt_store());
806
807 let _result = agent.run("Use unknown tool").await.unwrap();
808
809 let messages = &agent.session().messages;
811 assert_eq!(messages.len(), 4);
813 }
814
815 #[test]
816 fn test_turn_result() {
817 let result = TurnResult::new(
818 "Hello".to_string(),
819 vec![],
820 StopReason::EndTurn,
821 1,
822 );
823
824 assert_eq!(result.text, "Hello");
825 assert!(result.tool_calls.is_empty());
826 assert_eq!(result.stop_reason, StopReason::EndTurn);
827 assert_eq!(result.steps, 1);
828 }
829
830 #[test]
831 fn test_agent_run_error_display() {
832 let err = AgentRunError::tool("Tool failed");
833 assert!(err.to_string().contains("Tool failed"));
834
835 let err = AgentRunError::MaxStepsExceeded { max_steps: 10 };
836 assert!(err.to_string().contains("10"));
837 }
838
839 #[test]
840 fn test_cancellation_error() {
841 let err = AgentRunError::Cancelled;
842 assert!(err.is_cancelled());
843 assert!(err.to_string().contains("cancelled"));
844
845 let err = AgentRunError::tool("some error");
846 assert!(!err.is_cancelled());
847 }
848
849 #[tokio::test]
850 async fn test_run_with_already_cancelled_token() {
851 let provider = Arc::new(MockProvider::single_response("Hello"));
852 let config = AgentConfig::default();
853 let mut agent = Agent::new(provider, config, test_prompt_store());
854
855 let token = CancellationToken::new();
857 token.cancel();
858
859 let result = agent.run_with_cancellation("Hello", Some(token)).await;
860 assert!(matches!(result, Err(AgentRunError::Cancelled)));
861 }
862
863 #[tokio::test]
864 async fn test_run_with_no_cancellation() {
865 let provider = Arc::new(MockProvider::single_response("Hello, I'm Claude!"));
866 let config = AgentConfig::default();
867 let mut agent = Agent::new(provider, config, test_prompt_store());
868
869 let token = CancellationToken::new();
871
872 let result = agent.run_with_cancellation("Hello!", Some(token)).await.unwrap();
873 assert_eq!(result.text, "Hello, I'm Claude!");
874 }
875
876 #[tokio::test]
877 async fn test_run_without_token_works() {
878 let provider = Arc::new(MockProvider::single_response("Response"));
879 let config = AgentConfig::default();
880 let mut agent = Agent::new(provider, config, test_prompt_store());
881
882 let result = agent.run_with_cancellation("Hello", None).await.unwrap();
884 assert_eq!(result.text, "Response");
885 }
886
887 #[tokio::test]
888 async fn test_cancellation_during_tool_loop() {
889 let responses = vec![
891 vec![
892 StreamEvent::message_start("msg_1"),
893 StreamEvent::ToolCallStart {
894 index: 0,
895 id: "call_1".to_string(),
896 name: "echo".to_string(),
897 },
898 StreamEvent::ToolCallDelta {
899 index: 0,
900 arguments_delta: r#"{"message":"test"}"#.to_string(),
901 },
902 StreamEvent::ToolCallEnd { index: 0 },
903 StreamEvent::MessageEnd {
904 stop_reason: StopReason::ToolUse,
905 usage: None,
906 },
907 ],
908 ];
909
910 let provider = Arc::new(MockProvider::new(responses));
911 let config = AgentConfig::default();
912 let mut agent = Agent::new(provider, config, test_prompt_store());
913 agent.tools_mut().register(Arc::new(EchoTool));
914
915 let token = CancellationToken::new();
916 let cancel_token = token.clone();
917
918 tokio::spawn(async move {
921 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
922 cancel_token.cancel();
923 });
924
925 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
927
928 let result = agent.run_with_cancellation("Use tool", Some(token)).await;
931
932 assert!(result.is_ok() || matches!(result, Err(AgentRunError::Cancelled)));
934 }
935}