symbi-runtime 1.4.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
//! Symbiont Agent Runtime System
//!
//! The Agent Runtime System is the core orchestration layer of the Symbiont platform,
//! responsible for managing the complete lifecycle of autonomous agents.

pub mod communication;
pub mod config;
pub mod context;
pub mod crypto;
pub mod error_handler;
pub mod integrations;
pub mod lifecycle;
pub mod logging;
pub mod metrics;
pub mod models;
pub mod rag;
pub mod resource;
pub mod routing;
pub mod sandbox;
pub mod scheduler;
pub mod secrets;
pub mod skills;
pub mod types;

#[cfg(feature = "cli-executor")]
pub mod cli_executor;

#[cfg(feature = "http-api")]
pub mod api;

#[cfg(feature = "http-api")]
use api::traits::RuntimeApiProvider;
#[cfg(feature = "http-api")]
use api::types::{
    AddIdentityMappingRequest, AgentStatusResponse, ChannelActionResponse, ChannelAuditResponse,
    ChannelDetail, ChannelHealthResponse, ChannelSummary, CreateAgentRequest, CreateAgentResponse,
    CreateScheduleRequest, CreateScheduleResponse, DeleteAgentResponse, DeleteChannelResponse,
    DeleteScheduleResponse, ExecuteAgentRequest, ExecuteAgentResponse, GetAgentHistoryResponse,
    IdentityMappingEntry, NextRunsResponse, RegisterChannelRequest, RegisterChannelResponse,
    ScheduleActionResponse, ScheduleDetail, ScheduleHistoryResponse, ScheduleSummary,
    UpdateAgentRequest, UpdateAgentResponse, UpdateChannelRequest, UpdateScheduleRequest,
    WorkflowExecutionRequest,
};
#[cfg(feature = "http-api")]
use async_trait::async_trait;

#[cfg(feature = "http-input")]
pub mod http_input;

// Re-export commonly used types
pub use communication::{CommunicationBus, CommunicationConfig, DefaultCommunicationBus};
pub use config::SecurityConfig;
pub use context::{ContextManager, ContextManagerConfig, StandardContextManager};
pub use error_handler::{DefaultErrorHandler, ErrorHandler, ErrorHandlerConfig};
pub use lifecycle::{DefaultLifecycleController, LifecycleConfig, LifecycleController};
pub use logging::{LoggingConfig, ModelInteractionType, ModelLogger, RequestData, ResponseData};
pub use models::{ModelCatalog, ModelCatalogError, SlmRunner, SlmRunnerError};
pub use resource::{DefaultResourceManager, ResourceManager, ResourceManagerConfig};
pub use routing::{
    DefaultRoutingEngine, RouteDecision, RoutingConfig, RoutingContext, RoutingEngine, TaskType,
};
pub use sandbox::{E2BSandbox, ExecutionResult, SandboxRunner, SandboxTier};
#[cfg(feature = "cron")]
pub use scheduler::{
    cron_scheduler::{
        CronMetrics, CronScheduler, CronSchedulerConfig, CronSchedulerError, CronSchedulerHealth,
    },
    cron_types::{
        AuditLevel, CronJobDefinition, CronJobId, CronJobStatus, DeliveryChannel, DeliveryConfig,
        DeliveryReceipt, JobRunRecord, JobRunStatus,
    },
    delivery::{CustomDeliveryHandler, DefaultDeliveryRouter, DeliveryResult, DeliveryRouter},
    heartbeat::{
        HeartbeatAssessment, HeartbeatConfig, HeartbeatContextMode, HeartbeatSeverity,
        HeartbeatState,
    },
    job_store::{JobStore, JobStoreError, SqliteJobStore},
    policy_gate::{
        PolicyGate, ScheduleContext, SchedulePolicyCondition, SchedulePolicyDecision,
        SchedulePolicyEffect, SchedulePolicyRule,
    },
};
pub use scheduler::{AgentScheduler, DefaultAgentScheduler, SchedulerConfig};
pub use secrets::{SecretStore, SecretsConfig};
pub use types::*;

use std::sync::Arc;
use tokio::sync::RwLock;

