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
//! Edit host integration implementation
//!
//! This module provides the concrete implementation of HostIntegration
//! specifically designed for Microsoft Edit console editor.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;

use crate::core::CoderLibError;
use crate::lsp::{Position, Range};
use crate::integration::{HostIntegration, HostCapabilities, HostInfo, CoderEvent, MessageLevel};
use crate::core::error::IntegrationError;
use crate::tools::Permission;

/// Edit-specific editor state information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EditState {
    /// Currently active file
    pub current_file: Option<PathBuf>,
    /// Cursor position in the current file
    pub cursor_position: Position,
    /// Current selection range (if any)
    pub selection: Option<Range>,
    /// List of all open files
    pub open_files: Vec<PathBuf>,
    /// Current working directory
    pub working_directory: PathBuf,
    /// Editor mode (insert, command, visual, etc.)
    pub editor_mode: String,
    /// Current line content
    pub current_line: String,
    /// Visible line range in the editor
    pub visible_range: Range,
    /// Whether the current file has unsaved changes
    pub has_unsaved_changes: bool,
}

/// Edit-specific configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EditConfig {
    /// Hotkey for AI assistant (default: "Ctrl+I")
    pub ai_hotkey: String,
    /// Auto-context gathering enabled
    pub auto_context: bool,
    /// Maximum number of context files to include
    pub max_context_files: usize,
    /// Maximum context size in characters
    pub max_context_size: usize,
    /// Enable streaming responses
    pub enable_streaming: bool,
    /// Show token usage information
    pub show_token_usage: bool,
    /// Auto-apply simple changes
    pub auto_apply_simple: bool,
}

impl Default for EditConfig {
    fn default() -> Self {
        Self {
            ai_hotkey: "Ctrl+I".to_string(),
            auto_context: true,
            max_context_files: 10,
            max_context_size: 50000,
            enable_streaming: true,
            show_token_usage: true,
            auto_apply_simple: false,
        }
    }
}

/// Edit host integration implementation
pub struct EditHost {
    /// Current editor state
    state: Arc<Mutex<EditState>>,
    /// Edit-specific configuration
    config: EditConfig,
    /// Event sender for communicating with Edit
    event_sender: Option<mpsc::UnboundedSender<EditCommand>>,
    /// File content cache
    file_cache: Arc<Mutex<HashMap<PathBuf, String>>>,
    /// Host capabilities
    capabilities: HostCapabilities,
    /// Host information
    host_info: HostInfo,
}

/// Commands that can be sent to Edit editor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EditCommand {
    /// Open a file
    OpenFile { path: PathBuf },
    /// Close a file
    CloseFile { path: PathBuf },
    /// Move cursor to position
    MoveCursor { position: Position },
    /// Set selection range
    SetSelection { range: Range },
    /// Insert text at cursor
    InsertText { text: String },
    /// Replace text in range
    ReplaceText { range: Range, text: String },
    /// Delete text in range
    DeleteText { range: Range },
    /// Save current file
    SaveFile,
    /// Save file as
    SaveFileAs { path: PathBuf },
    /// Show message to user
    ShowMessage { level: MessageLevel, message: String },
    /// Show AI assistant dialog
    ShowAIAssistant { initial_prompt: Option<String> },
    /// Update status bar
    UpdateStatus { message: String },
    /// Refresh file list
    RefreshFiles,
}

/// Responses from Edit editor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EditResponse {
    /// Command executed successfully
    Success,
    /// Command failed with error
    Error { message: String },
    /// File content response
    FileContent { path: PathBuf, content: String },
    /// Editor state update
    StateUpdate { state: EditState },
    /// User input response
    UserInput { input: String },
}

impl EditHost {
    /// Create a new Edit host integration
    pub fn new(config: EditConfig) -> Self {
        let initial_state = EditState {
            current_file: None,
            cursor_position: Position { line: 1, character: 1 },
            selection: None,
            open_files: Vec::new(),
            working_directory: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            editor_mode: "normal".to_string(),
            current_line: String::new(),
            visible_range: Range {
                start: Position { line: 1, character: 1 },
                end: Position { line: 50, character: 1 },
            },
            has_unsaved_changes: false,
        };

        let capabilities = HostCapabilities {
            file_modification: true,
            ui_dialogs: true,
            command_execution: true,
            notifications: true,
            project_access: true,
            cursor_control: true,
            syntax_highlighting: false,
            multi_file: true,
        };

        let host_info = HostInfo {
            name: "Microsoft Edit".to_string(),
            version: "1.0.0".to_string(),
            capabilities: capabilities.clone(),
            metadata: serde_json::json!({
                "editor_type": "console",
                "supports_streaming": config.enable_streaming,
                "max_file_size": 10 * 1024 * 1024,
                "supported_languages": [
                    "rust", "python", "javascript", "typescript", "go",
                    "java", "c", "cpp", "csharp", "html", "css",
                    "json", "yaml", "toml", "markdown"
                ]
            }),
        };

        Self {
            state: Arc::new(Mutex::new(initial_state)),
            config,
            event_sender: None,
            file_cache: Arc::new(Mutex::new(HashMap::new())),
            capabilities,
            host_info,
        }
    }

