matrixcode-core 0.4.43

MatrixCode Agent Core - Pure logic, no UI
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Context Callback Handler
//!
//! Handles context callback requests from external services.
//! Enables external nodes to access workflow context data.

use std::collections::HashMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

use super::security::SecurityValidator;
use crate::matrixrpc::{ErrorCode, JsonRpcError, JsonRpcId, JsonRpcResponse, ServiceId};

/// Context operation type
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextOperation {
    /// Get a value from context
    Get,

    /// Set a value in context
    Set,

    /// Delete a value from context
    Delete,

    /// List all keys
    List,

    /// Check if key exists
    Exists,

    /// Clear all context
    Clear,
}

impl Default for ContextOperation {
    fn default() -> Self {
        Self::Get
    }
}

impl ContextOperation {
    /// Get the string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            ContextOperation::Get => "get",
            ContextOperation::Set => "set",
            ContextOperation::Delete => "delete",
            ContextOperation::List => "list",
            ContextOperation::Exists => "exists",
            ContextOperation::Clear => "clear",
        }
    }
}

/// Context callback request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextCallbackRequest {
    /// Request ID from original node execution
    pub request_id: String,

    /// Service ID making the callback
    pub service_id: ServiceId,

    /// Security token
    pub token: String,

    /// Operation to perform
    #[serde(default)]
    pub operation: ContextOperation,

    /// Key to access
    #[serde(default)]
    pub key: Option<String>,

    /// Value to set (for Set operation)
    #[serde(default)]
    pub value: Option<JsonValue>,

    /// Namespace for the key
    #[serde(default)]
    pub namespace: Option<String>,
}

/// Context callback result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextCallbackResult {
    /// Operation that was performed
    pub operation: String,

    /// Key that was accessed
    #[serde(default)]
    pub key: Option<String>,

    /// Value (for Get operation)
    #[serde(default)]
    pub value: Option<JsonValue>,

    /// Keys (for List operation)
    #[serde(default)]
    pub keys: Vec<String>,

    /// Whether key exists (for Exists operation)
    #[serde(default)]
    pub exists: Option<bool>,

    /// Status message
    pub status: String,

    /// Additional metadata
    #[serde(default)]
    pub metadata: JsonValue,
}

/// Context callback error
#[derive(Debug, thiserror::Error)]
pub enum ContextCallbackError {
    /// Security validation failed
    #[error("Security validation failed: {0}")]
    SecurityFailed(String),

    /// Key not found
    #[error("Context key '{0}' not found")]
    KeyNotFound(String),

    /// Key already exists
    #[error("Context key '{0}' already exists")]
    KeyExists(String),

    /// Invalid operation
    #[error("Invalid context operation: {0}")]
    InvalidOperation(String),

    /// Missing key
    #[error("Missing key for context operation")]
    MissingKey,

    /// Missing value
    #[error("Missing value for Set operation")]
    MissingValue,

    /// Namespace not accessible
    #[error("Namespace '{0}' is not accessible")]
    NamespaceNotAccessible(String),

    /// Read-only context
    #[error("Context is read-only, cannot perform {0} operation")]
    ReadOnly(String),

    /// Internal error
    #[error("Internal error: {0}")]
    Internal(String),
}

/// Context namespace configuration
#[derive(Debug, Clone)]
pub struct ContextNamespaceConfig {
    /// Public namespaces (accessible to all)
    pub public: Vec<String>,

    /// Service-specific namespaces
    pub service_namespaces: HashMap<ServiceId, Vec<String>>,

    /// Read-only namespaces
    pub readonly: Vec<String>,

    /// Maximum context size per namespace
    pub max_size: usize,
}

impl Default for ContextNamespaceConfig {
    fn default() -> Self {
        Self {
            public: vec![
                "workflow".to_string(), "input".to_string(),
                "output".to_string(), "variables".to_string(),
            ],
            service_namespaces: HashMap::new(),
            readonly: vec![
                "input".to_string(), "system".to_string(),
            ],
            max_size: 1024,
        }
    }
}

/// Context store
#[derive(Debug, Default)]
struct ContextStore {
    /// Data store by namespace
    namespaces: HashMap<String, HashMap<String, JsonValue>>,
}

impl ContextStore {
    fn new() -> Self {
        Self::default()
    }

    fn get(&self, namespace: &str, key: &str) -> Option<&JsonValue> {
        self.namespaces.get(namespace)?.get(key)
    }

    fn set(&mut self, namespace: &str, key: &str, value: JsonValue) {
        self.namespaces
            .entry(namespace.to_string())
            .or_insert_with(HashMap::new)
            .insert(key.to_string(), value);
    }

