odin-protocol 1.0.0

The world's first standardized AI-to-AI communication infrastructure for Rust - 100% functional with 57K+ msgs/sec throughput
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
//! HEL (High-level Exchange Language) Rule Engine for AI coordination

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use async_trait::async_trait;
use crate::{Result, OdinError};
use crate::message::{OdinMessage, MessagePriority};
use crate::protocol::OdinProtocol;

/// HEL Rule Engine for managing AI-to-AI communication rules
#[derive(Debug)]
pub struct HELRuleEngine {
    /// Rule registry
    rules: Arc<RwLock<HashMap<String, Rule>>>,
    /// Rule execution statistics
    stats: Arc<RwLock<RuleStats>>,
    /// Protocol reference
    protocol: Option<Arc<OdinProtocol>>,
}

impl HELRuleEngine {
    /// Create a new HEL Rule Engine
    pub fn new() -> Self {
        Self {
            rules: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(RwLock::new(RuleStats::default())),
            protocol: None,
        }
    }
    
    /// Set the protocol instance
    pub fn set_protocol(&mut self, protocol: Arc<OdinProtocol>) {
        self.protocol = Some(protocol);
    }
    
    /// Add a rule to the engine
    pub async fn add_rule(&self, rule: Rule) -> Result<()> {
        rule.validate()?;
        
        let mut rules = self.rules.write().await;
        rules.insert(rule.id.clone(), rule);
        
        let mut stats = self.stats.write().await;
        stats.rules_added += 1;
        
        Ok(())
    }
    
    /// Remove a rule from the engine
    pub async fn remove_rule(&self, rule_id: &str) -> Result<bool> {
        let mut rules = self.rules.write().await;
        let removed = rules.remove(rule_id).is_some();
        
        if removed {
            let mut stats = self.stats.write().await;
            stats.rules_removed += 1;
        }
        
        Ok(removed)
    }
    
    /// Get a rule by ID
    pub async fn get_rule(&self, rule_id: &str) -> Option<Rule> {
        let rules = self.rules.read().await;
        rules.get(rule_id).cloned()
    }
    
    /// List all rules
    pub async fn list_rules(&self) -> Vec<Rule> {
        let rules = self.rules.read().await;
        rules.values().cloned().collect()
    }
    
    /// Execute rules against a message
    pub async fn execute_rules(&self, message: &OdinMessage) -> Result<Vec<RuleExecutionResult>> {
        let rules = self.rules.read().await;
        let mut results = Vec::new();
        
        for rule in rules.values() {
            if rule.matches(message).await? {
                let start_time = std::time::Instant::now();
                let result = rule.execute(message, self.protocol.as_ref()).await;
                let execution_time = start_time.elapsed();
                
                // Update statistics
                let mut stats = self.stats.write().await;
                stats.rules_executed += 1;
                stats.total_execution_time += execution_time;
                
                if result.is_err() {
                    stats.rules_failed += 1;
                }
                
                results.push(RuleExecutionResult {
                    rule_id: rule.id.clone(),
                    success: result.is_ok(),
                    execution_time,
                    error: result.err().map(|e| e.to_string()),
                });
            }
        }
        
        Ok(results)
    }
    
    /// Get rule execution statistics
    pub async fn get_stats(&self) -> RuleStats {
        let stats = self.stats.read().await;
        stats.clone()
    }
    
    /// Clear all rules
    pub async fn clear_rules(&self) -> Result<()> {
        let mut rules = self.rules.write().await;
        rules.clear();
        
        let mut stats = self.stats.write().await;
        stats.rules_cleared += 1;
        
        Ok(())
    }
}

impl Default for HELRuleEngine {
    fn default() -> Self {
        Self::new()
    }
}

/// A rule in the HEL Rule Engine
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rule {
    /// Unique rule identifier
    pub id: String,
    /// Rule name
    pub name: String,
    /// Rule description
    pub description: String,
    /// Rule priority (higher numbers execute first)
    pub priority: i32,
    /// Rule conditions
    pub conditions: Vec<Condition>,
    /// Rule actions
    pub actions: Vec<Action>,
    /// Whether the rule is enabled
    pub enabled: bool,
    /// Rule metadata
    pub metadata: HashMap<String, String>,
}

