trae-agent-rs-core 0.0.1

Core library for Trae Agent - LLM-based agent for software engineering tasks
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
//! TraeAgent implementation

use crate::agent::prompt::{build_system_prompt_with_context, build_user_message};
use crate::agent::{Agent, AgentExecution, AgentResult};
use crate::config::{AgentConfig, Config};

use crate::error::{AgentError, Result};
use crate::llm::{ChatOptions, LlmClient, LlmMessage, LlmResponse};
use crate::output::{
    AgentEvent, AgentExecutionContext, AgentOutput, TokenUsage, ToolExecutionInfo,
    ToolExecutionInfoBuilder, ToolExecutionStatus,
};
use crate::tools::{ToolExecutor, ToolRegistry};
use crate::trajectory::{TrajectoryEntry, TrajectoryRecorder};
use async_trait::async_trait;
use futures::StreamExt;
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;

/// TraeAgent - the main agent implementation
pub struct TraeAgent {
    config: AgentConfig,
    llm_client: Arc<dyn LlmClient>,
    tool_executor: ToolExecutor,
    trajectory_recorder: Option<TrajectoryRecorder>,
    conversation_history: Vec<LlmMessage>,
    output: Box<dyn AgentOutput>,
    current_task_displayed: bool,
    execution_context: Option<AgentExecutionContext>,
}

impl TraeAgent {
    /// Create a new TraeAgent with output handler
    pub async fn new_with_output(
        agent_config: AgentConfig,
        config: Config,
        output: Box<dyn AgentOutput>,
    ) -> Result<Self> {
        // Get model configuration
        let model_config = config
            .get_model(&agent_config.model)
            .ok_or_else(|| AgentError::NotInitialized)?
            .clone();

        // Get provider configuration
        let provider_config = config
            .get_provider(&model_config.model_provider)
            .ok_or_else(|| AgentError::NotInitialized)?
            .clone();

        // Create LLM client
        let llm_client: Arc<dyn LlmClient> = match provider_config.provider.as_str() {
            "anthropic" => Arc::new(crate::llm::AnthropicClient::new(
                &provider_config,
                &model_config,
            )?),
            "openai" => Arc::new(crate::llm::OpenAiClient::new(
                &provider_config,
                &model_config,
            )?),
            _ => {
                return Err(AgentError::NotInitialized.into());
            }
        };

        // Create tool executor
        let tool_registry = ToolRegistry::default();
        let tool_executor = tool_registry.create_executor(&agent_config.tools);

        Ok(Self {
            config: agent_config,
            llm_client,
            tool_executor,
            trajectory_recorder: None,
            conversation_history: Vec::new(),
            output,
            current_task_displayed: false,
            execution_context: None,
        })
    }

    /// Create a new TraeAgent with custom tool registry and output handler
    pub async fn new_with_output_and_registry(
        agent_config: AgentConfig,
        config: Config,
        output: Box<dyn AgentOutput>,
        tool_registry: ToolRegistry,
    ) -> Result<Self> {
        // Get model configuration
        let model_config = config
            .get_model(&agent_config.model)
            .ok_or_else(|| AgentError::NotInitialized)?
            .clone();

        // Get provider configuration
        let provider_config = config
            .get_provider(&model_config.model_provider)
            .ok_or_else(|| AgentError::NotInitialized)?
            .clone();

        // Create LLM client
        let llm_client: Arc<dyn LlmClient> = match provider_config.provider.as_str() {
            "anthropic" => Arc::new(crate::llm::AnthropicClient::new(
                &provider_config,
                &model_config,
            )?),
            "openai" => Arc::new(crate::llm::OpenAiClient::new(
                &provider_config,
                &model_config,
            )?),
            _ => {
                return Err(AgentError::NotInitialized.into());
            }
        };

        // Create tool executor with custom registry
        let tool_executor = tool_registry.create_executor(&agent_config.tools);

        Ok(Self {
            config: agent_config,
            llm_client,
            tool_executor,
            trajectory_recorder: None,
            conversation_history: Vec::new(),
            output,
            current_task_displayed: false,
            execution_context: None,
        })
    }

    /// Create a new TraeAgent with default null output (for backward compatibility)
    pub async fn new(agent_config: AgentConfig, config: Config) -> Result<Self> {
        use crate::output::events::NullOutput;
        Self::new_with_output(agent_config, config, Box::new(NullOutput)).await
    }