    fn delete(&mut self, namespace: &str, key: &str) -> Option<JsonValue> {
        self.namespaces.get_mut(namespace)?.remove(key)
    }

    fn list(&self, namespace: &str) -> Vec<String> {
        self.namespaces
            .get(namespace)
            .map(|ns| ns.keys().cloned().collect())
            .unwrap_or_default()
    }

    fn exists(&self, namespace: &str, key: &str) -> bool {
        self.namespaces
            .get(namespace)
            .map(|ns| ns.contains_key(key))
            .unwrap_or(false)
    }

    fn clear(&mut self, namespace: &str) {
        if let Some(ns) = self.namespaces.get_mut(namespace) {
            ns.clear();
        }
    }
}

/// Context Callback Handler
///
/// Handles context callback requests from external extension services.
pub struct ContextCallbackHandler {
    /// Security validator
    security: Arc<SecurityValidator>,

    /// Context store
    store: Arc<tokio::sync::RwLock<ContextStore>>,

    /// Namespace configuration
    namespace_config: ContextNamespaceConfig,
}

impl ContextCallbackHandler {
    /// Create a new context callback handler
    pub fn new(security: Arc<SecurityValidator>) -> Self {
        Self {
            security,
            store: Arc::new(tokio::sync::RwLock::new(ContextStore::new())),
            namespace_config: ContextNamespaceConfig::default(),
        }
    }

    /// Set namespace configuration
    pub fn with_namespace_config(mut self, config: ContextNamespaceConfig) -> Self {
        self.namespace_config = config;
        self
    }

    /// Initialize with existing context
    pub async fn initialize_context(&self, namespace: &str, data: HashMap<String, JsonValue>) {
        let mut store = self.store.write().await;
        store.namespaces.insert(namespace.to_string(), data);
    }

    /// Handle a context callback request
    pub async fn handle(&self, request: ContextCallbackRequest) -> Result<ContextCallbackResult, ContextCallbackError> {
        // Validate security
        let validation = self
            .security
            .validate(&request.token, &request.service_id, &request.request_id, "context")
            .await;

        if !validation.is_valid {
            return Err(ContextCallbackError::SecurityFailed(
                validation.error.unwrap_or_else(|| "Unknown security error".to_string()),
            ));
        }

        // Get namespace (default to "workflow")
        let namespace = request.namespace.clone().unwrap_or_else(|| "workflow".to_string());

        // Check namespace accessibility
        if !self.is_namespace_accessible(&namespace, &request.service_id) {
            return Err(ContextCallbackError::NamespaceNotAccessible(namespace));
        }

        // Check if read-only namespace for write operations
        if self.namespace_config.readonly.contains(&namespace)
            && matches!(
                request.operation,
                ContextOperation::Set | ContextOperation::Delete | ContextOperation::Clear
            )
        {
            return Err(ContextCallbackError::ReadOnly(request.operation.as_str().to_string()));
        }

        let mut store = self.store.write().await;

        match request.operation {
            ContextOperation::Get => {
                let key = request.key.clone().ok_or(ContextCallbackError::MissingKey)?;
                let value = store
                    .get(&namespace, &key)
                    .cloned()
                    .ok_or_else(|| ContextCallbackError::KeyNotFound(key.clone()))?;

                Ok(ContextCallbackResult {
                    operation: "get".to_string(),
                    key: Some(key),
                    value: Some(value),
                    keys: vec![],
                    exists: None,
                    status: "success".to_string(),
                    metadata: serde_json::json!({
                        "namespace": namespace,
                        "request_id": request.request_id,
                    }),
                })
            }

            ContextOperation::Set => {
                let key = request.key.clone().ok_or(ContextCallbackError::MissingKey)?;
                let value = request.value.clone().ok_or(ContextCallbackError::MissingValue)?;

                store.set(&namespace, &key, value.clone());

                Ok(ContextCallbackResult {
                    operation: "set".to_string(),
                    key: Some(key),
                    value: Some(value),
                    keys: vec![],
                    exists: None,
                    status: "success".to_string(),
                    metadata: serde_json::json!({
                        "namespace": namespace,
                        "request_id": request.request_id,
                    }),
                })
            }

            ContextOperation::Delete => {
                let key = request.key.clone().ok_or(ContextCallbackError::MissingKey)?;
                let existed = store.delete(&namespace, &key).is_some();

                Ok(ContextCallbackResult {
                    operation: "delete".to_string(),
                    key: Some(key),
                    value: None,
                    keys: vec![],
                    exists: Some(existed),
                    status: if existed { "success" } else { "not_found" }.to_string(),
                    metadata: serde_json::json!({
                        "namespace": namespace,
                        "request_id": request.request_id,
                    }),
                })
            }

            ContextOperation::List => {
                let keys = store.list(&namespace);
                let keys_count = keys.len();

                Ok(ContextCallbackResult {
                    operation: "list".to_string(),
                    key: None,
                    value: None,
                    keys,
                    exists: None,
                    status: "success".to_string(),
                    metadata: serde_json::json!({
                        "namespace": namespace,
                        "request_id": request.request_id,
                        "count": keys_count,
                    }),
                })
            }

            ContextOperation::Exists => {
                let key = request.key.clone().ok_or(ContextCallbackError::MissingKey)?;
                let exists = store.exists(&namespace, &key);

                Ok(ContextCallbackResult {
                    operation: "exists".to_string(),
                    key: Some(key),
                    value: None,
                    keys: vec![],
                    exists: Some(exists),
                    status: "success".to_string(),
                    metadata: serde_json::json!({
                        "namespace": namespace,
                        "request_id": request.request_id,
                    }),
                })
            }

            ContextOperation::Clear => {
                store.clear(&namespace);

                Ok(ContextCallbackResult {
                    operation: "clear".to_string(),
                    key: None,
                    value: None,
                    keys: vec![],
                    exists: None,
                    status: "success".to_string(),
                    metadata: serde_json::json!({
                        "namespace": namespace,
                        "request_id": request.request_id,
                    }),
                })
            }
        }
    }

