terraphim_kg_agents 1.0.0

Specialized knowledge graph-based agent implementations
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Knowledge graph-based worker agent implementation
//!
//! This module provides a specialized GenAgent implementation for domain-specific
//! task execution using knowledge graph context and thesaurus systems.

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

use async_trait::async_trait;
use log::{debug, info, warn};
use serde::{Deserialize, Serialize};

use terraphim_automata::Automata;
use terraphim_gen_agent::{GenAgent, GenAgentResult};
use terraphim_rolegraph::RoleGraph;
use terraphim_task_decomposition::Task;

use crate::{KgAgentError, KgAgentResult};

/// Message types for the worker agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WorkerMessage {
    /// Execute a task
    ExecuteTask { task: Task },
    /// Check task compatibility
    CheckCompatibility { task: Task },
    /// Update domain specialization
    UpdateSpecialization {
        domain: String,
        expertise_level: f64,
    },
    /// Get execution status
    GetStatus,
    /// Pause execution
    Pause,
    /// Resume execution
    Resume,
}

/// Worker agent state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerState {
    /// Current execution status
    pub status: WorkerStatus,
    /// Domain specializations
    pub specializations: HashMap<String, DomainSpecialization>,
    /// Execution history
    pub execution_history: Vec<TaskExecution>,
    /// Performance metrics
    pub metrics: WorkerMetrics,
    /// Configuration
    pub config: WorkerConfig,
}

/// Worker execution status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WorkerStatus {
    Idle,
    Executing,
    Paused,
    Error,
}

/// Domain specialization information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DomainSpecialization {
    /// Domain name
    pub domain: String,
    /// Expertise level (0.0 to 1.0)
    pub expertise_level: f64,
    /// Number of tasks completed in this domain
    pub tasks_completed: u64,
    /// Success rate in this domain
    pub success_rate: f64,
    /// Average execution time
    pub average_execution_time: std::time::Duration,
    /// Domain-specific knowledge concepts
    pub knowledge_concepts: Vec<String>,
}

/// Task execution record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskExecution {
    /// Task identifier
    pub task_id: String,
    /// Task domain
    pub domain: String,
    /// Execution start time
    pub start_time: std::time::SystemTime,
    /// Execution duration
    pub duration: std::time::Duration,
    /// Success status
    pub success: bool,
    /// Error message if failed
    pub error_message: Option<String>,
    /// Knowledge concepts used
    pub concepts_used: Vec<String>,
    /// Confidence score
    pub confidence: f64,
}

/// Worker performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerMetrics {
    /// Total tasks executed
    pub total_tasks: u64,
    /// Successful tasks
    pub successful_tasks: u64,
    /// Average execution time
    pub average_execution_time: std::time::Duration,
    /// Overall success rate
    pub success_rate: f64,
    /// Domain distribution
    pub domain_distribution: HashMap<String, u64>,
}

impl Default for WorkerMetrics {
    fn default() -> Self {
        Self {
            total_tasks: 0,
            successful_tasks: 0,
            average_execution_time: std::time::Duration::ZERO,
            success_rate: 0.0,
            domain_distribution: HashMap::new(),
        }
    }
}

/// Worker agent configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerConfig {
    /// Maximum concurrent tasks
    pub max_concurrent_tasks: usize,
    /// Task execution timeout
    pub execution_timeout: std::time::Duration,
    /// Minimum confidence threshold for task acceptance
    pub min_confidence_threshold: f64,
    /// Enable domain learning
    pub enable_domain_learning: bool,
    /// Knowledge graph query timeout
    pub kg_query_timeout: std::time::Duration,
}

impl Default for WorkerConfig {
    fn default() -> Self {
        Self {
            max_concurrent_tasks: 5,
            execution_timeout: std::time::Duration::from_secs(300),
            min_confidence_threshold: 0.5,
            enable_domain_learning: true,
            kg_query_timeout: std::time::Duration::from_secs(10),
        }
    }
}

impl Default for WorkerState {
    fn default() -> Self {
        Self {
            status: WorkerStatus::Idle,
            specializations: HashMap::new(),
            execution_history: Vec::new(),
            metrics: WorkerMetrics::default(),
            config: WorkerConfig::default(),
        }
    }
}

