1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct PluginMetadata {
17 pub name: String,
19 pub version: String,
21 pub author: String,
23 pub description: String,
25 pub capabilities: Vec<PluginCapability>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub enum PluginCapability {
32 PreProcessMessage,
34 PostProcessMessage,
36 CustomCommands,
38 ModifyResults,
40 CustomUI,
42 ExternalIntegration,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum PluginHook {
49 BeforeProcess,
51 AfterProcess,
53 BeforeSPARQL,
55 AfterSPARQL,
57 BeforeLLM,
59 AfterLLM,
61}
62
63#[derive(Debug, Clone)]
65pub struct PluginContext {
66 pub session_id: String,
68 pub message: Option<Message>,
70 pub data: HashMap<String, serde_json::Value>,
72}
73
74#[async_trait]
76pub trait Plugin: Send + Sync {
77 fn metadata(&self) -> &PluginMetadata;
79
80 async fn initialize(&mut self) -> Result<()> {
82 Ok(())
83 }
84
85 async fn execute(&self, hook: PluginHook, context: &mut PluginContext) -> Result<()>;
87
88 async fn shutdown(&mut self) -> Result<()> {
90 Ok(())
91 }
92
93 fn handles_hook(&self, hook: PluginHook) -> bool;
95}
96
97pub struct PluginManager {
99 plugins: Arc<RwLock<HashMap<String, Box<dyn Plugin>>>>,
100}
101
102impl PluginManager {
103 pub fn new() -> Self {
105 info!("Initialized plugin manager");
106
107 Self {
108 plugins: Arc::new(RwLock::new(HashMap::new())),
109 }
110 }
111
112 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 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 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 }
151 }
152 }
153
154 Ok(())
155 }
156
157 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 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
176pub 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
233pub 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 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}