opencrates 3.0.1

Enterprise-grade AI-powered Rust development companion with comprehensive automation, monitoring, and deployment capabilities
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
//! CodexProvider implementation for OpenAI Codex integration
//!
//! This provider integrates with OpenAI's API to provide advanced AI-powered code generation,
//! analysis, and patch application capabilities. It supports streaming responses, comprehensive
//! error handling, and production-ready features.
//!
//! # Features
//!
//! - Real-time code generation using OpenAI's latest models
//! - Streaming response handling for improved user experience
//! - Comprehensive error handling and retry logic
//! - Health monitoring and connection validation
//! - Integration with vendored patch application system
//! - Configurable temperature, token limits, and model selection
//! - Usage tracking and metrics collection
//!
//! # Example
//!
//! ```rust
//! use opencrates::providers::codex::CodexProvider;
//! use opencrates::utils::config::CodexConfig;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let config = CodexConfig {
//!         api_key: Some("your-api-key".to_string()),
//!         model: "gpt-4".to_string(),
//!         max_tokens: 2048,
//!         temperature: 0.7,
//!         ..Default::default()
//!     };
//!
//!     let provider = CodexProvider::new(config).await?;
//!     let code = provider.generate_code("Create a binary search function in Rust", None).await?;
//!     println!("Generated code: {}", code);
//!     Ok(())
//! }
//! ```

use crate::codex_vendored::apply_patch;
use crate::providers::{
    model_types::{ModelProviderInfo, Prompt},
    GenerationRequest, GenerationResponse, LLMProvider,
};
use crate::utils::config::CodexConfig;
use crate::utils::error::OpenCratesError;
use crate::utils::metrics::TokenUsage;
use crate::utils::openai_agents::Usage;
use async_trait::async_trait;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::io::{self, Write};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::time::timeout;
use tracing::{debug, error, info, warn};

/// `OpenAI` API response structure for chat completions
#[derive(Debug, Clone, Serialize, Deserialize)]
struct OpenAIResponse {
    id: Option<String>,
    object: Option<String>,
    created: Option<u64>,
    model: String,
    choices: Vec<Choice>,
    usage: Option<OpenAIUsage>,
}

/// Choice structure from `OpenAI` API response
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Choice {
    index: u32,
    message: Option<Message>,
    delta: Option<Delta>,
    finish_reason: Option<String>,
}

/// Message structure for `OpenAI` API
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Message {
    role: String,
    content: String,
}

/// Delta structure for streaming responses
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Delta {
    role: Option<String>,
    content: Option<String>,
}

/// Usage statistics from `OpenAI` API
#[derive(Debug, Clone, Serialize, Deserialize)]
struct OpenAIUsage {
    prompt_tokens: u32,
    completion_tokens: u32,
    total_tokens: u32,
}

/// Request structure for `OpenAI` API
#[derive(Debug, Clone, Serialize, Deserialize)]
struct OpenAIRequest {
    model: String,
    messages: Vec<Message>,
    max_tokens: Option<u32>,
    temperature: Option<f32>,
    stream: bool,
}

/// `CodexProvider` integrates with `OpenAI`'s API for advanced code generation and manipulation
///
/// This provider offers enterprise-grade features including:
/// - Real-time streaming code generation
/// - Comprehensive error handling and retry logic
/// - Health monitoring and connection validation
/// - Usage tracking and metrics
/// - Integration with patch application system
#[derive(Clone)]
pub struct CodexProvider {
    config: CodexConfig,
    client: reqwest::Client,
    api_base: String,
}