    /// Check if namespace is accessible for a service
    fn is_namespace_accessible(&self, namespace: &str, service_id: &ServiceId) -> bool {
        // Public namespaces are accessible to all
        if self.namespace_config.public.contains(&namespace.to_string()) {
            return true;
        }

        // Check service-specific namespaces
        if let Some(namespaces) = self.namespace_config.service_namespaces.get(service_id) {
            if namespaces.contains(&namespace.to_string()) {
                return true;
            }
        }

        false
    }

    /// Create a JSON-RPC error response for context callback failures
    pub fn create_error_response(&self, error: ContextCallbackError, id: JsonRpcId) -> JsonRpcResponse {
        let (code, message, data) = match error {
            ContextCallbackError::SecurityFailed(msg) => (
                ErrorCode::PERMISSION_DENIED,
                "Security validation failed".to_string(),
                Some(serde_json::json!({ "reason": msg })),
            ),
            ContextCallbackError::KeyNotFound(key) => (
                ErrorCode::RESOURCE_NOT_FOUND,
                format!("Context key '{}' not found", key),
                None,
            ),
            ContextCallbackError::KeyExists(key) => (
                ErrorCode::RESOURCE_EXISTS,
                format!("Context key '{}' already exists", key),
                None,
            ),
            ContextCallbackError::InvalidOperation(op) => (
                ErrorCode::INVALID_PARAMS,
                format!("Invalid context operation: {}", op),
                None,
            ),
            ContextCallbackError::MissingKey => (
                ErrorCode::INVALID_PARAMS,
                "Missing key for context operation".to_string(),
                None,
            ),
            ContextCallbackError::MissingValue => (
                ErrorCode::INVALID_PARAMS,
                "Missing value for Set operation".to_string(),
                None,
            ),
            ContextCallbackError::NamespaceNotAccessible(ns) => (
                ErrorCode::PERMISSION_DENIED,
                format!("Namespace '{}' is not accessible", ns),
                None,
            ),
            ContextCallbackError::ReadOnly(op) => (
                ErrorCode::PERMISSION_DENIED,
                format!("Context is read-only, cannot perform {} operation", op),
                None,
            ),
            ContextCallbackError::Internal(msg) => (
                ErrorCode::INTERNAL_ERROR,
                msg,
                None,
            ),
        };

        JsonRpcResponse::error(
            id,
            JsonRpcError::with_data(code, message, data.unwrap_or(JsonValue::Null)),
        )
    }

