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
//! Event handling system for Edit integration
//!
//! This module provides comprehensive event handling for all editor
//! actions and user interactions within Microsoft Edit.

use async_trait::async_trait;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{mpsc, RwLock};
use tracing::{debug, info, warn};

use crate::core::CoderLibError;
use crate::integration::{HostEvent, HostCommand, MessageLevel, EditState, EditConfig};

/// Event handler for Edit integration
pub struct EditEventHandler {
    /// Current editor state
    state: Arc<RwLock<EditState>>,
    /// Configuration
    config: EditConfig,
    /// Event listeners
    listeners: Arc<RwLock<HashMap<String, Box<dyn EventListener>>>>,
    /// Command sender to Edit
    command_sender: Option<mpsc::UnboundedSender<HostCommand>>,
    /// AI hotkey sequence tracker
    hotkey_tracker: Arc<RwLock<HotkeyTracker>>,
}

/// Event listener trait for handling specific events
#[async_trait]
pub trait EventListener: Send + Sync {
    /// Handle an event
    async fn handle_event(&self, event: &HostEvent, state: &EditState) -> Result<Option<HostCommand>, CoderLibError>;
    
    /// Get the event types this listener is interested in
    fn event_types(&self) -> Vec<String>;
    
    /// Get listener priority (higher = processed first)
    fn priority(&self) -> i32 { 0 }
}

/// Hotkey sequence tracker
#[derive(Debug, Clone)]
pub struct HotkeyTracker {
    /// Current key sequence
    current_sequence: Vec<String>,
    /// Timestamp of last key press
    last_key_time: std::time::Instant,
    /// Maximum time between keys in a sequence (ms)
    sequence_timeout: u64,
}

/// AI assistant event listener
pub struct AIAssistantListener {
    /// Hotkey sequence to trigger AI assistant
    hotkey_sequence: Vec<String>,
}

/// File operation event listener
pub struct FileOperationListener;

/// Cursor tracking event listener
pub struct CursorTrackingListener;

/// Auto-save event listener
pub struct AutoSaveListener {
    /// Auto-save interval in seconds
    interval: u64,
    /// Last save times for files
    last_saves: Arc<RwLock<HashMap<PathBuf, std::time::Instant>>>,
}

/// Context gathering event listener
pub struct ContextGatheringListener {
    /// Whether to gather context automatically
    auto_gather: bool,
    /// Maximum context size
    max_context_size: usize,
}

impl EditEventHandler {
    /// Create a new event handler
    pub fn new(initial_state: EditState, config: EditConfig) -> Self {
        let hotkey_tracker = HotkeyTracker {
            current_sequence: Vec::new(),
            last_key_time: std::time::Instant::now(),
            sequence_timeout: 1000, // 1 second
        };

        Self {
            state: Arc::new(RwLock::new(initial_state)),
            config,
            listeners: Arc::new(RwLock::new(HashMap::new())),
            command_sender: None,
            hotkey_tracker: Arc::new(RwLock::new(hotkey_tracker)),
        }
    }

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

    /// Register default event listeners
    pub async fn register_default_listeners(&self) -> Result<(), CoderLibError> {
        // AI Assistant listener
        let ai_listener = AIAssistantListener::new(&self.config.ai_hotkey);
        self.register_listener("ai_assistant".to_string(), Box::new(ai_listener)).await;

        // File operation listener
        self.register_listener("file_operations".to_string(), Box::new(FileOperationListener)).await;

        // Cursor tracking listener
        self.register_listener("cursor_tracking".to_string(), Box::new(CursorTrackingListener)).await;

        // Auto-save listener (if enabled)
        if self.config.auto_apply_simple {
            let auto_save = AutoSaveListener::new(30); // 30 seconds
            self.register_listener("auto_save".to_string(), Box::new(auto_save)).await;
        }

        // Context gathering listener
        if self.config.auto_context {
            let context_listener = ContextGatheringListener::new(
                self.config.auto_context,
                self.config.max_context_size,
            );
            self.register_listener("context_gathering".to_string(), Box::new(context_listener)).await;
        }

        info!("Registered default event listeners for Edit integration");
        Ok(())
    }