/// Knowledge graph-based worker agent
pub struct KnowledgeGraphWorkerAgent {
    /// Agent identifier
    agent_id: String,
    /// Knowledge graph automata
    automata: Arc<Automata>,
    /// Role graph for domain specialization
    role_graph: Arc<RoleGraph>,
    /// Agent state
    state: WorkerState,
}

impl KnowledgeGraphWorkerAgent {
    /// Create a new worker agent
    pub fn new(
        agent_id: String,
        automata: Arc<Automata>,
        role_graph: Arc<RoleGraph>,
        config: WorkerConfig,
    ) -> Self {
        let state = WorkerState {
            status: WorkerStatus::Idle,
            specializations: HashMap::new(),
            execution_history: Vec::new(),
            metrics: WorkerMetrics::default(),
            config,
        };

        Self {
            agent_id,
            automata,
            role_graph,
            state,
        }
    }

    /// Execute a task using knowledge graph context
    async fn execute_task(&mut self, task: Task) -> KgAgentResult<TaskExecution> {
        info!("Executing task: {}", task.task_id);

        if self.state.status != WorkerStatus::Idle {
            return Err(KgAgentError::WorkerError(format!(
                "Worker {} is not idle (status: {:?})",
                self.agent_id, self.state.status
            )));
        }

        self.state.status = WorkerStatus::Executing;
        let start_time = std::time::SystemTime::now();

        // Check task compatibility first
        let compatibility = self.check_task_compatibility(&task).await?;
        if compatibility < self.state.config.min_confidence_threshold {
            self.state.status = WorkerStatus::Idle;
            return Err(KgAgentError::CompatibilityError(format!(
                "Task {} compatibility {} below threshold {}",
                task.task_id, compatibility, self.state.config.min_confidence_threshold
            )));
        }

        // Extract knowledge context for the task
        let knowledge_context = self.extract_knowledge_context(&task).await?;

        // Simulate task execution (in a real implementation, this would be domain-specific)
        let execution_result = self.perform_task_execution(&task, &knowledge_context).await;

        let duration = start_time.elapsed().unwrap_or(std::time::Duration::ZERO);
        let success = execution_result.is_ok();
        let error_message = if let Err(ref e) = execution_result {
            Some(e.to_string())
        } else {
            None
        };

        // Create execution record
        let execution = TaskExecution {
            task_id: task.task_id.clone(),
            domain: task
                .required_domains
                .first()
                .unwrap_or(&"general".to_string())
                .clone(),
            start_time,
            duration,
            success,
            error_message,
            concepts_used: knowledge_context,
            confidence: compatibility,
        };

        // Update metrics and specializations
        self.update_metrics(&execution);
        self.update_specializations(&execution);

        // Store execution history
        self.state.execution_history.push(execution.clone());

        // Limit history size
        if self.state.execution_history.len() > 1000 {
            self.state.execution_history.remove(0);
        }

        self.state.status = WorkerStatus::Idle;

        if success {
            info!(
                "Task {} executed successfully in {:.2}s",
                task.task_id,
                duration.as_secs_f64()
            );
        } else {
            warn!(
                "Task {} execution failed after {:.2}s: {:?}",
                task.task_id,
                duration.as_secs_f64(),
                error_message
            );
        }

        Ok(execution)
    }

    /// Check task compatibility using knowledge graph analysis
    async fn check_task_compatibility(&self, task: &Task) -> KgAgentResult<f64> {
        debug!("Checking compatibility for task: {}", task.task_id);

        let mut compatibility_score = 0.0;
        let mut factors = 0;

        // Check domain specialization
        for required_domain in &task.required_domains {
            if let Some(specialization) = self.state.specializations.get(required_domain) {
                compatibility_score += specialization.expertise_level * specialization.success_rate;
                factors += 1;
            }
        }

        // Check knowledge graph connectivity
        let task_concepts = &task.concepts;
        if !task_concepts.is_empty() {
            let connectivity_score = self.analyze_concept_connectivity(task_concepts).await?;
            compatibility_score += connectivity_score;
            factors += 1;
        }

        // Check capability requirements
        for required_capability in &task.required_capabilities {
            // Simple heuristic: check if we have experience with similar capabilities
            let capability_score = self.assess_capability_compatibility(required_capability);
            compatibility_score += capability_score;
            factors += 1;
        }

        let final_score = if factors > 0 {
            compatibility_score / factors as f64
        } else {
            0.5 // Default compatibility if no specific factors
        };

        debug!(
            "Task {} compatibility: {:.2} (based on {} factors)",
            task.task_id, final_score, factors
        );

        Ok(final_score)
    }