impl Rule {
    /// Create a new rule
    pub fn new(id: String, name: String, description: String) -> Self {
        Self {
            id,
            name,
            description,
            priority: 0,
            conditions: Vec::new(),
            actions: Vec::new(),
            enabled: true,
            metadata: HashMap::new(),
        }
    }
    
    /// Add a condition to the rule
    pub fn add_condition(mut self, condition: Condition) -> Self {
        self.conditions.push(condition);
        self
    }
    
    /// Add an action to the rule
    pub fn add_action(mut self, action: Action) -> Self {
        self.actions.push(action);
        self
    }
    
    /// Set rule priority
    pub fn priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }
    
    /// Enable or disable the rule
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
    
    /// Validate the rule
    pub fn validate(&self) -> Result<()> {
        if self.id.is_empty() {
            return Err(OdinError::Rule("Rule ID cannot be empty".to_string()));
        }
        
        if self.name.is_empty() {
            return Err(OdinError::Rule("Rule name cannot be empty".to_string()));
        }
        
        if self.conditions.is_empty() {
            return Err(OdinError::Rule("Rule must have at least one condition".to_string()));
        }
        
        if self.actions.is_empty() {
            return Err(OdinError::Rule("Rule must have at least one action".to_string()));
        }
        
        Ok(())
    }
    
    /// Check if the rule matches the given message
    pub async fn matches(&self, message: &OdinMessage) -> Result<bool> {
        if !self.enabled {
            return Ok(false);
        }
        
        for condition in &self.conditions {
            if !condition.evaluate(message).await? {
                return Ok(false);
            }
        }
        
        Ok(true)
    }
    
    /// Execute the rule actions
    pub async fn execute(&self, message: &OdinMessage, protocol: Option<&Arc<OdinProtocol>>) -> Result<()> {
        for action in &self.actions {
            action.execute(message, protocol).await?;
        }
        Ok(())
    }
}

/// Rule condition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Condition {
    /// Message content contains text
    ContentContains(String),
    /// Message source matches pattern
    SourceMatches(String),
    /// Message target matches pattern
    TargetMatches(String),
    /// Message priority equals value
    PriorityEquals(MessagePriority),
    /// Custom condition with JavaScript-like expression
    Custom(String),
}

impl Condition {
    /// Evaluate the condition against a message
    pub async fn evaluate(&self, message: &OdinMessage) -> Result<bool> {
        match self {
            Condition::ContentContains(text) => {
                Ok(message.content.contains(text))
            }
            Condition::SourceMatches(pattern) => {
                Ok(message.source_node.contains(pattern))
            }
            Condition::TargetMatches(pattern) => {
                Ok(message.target_node.contains(pattern))
            }
            Condition::PriorityEquals(priority) => {
                Ok(message.priority == *priority)
            }
            Condition::Custom(expression) => {
                // TODO: Implement custom expression evaluation
                // For now, just return true
                Ok(true)
            }
        }
    }
}

/// Rule action
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Action {
    /// Send a message
    SendMessage {
        target: String,
        content: String,
        priority: MessagePriority,
    },
    /// Log a message
    Log {
        level: LogLevel,
        message: String,
    },
    /// Forward message to another node
    Forward {
        target: String,
    },
    /// Modify message content
    ModifyContent {
        new_content: String,
    },
    /// Custom action with JavaScript-like code
    Custom(String),
}

