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
532
533
534
535
536
537
538
//! Integration module for CoderLib
//!
//! This module provides the interface for integrating CoderLib with host applications
//! like text editors, IDEs, and other development tools.

pub mod edit_plugin;
pub mod events;
pub mod edit_host;
pub mod plugin_manager;
pub mod event_handler;
pub mod context_gatherer;
pub mod ai_assistant;
pub mod streaming_handler;
pub mod config_integration;

use async_trait::async_trait;
use std::path::{Path, PathBuf};

use crate::lsp::{Position, Range};
use crate::core::error::IntegrationError;
use crate::tools::Permission;

/// Trait for host application integration
#[async_trait]
pub trait HostIntegration: Send + Sync {
    /// Handle events from CoderLib
    async fn on_event(&self, event: CoderEvent) -> Result<(), IntegrationError>;
    
    /// Request permission for potentially dangerous operations
    async fn request_permission(&self, permission: Permission) -> Result<bool, IntegrationError>;
    
    /// Get content of a file (from buffer or filesystem)
    async fn get_file_content(&self, path: &Path) -> Result<String, IntegrationError>;
    
    /// Update file content (in buffer or filesystem)
    async fn update_file_content(&self, path: &Path, content: &str) -> Result<(), IntegrationError>;
    
    /// Get current cursor position
    async fn get_cursor_position(&self) -> Result<Position, IntegrationError>;
    
    /// Set cursor position
    async fn set_cursor_position(&self, position: Position) -> Result<(), IntegrationError>;
    
    /// Get current text selection
    async fn get_selection(&self) -> Result<Option<Range>, IntegrationError>;
    
    /// Set text selection
    async fn set_selection(&self, range: Range) -> Result<(), IntegrationError>;
    
    /// Insert text at the current cursor position
    async fn insert_text(&self, text: &str) -> Result<(), IntegrationError>;
    
    /// Replace text in the given range
    async fn replace_text(&self, range: Range, text: &str) -> Result<(), IntegrationError>;
    
    /// Get the currently active file
    async fn get_active_file(&self) -> Result<Option<PathBuf>, IntegrationError>;
    
    /// Get list of open files
    async fn get_open_files(&self) -> Result<Vec<PathBuf>, IntegrationError>;
    
    /// Get project root directory
    async fn get_project_root(&self) -> Result<Option<PathBuf>, IntegrationError>;
    
    /// Show a message to the user
    async fn show_message(&self, message: &str, level: MessageLevel) -> Result<(), IntegrationError>;
    
    /// Show a notification to the user
    async fn show_notification(&self, title: &str, message: &str) -> Result<(), IntegrationError>;
    
    /// Request input from the user
    async fn request_input(&self, prompt: &str, default: Option<&str>) -> Result<Option<String>, IntegrationError>;
    
    /// Show a confirmation dialog
    async fn confirm(&self, message: &str) -> Result<bool, IntegrationError>;
    
    /// Execute a command in the host application
    async fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, IntegrationError>;
    
    /// Get host application information
    fn get_host_info(&self) -> HostInfo;
}

/// Events that CoderLib can emit to the host application
#[derive(Debug, Clone)]
pub enum CoderEvent {
    /// AI processing started
    ProcessingStarted {
        session_id: String,
    },
    
    /// AI response chunk received
    ResponseChunk {
        session_id: String,
        content: String,
    },
    
    /// AI processing completed
    ProcessingCompleted {
        session_id: String,
        response: String,
    },
    
    /// AI processing failed
    ProcessingFailed {
        session_id: String,
        error: String,
    },
    
    /// Tool execution started
    ToolExecutionStarted {
        session_id: String,
        tool_name: String,
        parameters: serde_json::Value,
    },
    
    /// Tool execution completed
    ToolExecutionCompleted {
        session_id: String,
        tool_name: String,
        result: String,
        success: bool,
    },
    
    /// File was modified by AI
    FileModified {
        path: PathBuf,
        changes: Vec<TextEdit>,
    },
    
    /// Status update
    StatusUpdate {
        message: String,
    },
    
    /// Progress update
    ProgressUpdate {
        current: u32,
        total: u32,
        message: String,
    },
    
    /// Session created
    SessionCreated {
        session_id: String,
        title: String,
    },
    
    /// Session updated
    SessionUpdated {
        session_id: String,
        title: String,
    },
}

/// Message levels for user notifications
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MessageLevel {
    Info,
    Warning,
    Error,
    Success,
}

/// Information about the host application
#[derive(Debug, Clone)]
pub struct HostInfo {
    /// Name of the host application
    pub name: String,
    