    /// Get all available namespaces for a service
    pub fn get_available_namespaces(&self, service_id: &ServiceId) -> Vec<String> {
        let mut namespaces = self.namespace_config.public.clone();

        if let Some(service_ns) = self.namespace_config.service_namespaces.get(service_id) {
            namespaces.extend(service_ns.clone());
        }

        namespaces
    }
}

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

    #[tokio::test]
    async fn test_context_callback_handler_creation() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security);

        assert!(!handler.namespace_config.public.is_empty());
    }

    #[tokio::test]
    async fn test_initialize_context() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security);

        let data = HashMap::from([
            ("key1".to_string(), serde_json::json!("value1")),
            ("key2".to_string(), serde_json::json!(42)),
        ]);

        handler.initialize_context("workflow", data).await;

        // Verify by doing a List operation
        let store = handler.store.read().await;
        let keys = store.list("workflow");
        assert_eq!(keys.len(), 2);
    }

    #[tokio::test]
    async fn test_context_get() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security.clone());

        // Initialize context
        handler
            .initialize_context(
                "workflow",
                HashMap::from([("test_key".to_string(), serde_json::json!("test_value"))]),
            )
            .await;

        // Generate token
        let service_id = ServiceId::new("test-service");
        let request_id = "req-001".to_string();
        let token = security
            .generate_token(service_id.clone(), request_id.clone(), vec!["context".to_string()])
            .await
            .unwrap();

        let request = ContextCallbackRequest {
            request_id,
            service_id,
            token,
            operation: ContextOperation::Get,
            key: Some("test_key".to_string()),
            value: None,
            namespace: Some("workflow".to_string()),
        };

        let result = handler.handle(request).await.unwrap();
        assert_eq!(result.operation, "get");
        assert_eq!(result.key, Some("test_key".to_string()));
        assert_eq!(result.value, Some(serde_json::json!("test_value")));
    }

    #[tokio::test]
    async fn test_context_set() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security.clone());

        // Generate token
        let service_id = ServiceId::new("test-service");
        let request_id = "req-001".to_string();
        let token = security
            .generate_token(service_id.clone(), request_id.clone(), vec!["context".to_string()])
            .await
            .unwrap();

        let request = ContextCallbackRequest {
            request_id,
            service_id,
            token,
            operation: ContextOperation::Set,
            key: Some("new_key".to_string()),
            value: Some(serde_json::json!("new_value")),
            namespace: Some("workflow".to_string()),
        };

        let result = handler.handle(request).await.unwrap();
        assert_eq!(result.operation, "set");
        assert_eq!(result.status, "success");
    }

    #[tokio::test]
    async fn test_context_list() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security.clone());

        handler
            .initialize_context(
                "workflow",
                HashMap::from([
                    ("key1".to_string(), serde_json::json!(1)),
                    ("key2".to_string(), serde_json::json!(2)),
                ]),
            )
            .await;

        let service_id = ServiceId::new("test-service");
        let request_id = "req-001".to_string();
        let token = security
            .generate_token(service_id.clone(), request_id.clone(), vec!["context".to_string()])
            .await
            .unwrap();

        let request = ContextCallbackRequest {
            request_id,
            service_id,
            token,
            operation: ContextOperation::List,
            key: None,
            value: None,
            namespace: Some("workflow".to_string()),
        };

        let result = handler.handle(request).await.unwrap();
        assert_eq!(result.keys.len(), 2);
    }

    #[tokio::test]
    async fn test_context_exists() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security.clone());

        handler
            .initialize_context(
                "workflow",
                HashMap::from([("existing_key".to_string(), serde_json::json!("value"))]),
            )
            .await;

        let service_id = ServiceId::new("test-service");
        let request_id = "req-001".to_string();
        let token = security
            .generate_token(service_id.clone(), request_id.clone(), vec!["context".to_string()])
            .await
            .unwrap();

        // Test existing key
        let request = ContextCallbackRequest {
            request_id,
            service_id,
            token,
            operation: ContextOperation::Exists,
            key: Some("existing_key".to_string()),
            value: None,
            namespace: Some("workflow".to_string()),
        };

        let result = handler.handle(request).await.unwrap();
        assert_eq!(result.exists, Some(true));
    }

    #[tokio::test]
    async fn test_context_readonly_namespace() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security.clone());

        let service_id = ServiceId::new("test-service");
        let request_id = "req-001".to_string();
        let token = security
            .generate_token(service_id.clone(), request_id.clone(), vec!["context".to_string()])
            .await
            .unwrap();

        // "input" is read-only by default
        let request = ContextCallbackRequest {
            request_id,
            service_id,
            token,
            operation: ContextOperation::Set,
            key: Some("key".to_string()),
            value: Some(serde_json::json!("value")),
            namespace: Some("input".to_string()),
        };

        let result = handler.handle(request).await;
        assert!(matches!(result, Err(ContextCallbackError::ReadOnly(_))));
    }

    #[test]
    fn test_namespace_accessible() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security);

        // Public namespace
        assert!(handler.is_namespace_accessible("workflow", &ServiceId::new("any")));

        // Not accessible (not public and not in service namespaces)
        assert!(!handler.is_namespace_accessible("private", &ServiceId::new("any")));
    }

    #[test]
    fn test_get_available_namespaces() {
        let security = Arc::new(SecurityValidator::new());
        let handler = ContextCallbackHandler::new(security);

        let namespaces = handler.get_available_namespaces(&ServiceId::new("test"));
        assert!(namespaces.contains(&"workflow".to_string()));
        assert!(namespaces.contains(&"input".to_string()));
    }
}