    /// Register an event listener
    pub async fn register_listener(&self, name: String, listener: Box<dyn EventListener>) {
        let mut listeners = self.listeners.write().await;
        listeners.insert(name, listener);
    }

    /// Unregister an event listener
    pub async fn unregister_listener(&self, name: &str) {
        let mut listeners = self.listeners.write().await;
        listeners.remove(name);
    }

    /// Handle an event from Edit
    pub async fn handle_event(&self, event: HostEvent) -> Result<Vec<HostCommand>, CoderLibError> {
        debug!("Handling event: {:?}", event);

        // Update internal state based on event
        self.update_state_from_event(&event).await?;

        // Handle hotkey tracking for key press events
        if let HostEvent::KeyPressed(key) = &event {
            if let Some(command) = self.handle_hotkey(key).await? {
                return Ok(vec![command]);
            }
        }

        // Process event through all registered listeners
        let mut commands = Vec::new();
        let listeners = self.listeners.read().await;
        let state = self.state.read().await;

        // Sort listeners by priority (highest first)
        let mut listener_pairs: Vec<_> = listeners.iter().collect();
        listener_pairs.sort_by(|a, b| b.1.priority().cmp(&a.1.priority()));

        for (name, listener) in listener_pairs {
            // Check if listener is interested in this event type
            let event_type = self.get_event_type(&event);
            if listener.event_types().contains(&event_type) || listener.event_types().contains(&"*".to_string()) {
                match listener.handle_event(&event, &state).await {
                    Ok(Some(command)) => {
                        debug!("Listener '{}' generated command: {:?}", name, command);
                        commands.push(command);
                    }
                    Ok(None) => {
                        debug!("Listener '{}' handled event without generating command", name);
                    }
                    Err(e) => {
                        warn!("Listener '{}' failed to handle event: {}", name, e);
                    }
                }
            }
        }

        Ok(commands)
    }

    /// Update internal state based on event
    async fn update_state_from_event(&self, event: &HostEvent) -> Result<(), CoderLibError> {
        let mut state = self.state.write().await;

        match event {
            HostEvent::FileOpened(path) => {
                state.current_file = Some(path.clone());
                if !state.open_files.contains(path) {
                    state.open_files.push(path.clone());
                }
            }
            HostEvent::FileClosed(path) => {
                state.open_files.retain(|f| f != path);
                if state.current_file.as_ref() == Some(path) {
                    state.current_file = state.open_files.first().cloned();
                }
            }
            HostEvent::FileSaved(path) => {
                if state.current_file.as_ref() == Some(path) {
                    state.has_unsaved_changes = false;
                }
            }
            HostEvent::CursorMoved(position) => {
                state.cursor_position = *position;
            }
            HostEvent::SelectionChanged(range) => {
                state.selection = *range;
            }
            HostEvent::ProjectOpened(path) => {
                state.working_directory = path.clone();
            }
            _ => {} // Other events don't affect our tracked state
        }

        Ok(())
    }

    /// Handle hotkey sequences
    async fn handle_hotkey(&self, key: &str) -> Result<Option<HostCommand>, CoderLibError> {
        let mut tracker = self.hotkey_tracker.write().await;
        let now = std::time::Instant::now();

        // Check if this key is part of a sequence or starts a new one
        if now.duration_since(tracker.last_key_time).as_millis() > tracker.sequence_timeout as u128 {
            tracker.current_sequence.clear();
        }

        tracker.current_sequence.push(key.to_string());
        tracker.last_key_time = now;

        // Check if current sequence matches AI hotkey
        let ai_hotkey_parts: Vec<&str> = self.config.ai_hotkey.split('+').collect();
        if tracker.current_sequence.len() == ai_hotkey_parts.len() {
            let matches = tracker.current_sequence.iter()
                .zip(ai_hotkey_parts.iter())
                .all(|(pressed, expected)| pressed == expected);

            if matches {
                tracker.current_sequence.clear();
                return Ok(Some(HostCommand::ShowDialog {
                    title: "AI Assistant".to_string(),
                    message: "How can I help you with your code?".to_string(),
                    buttons: vec!["Ask Question".to_string(), "Cancel".to_string()],
                }));
            }
        }

        Ok(None)
    }

