symbi-runtime 1.12.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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
//! 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 env;
pub mod error_handler;
pub mod integrations;
pub mod lifecycle;
pub mod logging;
pub mod metrics;
pub mod models;
pub mod net_guard;
pub mod rag;
pub mod reasoning;
pub mod resource;
pub mod routing;
pub mod sandbox;
pub mod scheduler;
pub mod secrets;
pub mod skills;
pub mod toolclad;
pub mod types;

pub mod prelude;

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

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

#[cfg(feature = "http-api")]
use api::traits::RuntimeApiProvider;
#[cfg(all(feature = "http-api", feature = "cron"))]
use api::types::ScheduleRunEntry;
#[cfg(feature = "http-api")]
use api::types::{
    AddIdentityMappingRequest, AgentExecutionRecord, 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;

/// Bounded in-memory execution log for agent history tracking.
///
/// Stores execution records in a thread-safe ring buffer. When the buffer
/// reaches capacity, oldest entries are evicted. All operations are O(1)
/// amortized except `get_history` which is O(n) in the number of records
/// for the requested agent.
#[cfg(feature = "http-api")]
pub struct ExecutionLog {
    entries: parking_lot::RwLock<std::collections::VecDeque<ExecutionEntry>>,
    capacity: usize,
}

#[cfg(feature = "http-api")]
#[derive(Debug, Clone)]
struct ExecutionEntry {
    agent_id: AgentId,
    execution_id: String,
    status: String,
    timestamp: chrono::DateTime<chrono::Utc>,
}

#[cfg(feature = "http-api")]
impl ExecutionLog {
    fn new(capacity: usize) -> Self {
        Self {
            entries: parking_lot::RwLock::new(std::collections::VecDeque::with_capacity(capacity)),
            capacity,
        }
    }

    /// Record an execution event for an agent.
    fn record(&self, agent_id: AgentId, execution_id: &str, status: &str) {
        let entry = ExecutionEntry {
            agent_id,
            execution_id: execution_id.to_string(),
            status: status.to_string(),
            timestamp: chrono::Utc::now(),
        };
        let mut entries = self.entries.write();
        if entries.len() >= self.capacity {
            entries.pop_front();
        }
        entries.push_back(entry);
    }

    /// Retrieve execution history for a specific agent, most recent first.
    fn get_history(&self, agent_id: AgentId, limit: usize) -> Vec<ExecutionEntry> {
        let entries = self.entries.read();
        entries
            .iter()
            .rev()
            .filter(|e| e.agent_id == agent_id)
            .take(limit)
            .cloned()
            .collect()
    }
}

/// 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>>,
    /// Stable identity for system-originated messages (API calls, HTTP input).
    /// Created once at runtime startup and reused for all internal messages
    /// so audit trails can consistently attribute system actions.
    pub system_agent_id: AgentId,
    /// Optional AgentPin verifier, constructed when
    /// `RuntimeConfig.agentpin.enabled == true`. When present, the HTTP
    /// ingress paths (inter-agent messaging, heartbeat, push-event) and
    /// the cron scheduler require a valid AgentPin JWT whose `sub`/agent
    /// claims cover the acting agent.
    pub agentpin_verifier: Option<Arc<dyn integrations::AgentPinVerifier>>,
    #[cfg(feature = "cron")]
    cron_scheduler: Option<Arc<scheduler::cron_scheduler::CronScheduler>>,
    config: Arc<RwLock<RuntimeConfig>>,
    /// In-memory execution log for agent history tracking.
    #[cfg(feature = "http-api")]
    execution_log: Arc<ExecutionLog>,
}

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
        };

        // Initialize AgentPin verifier if enabled in config. Failing to
        // build the verifier is NOT fail-open: we return the error so the
        // operator sees the misconfiguration at startup rather than
        // silently running without identity checks.
        let agentpin_verifier: Option<Arc<dyn integrations::AgentPinVerifier>> = {
            let cfg = config.read().await;
            match cfg.agentpin.as_ref() {
                Some(ap_cfg) if ap_cfg.enabled => {
                    let verifier = integrations::DefaultAgentPinVerifier::new(ap_cfg.clone())
                        .map_err(|e| {
                            RuntimeError::Internal(format!(
                                "Failed to construct AgentPin verifier: {}",
                                e
                            ))
                        })?;
                    tracing::info!(
                        "AgentPin verifier enabled (discovery_mode={:?}, audience={:?})",
                        ap_cfg.discovery_mode,
                        ap_cfg.audience
                    );
                    Some(Arc::new(verifier) as Arc<dyn integrations::AgentPinVerifier>)
                }
                Some(_) => {
                    tracing::info!("AgentPin configured but disabled; identity checks skipped");
                    None
                }
                None => None,
            }
        };

        Ok(Self {
            scheduler,
            lifecycle,
            resource_manager,
            communication,
            error_handler,
            context_manager,
            model_logger,
            model_catalog,
            system_agent_id: AgentId::new(),
            agentpin_verifier,
            #[cfg(feature = "cron")]
            cron_scheduler: None,
            config,
            #[cfg(feature = "http-api")]
            execution_log: Arc::new(ExecutionLog::new(10_000)),
        })
    }

    /// Attach a CronScheduler to the runtime so schedule APIs become functional.
    #[cfg(feature = "cron")]
    pub fn with_cron_scheduler(
        mut self,
        cron: Arc<scheduler::cron_scheduler::CronScheduler>,
    ) -> Self {
        self.cron_scheduler = Some(cron);
        self
    }

    /// 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(())
    }

    /// Verify that `jwt` is a valid AgentPin credential covering `agent_id`.
    ///
    /// Returns `Ok(())` when no AgentPin verifier is configured on this
    /// runtime. When a verifier IS configured, `jwt` must be present and
    /// its `sub` must equal the target agent's UUID string. Used by
    /// heartbeat, push-event, and any other per-agent ingress path.
    pub async fn verify_agentpin_for_agent(
        &self,
        jwt: Option<&str>,
        agent_id: AgentId,
    ) -> Result<(), RuntimeError> {
        let Some(verifier) = self.agentpin_verifier.as_ref() else {
            if jwt.is_some() {
                tracing::warn!("AgentPin JWT supplied but verifier is disabled on this runtime");
            }
            return Ok(());
        };
        let jwt = jwt.ok_or_else(|| {
            RuntimeError::Authentication(
                "AgentPin verification is enabled; agentpin_jwt is required".to_string(),
            )
        })?;
        let result = verifier
            .verify_credential(jwt)
            .await
            .map_err(|e| RuntimeError::Authentication(format!("AgentPin: {}", e)))?;
        if !result.valid {
            return Err(RuntimeError::Authentication(format!(
                "AgentPin credential invalid: {}",
                result
                    .error_message
                    .unwrap_or_else(|| "no reason".to_string())
            )));
        }
        let expected = agent_id.0.to_string();
        let sub_matches = result
            .agent_id
            .as_deref()
            .map(|sub| sub == expected)
            .unwrap_or(false);
        if !sub_matches {
            return Err(RuntimeError::Authentication(format!(
                "AgentPin JWT does not cover agent {}: sub={:?}",
                expected, result.agent_id
            )));
        }
        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>,
    /// Optional AgentPin configuration. When `enabled = true`, every
    /// inter-agent messaging / heartbeat / cron-trigger path requires a
    /// valid AgentPin JWT whose `sub` covers the acting agent.
    pub agentpin: Option<crate::integrations::AgentPinConfig>,
}