    /// Set the event sender for communicating with Edit
    pub fn set_event_sender(&mut self, sender: mpsc::UnboundedSender<EditCommand>) {
        self.event_sender = Some(sender);
    }

    /// Update the editor state
    pub fn update_state(&self, new_state: EditState) {
        if let Ok(mut state) = self.state.lock() {
            *state = new_state;
        }
    }

    /// Get the current editor state
    pub fn get_state(&self) -> EditState {
        self.state.lock().unwrap().clone()
    }

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

    /// Get context around the current cursor position
    pub async fn get_cursor_context(&self, lines_before: usize, lines_after: usize) -> Result<String, CoderLibError> {
        let state = self.get_state();
        
        if let Some(current_file) = &state.current_file {
            let content = self.get_file_content(current_file).await?;
            let lines: Vec<&str> = content.lines().collect();
            
            let current_line = (state.cursor_position.line as usize).saturating_sub(1);
            let start_line = current_line.saturating_sub(lines_before);
            let end_line = (current_line + lines_after + 1).min(lines.len());
            
            let context_lines = &lines[start_line..end_line];
            Ok(context_lines.join("\n"))
        } else {
            Ok(String::new())
        }
    }

    /// Get project context by analyzing open files and project structure
    pub async fn get_project_context(&self) -> Result<String, CoderLibError> {
        let state = self.get_state();
        let mut context = String::new();
        
        // Add current file information
        if let Some(current_file) = &state.current_file {
            context.push_str(&format!("Current file: {}\n", current_file.display()));
            context.push_str(&format!("Cursor: line {}, column {}\n", 
                state.cursor_position.line, state.cursor_position.character));
            
            if let Some(selection) = &state.selection {
                context.push_str(&format!("Selection: {}:{} to {}:{}\n",
                    selection.start.line, selection.start.character,
                    selection.end.line, selection.end.character));
            }
        }
        
        // Add open files
        if !state.open_files.is_empty() {
            context.push_str("\nOpen files:\n");
            for file in &state.open_files {
                context.push_str(&format!("- {}\n", file.display()));
            }
        }
        
        // Add working directory
        context.push_str(&format!("\nWorking directory: {}\n", state.working_directory.display()));
        
        Ok(context)
    }

    /// Gather intelligent context for AI requests
    pub async fn gather_intelligent_context(&self) -> Result<String, CoderLibError> {
        let mut context = String::new();
        
        // Get project context
        context.push_str(&self.get_project_context().await?);
        context.push_str("\n");
        
        // Get cursor context
        let cursor_context = self.get_cursor_context(5, 5).await?;
        if !cursor_context.is_empty() {
            context.push_str("Context around cursor:\n");
            context.push_str("```\n");
            context.push_str(&cursor_context);
            context.push_str("\n```\n\n");
        }
        
        // Limit context size
        if context.len() > self.config.max_context_size {
            let truncated = &context[..self.config.max_context_size];
            context = format!("{}...\n[Context truncated]", truncated);
        }
        
        Ok(context)
    }
}

#[async_trait]
impl HostIntegration for EditHost {
    async fn on_event(&self, event: CoderEvent) -> Result<(), IntegrationError> {
        // Handle events from CoderLib
        match event {
            CoderEvent::ProcessingStarted { session_id } => {
                self.send_command(EditCommand::UpdateStatus {
                    message: format!("AI processing started ({})", session_id)
                }).await.map_err(|e| IntegrationError::OperationFailed(e.to_string()))?;
            }
            CoderEvent::ProcessingCompleted { session_id, response: _ } => {
                self.send_command(EditCommand::UpdateStatus {
                    message: format!("AI processing completed ({})", session_id)
                }).await.map_err(|e| IntegrationError::OperationFailed(e.to_string()))?;
            }
            CoderEvent::ProcessingFailed { session_id, error } => {
                self.send_command(EditCommand::ShowMessage {
                    level: MessageLevel::Error,
                    message: format!("AI processing failed ({}): {}", session_id, error)
                }).await.map_err(|e| IntegrationError::OperationFailed(e.to_string()))?;
            }
            _ => {} // Handle other events as needed
        }
        Ok(())
    }

    async fn request_permission(&self, _permission: Permission) -> Result<bool, IntegrationError> {
        // For Edit integration, we'll assume permissions are granted
        // In a real implementation, this might show a dialog
        Ok(true)
    }