/// Main Agent Runtime System
#[derive(Clone)]
pub struct AgentRuntime {
    pub scheduler: Arc<dyn scheduler::AgentScheduler + Send + Sync>,
    pub lifecycle: Arc<dyn lifecycle::LifecycleController + Send + Sync>,
    pub resource_manager: Arc<dyn resource::ResourceManager + Send + Sync>,
    pub communication: Arc<dyn communication::CommunicationBus + Send + Sync>,
    pub error_handler: Arc<dyn error_handler::ErrorHandler + Send + Sync>,
    pub context_manager: Arc<dyn context::ContextManager + Send + Sync>,
    pub model_logger: Option<Arc<logging::ModelLogger>>,
    pub model_catalog: Option<Arc<models::ModelCatalog>>,
    config: Arc<RwLock<RuntimeConfig>>,
}

impl AgentRuntime {
    /// Create a new Agent Runtime System instance
    pub async fn new(config: RuntimeConfig) -> Result<Self, RuntimeError> {
        let config = Arc::new(RwLock::new(config));

        // Initialize components
        let scheduler = Arc::new(
            scheduler::DefaultAgentScheduler::new(config.read().await.scheduler.clone()).await?,
        );

        let resource_manager = Arc::new(
            resource::DefaultResourceManager::new(config.read().await.resource_manager.clone())
                .await?,
        );

        let communication = Arc::new(
            communication::DefaultCommunicationBus::new(config.read().await.communication.clone())
                .await?,
        );

        let error_handler = Arc::new(
            error_handler::DefaultErrorHandler::new(config.read().await.error_handler.clone())
                .await?,
        );

        let lifecycle_config = lifecycle::LifecycleConfig {
            max_agents: 1000,
            initialization_timeout: std::time::Duration::from_secs(30),
            termination_timeout: std::time::Duration::from_secs(30),
            state_check_interval: std::time::Duration::from_secs(10),
            enable_auto_recovery: true,
            max_restart_attempts: 3,
        };
        let lifecycle =
            Arc::new(lifecycle::DefaultLifecycleController::new(lifecycle_config).await?);

        let context_manager = Arc::new(
            context::StandardContextManager::new(
                config.read().await.context_manager.clone(),
                "runtime-system",
            )
            .await
            .map_err(|e| {
                RuntimeError::Internal(format!("Failed to create context manager: {}", e))
            })?,
        );

        // Initialize context manager
        context_manager.initialize().await.map_err(|e| {
            RuntimeError::Internal(format!("Failed to initialize context manager: {}", e))
        })?;

        // Initialize model logger if enabled
        let model_logger = if config.read().await.logging.enabled {
            // For now, initialize without secret store to avoid type conversion issues
            match logging::ModelLogger::new(config.read().await.logging.clone(), None) {
                Ok(logger) => {
                    tracing::info!("Model logging initialized successfully");
                    Some(Arc::new(logger))
                }
                Err(e) => {
                    tracing::warn!("Failed to initialize model logger: {}", e);
                    None
                }
            }
        } else {
            tracing::info!("Model logging is disabled");
            None
        };

        // Initialize model catalog if SLM is enabled
        let model_catalog = if let Some(ref slm_config) = config.read().await.slm {
            if slm_config.enabled {
                match models::ModelCatalog::new(slm_config.clone()) {
                    Ok(catalog) => {
                        tracing::info!(
                            "Model catalog initialized with {} models",
                            catalog.list_models().len()
                        );
                        Some(Arc::new(catalog))
                    }
                    Err(e) => {
                        tracing::warn!("Failed to initialize model catalog: {}", e);
                        None
                    }
                }
            } else {
                tracing::info!("SLM support is disabled");
                None
            }
        } else {
            tracing::info!("No SLM configuration provided");
            None
        };

        Ok(Self {
            scheduler,
            lifecycle,
            resource_manager,
            communication,
            error_handler,
            context_manager,
            model_logger,
            model_catalog,
            config,
        })
    }

    /// Get the current runtime configuration
    pub async fn get_config(&self) -> RuntimeConfig {
        self.config.read().await.clone()
    }

    /// Update the runtime configuration
    pub async fn update_config(&self, config: RuntimeConfig) -> Result<(), RuntimeError> {
        *self.config.write().await = config;
        Ok(())
    }