/// Implementation of RuntimeApiProvider for AgentRuntime
#[cfg(feature = "http-api")]
#[async_trait]
#[allow(unused_variables)] // Params used inside #[cfg(feature = "cron")] blocks
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;
        }

        // Record execution in history log
        self.execution_log.record(
            scheduled_agent_id,
            &scheduled_agent_id.to_string(),
            "workflow_started",
        );

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

    async fn get_agent_status(
        &self,
        agent_id: AgentId,
    ) -> Result<AgentStatusResponse, RuntimeError> {
        let external_state = self.scheduler.get_external_agent_state(agent_id);
        let agent_config = self.scheduler.get_agent_config(agent_id);

        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);

                let execution_mode_label = agent_config.as_ref().map(|c| match &c.execution_mode {
                    crate::types::agent::ExecutionMode::External { .. } => "External".to_string(),
                    crate::types::agent::ExecutionMode::Persistent => "Persistent".to_string(),
                    crate::types::agent::ExecutionMode::Ephemeral => "Ephemeral".to_string(),
                    crate::types::agent::ExecutionMode::Scheduled { .. } => "Scheduled".to_string(),
                    crate::types::agent::ExecutionMode::CronScheduled { .. } => {
                        "CronScheduled".to_string()
                    }
                    crate::types::agent::ExecutionMode::EventDriven => "EventDriven".to_string(),
                });

                let (metadata, last_result, recent_events) = if let Some(ref ext) = external_state {
                    (
                        Some(ext.metadata.clone()),
                        ext.last_result.clone(),
                        Some(ext.events.iter().cloned().collect::<Vec<_>>()),
                    )
                } else {
                    (None, None, None)
                };

                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,
                    },
                    metadata,
                    last_result,
                    recent_events,
                    execution_mode: execution_mode_label,
                })
            }
            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 list_agents_detailed(
        &self,
    ) -> Result<Vec<crate::api::types::AgentSummary>, RuntimeError> {
        let ids = self.scheduler.list_agents().await;
        let mut summaries = Vec::new();
        for id in ids {
            let name = self
                .scheduler
                .get_agent_config(id)
                .map(|c| c.name)
                .unwrap_or_default();
            let state = self
                .scheduler
                .get_agent_status(id)
                .await
                .map(|s| s.state)
                .unwrap_or(AgentState::Created);
            summaries.push(crate::api::types::AgentSummary { id, name, state });
        }
        Ok(summaries)
    }

    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;

        // Count agents in error/failed state by checking each agent's status
        let agent_ids = self.scheduler.list_agents().await;
        let mut error_count: usize = 0;
        for aid in &agent_ids {
            if let Ok(agent_status) = self.scheduler.get_agent_status(*aid).await {
                if agent_status.state == AgentState::Failed {
                    error_count += 1;
                }
            }
        }

        let idle = status
            .total_agents
            .saturating_sub(status.running_agents)
            .saturating_sub(error_count);

        Ok(serde_json::json!({
            "agents": {
                "total": status.total_agents,
                "running": status.running_agents,
                "idle": idle,
                "error": error_count
            },
            "system": {
                "uptime_seconds": status.uptime.as_secs(),
                "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(),
            ));
        }

        let execution_mode = request.execution_mode.clone().unwrap_or_default();

        let dsl_source = match &execution_mode {
            crate::types::agent::ExecutionMode::External { .. } => {
                request.dsl.clone().unwrap_or_default()
            }
            _ => {
                let dsl = request.dsl.as_deref().unwrap_or("");
                if dsl.is_empty() {
                    return Err(RuntimeError::Internal(
                        "Agent DSL cannot be empty for non-external agents".to_string(),
                    ));
                }
                dsl.to_string()
            }
        };

        // Create agent configuration
        let agent_id = AgentId::new();
        let agent_config = AgentConfig {
            id: agent_id,
            name: request.name,
            dsl_source,
            execution_mode,
            security_tier: SecurityTier::Tier1,
            resource_limits: ResourceLimits::default(),
            capabilities: request
                .capabilities
                .unwrap_or_default()
                .into_iter()
                .map(Capability::Custom)
                .collect(),
            policies: vec![],
            metadata: request.metadata.unwrap_or_default(),
            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);

        // Record creation in execution log
        self.execution_log.record(
            scheduled_agent_id,
            &scheduled_agent_id.to_string(),
            "created",
        );

        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> {
        self.scheduler
            .delete_agent(agent_id)
            .await
            .map_err(RuntimeError::Scheduler)?;

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

    async fn execute_agent(
        &self,
        agent_id: AgentId,
        request: ExecuteAgentRequest,
    ) -> Result<ExecuteAgentResponse, RuntimeError> {
        // Ensure the agent exists in the registry
        if !self.scheduler.has_agent(agent_id) {
            return Err(RuntimeError::Internal(format!(
                "Agent {} not found",
                agent_id
            )));
        }

        // Re-schedule from stored config if the agent isn't currently active
        let status = self.get_agent_status(agent_id).await?;
        if status.state == AgentState::Completed {
            if let Some(config) = self.scheduler.get_agent_config(agent_id) {
                self.scheduler
                    .schedule_agent(config)
                    .await
                    .map_err(RuntimeError::Scheduler)?;
            }
        } else 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(
            self.system_agent_id,
            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)?;

        // Record execution in the history log
        #[cfg(feature = "http-api")]
        self.execution_log
            .record(agent_id, &execution_id, "execution_started");

        Ok(ExecuteAgentResponse {
            execution_id,
            status: "execution_started".to_string(),
        })
    }

    async fn get_agent_history(
        &self,
        agent_id: AgentId,
    ) -> Result<GetAgentHistoryResponse, RuntimeError> {
        let entries = self.execution_log.get_history(agent_id, 100);
        let history = entries
            .into_iter()
            .map(|e| AgentExecutionRecord {
                execution_id: e.execution_id,
                status: e.status,
                timestamp: e.timestamp.to_rfc3339(),
            })
            .collect();
        Ok(GetAgentHistoryResponse { history })
    }

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

    async fn list_schedules(&self) -> Result<Vec<ScheduleSummary>, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let jobs = cron
                .list_jobs()
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(jobs
                .into_iter()
                .map(|j| ScheduleSummary {
                    job_id: j.job_id.to_string(),
                    name: j.name,
                    cron_expression: j.cron_expression,
                    timezone: j.timezone,
                    status: format!("{:?}", j.status),
                    enabled: j.enabled,
                    next_run: j.next_run.map(|t| t.to_rfc3339()),
                    run_count: j.run_count,
                })
                .collect());
        }
        Ok(vec![])
    }

    async fn create_schedule(
        &self,
        request: CreateScheduleRequest,
    ) -> Result<CreateScheduleResponse, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            use scheduler::cron_types::{CronJobDefinition, CronJobId};
            let now = chrono::Utc::now();
            let tz = if request.timezone.is_empty() {
                "UTC".to_string()
            } else {
                request.timezone
            };
            let agent_config = types::AgentConfig {
                id: types::AgentId::new(),
                name: request.agent_name,
                dsl_source: String::new(),
                execution_mode: Default::default(),
                security_tier: Default::default(),
                resource_limits: Default::default(),
                capabilities: Vec::new(),
                policies: Vec::new(),
                metadata: Default::default(),
                priority: Default::default(),
            };
            let job = CronJobDefinition {
                job_id: CronJobId::new(),
                name: request.name,
                cron_expression: request.cron_expression,
                timezone: tz,
                agent_config,
                policy_ids: request.policy_ids,
                audit_level: Default::default(),
                status: scheduler::cron_types::CronJobStatus::Active,
                enabled: true,
                one_shot: request.one_shot,
                created_at: now,
                updated_at: now,
                last_run: None,
                next_run: None,
                run_count: 0,
                failure_count: 0,
                max_retries: 3,
                max_concurrent: 1,
                delivery_config: None,
                jitter_max_secs: 0,
                session_mode: Default::default(),
                agentpin_jwt: None,
            };
            let job_id = cron
                .add_job(job)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            // Retrieve the saved job to get the computed next_run.
            let saved = cron
                .get_job(job_id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(CreateScheduleResponse {
                job_id: job_id.to_string(),
                next_run: saved.next_run.map(|t| t.to_rfc3339()),
                status: "created".to_string(),
            });
        }
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn get_schedule(&self, job_id: &str) -> Result<ScheduleDetail, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            let j = cron
                .get_job(id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(ScheduleDetail {
                job_id: j.job_id.to_string(),
                name: j.name,
                cron_expression: j.cron_expression,
                timezone: j.timezone,
                status: format!("{:?}", j.status),
                enabled: j.enabled,
                one_shot: j.one_shot,
                next_run: j.next_run.map(|t| t.to_rfc3339()),
                last_run: j.last_run.map(|t| t.to_rfc3339()),
                run_count: j.run_count,
                failure_count: j.failure_count,
                created_at: j.created_at.to_rfc3339(),
                updated_at: j.updated_at.to_rfc3339(),
            });
        }
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn update_schedule(
        &self,
        job_id: &str,
        request: UpdateScheduleRequest,
    ) -> Result<ScheduleDetail, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            let mut job = cron
                .get_job(id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            if let Some(expr) = request.cron_expression {
                job.cron_expression = expr;
            }
            if let Some(tz) = request.timezone {
                job.timezone = tz;
            }
            if let Some(pids) = request.policy_ids {
                job.policy_ids = pids;
            }
            if let Some(one_shot) = request.one_shot {
                job.one_shot = one_shot;
            }
            cron.update_job(job)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return self.get_schedule(job_id).await;
        }
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn delete_schedule(&self, job_id: &str) -> Result<DeleteScheduleResponse, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            cron.remove_job(id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(DeleteScheduleResponse {
                job_id: job_id.to_string(),
                deleted: true,
            });
        }
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn pause_schedule(&self, job_id: &str) -> Result<ScheduleActionResponse, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            cron.pause_job(id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(ScheduleActionResponse {
                job_id: job_id.to_string(),
                action: "pause".to_string(),
                status: "paused".to_string(),
            });
        }
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn resume_schedule(&self, job_id: &str) -> Result<ScheduleActionResponse, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            cron.resume_job(id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(ScheduleActionResponse {
                job_id: job_id.to_string(),
                action: "resume".to_string(),
                status: "active".to_string(),
            });
        }
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn trigger_schedule(&self, job_id: &str) -> Result<ScheduleActionResponse, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            cron.trigger_now(id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(ScheduleActionResponse {
                job_id: job_id.to_string(),
                action: "trigger".to_string(),
                status: "triggered".to_string(),
            });
        }
        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> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            let runs = cron
                .get_run_history(id, limit)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(ScheduleHistoryResponse {
                job_id: job_id.to_string(),
                history: runs
                    .into_iter()
                    .map(|r| ScheduleRunEntry {
                        run_id: r.run_id.to_string(),
                        started_at: r.started_at.to_rfc3339(),
                        completed_at: r.completed_at.map(|t| t.to_rfc3339()),
                        status: format!("{:?}", r.status),
                        error: r.error,
                        execution_time_ms: r.execution_time_ms,
                    })
                    .collect(),
            });
        }
        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> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let id: scheduler::cron_types::CronJobId = job_id
                .parse()
                .map_err(|_| RuntimeError::Internal(format!("Invalid job ID: {}", job_id)))?;
            let job = cron
                .get_job(id)
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            let runs = cron
                .get_next_runs(&job.cron_expression, &job.timezone, count)
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            return Ok(NextRunsResponse {
                job_id: job_id.to_string(),
                next_runs: runs.into_iter().map(|t| t.to_rfc3339()).collect(),
            });
        }
        Err(RuntimeError::Internal(
            "Schedule API requires a running CronScheduler".to_string(),
        ))
    }

    async fn get_scheduler_health(
        &self,
    ) -> Result<api::types::SchedulerHealthResponse, RuntimeError> {
        #[cfg(feature = "cron")]
        if let Some(ref cron) = self.cron_scheduler {
            let h = cron
                .check_health()
                .await
                .map_err(|e| RuntimeError::Internal(e.to_string()))?;
            let m = cron.metrics();
            return Ok(api::types::SchedulerHealthResponse {
                is_running: h.is_running,
                store_accessible: h.store_accessible,
                jobs_total: h.jobs_total,
                jobs_active: h.jobs_active,
                jobs_paused: h.jobs_paused,
                jobs_dead_letter: h.jobs_dead_letter,
                global_active_runs: h.global_active_runs,
                max_concurrent: h.max_concurrent,
                runs_total: m.runs_total,
                runs_succeeded: m.runs_succeeded,
                runs_failed: m.runs_failed,
                average_execution_time_ms: m.average_execution_time_ms,
                longest_run_ms: m.longest_run_ms,
            });
        }
        // No CronScheduler — 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> {
        // No ChannelAdapterManager — return empty list so dashboard renders gracefully
        Ok(vec![])
    }

    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(),
        ))
    }

    // ── External agent endpoints ─────────────────────────────────────

    async fn update_agent_heartbeat(
        &self,
        agent_id: AgentId,
        heartbeat: api::types::HeartbeatRequest,
    ) -> Result<(), RuntimeError> {
        // AP-4: gate external heartbeats on AgentPin when enabled.
        self.verify_agentpin_for_agent(heartbeat.agentpin_jwt.as_deref(), agent_id)
            .await?;

        let ext_agents = self.scheduler.external_agents();
        let mut entry = ext_agents.get_mut(&agent_id).ok_or_else(|| {
            RuntimeError::Internal(format!("Agent {} is not an external agent", agent_id))
        })?;

        entry.last_heartbeat = Some(chrono::Utc::now());
        entry.reported_state = heartbeat.state;

        if let Some(metadata) = heartbeat.metadata {
            entry.metadata.extend(metadata);
        }
        if let Some(last_result) = heartbeat.last_result {
            entry.last_result = Some(last_result);
        }

        Ok(())
    }

    async fn push_agent_event(
        &self,
        agent_id: AgentId,
        event: api::types::PushEventRequest,
    ) -> Result<(), RuntimeError> {
        // AP-4: gate external agent events on AgentPin when enabled.
        self.verify_agentpin_for_agent(event.agentpin_jwt.as_deref(), agent_id)
            .await?;

        let ext_agents = self.scheduler.external_agents();
        let mut entry = ext_agents.get_mut(&agent_id).ok_or_else(|| {
            RuntimeError::Internal(format!("Agent {} is not an external agent", agent_id))
        })?;

        entry.push_event(api::types::AgentEvent {
            event_type: event.event_type,
            payload: event.payload,
            timestamp: chrono::Utc::now(),
        });

        Ok(())
    }

    async fn check_unreachable_agents(&self) {
        self.scheduler.check_unreachable_agents();
    }

    async fn send_agent_message(
        &self,
        recipient: crate::types::AgentId,
        request: api::types::SendMessageRequest,
    ) -> Result<api::types::SendMessageResponse, crate::types::RuntimeError> {
        // AgentPin identity check (AP-1): reuse the shared helper so
        // every per-agent ingress path (messaging, heartbeat, push_event)
        // enforces the same rule.
        self.verify_agentpin_for_agent(request.agentpin_jwt.as_deref(), request.sender)
            .await?;

        // Trust-boundary note (H-5 / M-1):
        // The `request` arrives from an HTTP caller (potentially another
        // runtime via RemoteCommunicationBus). We deliberately build a fresh
        // SecureMessage here via `create_internal_message` so it is signed
        // by THIS bus's Ed25519 key. The local bus then rejects any message
        // whose signature doesn't verify against its own key (see
        // DefaultCommunicationBus::verify_message_signature), which means
        // untrusted wire bytes — including SignatureAlgorithm::None or
        // EncryptionAlgorithm::None from a remote shim — can never survive
        // ingress without being re-wrapped here.
        //
        // Clamp TTL: bound by the bus's configured `message_ttl` so a caller
        // cannot pin queued messages beyond operator intent, and by a hard
        // safety cap so a misconfigured config can't allow forever-TTLs.
        const MAX_TTL_SECS: u64 = 24 * 3600;
        const DEFAULT_TTL_SECS: u64 = 300;
        let requested_secs = request.ttl_seconds.unwrap_or(DEFAULT_TTL_SECS);
        let configured_secs = self.config.read().await.communication.message_ttl.as_secs();
        let ttl_secs = requested_secs.min(configured_secs).clamp(1, MAX_TTL_SECS);
        let ttl = std::time::Duration::from_secs(ttl_secs);

        // Decide message type: topic = publish, otherwise direct
        if let Some(ref topic) = request.topic {
            let msg = self.communication.create_internal_message(
                request.sender,
                recipient,
                bytes::Bytes::from(request.payload.into_bytes()),
                crate::types::communication::MessageType::Publish(topic.clone()),
                ttl,
            );
            let message_id = msg.id;
            self.communication
                .publish(topic.clone(), msg)
                .await
                .map_err(crate::types::RuntimeError::Communication)?;
            Ok(api::types::SendMessageResponse {
                message_id: message_id.0.to_string(),
                status: "pending".to_string(),
            })
        } else {
            let msg = self.communication.create_internal_message(
                request.sender,
                recipient,
                bytes::Bytes::from(request.payload.into_bytes()),
                crate::types::communication::MessageType::Direct(recipient),
                ttl,
            );
            let message_id = self
                .communication
                .send_message(msg)
                .await
                .map_err(crate::types::RuntimeError::Communication)?;
            Ok(api::types::SendMessageResponse {
                message_id: message_id.0.to_string(),
                status: "pending".to_string(),
            })
        }
    }

    async fn receive_agent_messages(
        &self,
        agent_id: crate::types::AgentId,
    ) -> Result<api::types::ReceiveMessagesResponse, crate::types::RuntimeError> {
        let messages = self
            .communication
            .receive_messages(agent_id)
            .await
            .map_err(crate::types::RuntimeError::Communication)?;

        let envelopes = messages
            .into_iter()
            .map(|m| {
                let timestamp_secs = m
                    .timestamp
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d: std::time::Duration| d.as_secs())
                    .unwrap_or(0);
                let ttl_seconds = m.ttl.as_secs();
                let (message_type, topic) = match &m.message_type {
                    crate::types::communication::MessageType::Direct(_) => {
                        ("direct".to_string(), None)
                    }
                    crate::types::communication::MessageType::Publish(t) => {
                        ("publish".to_string(), Some(t.clone()))
                    }
                    crate::types::communication::MessageType::Subscribe(t) => {
                        ("subscribe".to_string(), Some(t.clone()))
                    }
                    crate::types::communication::MessageType::Broadcast => {
                        ("broadcast".to_string(), None)
                    }
                    crate::types::communication::MessageType::Request(_) => {
                        ("request".to_string(), None)
                    }
                    crate::types::communication::MessageType::Response(_) => {
                        ("response".to_string(), None)
                    }
                };
                // Payload is encrypted in-flight; for HTTP API return decrypted UTF-8 bytes.
                // The bus uses AES-256-GCM internally — the HTTP layer treats the payload
                // as opaque bytes that the receiver should decrypt if needed. For the
                // default bus (in-process), encryption is symmetric so callers see the
                // raw bytes they put in.
                let payload = String::from_utf8_lossy(&m.payload.data).to_string();
                api::types::MessageEnvelope {
                    message_id: m.id.0.to_string(),
                    sender: m.sender,
                    recipient: m.recipient,
                    topic,
                    payload,
                    message_type,
                    timestamp_secs,
                    ttl_seconds,
                }
            })
            .collect();

        Ok(api::types::ReceiveMessagesResponse {
            messages: envelopes,
        })
    }

    async fn get_message_status(
        &self,
        message_id: &str,
    ) -> Result<api::types::MessageStatusResponse, crate::types::RuntimeError> {
        let uuid = uuid::Uuid::parse_str(message_id).map_err(|_| {
            crate::types::RuntimeError::Communication(
                crate::types::CommunicationError::InvalidFormat(format!(
                    "Invalid message ID: {}",
                    message_id
                )),
            )
        })?;
        let mid = crate::types::MessageId(uuid);
        let status = self
            .communication
            .get_delivery_status(mid)
            .await
            .map_err(crate::types::RuntimeError::Communication)?;
        let status_str = match status {
            crate::communication::DeliveryStatus::Pending => "pending",
            crate::communication::DeliveryStatus::Delivered => "delivered",
            crate::communication::DeliveryStatus::Failed => "failed",
            crate::communication::DeliveryStatus::Expired => "expired",
        };
        Ok(api::types::MessageStatusResponse {
            message_id: message_id.to_string(),
            status: status_str.to_string(),
        })
    }
}