Skip to main content

oxirs_chat/
plugins.rs

1//! Plugin System
2//!
3//! Extensible plugin architecture for adding custom functionality to oxirs-chat.
4
5use crate::messages::Message;
6use anyhow::Result;
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::sync::Arc;
11use tokio::sync::RwLock;
12use tracing::{debug, info, warn};
13
14/// Plugin metadata
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct PluginMetadata {
17    /// Plugin name
18    pub name: String,
19    /// Plugin version
20    pub version: String,
21    /// Author
22    pub author: String,
23    /// Description
24    pub description: String,
25    /// Plugin capabilities
26    pub capabilities: Vec<PluginCapability>,
27}
28
29/// Plugin capabilities
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub enum PluginCapability {
32    /// Process messages before they are sent to the LLM
33    PreProcessMessage,
34    /// Process messages after LLM response
35    PostProcessMessage,
36    /// Add custom commands
37    CustomCommands,
38    /// Modify query results
39    ModifyResults,
40    /// Add custom UI elements
41    CustomUI,
42    /// Integrate external services
43    ExternalIntegration,
44}
45
46/// Plugin hook points
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum PluginHook {
49    /// Before message processing
50    BeforeProcess,
51    /// After message processing
52    AfterProcess,
53    /// Before SPARQL execution
54    BeforeSPARQL,
55    /// After SPARQL execution
56    AfterSPARQL,
57    /// Before LLM call
58    BeforeLLM,
59    /// After LLM call
60    AfterLLM,
61}
62
63/// Plugin execution context
64#[derive(Debug, Clone)]
65pub struct PluginContext {
66    /// Current session ID
67    pub session_id: String,
68    /// User message
69    pub message: Option<Message>,
70    /// Additional context data
71    pub data: HashMap<String, serde_json::Value>,
72}
73
74/// Plugin trait - all plugins must implement this
75#[async_trait]
76pub trait Plugin: Send + Sync {
77    /// Get plugin metadata
78    fn metadata(&self) -> &PluginMetadata;
79
80    /// Initialize the plugin
81    async fn initialize(&mut self) -> Result<()> {
82        Ok(())
83    }
84
85    /// Execute plugin at a specific hook point
86    async fn execute(&self, hook: PluginHook, context: &mut PluginContext) -> Result<()>;
87
88    /// Shutdown the plugin
89    async fn shutdown(&mut self) -> Result<()> {
90        Ok(())
91    }
92
93    /// Check if plugin handles a specific hook
94    fn handles_hook(&self, hook: PluginHook) -> bool;
95}
96
97/// Plugin manager
98pub struct PluginManager {
99    plugins: Arc<RwLock<HashMap<String, Box<dyn Plugin>>>>,
100}
101
102impl PluginManager {
103    /// Create a new plugin manager
104    pub fn new() -> Self {
105        info!("Initialized plugin manager");
106
107        Self {
108            plugins: Arc::new(RwLock::new(HashMap::new())),
109        }
110    }
111
112    /// Register a plugin
113    pub async fn register_plugin(&self, plugin: Box<dyn Plugin>) -> Result<()> {
114        let metadata = plugin.metadata();
115        let plugin_name = metadata.name.clone();
116
117        info!("Registering plugin: {} v{}", plugin_name, metadata.version);
118
119        let mut plugins = self.plugins.write().await;
120        plugins.insert(plugin_name, plugin);
121
122        Ok(())
123    }
124
125    /// Unregister a plugin
126    pub async fn unregister_plugin(&self, plugin_name: &str) -> Result<()> {
127        info!("Unregistering plugin: {}", plugin_name);
128
129        let mut plugins = self.plugins.write().await;
130        if let Some(mut plugin) = plugins.remove(plugin_name) {
131            plugin.shutdown().await?;
132        }
133
134        Ok(())
135    }
136
137    /// Execute all plugins at a specific hook point
138    pub async fn execute_hook(&self, hook: PluginHook, context: &mut PluginContext) -> Result<()> {
139        debug!("Executing hook: {:?}", hook);
140
141        let plugins = self.plugins.read().await;
142
143        for (name, plugin) in plugins.iter() {
144            if plugin.handles_hook(hook) {
145                debug!("Executing plugin {} for hook {:?}", name, hook);
146
147                if let Err(e) = plugin.execute(hook, context).await {
148                    warn!("Plugin {} failed at hook {:?}: {}", name, hook, e);
149                    // Continue with other plugins
150                }
151            }
152        }
153
154        Ok(())
155    }
156
157    /// Get list of registered plugins
158    pub async fn list_plugins(&self) -> Vec<PluginMetadata> {
159        let plugins = self.plugins.read().await;
160        plugins.values().map(|p| p.metadata().clone()).collect()
161    }
162
163    /// Get plugin by name
164    pub async fn get_plugin(&self, name: &str) -> Option<PluginMetadata> {
165        let plugins = self.plugins.read().await;
166        plugins.get(name).map(|p| p.metadata().clone())
167    }
168}
169
170impl Default for PluginManager {
171    fn default() -> Self {
172        Self::new()
173    }
174}
175
176/// Example plugin: Message logger
177pub struct MessageLoggerPlugin {
178    metadata: PluginMetadata,
179    log_file: Option<String>,
180}
181
182impl MessageLoggerPlugin {
183    pub fn new(log_file: Option<String>) -> Self {
184        Self {
185            metadata: PluginMetadata {
186                name: "message-logger".to_string(),
187                version: "1.0.0".to_string(),
188                author: "OxiRS Team".to_string(),
189                description: "Logs all messages to a file".to_string(),
190                capabilities: vec![
191                    PluginCapability::PreProcessMessage,
192                    PluginCapability::PostProcessMessage,
193                ],
194            },
195            log_file,
196        }
197    }
198}
199
200#[async_trait]
201impl Plugin for MessageLoggerPlugin {
202    fn metadata(&self) -> &PluginMetadata {
203        &self.metadata
204    }
205
206    async fn execute(&self, hook: PluginHook, context: &mut PluginContext) -> Result<()> {
207        if let Some(message) = &context.message {
208            let log_entry = format!(
209                "[{:?}] Session: {}, Message: {}",
210                hook, context.session_id, message.content
211            );
212
213            if let Some(ref file) = self.log_file {
214                use std::fs::OpenOptions;
215                use std::io::Write;
216
217                let mut file = OpenOptions::new().create(true).append(true).open(file)?;
218
219                writeln!(file, "{}", log_entry)?;
220            } else {
221                info!("{}", log_entry);
222            }
223        }
224
225        Ok(())
226    }
227
228    fn handles_hook(&self, hook: PluginHook) -> bool {
229        matches!(hook, PluginHook::BeforeProcess | PluginHook::AfterProcess)
230    }
231}
232
233/// Example plugin: Profanity filter
234pub struct ProfanityFilterPlugin {
235    metadata: PluginMetadata,
236    blocked_words: Vec<String>,
237}
238
239impl ProfanityFilterPlugin {
240    pub fn new() -> Self {
241        Self {
242            metadata: PluginMetadata {
243                name: "profanity-filter".to_string(),
244                version: "1.0.0".to_string(),
245                author: "OxiRS Team".to_string(),
246                description: "Filters profanity from messages".to_string(),
247                capabilities: vec![PluginCapability::PreProcessMessage],
248            },
249            blocked_words: vec!["badword1".to_string(), "badword2".to_string()],
250        }
251    }
252}
253
254#[async_trait]
255impl Plugin for ProfanityFilterPlugin {
256    fn metadata(&self) -> &PluginMetadata {
257        &self.metadata
258    }
259
260    async fn execute(&self, _hook: PluginHook, context: &mut PluginContext) -> Result<()> {
261        if let Some(message) = &mut context.message {
262            let mut content = message.content.to_string();
263
264            for word in &self.blocked_words {
265                content = content.replace(word, &"*".repeat(word.len()));
266            }
267
268            // Update message content (simplified - would need proper MessageContent handling)
269            context
270                .data
271                .insert("filtered_content".to_string(), serde_json::json!(content));
272        }
273
274        Ok(())
275    }
276
277    fn handles_hook(&self, hook: PluginHook) -> bool {
278        matches!(hook, PluginHook::BeforeProcess)
279    }
280}
281
282impl Default for ProfanityFilterPlugin {
283    fn default() -> Self {
284        Self::new()
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use crate::messages::{MessageContent, MessageRole};
292    use chrono::Utc;
293
294    #[tokio::test]
295    async fn test_plugin_registration() {
296        let manager = PluginManager::new();
297        let plugin = Box::new(MessageLoggerPlugin::new(None));
298
299        manager
300            .register_plugin(plugin)
301            .await
302            .expect("should succeed");
303
304        let plugins = manager.list_plugins().await;
305        assert_eq!(plugins.len(), 1);
306        assert_eq!(plugins[0].name, "message-logger");
307    }
308
309    #[tokio::test]
310    async fn test_plugin_execution() {
311        let manager = PluginManager::new();
312        let plugin = Box::new(MessageLoggerPlugin::new(None));
313
314        manager
315            .register_plugin(plugin)
316            .await
317            .expect("should succeed");
318
319        let message = Message {
320            id: uuid::Uuid::new_v4().to_string(),
321            role: MessageRole::User,
322            content: MessageContent::from_text("Test message".to_string()),
323            timestamp: Utc::now(),
324            metadata: None,
325            thread_id: None,
326            parent_message_id: None,
327            token_count: None,
328            reactions: Vec::new(),
329            attachments: Vec::new(),
330            rich_elements: Vec::new(),
331        };
332
333        let mut context = PluginContext {
334            session_id: "test-session".to_string(),
335            message: Some(message),
336            data: HashMap::new(),
337        };
338
339        manager
340            .execute_hook(PluginHook::BeforeProcess, &mut context)
341            .await
342            .expect("should succeed");
343    }
344}