    /// Shutdown the runtime system gracefully
    pub async fn shutdown(&self) -> Result<(), RuntimeError> {
        tracing::info!("Starting Agent Runtime shutdown sequence");

        // Shutdown components in reverse order of initialization
        self.lifecycle
            .shutdown()
            .await
            .map_err(RuntimeError::Lifecycle)?;
        self.communication
            .shutdown()
            .await
            .map_err(RuntimeError::Communication)?;
        self.resource_manager
            .shutdown()
            .await
            .map_err(RuntimeError::Resource)?;
        self.scheduler
            .shutdown()
            .await
            .map_err(RuntimeError::Scheduler)?;
        self.error_handler
            .shutdown()
            .await
            .map_err(RuntimeError::ErrorHandler)?;

        // Shutdown context manager last to ensure all contexts are saved
        self.context_manager.shutdown().await.map_err(|e| {
            RuntimeError::Internal(format!("Context manager shutdown failed: {}", e))
        })?;

        tracing::info!("Agent Runtime shutdown completed successfully");
        Ok(())
    }

    /// Get system status
    pub async fn get_status(&self) -> SystemStatus {
        self.scheduler.get_system_status().await
    }
}

/// Runtime configuration
#[derive(Debug, Clone, Default)]
pub struct RuntimeConfig {
    pub scheduler: scheduler::SchedulerConfig,
    pub resource_manager: resource::ResourceManagerConfig,
    pub communication: communication::CommunicationConfig,
    pub context_manager: context::ContextManagerConfig,
    pub security: SecurityConfig,
    pub audit: AuditConfig,
    pub error_handler: error_handler::ErrorHandlerConfig,
    pub logging: logging::LoggingConfig,
    pub slm: Option<config::Slm>,
    pub routing: Option<routing::RoutingConfig>,
}

/// Implementation of RuntimeApiProvider for AgentRuntime
#[cfg(feature = "http-api")]
#[async_trait]
impl RuntimeApiProvider for AgentRuntime {
    async fn execute_workflow(
        &self,
        request: WorkflowExecutionRequest,
    ) -> Result<serde_json::Value, RuntimeError> {
        tracing::info!("Executing workflow: {}", request.workflow_id);

        // Step 1: Parse the workflow DSL and extract metadata (before any await)
        let workflow_dsl = &request.workflow_id; // For now, treat workflow_id as DSL source
        let (metadata, agent_config) = {
            let parsed_tree = dsl::parse_dsl(workflow_dsl)
                .map_err(|e| RuntimeError::Internal(format!("DSL parsing failed: {}", e)))?;

            // Extract metadata from the parsed workflow
            let metadata = dsl::extract_metadata(&parsed_tree, workflow_dsl);

            // Check for parsing errors
            let root_node = parsed_tree.root_node();
            if root_node.has_error() {
                return Err(RuntimeError::Internal(
                    "DSL contains syntax errors".to_string(),
                ));
            }

            // Create agent configuration from the workflow
            let agent_id = request.agent_id.unwrap_or_default();
            let agent_config = AgentConfig {
                id: agent_id,
                name: metadata
                    .get("name")
                    .cloned()
                    .unwrap_or_else(|| "workflow_agent".to_string()),
                dsl_source: workflow_dsl.to_string(),
                execution_mode: ExecutionMode::Ephemeral,
                security_tier: SecurityTier::Tier1,
                resource_limits: ResourceLimits::default(),
                capabilities: vec![Capability::Computation], // Basic capability for workflow execution
                policies: vec![],
                metadata: metadata.clone(),
                priority: Priority::Normal,
            };

            (metadata, agent_config)
        };

        // Step 2: Schedule the agent for execution
        let scheduled_agent_id = self
            .scheduler
            .schedule_agent(agent_config)
            .await
            .map_err(RuntimeError::Scheduler)?;

        // Step 3: Wait briefly and check initial status (simple implementation)
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Step 4: Collect basic execution information
        let system_status = self.scheduler.get_system_status().await;

        // Step 5: Prepare and return result
        let mut result = serde_json::json!({
            "status": "success",
            "workflow_id": request.workflow_id,
            "agent_id": scheduled_agent_id.to_string(),
            "execution_started": true,
            "metadata": metadata,
            "system_status": {
                "total_agents": system_status.total_agents,
                "running_agents": system_status.running_agents,
                "resource_utilization": {
                    "memory_used": system_status.resource_utilization.memory_used,
                    "cpu_utilization": system_status.resource_utilization.cpu_utilization,
                    "disk_io_rate": system_status.resource_utilization.disk_io_rate,
                    "network_io_rate": system_status.resource_utilization.network_io_rate
                }
            }
        });

        // Add parameters if provided
        if !request.parameters.is_null() {
            result["parameters"] = request.parameters;
        }

        tracing::info!(
            "Workflow execution initiated for agent: {}",
            scheduled_agent_id
        );
        Ok(result)
    }

