coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
//! AI Assistant Interface for Edit integration
//!
//! This module provides the user interface components and interaction
//! logic for AI assistance within Microsoft Edit.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{mpsc, RwLock};
use tracing::{debug, info};

use crate::core::{CoderLib, CoderLibError, CodeRequest, CodeResponse};
use crate::integration::{
    EditHost, ContextGatherer, ContextConfig, GatheredContext,
    HostCommand
};
use crate::storage::{Message, MessageRole, MessageContent};

/// AI Assistant interface for Edit
pub struct AIAssistant {
    /// CoderLib instance
    coderlib: Arc<CoderLib>,
    /// Edit host integration
    edit_host: Arc<EditHost>,
    /// Context gatherer
    context_gatherer: ContextGatherer,
    /// Active sessions
    sessions: Arc<RwLock<HashMap<String, AssistantSession>>>,
    /// UI state
    ui_state: Arc<RwLock<UIState>>,
    /// Command sender to Edit
    command_sender: Option<mpsc::UnboundedSender<HostCommand>>,
}

/// AI Assistant session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantSession {
    /// Session ID
    pub id: String,
    /// Session type
    pub session_type: SessionType,
    /// Conversation history
    pub messages: Vec<Message>,
    /// Current context
    pub context: Option<GatheredContext>,
    /// Session state
    pub state: SessionState,
    /// Created timestamp
    pub created_at: std::time::SystemTime,
    /// Last activity timestamp
    pub last_activity: std::time::SystemTime,
}

/// Types of AI assistant sessions
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SessionType {
    /// General code assistance
    CodeAssistance,
    /// Code explanation
    CodeExplanation,
    /// Code refactoring
    CodeRefactoring,
    /// Bug fixing
    BugFix,
    /// Code review
    CodeReview,
    /// Documentation generation
    Documentation,
    /// Test generation
    TestGeneration,
    /// Performance optimization
    Performance,
}

/// Session state
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SessionState {
    /// Session is active and ready for input
    Active,
    /// AI is processing a request
    Processing,
    /// Waiting for user response
    WaitingForUser,
    /// Session is paused
    Paused,
    /// Session completed successfully
    Completed,
    /// Session ended with error
    Error(String),
}

/// UI state for the AI assistant
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UIState {
    /// Whether the assistant panel is visible
    pub panel_visible: bool,
    /// Current active session ID
    pub active_session: Option<String>,
    /// Panel size and position
    pub panel_bounds: PanelBounds,
    /// UI preferences
    pub preferences: UIPreferences,
}

/// Panel bounds and positioning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PanelBounds {
    /// Panel width (percentage of editor width)
    pub width_percent: f32,
    /// Panel height (percentage of editor height)
    pub height_percent: f32,
    /// Panel position
    pub position: PanelPosition,
}

/// Panel position options
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PanelPosition {
    /// Right side of editor
    Right,
    /// Left side of editor
    Left,
    /// Bottom of editor
    Bottom,
    /// Floating window
    Floating { x: i32, y: i32 },
}

/// UI preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UIPreferences {
    /// Theme (light/dark)
    pub theme: String,
    /// Font size
    pub font_size: u32,
    /// Show token usage
    pub show_token_usage: bool,
    /// Auto-apply simple changes
    pub auto_apply_simple: bool,
    /// Show context preview
    pub show_context_preview: bool,
    /// Maximum visible messages
    pub max_visible_messages: usize,
}

/// AI Assistant request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantRequest {
    /// Session ID (optional, creates new session if not provided)
    pub session_id: Option<String>,
    /// Session type
    pub session_type: SessionType,
    /// User message
    pub message: String,
    /// Whether to include context
    pub include_context: bool,
    /// Additional context hints
    pub context_hints: Vec<String>,
}

/// AI Assistant response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantResponse {
    /// Session ID
    pub session_id: String,
    /// Response message
    pub message: String,
    /// Suggested actions
    pub suggested_actions: Vec<SuggestedAction>,
    /// Token usage information
    pub token_usage: Option<TokenUsage>,
    /// Response metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Suggested action from AI
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestedAction {
    /// Action type
    pub action_type: ActionType,
    /// Action description
    pub description: String,
    /// Action data
    pub data: serde_json::Value,
    /// Confidence score (0.0 to 1.0)
    pub confidence: f64,
}

/// Types of suggested actions
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ActionType {
    /// Apply code changes
    ApplyChanges,
    /// Open file
    OpenFile,
    /// Create new file
    CreateFile,
    /// Run command
    RunCommand,
    /// Show documentation
    ShowDocumentation,
    /// Navigate to definition
    NavigateToDefinition,
    /// Add import/dependency
    AddImport,
    /// Generate tests
    GenerateTests,
}

/// Token usage information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenUsage {
    /// Input tokens
    pub input_tokens: u32,
    /// Output tokens
    pub output_tokens: u32,
    /// Total tokens
    pub total_tokens: u32,
    /// Estimated cost
    pub estimated_cost: Option<f64>,
}