    /// Set a custom system prompt for the agent
    /// This will override any system prompt set in the configuration
    pub fn set_system_prompt(&mut self, system_prompt: Option<String>) {
        self.config.system_prompt = system_prompt;
    }

    /// Get the current system prompt from configuration
    pub fn get_configured_system_prompt(&self) -> Option<&String> {
        self.config.system_prompt.as_ref()
    }

    /// Get the system prompt for the agent with project context
    fn get_system_prompt(&self, project_path: &Path) -> String {
        // Use custom system prompt if provided, otherwise use default
        let base_prompt = if let Some(custom_prompt) = &self.config.system_prompt {
            // If custom prompt is provided, use it as-is with minimal generic context
            let system_context = crate::agent::prompt::build_system_context();

            format!(
                "{}\n\n\
                 [System Context]:\n{}",
                custom_prompt, system_context
            )
        } else {
            // Use default system prompt with full environment context from prompt.rs
            build_system_prompt_with_context(project_path)
        };

        format!(
            "{}\n\nAvailable tools: {}",
            base_prompt,
            self.tool_executor.list_tools().join(", ")
        )
    }

    /// Execute a step with streaming LLM response
    async fn execute_step_with_streaming(
        &mut self,
        messages: Vec<LlmMessage>,
        tool_definitions: Vec<crate::llm::ToolDefinition>,
        _step: usize,
    ) -> Result<LlmResponse> {
        // Set up streaming options
        let options = Some(ChatOptions {
            stream: Some(true),
            ..Default::default()
        });

        // Start streaming
        let mut stream = self
            .llm_client
            .chat_completion_stream(messages, Some(tool_definitions), options)
            .await?;

        let mut full_content = String::new();
        let mut final_usage = None;
        let mut final_finish_reason = None;
        let mut tool_call_accumulator: std::collections::HashMap<String, (String, String)> =
            std::collections::HashMap::new();

        // Log agent thinking in debug mode
        let _ = self.output.debug("🤖 Agent thinking...").await;

        // Process stream chunks
        while let Some(chunk_result) = stream.next().await {
            match chunk_result {
                Ok(chunk) => {
                    if let Some(delta) = chunk.delta {
                        // Emit streaming content through output handler
                        self.output.normal(&delta).await.unwrap_or_else(|e| {
                            // Use debug level for internal errors to avoid noise
                            let _ = futures::executor::block_on(
                                self.output
                                    .debug(&format!("Failed to emit streaming content: {}", e)),
                            );
                        });
                        full_content.push_str(&delta);
                    }

                    // Accumulate tool calls from streaming
                    if let Some(tool_calls) = chunk.tool_calls {
                        for tool_call in tool_calls {
                            let id = tool_call.id.clone();
                            let name = tool_call.name.clone();
                            let params_str = match &tool_call.parameters {
                                serde_json::Value::String(s) => s.clone(),
                                other => other.to_string(),
                            };

                            // Accumulate tool call data
                            let entry = tool_call_accumulator
                                .entry(id)
                                .or_insert((String::new(), String::new()));
                            if !name.is_empty() {
                                entry.0 = name; // Update name
                            }
                            entry.1.push_str(&params_str); // Accumulate parameters
                        }
                    }

                    if let Some(usage) = chunk.usage {
                        final_usage = Some(usage);
                    }

                    if let Some(finish_reason) = chunk.finish_reason {
                        final_finish_reason = Some(finish_reason);
                        break;
                    }
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }

        // Add newline after streaming through output handler
        self.output.normal("").await.unwrap_or_else(|e| {
            let _ = futures::executor::block_on(
                self.output.debug(&format!("Failed to emit newline: {}", e)),
            );
        });

        // Construct the final response with accumulated tool calls
        let mut final_tool_calls = Vec::new();

        for (id, (name, params_str)) in tool_call_accumulator {
            if !name.is_empty() && !params_str.is_empty() {
                // Parse the accumulated parameters as JSON
                match serde_json::from_str(&params_str) {
                    Ok(params) => {
                        final_tool_calls.push(crate::llm::ContentBlock::ToolUse {
                            id,
                            name,
                            input: params,
                        });
                    }
                    Err(_e) => {
                        // Truncate error message for tool params parsing
                        let truncated_params = if params_str.len() > 100 {
                            format!("{}...", &params_str[..100])
                        } else {
                            params_str
                        };
                        self.output
                            .warning(&format!(
                                "🔧 Failed to parse tool params: {}",
                                truncated_params
                            ))
                            .await
                            .unwrap_or_else(|e| {
                                let _ = futures::executor::block_on(
                                    self.output
                                        .debug(&format!("Failed to emit tool params error: {}", e)),
                                );
                            });
                    }
                }
            }
        }

        let message_content = if final_tool_calls.is_empty() {
            crate::llm::MessageContent::Text(full_content)
        } else {
            let mut content_blocks = Vec::new();
            if !full_content.is_empty() {
                content_blocks.push(crate::llm::ContentBlock::Text { text: full_content });
            }
            content_blocks.extend(final_tool_calls);
            crate::llm::MessageContent::MultiModal(content_blocks)
        };

        let response = LlmResponse {
            message: LlmMessage {
                role: crate::llm::MessageRole::Assistant,
                content: message_content,
                metadata: None,
            },
            usage: final_usage,
            model: self.llm_client.model_name().to_string(),
            finish_reason: final_finish_reason,
            metadata: None,
        };

        Ok(response)
    }

    /// Execute a single step of the agent
    async fn execute_step(&mut self, step: usize, project_path: &Path) -> Result<bool> {
        // Prepare messages - only add system prompt if conversation history doesn't start with one
        let mut messages = Vec::new();
        let needs_system_prompt = self.conversation_history.is_empty()
            || !matches!(
                self.conversation_history[0].role,
                crate::llm::MessageRole::System
            );

        if needs_system_prompt {
            messages.push(LlmMessage::system(self.get_system_prompt(project_path)));
        }
        messages.extend(self.conversation_history.clone());

        // Record LLM request
        if let Some(recorder) = &self.trajectory_recorder {
            recorder
                .record(TrajectoryEntry::llm_request(
                    messages.clone(),
                    self.llm_client.model_name().to_string(),
                    self.llm_client.provider_name().to_string(),
                    step,
                ))
                .await?;
        }

        // Get tool definitions
        let tool_definitions = self.tool_executor.get_tool_definitions();

        // Log agent thinking in debug mode
        let _ = self.output.debug("🤖 Agent thinking...").await;

        // Set up options
        let options = Some(ChatOptions {
            ..Default::default()
        });

        // Make LLM request (non-streaming)
        let response = self
            .llm_client
            .chat_completion(messages, Some(tool_definitions), options)
            .await?;

        // Update token usage
        if let Some(usage) = &response.usage {
            if let Some(context) = &mut self.execution_context {
                context.token_usage.input_tokens += usage.prompt_tokens;
                context.token_usage.output_tokens += usage.completion_tokens;
                context.token_usage.total_tokens += usage.total_tokens;

                // Emit token update event immediately after LLM call
                self.output
                    .emit_token_update(context.token_usage.clone())
                    .await
                    .unwrap_or_else(|e| {
                        let _ = futures::executor::block_on(
                            self.output
                                .debug(&format!("Failed to emit token update event: {}", e)),
                        );
                    });
            }
        }

        // Record LLM response
        if let Some(recorder) = &self.trajectory_recorder {
            recorder
                .record(TrajectoryEntry::llm_response(
                    response.message.clone(),
                    response.usage.clone(),
                    response.finish_reason.as_ref().map(|r| format!("{:?}", r)),
                    step,
                ))
                .await?;
        }

        // Add response to conversation history
        self.conversation_history.push(response.message.clone());

        // Check if there are tool calls to execute
        if response.message.has_tool_use() {
            let tool_uses = response.message.get_tool_uses();

            for tool_use in tool_uses {
                if let crate::llm::ContentBlock::ToolUse { id, name, input } = tool_use {
                    // Display tool execution based on output mode
                    let tool_call = crate::tools::ToolCall {
                        id: id.clone(),
                        name: name.clone(),
                        parameters: input.clone(),
                        metadata: None,
                    };

                    // Create tool execution info and emit started event
                    let tool_info = ToolExecutionInfo::create_tool_execution_info(
                        &tool_call,
                        ToolExecutionStatus::Executing,
                        None,
                    );

                    self.output
                        .emit_event(AgentEvent::ToolExecutionStarted {
                            tool_info: tool_info.clone(),
                        })
                        .await
                        .unwrap_or_else(|e| {
                            let _ = futures::executor::block_on(self.output.debug(&format!(
                                "Failed to emit tool execution started event: {}",
                                e
                            )));
                        });

                    // Record tool call
                    if let Some(recorder) = &self.trajectory_recorder {
                        recorder
                            .record(TrajectoryEntry::tool_call(tool_call.clone(), step))
                            .await?;
                    }

                    // Execute tool
                    let tool_result = self.tool_executor.execute(tool_call.clone()).await?;

                    // Create completed tool execution info and emit completed event
                    let completed_tool_info = ToolExecutionInfo::create_tool_execution_info(
                        &tool_call,
                        if tool_result.success {
                            ToolExecutionStatus::Success
                        } else {
                            ToolExecutionStatus::Error
                        },
                        Some(&tool_result),
                    );

                    self.output
                        .emit_event(AgentEvent::ToolExecutionCompleted {
                            tool_info: completed_tool_info,
                        })
                        .await
                        .unwrap_or_else(|e| {
                            let _ = futures::executor::block_on(self.output.debug(&format!(
                                "Failed to emit tool execution completed event: {}",
                                e
                            )));
                        });

                    // Handle special tool behaviors
                    if name == "sequentialthinking" {
                        // For thinking tool, emit thinking event
                        if let Some(data) = &tool_result.data {
                            if let Some(thought) = data.get("thought") {
                                if let Some(thought_str) = thought.as_str() {
                                    self.output
                                        .emit_event(AgentEvent::AgentThinking {
                                            step_number: step,
                                            thinking: thought_str.to_string(),
                                        })
                                        .await
                                        .unwrap_or_else(|e| {
                                            let _ = futures::executor::block_on(self.output.debug(
                                                &format!("Failed to emit thinking event: {}", e),
                                            ));
                                        });
                                }
                            }
                        } else {
                            // Fallback: try to extract from content
                            if let Some(start) = tool_result.content.find("Thought: ") {
                                let thought_start = start + "Thought: ".len();
                                if let Some(end) = tool_result.content[thought_start..].find("\n\n")
                                {
                                    let thought =
                                        &tool_result.content[thought_start..thought_start + end];
                                    self.output
                                        .emit_event(AgentEvent::AgentThinking {
                                            step_number: step,
                                            thinking: thought.to_string(),
                                        })
                                        .await
                                        .unwrap_or_else(|e| {
                                            let _ = futures::executor::block_on(self.output.debug(
                                                &format!("Failed to emit thinking event: {}", e),
                                            ));
                                        });
                                }
                            }
                        }
                    }

                    // Record tool result
                    if let Some(recorder) = &self.trajectory_recorder {
                        recorder
                            .record(TrajectoryEntry::tool_result(tool_result.clone(), step))
                            .await?;
                    }

                    // Check if this is a task completion
                    if name == "task_done" && tool_result.success {
                        return Ok(true); // Task completed
                    }

                    // Add tool result to conversation
                    let result_message = LlmMessage {
                        role: crate::llm::MessageRole::Tool,
                        content: crate::llm::MessageContent::MultiModal(vec![
                            crate::llm::ContentBlock::ToolResult {
                                tool_use_id: id.clone(),
                                is_error: Some(!tool_result.success),
                                content: tool_result.content,
                            },
                        ]),
                        metadata: None,
                    };

                    self.conversation_history.push(result_message);
                }
            }

            // After executing tools, proceed to the next step.
            // Align with Python scheduler: one LLM call per step; tool results are appended,
            // and the next step will let the LLM process those results.
            return Ok(false);
        }

        // If no tool calls, handle text response
        if let Some(text_content) = response.message.get_text() {
            if !text_content.trim().is_empty() {
                // Emit the agent's text response as a normal message
                self.output.normal(&text_content).await.unwrap_or_else(|e| {
                    let _ = futures::executor::block_on(
                        self.output
                            .debug(&format!("Failed to emit agent response message: {}", e)),
                    );
                });
            }
        }

        // If no tool calls, we're done for this step
        Ok(false)
    }
}

#[async_trait]
impl Agent for TraeAgent {
    async fn execute_task(&mut self, task: &str) -> AgentResult<AgentExecution> {
        // Use execute_task_with_context with current directory as default
        let current_dir = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        self.execute_task_with_context(task, &current_dir).await
    }

    fn config(&self) -> &AgentConfig {
        &self.config
    }

    fn agent_type(&self) -> &str {
        "trae_agent"
    }

    fn set_trajectory_recorder(&mut self, recorder: TrajectoryRecorder) {
        self.trajectory_recorder = Some(recorder);
    }

    fn trajectory_recorder(&self) -> Option<&TrajectoryRecorder> {
        self.trajectory_recorder.as_ref()
    }
}

impl TraeAgent {
    /// Execute a task with project context (like Python version)
    pub async fn execute_task_with_context(
        &mut self,
        task: &str,
        project_path: &Path,
    ) -> AgentResult<AgentExecution> {
        let start_time = Instant::now();

        // Initialize conversation with system prompt and user message with context
        self.conversation_history.clear();
        // Reset task display flag when starting a new conversation
        self.current_task_displayed = false;

        // Create execution context
        self.execution_context = Some(AgentExecutionContext {
            agent_id: "trae_agent".to_string(),
            task: task.to_string(),
            project_path: project_path.to_string_lossy().to_string(),
            max_steps: self.config.max_steps,
            current_step: 0,
            execution_time: std::time::Duration::from_secs(0),
            token_usage: TokenUsage::default(),
        });

        // Emit execution started event
        if let Some(context) = &self.execution_context {
            self.output
                .emit_event(AgentEvent::ExecutionStarted {
                    context: context.clone(),
                })
                .await
                .unwrap_or_else(|e| {
                    let _ = futures::executor::block_on(
                        self.output
                            .debug(&format!("Failed to emit execution started event: {}", e)),
                    );
                });
        }

        self.current_task_displayed = true;

        // Record task start
        if let Some(recorder) = &self.trajectory_recorder {
            recorder
                .record(TrajectoryEntry::task_start(
                    task.to_string(),
                    serde_json::to_value(&self.config).unwrap_or_default(),
                ))
                .await?;
        }

        // Add system prompt with tool information and environment context
        self.conversation_history
            .push(LlmMessage::system(self.get_system_prompt(project_path)));

        // Add user message with task only (environment context is now in system prompt)
        let user_message = build_user_message(task);
        self.conversation_history
            .push(LlmMessage::user(&user_message));

        let mut step = 0;
        let mut task_completed = false;

        // Execute steps until completion or max steps reached
        while step < self.config.max_steps && !task_completed {
            step += 1;

            match self.execute_step(step, project_path).await {
                Ok(completed) => {
                    task_completed = completed;

                    // Record step completion
                    if let Some(recorder) = &self.trajectory_recorder {
                        recorder
                            .record(TrajectoryEntry::step_complete(
                                format!("Step {} completed", step),
                                true,
                                step,
                            ))
                            .await?;
                    }
                }
                Err(e) => {
                    // Record error
                    if let Some(recorder) = &self.trajectory_recorder {
                        recorder
                            .record(TrajectoryEntry::error(
                                e.to_string(),
                                Some(format!("Step {}", step)),
                                step,
                            ))
                            .await?;
                    }

                    let duration = start_time.elapsed().as_millis() as u64;
                    return Ok(AgentExecution::failure(
                        format!("Error in step {}: {}", step, e),
                        step,
                        duration,
                    ));
                }
            }
        }

        let duration = start_time.elapsed();

        // Update execution context
        if let Some(context) = &mut self.execution_context {
            context.current_step = step;
            context.execution_time = duration;
        }

        // Record task completion
        if let Some(recorder) = &self.trajectory_recorder {
            recorder
                .record(TrajectoryEntry::task_complete(
                    task_completed,
                    if task_completed {
                        "Task completed successfully".to_string()
                    } else {
                        format!("Task incomplete after {} steps", step)
                    },
                    step,
                    duration.as_millis() as u64,
                ))
                .await?;
        }

        // Emit execution completed event
        if let Some(context) = &self.execution_context {
            let summary = if task_completed {
                "Task completed successfully".to_string()
            } else {
                format!("Task incomplete after {} steps", step)
            };

            self.output
                .emit_event(AgentEvent::ExecutionCompleted {
                    context: context.clone(),
                    success: task_completed,
                    summary: summary.clone(),
                })
                .await
                .unwrap_or_else(|e| {
                    let _ = futures::executor::block_on(
                        self.output
                            .debug(&format!("Failed to emit execution completed event: {}", e)),
                    );
                });
        }

        let duration_ms = duration.as_millis() as u64;

        if task_completed {
            Ok(AgentExecution::success(
                "Task completed successfully".to_string(),
                step,
                duration_ms,
            ))
        } else {
            Ok(AgentExecution::failure(
                format!("Task incomplete after {} steps", step),
                step,
                duration_ms,
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::AgentConfig;
    use crate::error::Result;
    use crate::llm::{
        ChatOptions, LlmClient, LlmMessage, LlmResponse, MessageContent, MessageRole,
        ToolDefinition,
    };
    use async_trait::async_trait;

    // Mock LLM client for testing
    struct MockLlmClient;

    impl MockLlmClient {
        fn new() -> Self {
            Self
        }
    }

    #[async_trait]
    impl LlmClient for MockLlmClient {
        async fn chat_completion(
            &self,
            _messages: Vec<LlmMessage>,
            _tools: Option<Vec<ToolDefinition>>,
            _options: Option<ChatOptions>,
        ) -> Result<LlmResponse> {
            Ok(LlmResponse {
                message: LlmMessage {
                    role: MessageRole::Assistant,
                    content: MessageContent::Text("Mock response".to_string()),
                    metadata: None,
                },
                usage: None,
                model: "mock-model".to_string(),
                finish_reason: None,
                metadata: None,
            })
        }

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

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

    #[test]
    fn test_system_prompt_configuration() {
        // Test AgentConfig with custom system prompt
        let mut agent_config = AgentConfig::default();
        agent_config.system_prompt = Some("Custom system prompt for testing".to_string());

        assert_eq!(
            agent_config.system_prompt,
            Some("Custom system prompt for testing".to_string())
        );

        // Test default AgentConfig has no system prompt
        let default_config = AgentConfig::default();
        assert_eq!(default_config.system_prompt, None);
    }

    #[test]
    fn test_system_prompt_serialization() {
        // Test that AgentConfig with system_prompt can be serialized/deserialized
        let mut config = AgentConfig::default();
        config.system_prompt = Some("Custom prompt".to_string());

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: AgentConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(
            deserialized.system_prompt,
            Some("Custom prompt".to_string())
        );
    }

    #[test]
    fn test_system_prompt_default_none() {
        // Test that default AgentConfig has None for system_prompt
        let config = AgentConfig::default();
        assert_eq!(config.system_prompt, None);
    }

    #[test]
    fn test_custom_system_prompt_excludes_project_context() {
        // Test that custom system prompt doesn't include project-specific information
        use crate::output::events::NullOutput;
        use crate::tools::ToolRegistry;
        use std::path::PathBuf;

        // Create a mock agent with custom system prompt
        let mut agent_config = AgentConfig::default();
        agent_config.system_prompt = Some("You are a general purpose AI assistant.".to_string());

        // Create minimal components for testing
        let tool_registry = ToolRegistry::default();
        let tool_executor = tool_registry.create_executor(&agent_config.tools);

        let agent = TraeAgent {
            config: agent_config,
            llm_client: std::sync::Arc::new(MockLlmClient::new()),
            tool_executor,
            trajectory_recorder: None,
            conversation_history: Vec::new(),
            output: Box::new(NullOutput),
            current_task_displayed: false,
            execution_context: None,
        };

        let project_path = PathBuf::from("/some/project/path");
        let system_prompt = agent.get_system_prompt(&project_path);

        // Should contain the custom prompt
        assert!(system_prompt.contains("You are a general purpose AI assistant."));

        // Should contain system context (OS, architecture, etc.)
        assert!(system_prompt.contains("System Information:"));
        assert!(system_prompt.contains("Operating System:"));

        // Should contain available tools
        assert!(system_prompt.contains("Available tools:"));

        // Should NOT contain project-specific information
        assert!(!system_prompt.contains("Project root path"));
        assert!(!system_prompt.contains("/some/project/path"));
        assert!(!system_prompt.contains("IMPORTANT: When using tools that require file paths"));
        assert!(!system_prompt.contains("You are an expert AI software engineering agent"));
    }
}