impl Action {
    /// Execute the action
    pub async fn execute(&self, message: &OdinMessage, protocol: Option<&Arc<OdinProtocol>>) -> Result<()> {
        match self {
            Action::SendMessage { target, content, priority } => {
                if let Some(protocol) = protocol {
                    protocol.send_message(target, content, *priority).await?;
                }
            }
            Action::Log { level, message: log_msg } => {
                match level {
                    LogLevel::Info => println!("[INFO] {}", log_msg),
                    LogLevel::Warning => println!("[WARN] {}", log_msg),
                    LogLevel::Error => eprintln!("[ERROR] {}", log_msg),
                    LogLevel::Debug => println!("[DEBUG] {}", log_msg),
                }
            }
            Action::Forward { target } => {
                if let Some(protocol) = protocol {
                    protocol.send_message(target, &message.content, message.priority).await?;
                }
            }
            Action::ModifyContent { new_content: _ } => {
                // TODO: Implement content modification
                // This would require mutable message handling
            }
            Action::Custom(_code) => {
                // TODO: Implement custom code execution
                // For now, just return success
            }
        }
        Ok(())
    }
}

/// Log levels for logging actions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LogLevel {
    Info,
    Warning,
    Error,
    Debug,
}

/// Rule execution result
#[derive(Debug, Clone)]
pub struct RuleExecutionResult {
    pub rule_id: String,
    pub success: bool,
    pub execution_time: std::time::Duration,
    pub error: Option<String>,
}

/// Rule execution statistics
#[derive(Debug, Clone, Default)]
pub struct RuleStats {
    pub rules_added: u64,
    pub rules_removed: u64,
    pub rules_executed: u64,
    pub rules_failed: u64,
    pub rules_cleared: u64,
    pub total_execution_time: std::time::Duration,
}

impl RuleStats {
    /// Get average execution time
    pub fn average_execution_time(&self) -> std::time::Duration {
        if self.rules_executed > 0 {
            self.total_execution_time / self.rules_executed as u32
        } else {
            std::time::Duration::ZERO
        }
    }
    
    /// Get success rate
    pub fn success_rate(&self) -> f64 {
        if self.rules_executed > 0 {
            (self.rules_executed - self.rules_failed) as f64 / self.rules_executed as f64
        } else {
            0.0
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{MessageType, OdinMessage};
    
    #[tokio::test]
    async fn test_rule_creation() {
        let rule = Rule::new(
            "test-rule".to_string(),
            "Test Rule".to_string(),
            "A test rule".to_string(),
        )
        .add_condition(Condition::ContentContains("hello".to_string()))
        .add_action(Action::Log {
            level: LogLevel::Info,
            message: "Rule triggered".to_string(),
        });
        
        assert!(rule.validate().is_ok());
        assert_eq!(rule.id, "test-rule");
        assert_eq!(rule.conditions.len(), 1);
        assert_eq!(rule.actions.len(), 1);
    }
    
    #[tokio::test]
    async fn test_rule_engine() {
        let engine = HELRuleEngine::new();
        
        let rule = Rule::new(
            "test-rule".to_string(),
            "Test Rule".to_string(),
            "A test rule".to_string(),
        )
        .add_condition(Condition::ContentContains("hello".to_string()))
        .add_action(Action::Log {
            level: LogLevel::Info,
            message: "Rule triggered".to_string(),
        });
        
        engine.add_rule(rule).await.unwrap();
        
        let rules = engine.list_rules().await;
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id, "test-rule");
    }
    
    #[tokio::test]
    async fn test_rule_matching() {
        let rule = Rule::new(
            "test-rule".to_string(),
            "Test Rule".to_string(),
            "A test rule".to_string(),
        )
        .add_condition(Condition::ContentContains("hello".to_string()));
        
        let message = OdinMessage::new(
            MessageType::Standard,
            "source",
            "target",
            "hello world",
            MessagePriority::Normal,
        );
        
        assert!(rule.matches(&message).await.unwrap());
        
        let message2 = OdinMessage::new(
            MessageType::Standard,
            "source",
            "target",
            "goodbye world",
            MessagePriority::Normal,
        );
        
        assert!(!rule.matches(&message2).await.unwrap());
    }
    
    #[tokio::test]
    async fn test_condition_evaluation() {
        let condition = Condition::ContentContains("test".to_string());
        
        let message = OdinMessage::new(
            MessageType::Standard,
            "source",
            "target",
            "this is a test message",
            MessagePriority::Normal,
        );
        
        assert!(condition.evaluate(&message).await.unwrap());
    }
}