    /// Get event type string for an event
    fn get_event_type(&self, event: &HostEvent) -> String {
        match event {
            HostEvent::ApplicationStarted => "application_started".to_string(),
            HostEvent::ApplicationShutdown => "application_shutdown".to_string(),
            HostEvent::FileOpened(_) => "file_opened".to_string(),
            HostEvent::FileClosed(_) => "file_closed".to_string(),
            HostEvent::FileSaved(_) => "file_saved".to_string(),
            HostEvent::FileModified(_) => "file_modified".to_string(),
            HostEvent::CursorMoved(_) => "cursor_moved".to_string(),
            HostEvent::SelectionChanged(_) => "selection_changed".to_string(),
            HostEvent::KeyPressed(_) => "key_pressed".to_string(),
            HostEvent::CommandExecuted(_) => "command_executed".to_string(),
            HostEvent::ProjectOpened(_) => "project_opened".to_string(),
            HostEvent::ProjectClosed => "project_closed".to_string(),
        }
    }

    /// Get current editor state
    pub async fn get_state(&self) -> EditState {
        self.state.read().await.clone()
    }

    /// 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(())
    }
}

// Event Listener Implementations

impl AIAssistantListener {
    pub fn new(hotkey: &str) -> Self {
        let hotkey_sequence = hotkey.split('+').map(|s| s.to_string()).collect();
        Self { hotkey_sequence }
    }
}

#[async_trait]
impl EventListener for AIAssistantListener {
    async fn handle_event(&self, event: &HostEvent, state: &EditState) -> Result<Option<HostCommand>, CoderLibError> {
        match event {
            HostEvent::KeyPressed(key) => {
                // This is handled by the main hotkey tracker
                Ok(None)
            }
            HostEvent::CommandExecuted(cmd) if cmd == "ai_assistant" => {
                // Direct AI assistant command
                Ok(Some(HostCommand::ShowDialog {
                    title: "AI Assistant".to_string(),
                    message: format!(
                        "Current file: {}\nCursor: line {}, column {}\n\nHow can I help?",
                        state.current_file.as_ref().map(|p| p.display().to_string()).unwrap_or("None".to_string()),
                        state.cursor_position.line,
                        state.cursor_position.character
                    ),
                    buttons: vec!["Ask Question".to_string(), "Explain Code".to_string(), "Refactor".to_string(), "Cancel".to_string()],
                }))
            }
            _ => Ok(None),
        }
    }

    fn event_types(&self) -> Vec<String> {
        vec!["key_pressed".to_string(), "command_executed".to_string()]
    }

    fn priority(&self) -> i32 { 100 } // High priority for AI assistant
}

#[async_trait]
impl EventListener for FileOperationListener {
    async fn handle_event(&self, event: &HostEvent, _state: &EditState) -> Result<Option<HostCommand>, CoderLibError> {
        match event {
            HostEvent::FileOpened(path) => {
                info!("File opened: {}", path.display());
                Ok(Some(HostCommand::ShowMessage {
                    message: format!("Opened: {}", path.file_name().unwrap_or_default().to_string_lossy()),
                    level: MessageLevel::Info,
                }))
            }
            HostEvent::FileSaved(path) => {
                info!("File saved: {}", path.display());
                Ok(Some(HostCommand::ShowMessage {
                    message: format!("Saved: {}", path.file_name().unwrap_or_default().to_string_lossy()),
                    level: MessageLevel::Success,
                }))
            }
            HostEvent::FileModified(path) => {
                debug!("File modified: {}", path.display());
                // Could trigger auto-analysis or other features
                Ok(None)
            }
            _ => Ok(None),
        }
    }

