symbi-runtime 1.10.0

Agent Runtime System for the Symbi platform
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# Symbiont Agent Runtime API Reference

Complete API documentation for the Symbiont Agent Runtime System.

## Core Types

### Identifiers

```rust
// Unique identifiers for various entities
pub struct AgentId(Uuid);
pub struct TaskId(Uuid);
pub struct MessageId(Uuid);
pub struct RequestId(Uuid);
pub struct AuditId(Uuid);
pub struct SandboxId(Uuid);
pub struct SnapshotId(Uuid);

impl AgentId {
    pub fn new() -> Self;
}
// Similar for all ID types
```

### Agent Types

```rust
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentState {
    Created,
    Initializing,
    Ready,
    Running,
    Suspended,
    Waiting,
    Completed,
    Failed,
    Terminating,
    Terminated,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionMode {
    Persistent,
    Ephemeral,
    Scheduled { interval: Duration },
    EventDriven,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Priority {
    Critical = 4,
    High = 3,
    Normal = 2,
    Low = 1,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Capability {
    FileSystem,
    Network,
    Database,
    Custom(String),
}

pub struct AgentConfig {
    pub id: AgentId,
    pub name: String,
    pub dsl_source: String,
    pub execution_mode: ExecutionMode,
    pub security_tier: SecurityTier,
    pub resource_limits: ResourceLimits,
    pub capabilities: Vec<Capability>,
    pub policies: Vec<Policy>,
    pub metadata: HashMap<String, String>,
    pub priority: Priority,
}

pub struct AgentInstance {
    pub id: AgentId,
    pub config: AgentConfig,
    pub state: AgentState,
    pub created_at: SystemTime,
    pub last_updated: SystemTime,
    pub execution_count: u64,
    pub error_count: u32,
    pub restart_count: u32,
}
```

### Resource Types

```rust
pub struct ResourceLimits {
    pub memory_mb: u64,
    pub cpu_cores: f64,
    pub disk_io_mbps: u64,
    pub network_io_mbps: u64,
    pub execution_timeout: Duration,
    pub idle_timeout: Duration,
}

pub struct ResourceUsage {
    pub memory_used: u64,
    pub cpu_usage: f64,
    pub disk_io_rate: u64,
    pub network_io_rate: u64,
    pub uptime: Duration,
}

pub struct ResourceAllocation {
    pub agent_id: AgentId,
    pub allocated_at: SystemTime,
    pub limits: ResourceLimits,
    pub current_usage: ResourceUsage,
}
```