    async fn get_file_content(&self, path: &Path) -> Result<String, IntegrationError> {
        // Check cache first
        if let Ok(cache) = self.file_cache.lock() {
            if let Some(content) = cache.get(path) {
                return Ok(content.clone());
            }
        }

        // Read from file system
        let content = tokio::fs::read_to_string(path).await
            .map_err(|e| IntegrationError::FileNotFound(path.to_path_buf()))?;

        // Cache the content
        if let Ok(mut cache) = self.file_cache.lock() {
            cache.insert(path.to_path_buf(), content.clone());
        }

        Ok(content)
    }

    async fn update_file_content(&self, path: &Path, content: &str) -> Result<(), IntegrationError> {
        // Update cache
        if let Ok(mut cache) = self.file_cache.lock() {
            cache.insert(path.to_path_buf(), content.to_string());
        }

        // Send command to Edit to update the file
        self.send_command(EditCommand::ReplaceText {
            range: Range {
                start: Position { line: 1, character: 1 },
                end: Position { line: u32::MAX, character: u32::MAX },
            },
            text: content.to_string(),
        }).await.map_err(|e| IntegrationError::OperationFailed(e.to_string()))?;

        Ok(())
    }

    async fn get_cursor_position(&self) -> Result<Position, IntegrationError> {
        let state = self.get_state();
        Ok(state.cursor_position)
    }

    async fn set_cursor_position(&self, position: Position) -> Result<(), IntegrationError> {
        self.send_command(EditCommand::MoveCursor { position }).await
            .map_err(|e| IntegrationError::OperationFailed(e.to_string()))
    }

    async fn get_selection(&self) -> Result<Option<Range>, IntegrationError> {
        let state = self.get_state();
        Ok(state.selection)
    }

    async fn set_selection(&self, range: Range) -> Result<(), IntegrationError> {
        self.send_command(EditCommand::SetSelection { range }).await
            .map_err(|e| IntegrationError::OperationFailed(e.to_string()))
    }

    async fn insert_text(&self, text: &str) -> Result<(), IntegrationError> {
        self.send_command(EditCommand::InsertText { text: text.to_string() }).await
            .map_err(|e| IntegrationError::OperationFailed(e.to_string()))
    }

    async fn replace_text(&self, range: Range, text: &str) -> Result<(), IntegrationError> {
        self.send_command(EditCommand::ReplaceText {
            range,
            text: text.to_string()
        }).await.map_err(|e| IntegrationError::OperationFailed(e.to_string()))
    }

    async fn get_active_file(&self) -> Result<Option<PathBuf>, IntegrationError> {
        let state = self.get_state();
        Ok(state.current_file)
    }

    async fn get_open_files(&self) -> Result<Vec<PathBuf>, IntegrationError> {
        let state = self.get_state();
        Ok(state.open_files)
    }

    async fn get_project_root(&self) -> Result<Option<PathBuf>, IntegrationError> {
        let state = self.get_state();
        Ok(Some(state.working_directory))
    }

    async fn show_message(&self, message: &str, level: MessageLevel) -> Result<(), IntegrationError> {
        self.send_command(EditCommand::ShowMessage {
            level,
            message: message.to_string()
        }).await.map_err(|e| IntegrationError::OperationFailed(e.to_string()))
    }

    async fn show_notification(&self, title: &str, message: &str) -> Result<(), IntegrationError> {
        // For Edit, we'll show this as a regular message with the title included
        let full_message = format!("{}: {}", title, message);
        self.show_message(&full_message, MessageLevel::Info).await
    }

    async fn request_input(&self, prompt: &str, _default: Option<&str>) -> Result<Option<String>, IntegrationError> {
        // For now, we'll just show the prompt as a message
        // In a real implementation, this would show an input dialog
        self.show_message(prompt, MessageLevel::Info).await?;
        Ok(None) // Placeholder - would need actual input mechanism
    }

    async fn confirm(&self, message: &str) -> Result<bool, IntegrationError> {
        // For now, we'll just show the message and return true
        // In a real implementation, this would show a confirmation dialog
        self.show_message(message, MessageLevel::Info).await?;
        Ok(true) // Placeholder - would need actual confirmation mechanism
    }

    async fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, IntegrationError> {
        // For Edit integration, we might want to execute commands through Edit's command system
        // For now, we'll use the standard system command execution
        let output = tokio::process::Command::new(command)
            .args(args)
            .current_dir(&self.get_state().working_directory)
            .output()
            .await
            .map_err(|e| IntegrationError::OperationFailed(format!("Failed to execute command: {}", e)))?;

        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).to_string())
        } else {
            Err(IntegrationError::OperationFailed(format!(
                "Command failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )))
        }
    }

    fn get_host_info(&self) -> HostInfo {
        self.host_info.clone()
    }
}