    /// Version of the host application
    pub version: String,
    
    /// Capabilities supported by the host
    pub capabilities: HostCapabilities,
    
    /// Additional metadata
    pub metadata: serde_json::Value,
}

/// Capabilities supported by the host application
#[derive(Debug, Clone)]
pub struct HostCapabilities {
    /// Can modify file contents
    pub file_modification: bool,
    
    /// Can show UI dialogs
    pub ui_dialogs: bool,
    
    /// Can execute commands
    pub command_execution: bool,
    
    /// Can show notifications
    pub notifications: bool,
    
    /// Can access project information
    pub project_access: bool,
    
    /// Can manipulate cursor and selection
    pub cursor_control: bool,
    
    /// Supports syntax highlighting
    pub syntax_highlighting: bool,
    
    /// Supports multiple files/tabs
    pub multi_file: bool,
}

/// Text edit operation
#[derive(Debug, Clone)]
pub struct TextEdit {
    /// Range to replace (None means insert at cursor)
    pub range: Option<Range>,
    
    /// New text to insert
    pub new_text: String,
    
    /// Description of the edit
    pub description: Option<String>,
}

/// Plugin interface for host applications
pub trait Plugin: Send + Sync {
    /// Get the plugin name
    fn name(&self) -> &str;
    
    /// Get the plugin version
    fn version(&self) -> &str;
    
    /// Initialize the plugin with the host context
    fn initialize(&mut self, context: PluginContext) -> Result<(), IntegrationError>;
    
    /// Handle events from the host application
    fn handle_event(&mut self, event: HostEvent) -> Result<Option<HostCommand>, IntegrationError>;
    
    /// Shutdown the plugin
    fn shutdown(&mut self) -> Result<(), IntegrationError>;
}

/// Context provided to plugins during initialization
#[derive(Debug, Clone)]
pub struct PluginContext {
    /// Host application information
    pub host_info: HostInfo,
    
    /// Configuration for the plugin
    pub config: serde_json::Value,
    
    /// Data directory for the plugin
    pub data_dir: PathBuf,
}

/// Events from the host application to plugins
#[derive(Debug, Clone)]
pub enum HostEvent {
    /// Application started
    ApplicationStarted,
    
    /// Application shutting down
    ApplicationShutdown,
    
    /// File opened
    FileOpened(PathBuf),
    
    /// File closed
    FileClosed(PathBuf),
    
    /// File saved
    FileSaved(PathBuf),
    
    /// File modified
    FileModified(PathBuf),
    
    /// Cursor moved
    CursorMoved(Position),
    
    /// Selection changed
    SelectionChanged(Option<Range>),
    
    /// Key pressed
    KeyPressed(String),
    
    /// Command executed
    CommandExecuted(String),
    
    /// Project opened
    ProjectOpened(PathBuf),
    
    /// Project closed
    ProjectClosed,
}

/// Commands that plugins can send to the host
#[derive(Debug, Clone)]
pub enum HostCommand {
    /// Show a message
    ShowMessage {
        message: String,
        level: MessageLevel,
    },
    
    /// Execute a command
    ExecuteCommand {
        command: String,
        args: Vec<String>,
    },
    
    /// Modify file content
    ModifyFile {
        path: PathBuf,
        edits: Vec<TextEdit>,
    },
    
    /// Set cursor position
    SetCursor(Position),
    
    /// Set selection
    SetSelection(Range),
    
    /// Insert text
    InsertText(String),
    
    /// Open file
    OpenFile(PathBuf),
    
    /// Save file
    SaveFile(PathBuf),
    
    /// Show dialog
    ShowDialog {
        title: String,
        message: String,
        buttons: Vec<String>,
    },
}

impl Default for HostCapabilities {
    fn default() -> Self {
        Self {
            file_modification: true,
            ui_dialogs: true,
            command_execution: false,
            notifications: true,
            project_access: true,
            cursor_control: true,
            syntax_highlighting: false,
            multi_file: true,
        }
    }
}

impl TextEdit {
    /// Create a new text edit that inserts text at the cursor
    pub fn insert(text: String) -> Self {
        Self {
            range: None,
            new_text: text,
            description: None,
        }
    }
    
    /// Create a new text edit that replaces text in a range
    pub fn replace(range: Range, text: String) -> Self {
        Self {
            range: Some(range),
            new_text: text,
            description: None,
        }
    }
    
    /// Create a new text edit with a description
    pub fn with_description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }
}