    /// Extract knowledge context using automata
    async fn extract_knowledge_context(&self, task: &Task) -> KgAgentResult<Vec<String>> {
        let context_text = format!(
            "{} {} {}",
            task.description,
            task.context_keywords.join(" "),
            task.concepts.join(" ")
        );

        // Mock implementation - in reality would use extract_paragraphs_from_automata
        let concepts = context_text
            .split_whitespace()
            .take(10)
            .map(|s| s.to_lowercase())
            .collect();

        debug!(
            "Extracted {} knowledge concepts for task {}",
            concepts.len(),
            task.task_id
        );

        Ok(concepts)
    }

    /// Perform the actual task execution
    async fn perform_task_execution(
        &self,
        task: &Task,
        knowledge_context: &[String],
    ) -> KgAgentResult<String> {
        debug!(
            "Performing execution for task {} with {} context concepts",
            task.task_id,
            knowledge_context.len()
        );

        // Simulate task execution based on complexity
        let execution_time = match task.complexity {
            terraphim_task_decomposition::TaskComplexity::Simple => {
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
            terraphim_task_decomposition::TaskComplexity::Moderate => {
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            }
            terraphim_task_decomposition::TaskComplexity::Complex => {
                tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
            }
            terraphim_task_decomposition::TaskComplexity::VeryComplex => {
                tokio::time::sleep(std::time::Duration::from_millis(2000)).await;
            }
        };

        // Simulate success/failure based on compatibility and knowledge context
        let success_probability = if knowledge_context.len() > 5 {
            0.9
        } else {
            0.7
        };
        let random_value: f64 = fastrand::f64();

        if random_value < success_probability {
            Ok(format!("Task {} completed successfully", task.task_id))
        } else {
            Err(KgAgentError::ExecutionFailed(format!(
                "Task {} execution failed due to insufficient context",
                task.task_id
            )))
        }
    }

    /// Analyze concept connectivity in knowledge graph
    async fn analyze_concept_connectivity(&self, concepts: &[String]) -> KgAgentResult<f64> {
        if concepts.len() < 2 {
            return Ok(1.0);
        }

        // Mock implementation - would use is_all_terms_connected_by_path
        let mut connectivity_score = 0.0;
        let mut pairs = 0;

        for i in 0..concepts.len() {
            for j in (i + 1)..concepts.len() {
                pairs += 1;
                // Simple heuristic: concepts are connected if they share characters
                let concept1 = &concepts[i];
                let concept2 = &concepts[j];
                if concept1.chars().any(|c| concept2.contains(c)) {
                    connectivity_score += 1.0;
                }
            }
        }

        let final_score = if pairs > 0 {
            connectivity_score / pairs as f64
        } else {
            0.0
        };

        Ok(final_score)
    }

    /// Assess capability compatibility
    fn assess_capability_compatibility(&self, capability: &str) -> f64 {
        // Check if we have experience with similar capabilities
        for execution in &self.state.execution_history {
            if execution.success
                && execution
                    .concepts_used
                    .iter()
                    .any(|c| c.contains(capability))
            {
                return 0.8;
            }
        }

        // Check domain specializations
        for specialization in self.state.specializations.values() {
            if specialization
                .knowledge_concepts
                .iter()
                .any(|c| c.contains(capability))
            {
                return specialization.expertise_level;
            }
        }

        0.3 // Default low compatibility
    }

    /// Update performance metrics
    fn update_metrics(&mut self, execution: &TaskExecution) {
        self.state.metrics.total_tasks += 1;
        if execution.success {
            self.state.metrics.successful_tasks += 1;
        }

        // Update success rate
        self.state.metrics.success_rate =
            self.state.metrics.successful_tasks as f64 / self.state.metrics.total_tasks as f64;

        // Update average execution time
        let total_time = self.state.metrics.average_execution_time.as_secs_f64()
            * (self.state.metrics.total_tasks - 1) as f64
            + execution.duration.as_secs_f64();
        self.state.metrics.average_execution_time =
            std::time::Duration::from_secs_f64(total_time / self.state.metrics.total_tasks as f64);

        // Update domain distribution
        *self
            .state
            .metrics
            .domain_distribution
            .entry(execution.domain.clone())
            .or_insert(0) += 1;
    }

    /// Update domain specializations
    fn update_specializations(&mut self, execution: &TaskExecution) {
        if !self.state.config.enable_domain_learning {
            return;
        }

        let specialization = self
            .state
            .specializations
            .entry(execution.domain.clone())
            .or_insert_with(|| DomainSpecialization {
                domain: execution.domain.clone(),
                expertise_level: 0.1,
                tasks_completed: 0,
                success_rate: 0.0,
                average_execution_time: std::time::Duration::ZERO,
                knowledge_concepts: Vec::new(),
            });

        specialization.tasks_completed += 1;

        // Update success rate
        let previous_successes =
            (specialization.success_rate * (specialization.tasks_completed - 1) as f64) as u64;
        let new_successes = if execution.success {
            previous_successes + 1
        } else {
            previous_successes
        };
        specialization.success_rate = new_successes as f64 / specialization.tasks_completed as f64;

        // Update expertise level based on success rate and experience
        let experience_factor = (specialization.tasks_completed as f64).ln().max(1.0) / 10.0;
        specialization.expertise_level =
            (specialization.success_rate * 0.7 + experience_factor * 0.3).min(1.0);

        // Update average execution time
        let total_time = specialization.average_execution_time.as_secs_f64()
            * (specialization.tasks_completed - 1) as f64
            + execution.duration.as_secs_f64();
        specialization.average_execution_time =
            std::time::Duration::from_secs_f64(total_time / specialization.tasks_completed as f64);

        // Update knowledge concepts
        for concept in &execution.concepts_used {
            if !specialization.knowledge_concepts.contains(concept) {
                specialization.knowledge_concepts.push(concept.clone());
            }
        }

        // Limit concept list size
        if specialization.knowledge_concepts.len() > 100 {
            specialization.knowledge_concepts.truncate(100);
        }
    }
}

#[async_trait]
impl GenAgent<WorkerState> for KnowledgeGraphWorkerAgent {
    type Message = WorkerMessage;