    async fn get_agent_status(
        &self,
        agent_id: AgentId,
    ) -> Result<AgentStatusResponse, RuntimeError> {
        // Call the scheduler to get agent status
        match self.scheduler.get_agent_status(agent_id).await {
            Ok(agent_status) => {
                // Convert SystemTime to DateTime<Utc>
                let last_activity =
                    chrono::DateTime::<chrono::Utc>::from(agent_status.last_activity);

                Ok(AgentStatusResponse {
                    agent_id: agent_status.agent_id,
                    state: agent_status.state,
                    last_activity,
                    resource_usage: api::types::ResourceUsage {
                        memory_bytes: agent_status.memory_usage,
                        cpu_percent: agent_status.cpu_usage,
                        active_tasks: agent_status.active_tasks,
                    },
                })
            }
            Err(scheduler_error) => {
                tracing::warn!(
                    "Failed to get agent status for {}: {}",
                    agent_id,
                    scheduler_error
                );
                Err(RuntimeError::Internal(format!(
                    "Agent {} not found",
                    agent_id
                )))
            }
        }
    }

    async fn get_system_health(&self) -> Result<serde_json::Value, RuntimeError> {
        // Check health of all components
        let scheduler_health =
            self.scheduler.check_health().await.map_err(|e| {
                RuntimeError::Internal(format!("Scheduler health check failed: {}", e))
            })?;

        let lifecycle_health =
            self.lifecycle.check_health().await.map_err(|e| {
                RuntimeError::Internal(format!("Lifecycle health check failed: {}", e))
            })?;

        let resource_health = self.resource_manager.check_health().await.map_err(|e| {
            RuntimeError::Internal(format!("Resource manager health check failed: {}", e))
        })?;

        let communication_health = self.communication.check_health().await.map_err(|e| {
            RuntimeError::Internal(format!("Communication health check failed: {}", e))
        })?;

        // Determine overall system status
        let component_healths = vec![
            ("scheduler", &scheduler_health),
            ("lifecycle", &lifecycle_health),
            ("resource_manager", &resource_health),
            ("communication", &communication_health),
        ];

        let overall_status = if component_healths
            .iter()
            .all(|(_, h)| h.status == HealthStatus::Healthy)
        {
            "healthy"
        } else if component_healths
            .iter()
            .any(|(_, h)| h.status == HealthStatus::Unhealthy)
        {
            "unhealthy"
        } else {
            "degraded"
        };

        // Build response with detailed component information
        let mut components = serde_json::Map::new();
        for (name, health) in component_healths {
            let component_info = serde_json::json!({
                "status": match health.status {
                    HealthStatus::Healthy => "healthy",
                    HealthStatus::Degraded => "degraded",
                    HealthStatus::Unhealthy => "unhealthy",
                },
                "message": health.message,
                "last_check": health.last_check
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs(),
                "uptime_seconds": health.uptime.as_secs(),
                "metrics": health.metrics
            });
            components.insert(name.to_string(), component_info);
        }

        Ok(serde_json::json!({
            "status": overall_status,
            "timestamp": std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            "components": components
        }))
    }

    async fn list_agents(&self) -> Result<Vec<AgentId>, RuntimeError> {
        Ok(self.scheduler.list_agents().await)
    }

    async fn shutdown_agent(&self, agent_id: AgentId) -> Result<(), RuntimeError> {
        self.scheduler
            .shutdown_agent(agent_id)
            .await
            .map_err(RuntimeError::Scheduler)
    }