### Security Types

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SecurityTier {
    Tier1 = 1, // Docker
    Tier2 = 2, // gVisor
    Tier3 = 3, // Firecracker
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    None,
    Low,
    Medium,
    High,
    Maximum,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EncryptionAlgorithm {
    Aes256Gcm,
    ChaCha20Poly1305,
}

pub struct SecurityContext {
    pub tier: SecurityTier,
    pub isolation_level: IsolationLevel,
    pub encryption_algorithm: EncryptionAlgorithm,
    pub signing_key: Option<Vec<u8>>,
    pub encryption_key: Option<Vec<u8>>,
}
```

### Communication Types

```rust
pub struct Message {
    pub id: MessageId,
    pub from: AgentId,
    pub to: AgentId,
    pub topic: String,
    pub payload: Vec<u8>,
    pub priority: Priority,
    pub ttl: Duration,
}

pub struct SecureMessage {
    pub message: Message,
    pub signature: Vec<u8>,
    pub encrypted_payload: Vec<u8>,
    pub timestamp: SystemTime,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeliveryStatus {
    Pending,
    Delivered,
    Failed,
    Expired,
}
```

### Error Types

```rust
#[derive(Debug, Clone)]
pub enum RuntimeError {
    Resource(ResourceError),
    Communication(CommunicationError),
    Security(SecurityError),
    Scheduler(SchedulerError),
    Lifecycle(LifecycleError),
    ErrorHandler(ErrorHandlerError),
    Configuration(ConfigurationError),
    Policy(PolicyError),
    Sandbox(SandboxError),
    Audit(AuditError),
    Internal(String),
}

#[derive(Debug, Clone)]
pub enum ResourceError {
    InsufficientResources { requirements: String },
    AllocationFailed { agent_id: AgentId },
    DeallocationFailed { agent_id: AgentId },
    UsageExceeded { agent_id: AgentId, resource: String },
    MonitoringFailed { reason: String },
}

#[derive(Debug, Clone)]
pub enum LifecycleError {
    AgentNotFound { agent_id: AgentId },
    InvalidStateTransition { from: AgentState, to: AgentState },
    InitializationFailed { agent_id: AgentId, reason: String },
    TerminationFailed { agent_id: AgentId, reason: String },
    ConfigurationInvalid { reason: String },
}

#[derive(Debug, Clone)]
pub enum CommunicationError {
    AgentNotRegistered { agent_id: AgentId },
    MessageTooLarge { size: usize, max_size: usize },
    DeliveryFailed { message_id: MessageId, reason: String },
    EncryptionFailed { reason: String },
    TopicNotFound { topic: String },
}
```

## Core Interfaces

### 1. Lifecycle Controller

```rust
#[async_trait]
pub trait LifecycleController {
    async fn create_agent(&self, config: AgentConfig) -> Result<AgentInstance, LifecycleError>;
    async fn initialize_agent(&self, agent_id: AgentId) -> Result<(), LifecycleError>;
    async fn start_agent(&self, agent_id: AgentId) -> Result<(), LifecycleError>;
    async fn stop_agent(&self, agent_id: AgentId) -> Result<(), LifecycleError>;
    async fn suspend_agent(&self, agent_id: AgentId) -> Result<(), LifecycleError>;
    async fn resume_agent(&self, agent_id: AgentId) -> Result<(), LifecycleError>;
    async fn terminate_agent(&self, agent_id: AgentId) -> Result<(), LifecycleError>;
    async fn get_agent_state(&self, agent_id: AgentId) -> Result<AgentState, LifecycleError>;
    async fn list_agents(&self) -> Vec<AgentInstance>;
    async fn get_agent(&self, agent_id: AgentId) -> Result<AgentInstance, LifecycleError>;
    async fn update_agent_config(&self, agent_id: AgentId, config: AgentConfig) -> Result<(), LifecycleError>;
    async fn restart_agent(&self, agent_id: AgentId) -> Result<(), LifecycleError>;
    async fn get_system_status(&self) -> SystemStatus;
    async fn shutdown(&self) -> Result<(), LifecycleError>;
}

pub struct LifecycleConfig {
    pub initialization_timeout: Duration,
    pub termination_timeout: Duration,
    pub state_check_interval: Duration,
    pub enable_auto_recovery: bool,
    pub max_restart_attempts: u32,
    pub max_agents: usize,
}
```

### 2. Resource Manager

```rust
#[async_trait]
pub trait ResourceManager {
    async fn allocate_resources(&self, agent_id: AgentId, limits: ResourceLimits) -> Result<ResourceAllocation, ResourceError>;
    async fn deallocate_resources(&self, agent_id: AgentId) -> Result<(), ResourceError>;
    async fn update_resource_limits(&self, agent_id: AgentId, limits: ResourceLimits) -> Result<(), ResourceError>;
    async fn get_resource_usage(&self, agent_id: AgentId) -> Result<ResourceUsage, ResourceError>;
    async fn get_system_resources(&self) -> SystemResourceStatus;
    async fn check_resource_violations(&self) -> Vec<ResourceViolation>;
    async fn set_resource_alerts(&self, agent_id: AgentId, thresholds: ResourceThresholds) -> Result<(), ResourceError>;
    async fn get_resource_history(&self, agent_id: AgentId, duration: Duration) -> Result<Vec<ResourceSnapshot>, ResourceError>;
    async fn shutdown(&self) -> Result<(), ResourceError>;
}

pub struct ResourceManagerConfig {
    pub total_memory: usize,
    pub total_cpu_cores: u32,
    pub total_disk_space: usize,
    pub total_network_bandwidth: usize,
    pub enforcement_enabled: bool,
    pub auto_scaling_enabled: bool,
    pub resource_reservation_percentage: f32,
    pub monitoring_interval: Duration,
}
```

### 3. Scheduler

```rust
#[async_trait]
pub trait Scheduler {
    async fn schedule_task(&self, task: ScheduledTask) -> Result<(), SchedulerError>;
    async fn cancel_task(&self, task_id: TaskId) -> Result<(), SchedulerError>;
    async fn get_task_status(&self, task_id: TaskId) -> Result<TaskStatus, SchedulerError>;
    async fn list_pending_tasks(&self) -> Vec<ScheduledTask>;
    async fn list_running_tasks(&self) -> Vec<RunningTask>;
    async fn get_scheduler_metrics(&self) -> SchedulerMetrics;
    async fn update_task_priority(&self, task_id: TaskId, priority: Priority) -> Result<(), SchedulerError>;
    async fn pause_scheduling(&self) -> Result<(), SchedulerError>;
    async fn resume_scheduling(&self) -> Result<(), SchedulerError>;
    async fn shutdown(&self) -> Result<(), SchedulerError>;
}

pub struct ScheduledTask {
    pub id: TaskId,
    pub agent_id: AgentId,
    pub priority: Priority,
    pub scheduled_time: SystemTime,
    pub timeout: Duration,
    pub retry_count: u32,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoadBalancingStrategy {
    RoundRobin,
    LeastConnections,
    ResourceBased,
    WeightedRoundRobin,
}

pub struct SchedulerConfig {
    pub max_concurrent_tasks: usize,
    pub task_timeout: Duration,
    pub retry_attempts: u32,
    pub load_balancing_strategy: LoadBalancingStrategy,
    pub enable_priority_scheduling: bool,
    pub task_queue_size: usize,
    pub worker_threads: usize,
    pub health_check_interval: Duration,
}
```

### 4. Communication Bus

```rust
#[async_trait]
pub trait CommunicationBus {
    async fn register_agent(&self, agent_id: AgentId, capabilities: Vec<Capability>) -> Result<(), CommunicationError>;
    async fn unregister_agent(&self, agent_id: AgentId) -> Result<(), CommunicationError>;
    async fn send_message(&self, message: Message) -> Result<MessageId, CommunicationError>;
    async fn receive_messages(&self, agent_id: AgentId) -> Result<Vec<SecureMessage>, CommunicationError>;
    async fn subscribe_to_topic(&self, agent_id: AgentId, topic: String) -> Result<(), CommunicationError>;
    async fn unsubscribe_from_topic(&self, agent_id: AgentId, topic: String) -> Result<(), CommunicationError>;
    async fn broadcast_message(&self, topic: String, message: Message) -> Result<Vec<MessageId>, CommunicationError>;
    async fn get_message_status(&self, message_id: MessageId) -> Result<DeliveryStatus, CommunicationError>;
    async fn get_agent_topics(&self, agent_id: AgentId) -> Result<Vec<String>, CommunicationError>;
    async fn shutdown(&self) -> Result<(), CommunicationError>;
}

pub struct CommunicationConfig {
    pub message_ttl: Duration,
    pub max_queue_size: usize,
    pub delivery_timeout: Duration,
    pub retry_attempts: u32,
    pub enable_encryption: bool,
    pub enable_compression: bool,
    pub max_message_size: usize,
    pub dead_letter_queue_size: usize,
}
```

### 5. Error Handler

```rust
#[async_trait]
pub trait ErrorHandler {
    async fn handle_error(&self, agent_id: AgentId, error: RuntimeError) -> Result<ErrorAction, ErrorHandlerError>;
    async fn register_strategy(&self, error_type: ErrorType, strategy: RecoveryStrategy) -> Result<(), ErrorHandlerError>;
    async fn get_error_stats(&self, agent_id: AgentId) -> Result<ErrorStatistics, ErrorHandlerError>;
    async fn get_system_error_stats(&self) -> SystemErrorStatistics;
    async fn set_error_thresholds(&self, agent_id: AgentId, thresholds: ErrorThresholds) -> Result<(), ErrorHandlerError>;
    async fn clear_error_history(&self, agent_id: AgentId) -> Result<(), ErrorHandlerError>;
    async fn shutdown(&self) -> Result<(), ErrorHandlerError>;
}

#[derive(Debug, Clone)]
pub enum ErrorAction {
    Retry { max_attempts: u32, backoff: Duration },
    Restart,
    Suspend,
    Terminate,
    Failover,
}

#[derive(Debug, Clone)]
pub enum RecoveryStrategy {
    Retry { max_attempts: u32, backoff: Duration },
    Restart { preserve_state: bool },
    Failover { backup_agent: Option<AgentId> },
    Terminate { cleanup: bool },
    Manual { reason: String },
    None,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorType {
    ResourceExhaustion,
    NetworkError,
    SecurityViolation,
    PolicyViolation,
    SystemError,
    ValidationError,
}

pub struct ErrorHandlerConfig {
    pub max_error_history: usize,
    pub error_aggregation_window: Duration,
    pub escalation_threshold: u32,
    pub circuit_breaker_threshold: u32,
    pub circuit_breaker_timeout: Duration,
    pub enable_auto_recovery: bool,
    pub max_recovery_attempts: u32,
    pub recovery_backoff_multiplier: f32,
}
```

## External Integrations

### 1. Policy Engine

```rust
#[async_trait]
pub trait PolicyEngine {
    async fn validate_agent_config(&self, config: &AgentConfig) -> Result<PolicyValidationResult, PolicyError>;
    async fn check_operation_allowed(&self, agent_id: AgentId, operation: &str, context: &PolicyContext) -> Result<bool, PolicyError>;
    async fn get_agent_policies(&self, agent_id: AgentId) -> Result<Vec<Policy>, PolicyError>;
    async fn update_policy(&self, policy: Policy) -> Result<(), PolicyError>;
    async fn delete_policy(&self, policy_id: String) -> Result<(), PolicyError>;
    async fn evaluate_policy(&self, policy_id: String, context: &PolicyContext) -> Result<PolicyDecision, PolicyError>;
}

pub struct Policy {
    pub id: String,
    pub name: String,
    pub description: String,
    pub rules: Vec<PolicyRule>,
    pub priority: u32,
    pub enabled: bool,
}

pub struct PolicyContext {
    pub agent_id: AgentId,
    pub operation: String,
    pub resource_requirements: Option<ResourceLimits>,
    pub security_context: SecurityContext,
    pub metadata: HashMap<String, String>,
}
```

### 2. Sandbox Orchestrator

```rust
#[async_trait]
pub trait SandboxOrchestrator {
    async fn create_sandbox(&self, config: SandboxConfig) -> Result<SandboxId, SandboxError>;
    async fn start_sandbox(&self, sandbox_id: SandboxId) -> Result<(), SandboxError>;
    async fn stop_sandbox(&self, sandbox_id: SandboxId) -> Result<(), SandboxError>;
    async fn destroy_sandbox(&self, sandbox_id: SandboxId) -> Result<(), SandboxError>;
    async fn get_sandbox_status(&self, sandbox_id: SandboxId) -> Result<SandboxStatus, SandboxError>;
    async fn execute_command(&self, sandbox_id: SandboxId, command: &str, args: Vec<String>) -> Result<CommandResult, SandboxError>;
    async fn upload_file(&self, sandbox_id: SandboxId, local_path: &str, remote_path: &str) -> Result<(), SandboxError>;
    async fn download_file(&self, sandbox_id: SandboxId, remote_path: &str, local_path: &str) -> Result<(), SandboxError>;
}

pub struct SandboxConfig {
    pub agent_id: AgentId,
    pub security_tier: SecurityTier,
    pub resource_limits: ResourceLimits,
    pub network_config: NetworkConfig,
    pub filesystem_config: FilesystemConfig,
    pub environment_variables: HashMap<String, String>,
}
```

### 3. Audit Trail

```rust
#[async_trait]
pub trait AuditTrail {
    async fn record_event(&self, event: AuditEvent) -> Result<AuditId, AuditError>;
    async fn query_events(&self, query: AuditQuery) -> Result<Vec<AuditEvent>, AuditError>;
    async fn verify_integrity(&self, from_time: SystemTime, to_time: SystemTime) -> Result<IntegrityReport, AuditError>;
    async fn get_event(&self, audit_id: AuditId) -> Result<AuditEvent, AuditError>;
    async fn export_events(&self, query: AuditQuery, format: ExportFormat) -> Result<Vec<u8>, AuditError>;
}

pub struct AuditEvent {
    pub id: AuditId,
    pub timestamp: SystemTime,
    pub event_type: AuditEventType,
    pub agent_id: Option<AgentId>,
    pub details: String,
    pub metadata: HashMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuditEventType {
    AgentCreated,
    AgentStarted,
    AgentStopped,
    AgentTerminated,
    ResourceAllocated,
    ResourceDeallocated,
    MessageSent,
    MessageReceived,
    ErrorOccurred,
    PolicyViolation,
    SecurityEvent,
}
```

## Usage Examples

### Complete Agent Lifecycle

```rust
use symbiont_runtime::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize components
    let lifecycle_controller = DefaultLifecycleController::new(LifecycleConfig::default()).await?;
    let resource_manager = DefaultResourceManager::new(ResourceManagerConfig::default()).await?;
    let scheduler = DefaultScheduler::new(SchedulerConfig::default()).await?;
    let comm_bus = DefaultCommunicationBus::new(CommunicationConfig::default()).await?;
    let error_handler = DefaultErrorHandler::new(ErrorHandlerConfig::default()).await?;

    // Create agent configuration
    let agent_config = AgentConfig {
        id: AgentId::new(),
        name: "example_agent".to_string(),
        dsl_source: "agent logic".to_string(),
        execution_mode: ExecutionMode::Persistent,
        security_tier: SecurityTier::Tier2,
        resource_limits: ResourceLimits {
            memory_mb: 512,
            cpu_cores: 1.0,
            disk_io_mbps: 50,
            network_io_mbps: 10,
            execution_timeout: Duration::from_secs(3600),
            idle_timeout: Duration::from_secs(300),
        },
        capabilities: vec![Capability::FileSystem, Capability::Network],
        policies: vec![],
        metadata: HashMap::new(),
        priority: Priority::Normal,
    };

    // Create and manage agent
    let agent = lifecycle_controller.create_agent(agent_config.clone()).await?;
    println!("Created agent: {}", agent.id);

    // Allocate resources
    let allocation = resource_manager.allocate_resources(agent.id, agent_config.resource_limits).await?;
    println!("Allocated resources for agent: {}", agent.id);

    // Register with communication bus
    comm_bus.register_agent(agent.id, agent_config.capabilities).await?;
    println!("Registered agent with communication bus");

    // Initialize and start agent
    lifecycle_controller.initialize_agent(agent.id).await?;
    lifecycle_controller.start_agent(agent.id).await?;
    println!("Agent started successfully");

    // Schedule a task
    let task = ScheduledTask {
        id: TaskId::new(),
        agent_id: agent.id,
        priority: Priority::Normal,
        scheduled_time: SystemTime::now(),
        timeout: Duration::from_secs(60),
        retry_count: 0,
    };
    scheduler.schedule_task(task).await?;

    // Send a message
    let message = Message {
        id: MessageId::new(),
        from: agent.id,
        to: agent.id, // Self-message for demo
        topic: "test_topic".to_string(),
        payload: b"Hello, world!".to_vec(),
        priority: Priority::Normal,
        ttl: Duration::from_secs(300),
    };
    comm_bus.send_message(message).await?;

    // Monitor and cleanup
    tokio::time::sleep(Duration::from_secs(5)).await;
    
    let state = lifecycle_controller.get_agent_state(agent.id).await?;
    println!("Agent state: {:?}", state);
    
    let usage = resource_manager.get_resource_usage(agent.id).await?;
    println!("Resource usage: {:?}", usage);

    // Shutdown
    lifecycle_controller.terminate_agent(agent.id).await?;
    resource_manager.deallocate_resources(agent.id).await?;
    comm_bus.unregister_agent(agent.id).await?;

    Ok(())
}
```

This API reference provides complete type definitions and interface specifications for all components of the Symbiont Agent Runtime System, including the optional HTTP API.

## HTTP API Reference

### Overview

The HTTP API provides RESTful endpoints for external system integration. This API is optional and requires the `http-api` feature flag to be enabled.

#### Feature Activation

```toml
[dependencies]
symbiont-runtime = { version = "0.1.0", features = ["http-api"] }
```

#### Configuration

```rust
#[cfg(feature = "http-api")]
use symbiont_runtime::api::{HttpApiServer, HttpApiConfig};

let config = HttpApiConfig {
    bind_address: "127.0.0.1".to_string(),
    port: 8080,
    enable_cors: true,
    enable_tracing: true,
};

let server = HttpApiServer::new(config);
server.start().await?;
```

### HTTP API Types

#### Request/Response Types

```rust
#[cfg(feature = "http-api")]
pub struct WorkflowExecutionRequest {
    pub workflow_id: String,
    pub parameters: serde_json::Value,
    pub agent_id: Option<AgentId>,
}

#[cfg(feature = "http-api")]
pub struct AgentStatusResponse {
    pub agent_id: AgentId,
    pub state: AgentState,
    pub last_activity: chrono::DateTime<chrono::Utc>,
    pub resource_usage: ResourceUsage,
}

#[cfg(feature = "http-api")]
pub struct HealthResponse {
    pub status: String,
    pub uptime_seconds: u64,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub version: String,
}

#[cfg(feature = "http-api")]
pub struct ErrorResponse {
    pub error: String,
    pub code: String,
    pub details: Option<serde_json::Value>,
}

#[cfg(feature = "http-api")]
pub struct ResourceUsage {
    pub memory_bytes: u64,
    pub cpu_percent: f64,
    pub active_tasks: u32,
}
```

### Endpoints

#### Health Check

**Endpoint:** `GET /api/v1/health`
**Description:** Returns system health status and version information.

**Response:**
```json
{
  "status": "healthy",
  "uptime_seconds": 3600,
  "timestamp": "2025-07-18T06:45:00Z",
  "version": "0.1.0"
}
```

**Example:**
```bash
curl http://localhost:8080/api/v1/health
```

#### List Agents

**Endpoint:** `GET /api/v1/agents`
**Description:** Returns a list of all active agent IDs.

**Response:**
```json
[
  "agent-id-1",
  "agent-id-2",
  "agent-id-3"
]
```

**Example:**
```bash
curl http://localhost:8080/api/v1/agents
```

#### Get Agent Status

**Endpoint:** `GET /api/v1/agents/{id}/status`
**Description:** Returns detailed status information for a specific agent.

**Parameters:**
- `id` (path): Agent ID

**Response:**
```json
{
  "agent_id": "agent-id-1",
  "state": "Running",
  "last_activity": "2025-07-18T06:45:00Z",
  "resource_usage": {
    "memory_bytes": 104857600,
    "cpu_percent": 15.5,
    "active_tasks": 3
  }
}
```

**Example:**
```bash
curl http://localhost:8080/api/v1/agents/agent-id-1/status
```

#### Execute Workflow

**Endpoint:** `POST /api/v1/workflows/execute`
**Description:** Executes a workflow with specified parameters.

**Request Body:**
```json
{
  "workflow_id": "data-processing",
  "parameters": {
    "input_file": "/data/input.csv",
    "output_format": "json"
  },
  "agent_id": "agent-id-1"
}
```

**Response:**
```json
{
  "result": "success",
  "output": {
    "processed_records": 1000,
    "output_file": "/data/output.json"
  }
}
```

**Example:**
```bash
curl -X POST http://localhost:8080/api/v1/workflows/execute \
  -H "Content-Type: application/json" \
  -d '{"workflow_id": "example", "parameters": {}}'
```

#### Get System Metrics

**Endpoint:** `GET /api/v1/metrics`
**Description:** Returns system performance metrics and statistics.

**Response:**
```json
{
  "agents": {
    "total": 10,
    "running": 8,
    "stopped": 2
  },
  "system": {
    "memory_usage": 85.5,
    "cpu_usage": 45.2,
    "uptime_seconds": 7200
  },
  "performance": {
    "messages_per_second": 1250,
    "avg_response_time_ms": 15
  }
}
```

**Example:**
```bash
curl http://localhost:8080/api/v1/metrics
```

### Error Handling

All endpoints return consistent error responses:

```json
{
  "error": "Agent not found",
  "code": "AGENT_NOT_FOUND",
  "details": {
    "agent_id": "invalid-agent-id"
  }
}
```

**HTTP Status Codes:**
- `200 OK` - Successful operation
- `400 Bad Request` - Invalid request parameters
- `404 Not Found` - Resource not found
- `500 Internal Server Error` - Server error

### Authentication & Security

The HTTP API includes middleware for:
- CORS handling (configurable)
- Request tracing and logging
- Rate limiting (planned)
- Authentication (planned)

Current implementation uses placeholder middleware that can be extended for production use.

This API reference provides complete type definitions and interface specifications for all components of the Symbiont Agent Runtime System, including the optional HTTP API.