    async fn init(&mut self, _init_args: serde_json::Value) -> GenAgentResult<()> {
        info!("Initializing worker agent: {}", self.agent_id);
        self.state.status = WorkerStatus::Idle;
        Ok(())
    }

    async fn handle_call(&mut self, message: Self::Message) -> GenAgentResult<serde_json::Value> {
        match message {
            WorkerMessage::ExecuteTask { task } => {
                let execution = self.execute_task(task).await.map_err(|e| {
                    terraphim_gen_agent::GenAgentError::ExecutionError(
                        self.agent_id.clone(),
                        e.to_string(),
                    )
                })?;
                Ok(serde_json::to_value(execution).unwrap())
            }
            WorkerMessage::CheckCompatibility { task } => {
                let compatibility = self.check_task_compatibility(&task).await.map_err(|e| {
                    terraphim_gen_agent::GenAgentError::ExecutionError(
                        self.agent_id.clone(),
                        e.to_string(),
                    )
                })?;
                Ok(serde_json::to_value(compatibility).unwrap())
            }
            WorkerMessage::GetStatus => Ok(serde_json::to_value(&self.state.status).unwrap()),
            _ => {
                // Other messages don't return values in call context
                Ok(serde_json::Value::Null)
            }
        }
    }

    async fn handle_cast(&mut self, message: Self::Message) -> GenAgentResult<()> {
        match message {
            WorkerMessage::ExecuteTask { task } => {
                let _ = self.execute_task(task).await;
            }
            WorkerMessage::UpdateSpecialization {
                domain,
                expertise_level,
            } => {
                let specialization = self
                    .state
                    .specializations
                    .entry(domain.clone())
                    .or_insert_with(|| DomainSpecialization {
                        domain: domain.clone(),
                        expertise_level: 0.1,
                        tasks_completed: 0,
                        success_rate: 0.0,
                        average_execution_time: std::time::Duration::ZERO,
                        knowledge_concepts: Vec::new(),
                    });
                specialization.expertise_level = expertise_level.clamp(0.0, 1.0);
            }
            WorkerMessage::Pause => {
                if self.state.status == WorkerStatus::Executing {
                    self.state.status = WorkerStatus::Paused;
                }
            }
            WorkerMessage::Resume => {
                if self.state.status == WorkerStatus::Paused {
                    self.state.status = WorkerStatus::Executing;
                }
            }
            _ => {
                // Other messages handled in call context
            }
        }
        Ok(())
    }