    async fn get_metrics(&self) -> Result<serde_json::Value, RuntimeError> {
        let status = self.get_status().await;
        Ok(serde_json::json!({
            "agents": {
                "total": status.total_agents,
                "running": status.running_agents,
                "idle": status.total_agents - status.running_agents,
                "error": 0
            },
            "system": {
                "uptime": 0,
                "memory_usage": status.resource_utilization.memory_used,
                "cpu_usage": status.resource_utilization.cpu_utilization
            }
        }))
    }

    async fn create_agent(
        &self,
        request: CreateAgentRequest,
    ) -> Result<CreateAgentResponse, RuntimeError> {
        // Validate input
        if request.name.is_empty() {
            return Err(RuntimeError::Internal(
                "Agent name cannot be empty".to_string(),
            ));
        }

        if request.dsl.is_empty() {
            return Err(RuntimeError::Internal(
                "Agent DSL cannot be empty".to_string(),
            ));
        }

        // Create agent configuration
        let agent_id = AgentId::new();
        let agent_config = AgentConfig {
            id: agent_id,
            name: request.name,
            dsl_source: request.dsl,
            execution_mode: ExecutionMode::Ephemeral,
            security_tier: SecurityTier::Tier1,
            resource_limits: ResourceLimits::default(),
            capabilities: vec![Capability::Computation],
            policies: vec![],
            metadata: std::collections::HashMap::new(),
            priority: Priority::Normal,
        };

        // Schedule the agent for execution
        let scheduled_agent_id = self
            .scheduler
            .schedule_agent(agent_config)
            .await
            .map_err(RuntimeError::Scheduler)?;

        tracing::info!("Created and scheduled agent: {}", scheduled_agent_id);

        Ok(CreateAgentResponse {
            id: scheduled_agent_id.to_string(),
            status: "scheduled".to_string(),
        })
    }

    async fn update_agent(
        &self,
        agent_id: AgentId,
        request: UpdateAgentRequest,
    ) -> Result<UpdateAgentResponse, RuntimeError> {
        // Validate that at least one field is provided for update
        if request.name.is_none() && request.dsl.is_none() {
            return Err(RuntimeError::Internal(
                "At least one field (name or dsl) must be provided for update".to_string(),
            ));
        }

        // Validate optional fields if provided
        if let Some(ref name) = request.name {
            if name.is_empty() {
                return Err(RuntimeError::Internal(
                    "Agent name cannot be empty".to_string(),
                ));
            }
        }

        if let Some(ref dsl) = request.dsl {
            if dsl.is_empty() {
                return Err(RuntimeError::Internal(
                    "Agent DSL cannot be empty".to_string(),
                ));
            }
        }

        // Call the scheduler to update the agent
        self.scheduler
            .update_agent(agent_id, request)
            .await
            .map_err(RuntimeError::Scheduler)?;

        tracing::info!("Successfully updated agent: {}", agent_id);

        Ok(UpdateAgentResponse {
            id: agent_id.to_string(),
            status: "updated".to_string(),
        })
    }

    async fn delete_agent(&self, agent_id: AgentId) -> Result<DeleteAgentResponse, RuntimeError> {
        // Placeholder implementation - validate input and return success

        Ok(DeleteAgentResponse {
            id: agent_id.to_string(),
            status: "deleted".to_string(),
        })
    }

    async fn execute_agent(
        &self,
        agent_id: AgentId,
        request: ExecuteAgentRequest,
    ) -> Result<ExecuteAgentResponse, RuntimeError> {
        let status = self.get_agent_status(agent_id).await?;
        if status.state != AgentState::Running {
            self.lifecycle
                .start_agent(agent_id)
                .await
                .map_err(RuntimeError::Lifecycle)?;
        }
        let execution_id = uuid::Uuid::new_v4().to_string();
        let payload_data: bytes::Bytes = serde_json::to_vec(&request)
            .map_err(|e| RuntimeError::Internal(e.to_string()))?
            .into();
        let message = self.communication.create_internal_message(
            AgentId::new(), // System sender
            agent_id,
            payload_data,
            types::MessageType::Direct(agent_id),
            std::time::Duration::from_secs(300),
        );
        self.communication
            .send_message(message)
            .await
            .map_err(RuntimeError::Communication)?;
        Ok(ExecuteAgentResponse {
            execution_id,
            status: "execution_started".to_string(),
        })
    }