impl CodexProvider {
    /// Create a new `CodexProvider` instance with the specified configuration
    ///
    /// # Arguments
    /// * `config` - Configuration containing API key, model settings, and other parameters
    ///
    /// # Returns
    /// A Result containing the configured `CodexProvider` or an error
    ///
    /// # Examples
    /// ```rust
    /// use opencrates::providers::codex::CodexProvider;
    /// use opencrates::utils::config::CodexConfig;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let config = CodexConfig {
    ///         api_key: Some("sk-...".to_string()),
    ///         model: "gpt-4".to_string(),
    ///         ..Default::default()
    ///     };
    ///     let provider = CodexProvider::new(config).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn new(config: CodexConfig) -> Result<Self, OpenCratesError> {
        info!("Initializing CodexProvider with model: {}", config.model);

        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        if let Some(ref api_key) = config.api_key {
            let auth_value = HeaderValue::from_str(&format!("Bearer {api_key}"))
                .map_err(|e| OpenCratesError::Config(format!("Invalid API key format: {e}")))?;
            headers.insert(AUTHORIZATION, auth_value);
        } else {
            warn!("No API key provided - using environment variable fallback");
            if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
                let auth_value =
                    HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|e| {
                        OpenCratesError::Config(format!(
                            "Invalid API key format from environment: {e}"
                        ))
                    })?;
                headers.insert(AUTHORIZATION, auth_value);
            }
        }

        let client = reqwest::Client::builder()
            .default_headers(headers)
            .timeout(Duration::from_secs(120))
            .build()
            .map_err(|e| OpenCratesError::internal(format!("Failed to create HTTP client: {e}")))?;

        let api_base = config.api_base.clone();

        let provider = Self {
            config,
            client,
            api_base,
        };

        // Validate connection on initialization
        if let Err(e) = provider.verify_connection().await {
            warn!("Initial connection validation failed: {}", e);
        }

        Ok(provider)
    }

    /// Create a new `CodexProvider` with default configuration
    ///
    /// Uses environment variables for configuration when available:
    /// - `OPENAI_API_KEY` for authentication
    /// - `OPENAI_API_BASE` for custom API endpoint (optional)
    /// - `OPENAI_MODEL` for model selection (optional)
    pub async fn new_default() -> Result<Self, OpenCratesError> {
        let mut config = CodexConfig::default();

        // Override with environment variables if available
        if let Ok(api_key) = std::env::var("OPENAI_API_KEY") {
            config.api_key = Some(api_key);
        }

        if let Ok(api_base) = std::env::var("OPENAI_API_BASE") {
            config.api_base = api_base;
        }

        if let Ok(model) = std::env::var("OPENAI_MODEL") {
            config.model = model;
        }

        Self::new(config).await
    }

    /// Make a chat completion request to `OpenAI` API
    ///
    /// # Arguments
    /// * `prompt_text` - The input prompt for code generation
    /// * `system_message` - Optional system message to guide behavior
    ///
    /// # Returns
    /// Generated text response or an error
    async fn get_chat_completion(
        &self,
        prompt_text: &str,
        system_message: Option<&str>,
    ) -> Result<(String, TokenUsage), OpenCratesError> {
        let start_time = Instant::now();
        debug!(
            "Starting chat completion for prompt: {:.100}...",
            prompt_text
        );

        let mut messages = Vec::new();

        if let Some(system_msg) = system_message {
            messages.push(Message {
                role: "system".to_string(),
                content: system_msg.to_string(),
            });
        }

        messages.push(Message {
            role: "user".to_string(),
            content: prompt_text.to_string(),
        });

        let request = OpenAIRequest {
            model: self.config.model.clone(),
            messages,
            max_tokens: Some(self.config.max_tokens),
            temperature: Some(self.config.temperature),
            stream: false,
        };

        let url = format!("{}/chat/completions", self.api_base);

        let response = timeout(
            Duration::from_secs(120),
            self.client.post(&url).json(&request).send(),
        )
        .await
        .map_err(|e| OpenCratesError::Network(format!("Request timed out: {e}")))?
        .map_err(|e| OpenCratesError::Network(format!("Failed to send request: {e}")))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| OpenCratesError::Network(format!("Failed to read response body: {e}")))?;

        if !status.is_success() {
            error!("OpenAI API error: {} - {}", status, response_text);
            return Err(OpenCratesError::external(format!(
                "OpenAI API error: {status} - {response_text}"
            )));
        }

        let openai_response: OpenAIResponse =
            serde_json::from_str(&response_text).map_err(OpenCratesError::Serialization)?;

        let content = openai_response
            .choices
            .first()
            .and_then(|choice| choice.message.as_ref())
            .map(|msg| msg.content.clone())
            .unwrap_or_default();

        let usage = openai_response.usage.map_or(
            TokenUsage {
                prompt_tokens: 0,
                completion_tokens: 0,
                total_tokens: 0,
            },
            |u| TokenUsage {
                prompt_tokens: u.prompt_tokens as usize,
                completion_tokens: u.completion_tokens as usize,
                total_tokens: u.total_tokens as usize,
            },
        );

        let duration = start_time.elapsed();
        info!(
            "Chat completion completed in {:.2}s, tokens: {}",
            duration.as_secs_f64(),
            usage.total_tokens
        );

        Ok((content, usage))
    }

    /// Apply a patch to a file using the vendored `apply_patch` functionality
    ///
    /// # Arguments
    /// * `file_path` - Path to the file to be patched
    /// * `patch_content` - The patch content in standard format
    ///
    /// # Returns
    /// Result indicating success or failure
    ///
    /// # Examples
    /// ```rust
    /// # use opencrates::providers::codex::CodexProvider;
    /// # use opencrates::utils::config::CodexConfig;
    /// # use std::path::Path;
    /// #
    /// # async fn example() -> anyhow::Result<()> {
    /// let provider = CodexProvider::new(CodexConfig::default()).await?;
    /// let patch = "*** Begin Patch\n*** Update File: src/main.rs\n+println!(\"Hello\");\n*** End Patch";
    /// provider.apply_patch(Path::new("src/main.rs"), patch)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn apply_patch(
        &self,
        file_path: &std::path::Path,
        patch_content: &str,
    ) -> Result<(), OpenCratesError> {
        info!("Applying patch to file: {}", file_path.display());
        debug!("Patch content: {}", patch_content);

        let mut stdout = io::stdout();
        let mut stderr = io::stderr();

        apply_patch(patch_content, &mut stdout, &mut stderr).map_err(|e| {
            OpenCratesError::internal(format!(
                "Failed to apply patch to {}: {}",
                file_path.display(),
                e
            ))
        })
    }

    /// Generate code with specific instructions and optional context
    ///
    /// # Arguments
    /// * `instruction` - The code generation instruction
    /// * `context` - Optional context to guide generation
    ///
    /// # Returns
    /// Generated code as a string
    ///
    /// # Examples
    /// ```rust
    /// # use opencrates::providers::codex::CodexProvider;
    /// # use opencrates::utils::config::CodexConfig;
    /// #
    /// # async fn example() -> anyhow::Result<()> {
    /// let provider = CodexProvider::new(CodexConfig::default()).await?;
    /// let code = provider.generate_code(
    ///     "Create a function to calculate fibonacci numbers",
    ///     Some("The function should be efficient and handle edge cases")
    /// ).await?;
    /// println!("Generated: {}", code);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn generate_code(
        &self,
        instruction: &str,
        context: Option<&str>,
    ) -> Result<String, OpenCratesError> {
        let system_message = "You are an expert Rust programmer. Generate clean, efficient, and well-documented code. Include appropriate error handling and follow Rust best practices.";

        let prompt = if let Some(ctx) = context {
            format!(
                "Context:\n{ctx}\n\nInstruction:\n{instruction}\n\nGenerate the requested Rust code:"
            )
        } else {
            format!("Instruction:\n{instruction}\n\nGenerate the requested Rust code:")
        };

        let (content, _usage) = self
            .get_chat_completion(&prompt, Some(system_message))
            .await?;
        Ok(content)
    }

    /// Verify API connectivity and authentication
    ///
    /// Performs a minimal API call to verify that the provider can successfully
    /// communicate with the `OpenAI` API.
    ///
    /// # Returns
    /// `true` if connection is successful, `false` otherwise
    pub async fn verify_connection(&self) -> Result<bool, OpenCratesError> {
        debug!("Verifying OpenAI API connection");

        match self
            .get_chat_completion("Test", Some("Respond with 'OK'"))
            .await
        {
            Ok((response, _)) => {
                debug!("Connection verification successful: {}", response);
                Ok(true)
            }
            Err(e) => {
                warn!("Connection verification failed: {}", e);
                Ok(false)
            }
        }
    }

    /// Get model information and capabilities
    ///
    /// # Returns
    /// Information about the currently configured model
    #[must_use]
    pub fn get_model_info(&self) -> ModelProviderInfo {
        ModelProviderInfo {
            base_url: self.api_base.clone(),
            api_key: self.config.api_key.clone(),
            name: self.config.model.clone(),
            provider: "OpenAI".to_string(),
            max_tokens: self.config.max_tokens,
            supports_streaming: true,
            supports_functions: true,
            context_window: match self.config.model.as_str() {
                "gpt-4" => 8192,
                "gpt-4-32k" => 32768,
                "gpt-4-turbo" => 128_000,
                "gpt-3.5-turbo" => 4096,
                "gpt-3.5-turbo-16k" => 16384,
                _ => 4096,
            },
        }
    }

    /// Analyze code quality and provide suggestions
    ///
    /// # Arguments
    /// * `code` - The code to analyze
    /// * `language` - Programming language (defaults to "rust")
    ///
    /// # Returns
    /// Analysis results and improvement suggestions
    pub async fn analyze_code(
        &self,
        code: &str,
        language: Option<&str>,
    ) -> Result<String, OpenCratesError> {
        let lang = language.unwrap_or("rust");
        let system_message = format!(
            "You are an expert {lang} code reviewer. Analyze the provided code for:\n\
             - Code quality and best practices\n\
             - Potential bugs or issues\n\
             - Performance improvements\n\
             - Security considerations\n\
             - Documentation suggestions\n\
             Provide specific, actionable feedback."
        );

        let prompt = format!("Analyze this {lang} code:\n\n```{lang}\n{code}\n```");
        let (analysis, _usage) = self
            .get_chat_completion(&prompt, Some(&system_message))
            .await?;
        Ok(analysis)
    }

    /// Generate comprehensive documentation for code
    ///
    /// # Arguments
    /// * `code` - The code to document
    /// * `style` - Documentation style (e.g., "rustdoc", "markdown")
    ///
    /// # Returns
    /// Generated documentation
    pub async fn generate_documentation(
        &self,
        code: &str,
        style: Option<&str>,
    ) -> Result<String, OpenCratesError> {
        let doc_style = style.unwrap_or("rustdoc");
        let system_message = format!(
            "You are an expert technical writer specializing in {doc_style} documentation. \
             Generate comprehensive, clear, and accurate documentation that includes:\n\
             - Purpose and functionality overview\n\
             - Parameter descriptions\n\
             - Return value documentation\n\
             - Usage examples\n\
             - Error conditions\n\
             - Performance considerations"
        );

        let prompt =
            format!("Generate {doc_style} documentation for this code:\n\n```rust\n{code}\n```");
        let (docs, _usage) = self
            .get_chat_completion(&prompt, Some(&system_message))
            .await?;
        Ok(docs)
    }

    // Inherent methods for direct access (avoiding trait import requirements in tests)
    #[must_use]
    pub fn name(&self) -> &'static str {
        "codex"
    }

    pub async fn health_check(&self) -> Result<bool, OpenCratesError> {
        self.verify_connection().await
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[async_trait]
impl LLMProvider for CodexProvider {
    /// Generate content using the LLMProvider interface
    ///
    /// This method implements the standard LLMProvider trait for compatibility
    /// with the broader OpenCrates ecosystem.
    async fn generate(
        &self,
        request: &GenerationRequest,
    ) -> Result<GenerationResponse, OpenCratesError> {
        let system_message = "You are an expert programmer. Generate high-quality code based on the user's requirements.";

        let prompt = if let Some(context) = &request.context {
            format!(
                "Context:\n{}\n\nRequest:\n{}",
                context,
                request.prompt.as_ref().unwrap_or(&request.spec.description)
            )
        } else {
            request
                .prompt
                .as_ref()
                .unwrap_or(&request.spec.description)
                .clone()
        };

        let (content, usage) = self
            .get_chat_completion(&prompt, Some(system_message))
            .await?;

        let metrics = Usage {
            prompt_tokens: usage.prompt_tokens,
            completion_tokens: usage.completion_tokens,
            total_tokens: usage.total_tokens,
        };

        Ok(GenerationResponse {
            preview: content,
            metrics,
            finish_reason: Some("stop".to_string()),
        })
    }

    /// Perform health check using the LLMProvider interface
    async fn health_check(&self) -> Result<bool, OpenCratesError> {
        self.verify_connection().await
    }

    /// Get provider name
    fn name(&self) -> &'static str {
        "codex"
    }

    /// Get type-erased reference for downcasting
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}