impl std::fmt::Display for MessageLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MessageLevel::Info => write!(f, "info"),
            MessageLevel::Warning => write!(f, "warning"),
            MessageLevel::Error => write!(f, "error"),
            MessageLevel::Success => write!(f, "success"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_text_edit_creation() {
        let insert_edit = TextEdit::insert("Hello, world!".to_string());
        assert!(insert_edit.range.is_none());
        assert_eq!(insert_edit.new_text, "Hello, world!");
        
        let range = Range {
            start: Position { line: 0, character: 0 },
            end: Position { line: 0, character: 5 },
        };
        let replace_edit = TextEdit::replace(range, "Hi".to_string());
        assert!(replace_edit.range.is_some());
        assert_eq!(replace_edit.new_text, "Hi");
    }

    #[test]
    fn test_message_level_display() {
        assert_eq!(MessageLevel::Info.to_string(), "info");
        assert_eq!(MessageLevel::Warning.to_string(), "warning");
        assert_eq!(MessageLevel::Error.to_string(), "error");
        assert_eq!(MessageLevel::Success.to_string(), "success");
    }

    #[test]
    fn test_host_capabilities_default() {
        let caps = HostCapabilities::default();
        assert!(caps.file_modification);
        assert!(caps.ui_dialogs);
        assert!(!caps.command_execution); // Default to false for security
        assert!(caps.notifications);
    }

    #[test]
    fn test_coder_event_creation() {
        let event = CoderEvent::ProcessingStarted {
            session_id: "test-session".to_string(),
        };
        
        match event {
            CoderEvent::ProcessingStarted { session_id } => {
                assert_eq!(session_id, "test-session");
            }
            _ => panic!("Expected ProcessingStarted event"),
        }
    }
}

// Re-export new components
pub use edit_host::*;
pub use plugin_manager::*;
pub use event_handler::*;
pub use context_gatherer::*;
pub use ai_assistant::*;
pub use streaming_handler::*;
pub use config_integration::*;

/// Mock host integration for testing
pub struct MockHost;

#[async_trait]
impl HostIntegration for MockHost {
    async fn on_event(&self, _event: CoderEvent) -> Result<(), IntegrationError> {
        Ok(())
    }

    async fn request_permission(&self, _permission: Permission) -> Result<bool, IntegrationError> {
        Ok(true)
    }

    async fn get_file_content(&self, path: &Path) -> Result<String, IntegrationError> {
        tokio::fs::read_to_string(path).await
            .map_err(|e| IntegrationError::FileNotFound(path.to_path_buf()))
    }

    async fn update_file_content(&self, path: &Path, content: &str) -> Result<(), IntegrationError> {
        tokio::fs::write(path, content).await
            .map_err(|e| IntegrationError::OperationFailed(e.to_string()))
    }

    async fn get_cursor_position(&self) -> Result<Position, IntegrationError> {
        Ok(Position { line: 0, character: 0 })
    }

    async fn get_selection(&self) -> Result<Option<Range>, IntegrationError> {
        Ok(None)
    }



    async fn set_cursor_position(&self, _position: Position) -> Result<(), IntegrationError> {
        Ok(())
    }

    async fn set_selection(&self, _range: Range) -> Result<(), IntegrationError> {
        Ok(())
    }

    async fn insert_text(&self, _text: &str) -> Result<(), IntegrationError> {
        Ok(())
    }

    async fn replace_text(&self, _range: Range, _text: &str) -> Result<(), IntegrationError> {
        Ok(())
    }

    async fn get_active_file(&self) -> Result<Option<PathBuf>, IntegrationError> {
        Ok(None)
    }

    async fn get_open_files(&self) -> Result<Vec<PathBuf>, IntegrationError> {
        Ok(Vec::new())
    }

    async fn get_project_root(&self) -> Result<Option<PathBuf>, IntegrationError> {
        Ok(Some(std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))))
    }

    async fn show_message(&self, _message: &str, _level: MessageLevel) -> Result<(), IntegrationError> {
        Ok(())
    }

    async fn show_notification(&self, _title: &str, _message: &str) -> Result<(), IntegrationError> {
        Ok(())
    }

    async fn request_input(&self, _prompt: &str, _default: Option<&str>) -> Result<Option<String>, IntegrationError> {
        Ok(Some("mock input".to_string()))
    }

    async fn confirm(&self, _message: &str) -> Result<bool, IntegrationError> {
        Ok(true)
    }

    async fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, IntegrationError> {
        Ok(format!("Mock execution: {} {:?}", command, args))
    }

    fn get_host_info(&self) -> HostInfo {
        HostInfo {
            name: "Mock Host".to_string(),
            version: "1.0.0".to_string(),
            capabilities: HostCapabilities::default(),
            metadata: serde_json::json!({}),
        }
    }
}