impl Default for UIState {
    fn default() -> Self {
        Self {
            panel_visible: false,
            active_session: None,
            panel_bounds: PanelBounds {
                width_percent: 40.0,
                height_percent: 60.0,
                position: PanelPosition::Right,
            },
            preferences: UIPreferences {
                theme: "dark".to_string(),
                font_size: 14,
                show_token_usage: true,
                auto_apply_simple: false,
                show_context_preview: true,
                max_visible_messages: 50,
            },
        }
    }
}

impl AIAssistant {
    /// Create a new AI assistant
    pub fn new(
        coderlib: Arc<CoderLib>,
        edit_host: Arc<EditHost>,
        context_config: ContextConfig,
    ) -> Self {
        let context_gatherer = ContextGatherer::new(context_config);
        
        Self {
            coderlib,
            edit_host,
            context_gatherer,
            sessions: Arc::new(RwLock::new(HashMap::new())),
            ui_state: Arc::new(RwLock::new(UIState::default())),
            command_sender: None,
        }
    }

    /// Set the command sender for communicating with Edit
    pub fn set_command_sender(&mut self, sender: mpsc::UnboundedSender<HostCommand>) {
        self.command_sender = Some(sender);
    }

    /// Show the AI assistant panel
    pub async fn show_panel(&self) -> Result<(), CoderLibError> {
        let mut ui_state = self.ui_state.write().await;
        ui_state.panel_visible = true;
        
        self.send_command(HostCommand::ShowDialog {
            title: "AI Assistant".to_string(),
            message: "AI Assistant is ready to help!".to_string(),
            buttons: vec!["Ask Question".to_string(), "Explain Code".to_string(), "Refactor".to_string(), "Close".to_string()],
        }).await?;
        
        info!("AI Assistant panel shown");
        Ok(())
    }

    /// Hide the AI assistant panel
    pub async fn hide_panel(&self) -> Result<(), CoderLibError> {
        let mut ui_state = self.ui_state.write().await;
        ui_state.panel_visible = false;
        
        info!("AI Assistant panel hidden");
        Ok(())
    }

    /// Process an AI assistant request
    pub async fn process_request(&self, request: AssistantRequest) -> Result<AssistantResponse, CoderLibError> {
        info!("Processing AI assistant request: {:?}", request.session_type);

        // Get or create session
        let session_id = if let Some(ref id) = request.session_id {
            id.clone()
        } else {
            self.create_new_session(request.session_type.clone()).await?
        };

        // Update session state to processing
        self.update_session_state(&session_id, SessionState::Processing).await?;

        // Gather context if requested
        let context = if request.include_context {
            let state = self.edit_host.get_state();
            Some(self.context_gatherer.gather_context(&state, self.edit_host.as_ref()).await?)
        } else {
            None
        };

        // Build the code request
        let code_request = self.build_code_request(&request, &context).await?;

        // Process with CoderLib
        let mut code_response_receiver = self.coderlib.process_request(code_request).await?;

        // Get the first response (simplified for now)
        let code_response = if let Ok(response) = code_response_receiver.recv().await {
            response
        } else {
            return Err(CoderLibError::Integration(
                crate::core::error::IntegrationError::OperationFailed("No response received".to_string())
            ));
        };

        // Convert to assistant response
        let assistant_response = self.build_assistant_response(&session_id, &code_response, &context).await?;

        // Update session with new messages
        self.update_session_messages(&session_id, &request.message, &assistant_response.message).await?;

        // Update session state
        self.update_session_state(&session_id, SessionState::WaitingForUser).await?;

        info!("AI assistant request processed successfully");
        Ok(assistant_response)
    }

    /// Create a new assistant session
    async fn create_new_session(&self, session_type: SessionType) -> Result<String, CoderLibError> {
        let session_id = uuid::Uuid::new_v4().to_string();
        let now = std::time::SystemTime::now();
        
        let session = AssistantSession {
            id: session_id.clone(),
            session_type,
            messages: Vec::new(),
            context: None,
            state: SessionState::Active,
            created_at: now,
            last_activity: now,
        };

        let mut sessions = self.sessions.write().await;
        sessions.insert(session_id.clone(), session);

        // Update UI state
        let mut ui_state = self.ui_state.write().await;
        ui_state.active_session = Some(session_id.clone());

        debug!("Created new AI assistant session: {}", session_id);
        Ok(session_id)
    }

    /// Update session state
    async fn update_session_state(&self, session_id: &str, new_state: SessionState) -> Result<(), CoderLibError> {
        let mut sessions = self.sessions.write().await;
        if let Some(session) = sessions.get_mut(session_id) {
            session.state = new_state;
            session.last_activity = std::time::SystemTime::now();
        }
        Ok(())
    }