    async fn get_agent_history(
        &self,
        _agent_id: AgentId,
    ) -> Result<GetAgentHistoryResponse, RuntimeError> {
        // For now, return empty history as the model logger API is not yet implemented
        let history = vec![];
        Ok(GetAgentHistoryResponse { history })
    }

    // ── Schedule endpoints ──────────────────────────────────────────

    async fn list_schedules(&self) -> Result<Vec<ScheduleSummary>, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler (use `symbi up` with --features cron)"
                .to_string(),
        ))
    }

    async fn create_schedule(
        &self,
        _request: CreateScheduleRequest,
    ) -> Result<CreateScheduleResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn get_schedule(&self, _job_id: &str) -> Result<ScheduleDetail, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn update_schedule(
        &self,
        _job_id: &str,
        _request: UpdateScheduleRequest,
    ) -> Result<ScheduleDetail, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn delete_schedule(&self, _job_id: &str) -> Result<DeleteScheduleResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn pause_schedule(&self, _job_id: &str) -> Result<ScheduleActionResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn resume_schedule(&self, _job_id: &str) -> Result<ScheduleActionResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn trigger_schedule(
        &self,
        _job_id: &str,
    ) -> Result<ScheduleActionResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn get_schedule_history(
        &self,
        _job_id: &str,
        _limit: usize,
    ) -> Result<ScheduleHistoryResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn get_schedule_next_runs(
        &self,
        _job_id: &str,
        _count: usize,
    ) -> Result<NextRunsResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn get_scheduler_health(
        &self,
    ) -> Result<api::types::SchedulerHealthResponse, RuntimeError> {
        // Without a CronScheduler instance, return a minimal response.
        Ok(api::types::SchedulerHealthResponse {
            is_running: false,
            store_accessible: false,
            jobs_total: 0,
            jobs_active: 0,
            jobs_paused: 0,
            jobs_dead_letter: 0,
            global_active_runs: 0,
            max_concurrent: 0,
            runs_total: 0,
            runs_succeeded: 0,
            runs_failed: 0,
            average_execution_time_ms: 0.0,
            longest_run_ms: 0,
        })
    }

    // ── Channel endpoints ──────────────────────────────────────────

    async fn list_channels(&self) -> Result<Vec<ChannelSummary>, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn register_channel(
        &self,
        _request: RegisterChannelRequest,
    ) -> Result<RegisterChannelResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn get_channel(&self, _id: &str) -> Result<ChannelDetail, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn update_channel(
        &self,
        _id: &str,
        _request: UpdateChannelRequest,
    ) -> Result<ChannelDetail, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn delete_channel(&self, _id: &str) -> Result<DeleteChannelResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn start_channel(&self, _id: &str) -> Result<ChannelActionResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn stop_channel(&self, _id: &str) -> Result<ChannelActionResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn get_channel_health(&self, _id: &str) -> Result<ChannelHealthResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel API requires a running ChannelAdapterManager".to_string(),
        ))
    }

    async fn list_channel_mappings(
        &self,
        _id: &str,
    ) -> Result<Vec<IdentityMappingEntry>, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel identity mappings require enterprise edition".to_string(),
        ))
    }

    async fn add_channel_mapping(
        &self,
        _id: &str,
        _request: AddIdentityMappingRequest,
    ) -> Result<IdentityMappingEntry, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel identity mappings require enterprise edition".to_string(),
        ))
    }

    async fn remove_channel_mapping(&self, _id: &str, _user_id: &str) -> Result<(), RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel identity mappings require enterprise edition".to_string(),
        ))
    }

    async fn get_channel_audit(
        &self,
        _id: &str,
        _limit: usize,
    ) -> Result<ChannelAuditResponse, RuntimeError> {
        Err(RuntimeError::Internal(
            "Channel audit log requires enterprise edition".to_string(),
        ))
    }
}