    fn event_types(&self) -> Vec<String> {
        vec!["file_opened".to_string(), "file_closed".to_string(), "file_saved".to_string(), "file_modified".to_string()]
    }

    fn priority(&self) -> i32 { 50 }
}

#[async_trait]
impl EventListener for CursorTrackingListener {
    async fn handle_event(&self, event: &HostEvent, state: &EditState) -> Result<Option<HostCommand>, CoderLibError> {
        match event {
            HostEvent::CursorMoved(position) => {
                debug!("Cursor moved to line {}, column {}", position.line, position.character);

                // Could trigger context updates, symbol highlighting, etc.
                if let Some(current_file) = &state.current_file {
                    if current_file.extension().and_then(|ext| ext.to_str()) == Some("rs") {
                        // For Rust files, we might want to show type information
                        // This is just a placeholder for more advanced features
                        debug!("Cursor in Rust file at {}:{}", position.line, position.character);
                    }
                }

                Ok(None)
            }
            HostEvent::SelectionChanged(Some(range)) => {
                debug!("Selection changed: {}:{} to {}:{}",
                    range.start.line, range.start.character,
                    range.end.line, range.end.character);

                // Could trigger selection-based analysis
                Ok(None)
            }
            _ => Ok(None),
        }
    }

    fn event_types(&self) -> Vec<String> {
        vec!["cursor_moved".to_string(), "selection_changed".to_string()]
    }

    fn priority(&self) -> i32 { 10 } // Low priority for tracking
}

impl AutoSaveListener {
    pub fn new(interval_seconds: u64) -> Self {
        Self {
            interval: interval_seconds,
            last_saves: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}

#[async_trait]
impl EventListener for AutoSaveListener {
    async fn handle_event(&self, event: &HostEvent, state: &EditState) -> Result<Option<HostCommand>, CoderLibError> {
        match event {
            HostEvent::FileModified(path) => {
                let now = std::time::Instant::now();
                let mut last_saves = self.last_saves.write().await;

                let should_save = if let Some(last_save) = last_saves.get(path) {
                    now.duration_since(*last_save).as_secs() >= self.interval
                } else {
                    true
                };

                if should_save && state.has_unsaved_changes {
                    last_saves.insert(path.clone(), now);
                    return Ok(Some(HostCommand::SaveFile(path.clone())));
                }
            }
            HostEvent::FileSaved(path) => {
                let mut last_saves = self.last_saves.write().await;
                last_saves.insert(path.clone(), std::time::Instant::now());
            }
            _ => {}
        }
        Ok(None)
    }

    fn event_types(&self) -> Vec<String> {
        vec!["file_modified".to_string(), "file_saved".to_string()]
    }

    fn priority(&self) -> i32 { 20 }
}

impl ContextGatheringListener {
    pub fn new(auto_gather: bool, max_context_size: usize) -> Self {
        Self {
            auto_gather,
            max_context_size,
        }
    }
}

#[async_trait]
impl EventListener for ContextGatheringListener {
    async fn handle_event(&self, event: &HostEvent, state: &EditState) -> Result<Option<HostCommand>, CoderLibError> {
        if !self.auto_gather {
            return Ok(None);
        }

        match event {
            HostEvent::FileOpened(_) | HostEvent::CursorMoved(_) | HostEvent::SelectionChanged(_) => {
                // Gather context for AI assistance
                debug!("Gathering context for AI assistance");

                // This would typically gather:
                // - Current file content around cursor
                // - Related files in the project
                // - Git status and recent changes
                // - Symbol definitions and references

                // For now, just log that we would gather context
                if let Some(current_file) = &state.current_file {
                    debug!("Would gather context for file: {} at position {}:{}",
                        current_file.display(),
                        state.cursor_position.line,
                        state.cursor_position.character);
                }

                Ok(None)
            }
            _ => Ok(None),
        }
    }

    fn event_types(&self) -> Vec<String> {
        vec!["file_opened".to_string(), "cursor_moved".to_string(), "selection_changed".to_string()]
    }

    fn priority(&self) -> i32 { 5 } // Very low priority for background context gathering
}