    /// Update session messages
    async fn update_session_messages(&self, session_id: &str, user_message: &str, assistant_message: &str) -> Result<(), CoderLibError> {
        let mut sessions = self.sessions.write().await;
        if let Some(session) = sessions.get_mut(session_id) {
            session.messages.push(Message {
                id: uuid::Uuid::new_v4().to_string(),
                session_id: session_id.to_string(),
                role: MessageRole::User,
                content: MessageContent::Text(user_message.to_string()),
                timestamp: chrono::Utc::now(),
                metadata: serde_json::Value::Null,
            });
            session.messages.push(Message {
                id: uuid::Uuid::new_v4().to_string(),
                session_id: session_id.to_string(),
                role: MessageRole::Assistant,
                content: MessageContent::Text(assistant_message.to_string()),
                timestamp: chrono::Utc::now(),
                metadata: serde_json::Value::Null,
            });
            session.last_activity = std::time::SystemTime::now();
        }
        Ok(())
    }

    /// Build code request from assistant request
    async fn build_code_request(&self, request: &AssistantRequest, context: &Option<GatheredContext>) -> Result<CodeRequest, CoderLibError> {
        let mut prompt = String::new();

        // Add session type specific prompt
        match request.session_type {
            SessionType::CodeExplanation => {
                prompt.push_str("Please explain the following code:\n\n");
            }
            SessionType::CodeRefactoring => {
                prompt.push_str("Please refactor the following code to improve its quality, readability, and performance:\n\n");
            }
            SessionType::BugFix => {
                prompt.push_str("Please help me identify and fix bugs in the following code:\n\n");
            }
            SessionType::CodeReview => {
                prompt.push_str("Please review the following code and provide feedback:\n\n");
            }
            SessionType::Documentation => {
                prompt.push_str("Please generate documentation for the following code:\n\n");
            }
            SessionType::TestGeneration => {
                prompt.push_str("Please generate comprehensive tests for the following code:\n\n");
            }
            SessionType::Performance => {
                prompt.push_str("Please analyze and optimize the performance of the following code:\n\n");
            }
            SessionType::CodeAssistance => {
                prompt.push_str("Please help me with the following code question:\n\n");
            }
        }

        // Add user message
        prompt.push_str(&request.message);
        prompt.push_str("\n\n");

        // Add context if available
        if let Some(ctx) = context {
            prompt.push_str("## Context\n");
            prompt.push_str(&self.context_gatherer.format_context_for_ai(ctx));
        }

        Ok(CodeRequest {
            content: prompt,
            attachments: Vec::new(),
            model: None,
            context: crate::core::RequestContext {
                current_file: None,
                cursor_position: None,
                selection: None,
                project_root: None,
                open_files: Vec::new(),
            },
            session_id: uuid::Uuid::new_v4().to_string(),
        })
    }

    /// Build assistant response from code response
    async fn build_assistant_response(&self, session_id: &str, code_response: &CodeResponse, _context: &Option<GatheredContext>) -> Result<AssistantResponse, CoderLibError> {
        let suggested_actions = self.extract_suggested_actions(&code_response.content).await;

        Ok(AssistantResponse {
            session_id: session_id.to_string(),
            message: code_response.content.clone(),
            suggested_actions,
            token_usage: None, // TODO: Extract from code_response when available
            metadata: HashMap::new(),
        })
    }

    /// Extract suggested actions from AI response
    async fn extract_suggested_actions(&self, _response_content: &str) -> Vec<SuggestedAction> {
        // This is a simplified implementation
        // In a real implementation, we would parse the AI response for actionable items
        vec![]
    }

    /// Send a command to Edit
    async fn send_command(&self, command: HostCommand) -> Result<(), CoderLibError> {
        if let Some(sender) = &self.command_sender {
            sender.send(command)
                .map_err(|e| CoderLibError::Integration(
                    crate::core::error::IntegrationError::OperationFailed(
                        format!("Failed to send command: {}", e)
                    )
                ))?;
        }
        Ok(())
    }

    /// Get current UI state
    pub async fn get_ui_state(&self) -> UIState {
        self.ui_state.read().await.clone()
    }

    /// Update UI preferences
    pub async fn update_preferences(&self, preferences: UIPreferences) -> Result<(), CoderLibError> {
        let mut ui_state = self.ui_state.write().await;
        ui_state.preferences = preferences;
        Ok(())
    }

    /// Get session by ID
    pub async fn get_session(&self, session_id: &str) -> Option<AssistantSession> {
        let sessions = self.sessions.read().await;
        sessions.get(session_id).cloned()
    }

    /// List all sessions
    pub async fn list_sessions(&self) -> Vec<AssistantSession> {
        let sessions = self.sessions.read().await;
        sessions.values().cloned().collect()
    }

    /// Close session
    pub async fn close_session(&self, session_id: &str) -> Result<(), CoderLibError> {
        let mut sessions = self.sessions.write().await;
        sessions.remove(session_id);
        
        // Update UI state if this was the active session
        let mut ui_state = self.ui_state.write().await;
        if ui_state.active_session.as_ref() == Some(&session_id.to_string()) {
            ui_state.active_session = None;
        }
        
        Ok(())
    }
}