    async fn handle_info(&mut self, _message: serde_json::Value) -> GenAgentResult<()> {
        // Handle system messages, health checks, etc.
        Ok(())
    }

    async fn terminate(&mut self, _reason: String) -> GenAgentResult<()> {
        info!("Terminating worker agent: {}", self.agent_id);
        self.state.status = WorkerStatus::Idle;
        Ok(())
    }

    fn get_state(&self) -> &WorkerState {
        &self.state
    }

    fn get_state_mut(&mut self) -> &mut WorkerState {
        &mut self.state
    }
}

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

    fn create_test_task() -> Task {
        let mut task = Task::new(
            "test_task".to_string(),
            "Test task for worker".to_string(),
            TaskComplexity::Simple,
            1,
        );
        task.required_domains = vec!["testing".to_string()];
        task.required_capabilities = vec!["test_execution".to_string()];
        task.concepts = vec!["test".to_string(), "execution".to_string()];
        task
    }

    async fn create_test_agent() -> KnowledgeGraphWorkerAgent {
        use terraphim_automata::{load_thesaurus, AutomataPath};
        use terraphim_types::RoleName;

        let automata = Arc::new(terraphim_automata::Automata::default());

        let role_name = RoleName::new("worker");
        let thesaurus = load_thesaurus(&AutomataPath::local_example())
            .await
            .unwrap();
        let role_graph = Arc::new(RoleGraph::new(role_name, thesaurus).await.unwrap());

        KnowledgeGraphWorkerAgent::new(
            "test_worker".to_string(),
            automata,
            role_graph,
            WorkerConfig::default(),
        )
    }

    #[tokio::test]
    async fn test_worker_agent_creation() {
        let agent = create_test_agent().await;
        assert_eq!(agent.agent_id, "test_worker");
        assert_eq!(agent.state.status, WorkerStatus::Idle);
    }

    #[tokio::test]
    async fn test_task_compatibility_check() {
        let agent = create_test_agent().await;
        let task = create_test_task();

        let compatibility = agent.check_task_compatibility(&task).await.unwrap();
        assert!(compatibility >= 0.0 && compatibility <= 1.0);
    }

    #[tokio::test]
    async fn test_knowledge_context_extraction() {
        let agent = create_test_agent().await;
        let task = create_test_task();

        let context = agent.extract_knowledge_context(&task).await.unwrap();
        assert!(!context.is_empty());
    }

    #[tokio::test]
    async fn test_concept_connectivity_analysis() {
        let agent = create_test_agent().await;
        let concepts = vec!["test".to_string(), "execution".to_string()];

        let connectivity = agent.analyze_concept_connectivity(&concepts).await.unwrap();
        assert!(connectivity >= 0.0 && connectivity <= 1.0);
    }

    #[tokio::test]
    async fn test_capability_compatibility() {
        let agent = create_test_agent().await;
        let compatibility = agent.assess_capability_compatibility("test_execution");
        assert!(compatibility >= 0.0 && compatibility <= 1.0);
    }

    #[tokio::test]
    async fn test_gen_agent_interface() {
        let mut agent = create_test_agent().await;

        // Test initialization
        let init_result = agent.init(serde_json::json!({})).await;
        assert!(init_result.is_ok());

        // Test call message
        let task = create_test_task();
        let message = WorkerMessage::CheckCompatibility { task };
        let call_result = agent.handle_call(message).await;
        assert!(call_result.is_ok());

        // Test cast message
        let message = WorkerMessage::Pause;
        let cast_result = agent.handle_cast(message).await;
        assert!(cast_result.is_ok());

        // Test termination
        let terminate_result = agent.terminate("test".to_string()).await;
        assert!(terminate_result.is_ok());
    }
}