dist_agent_lang 1.0.20

Agentic programming with library and CLI support for Off/On-chain network integration
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
use crate::runtime::values::Value;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

/// Agent ABI - Interface for AI Agent operations
///
/// This provides a namespace-based approach to AI Agent operations:
/// - agent::spawn(agent_type, config, capabilities) - Spawn new agent
/// - agent::coordinate(agent_id, task, coordination_type) - Coordinate agent activities
/// - agent::communicate(sender_id, receiver_id, message) - Agent-to-agent communication
/// - agent::evolve(agent_id, evolution_data) - Agent learning and evolution
/// - agent::validate_capabilities(agent_type, required_capabilities) - Validate agent capabilities

#[derive(Debug, Clone, PartialEq)]
pub enum AgentType {
    AI,
    System,
    Worker,
    IDE,
    Custom(String),
}

impl AgentType {
    pub fn from_string(s: &str) -> Option<Self> {
        match s {
            "ai" => Some(AgentType::AI),
            "system" => Some(AgentType::System),
            "worker" => Some(AgentType::Worker),
            "ide" => Some(AgentType::IDE),
            custom if custom.starts_with("custom:") => {
                Some(AgentType::Custom(custom[7..].to_string()))
            }
            _ => None,
        }
    }

    pub fn to_string(&self) -> String {
        match self {
            AgentType::AI => "ai".to_string(),
            AgentType::System => "system".to_string(),
            AgentType::Worker => "worker".to_string(),
            AgentType::IDE => "ide".to_string(),
            AgentType::Custom(name) => format!("custom:{}", name),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum AgentStatus {
    Idle,
    Active,
    Learning,
    Coordinating,
    Error,
    Terminated,
}

impl AgentStatus {
    pub fn from_string(s: &str) -> Option<Self> {
        match s {
            "idle" => Some(AgentStatus::Idle),
            "active" => Some(AgentStatus::Active),
            "learning" => Some(AgentStatus::Learning),
            "coordinating" => Some(AgentStatus::Coordinating),
            "error" => Some(AgentStatus::Error),
            "terminated" => Some(AgentStatus::Terminated),
            _ => None,
        }
    }

    pub fn to_string(&self) -> String {
        match self {
            AgentStatus::Idle => "idle".to_string(),
            AgentStatus::Active => "active".to_string(),
            AgentStatus::Learning => "learning".to_string(),
            AgentStatus::Coordinating => "coordinating".to_string(),
            AgentStatus::Error => "error".to_string(),
            AgentStatus::Terminated => "terminated".to_string(),
        }
    }
}

/// Lifecycle hooks: DAL code executed at agent events. Set by molds.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LifecycleHooks {
    pub on_create: Option<String>,
    pub on_message: Option<String>,
    pub on_evolve: Option<String>,
    pub on_destroy: Option<String>,
}

/// Resource limits for agent execution (wall clock, tokens, cost, tool call bounds).
/// Used by IDE agents and any agent that needs budget enforcement.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ResourceBudget {
    pub max_wall_clock_ms: Option<u64>,
    pub max_tool_calls_per_type: Option<u32>,
    pub max_repeated_identical_invocations: Option<u32>,
    pub max_consecutive_no_progress: Option<u32>,
    pub max_total_tokens: Option<u64>,
    pub max_cost_microusd: Option<u64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AgentConfig {
    pub name: String,
    pub agent_type: AgentType,
    pub role: String,
    pub capabilities: Vec<String>,
    /// Skill names (e.g. development, creative, office, home). Empty = use default learning path at serve time.
    pub skills: Vec<String>,
    pub trust_level: String,
    pub max_memory: usize,
    pub learning_enabled: bool,
    pub communication_enabled: bool,
    pub coordination_enabled: bool,
    pub metadata: HashMap<String, Value>,
    pub lifecycle: Option<LifecycleHooks>,
    pub resource_budget: Option<ResourceBudget>,
}

impl AgentConfig {
    pub fn new(name: String, agent_type: AgentType) -> Self {
        Self {
            name,
            agent_type,
            role: String::new(),
            capabilities: Vec::new(),
            skills: Vec::new(),
            trust_level: "standard".to_string(),
            max_memory: 1000,
            learning_enabled: true,
            communication_enabled: true,
            coordination_enabled: true,
            metadata: HashMap::new(),
            lifecycle: None,
            resource_budget: None,
        }
    }

    pub fn with_skills(mut self, skills: Vec<String>) -> Self {
        self.skills = skills;
        self
    }

    pub fn with_lifecycle(mut self, lifecycle: Option<LifecycleHooks>) -> Self {
        self.lifecycle = lifecycle;
        self
    }

    pub fn with_role(mut self, role: String) -> Self {
        self.role = role;
        self
    }

    pub fn with_capabilities(mut self, capabilities: Vec<String>) -> Self {
        self.capabilities = capabilities;
        self
    }

    pub fn with_trust_level(mut self, trust_level: String) -> Self {
        self.trust_level = trust_level;
        self
    }

    pub fn with_max_memory(mut self, max_memory: usize) -> Self {
        self.max_memory = max_memory;
        self
    }

    pub fn with_metadata(mut self, metadata: HashMap<String, Value>) -> Self {
        self.metadata = metadata;
        self
    }

    pub fn enable_learning(mut self, enabled: bool) -> Self {
        self.learning_enabled = enabled;
        self
    }

    pub fn with_learning_enabled(mut self, enabled: bool) -> Self {
        self.learning_enabled = enabled;
        self
    }

    pub fn enable_communication(mut self, enabled: bool) -> Self {
        self.communication_enabled = enabled;
        self
    }

    pub fn with_communication_enabled(mut self, enabled: bool) -> Self {
        self.communication_enabled = enabled;
        self
    }

    pub fn enable_coordination(mut self, enabled: bool) -> Self {
        self.coordination_enabled = enabled;
        self
    }

    pub fn with_coordination_enabled(mut self, enabled: bool) -> Self {
        self.coordination_enabled = enabled;
        self
    }

    pub fn with_resource_budget(mut self, budget: ResourceBudget) -> Self {
        self.resource_budget = Some(budget);
        self
    }
}

#[derive(Debug, Clone)]
pub struct AgentContext {
    pub agent_id: String,
    pub config: AgentConfig,
    pub status: AgentStatus,
    pub memory: HashMap<String, Value>,
    pub tasks: Vec<AgentTask>,
    pub message_queue: Vec<AgentMessage>,
    pub created_at: String,
    pub last_active: String,
    pub performance_metrics: AgentMetrics,
    pub trust_score: f64,
}

impl AgentContext {
    pub fn new(agent_id: String, config: AgentConfig) -> Self {
        Self {
            agent_id,
            config,
            status: AgentStatus::Idle,
            memory: HashMap::new(),
            tasks: Vec::new(),
            message_queue: Vec::new(),
            created_at: chrono::Utc::now().to_rfc3339(),
            last_active: chrono::Utc::now().to_rfc3339(),
            performance_metrics: AgentMetrics::new(),
            trust_score: 1.0,
        }
    }

    pub fn update_status(&mut self, status: AgentStatus) {
        self.status = status;
        self.last_active = chrono::Utc::now().to_rfc3339();
        self.performance_metrics.status_changes += 1;
    }

    pub fn add_task(&mut self, task: AgentTask) {
        self.tasks.push(task);
        self.performance_metrics.tasks_assigned += 1;
    }

    pub fn add_message(&mut self, message: AgentMessage) {
        self.message_queue.push(message);
        self.performance_metrics.messages_received += 1;
    }

    pub fn store_memory(&mut self, key: String, value: Value) {
        self.memory.insert(key, value);
        if self.memory.len() > self.config.max_memory {
            // Remove oldest entries if memory limit exceeded
            let keys_to_remove: Vec<String> = self
                .memory
                .keys()
                .take(self.memory.len() - self.config.max_memory)
                .cloned()
                .collect();
            for key in keys_to_remove {
                self.memory.remove(&key);
            }
        }
    }

    pub fn retrieve_memory(&self, key: &str) -> Option<&Value> {
        self.memory.get(key)
    }

    pub fn update_trust_score(&mut self, score_change: f64) {
        self.trust_score = (self.trust_score + score_change).max(0.0).min(1.0);
    }

    pub fn is_capable(&self, capability: &str) -> bool {
        self.config.capabilities.contains(&capability.to_string())
    }

    pub fn can_communicate(&self) -> bool {
        self.config.communication_enabled && self.status != AgentStatus::Error
    }

    pub fn can_coordinate(&self) -> bool {
        self.config.coordination_enabled && self.status != AgentStatus::Error
    }

    pub fn can_learn(&self) -> bool {
        self.config.learning_enabled && self.status != AgentStatus::Error
    }
}

#[derive(Debug, Clone)]
pub struct AgentTask {
    pub task_id: String,
    pub description: String,
    pub priority: TaskPriority,
    pub status: TaskStatus,
    pub assigned_at: String,
    pub completed_at: Option<String>,
    pub dependencies: Vec<String>,
    pub metadata: HashMap<String, Value>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum TaskPriority {
    Low,
    Medium,
    High,
    Critical,
}

impl TaskPriority {
    pub fn from_string(s: &str) -> Option<Self> {
        match s {
            "low" => Some(TaskPriority::Low),
            "medium" => Some(TaskPriority::Medium),
            "high" => Some(TaskPriority::High),
            "critical" => Some(TaskPriority::Critical),
            _ => None,
        }
    }

    pub fn to_string(&self) -> String {
        match self {
            TaskPriority::Low => "low".to_string(),
            TaskPriority::Medium => "medium".to_string(),
            TaskPriority::High => "high".to_string(),
            TaskPriority::Critical => "critical".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum TaskStatus {
    Pending,
    InProgress,
    Completed,
    Failed,
    Cancelled,
}

impl TaskStatus {
    pub fn from_string(s: &str) -> Option<Self> {
        match s {
            "pending" => Some(TaskStatus::Pending),
            "in_progress" => Some(TaskStatus::InProgress),
            "completed" => Some(TaskStatus::Completed),
            "failed" => Some(TaskStatus::Failed),
            "cancelled" => Some(TaskStatus::Cancelled),
            _ => None,
        }
    }

    pub fn to_string(&self) -> String {
        match self {
            TaskStatus::Pending => "pending".to_string(),
            TaskStatus::InProgress => "in_progress".to_string(),
            TaskStatus::Completed => "completed".to_string(),
            TaskStatus::Failed => "failed".to_string(),
            TaskStatus::Cancelled => "cancelled".to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct AgentMessage {
    pub message_id: String,
    pub sender_id: String,
    pub receiver_id: String,
    pub message_type: String,
    pub content: Value,
    pub timestamp: String,
    pub priority: MessagePriority,
    pub requires_response: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum MessagePriority {
    Low,
    Normal,
    High,
    Urgent,
}

impl MessagePriority {
    pub fn from_string(s: &str) -> Option<Self> {
        match s {
            "low" => Some(MessagePriority::Low),
            "normal" => Some(MessagePriority::Normal),
            "high" => Some(MessagePriority::High),
            "urgent" => Some(MessagePriority::Urgent),
            _ => None,
        }
    }

    pub fn to_string(&self) -> String {
        match self {
            MessagePriority::Low => "low".to_string(),
            MessagePriority::Normal => "normal".to_string(),
            MessagePriority::High => "high".to_string(),
            MessagePriority::Urgent => "urgent".to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct AgentMetrics {
    pub tasks_completed: u64,
    pub tasks_failed: u64,
    pub tasks_assigned: u64,
    pub messages_sent: u64,
    pub messages_received: u64,
    pub coordination_events: u64,
    pub learning_sessions: u64,
    pub status_changes: u64,
    pub average_response_time: f64,
    pub uptime_percentage: f64,
}

impl AgentMetrics {
    pub fn new() -> Self {
        Self {
            tasks_completed: 0,
            tasks_failed: 0,
            tasks_assigned: 0,
            messages_sent: 0,
            messages_received: 0,
            coordination_events: 0,
            learning_sessions: 0,
            status_changes: 0,
            average_response_time: 0.0,
            uptime_percentage: 100.0,
        }
    }

    pub fn record_task_completion(&mut self, success: bool) {
        if success {
            self.tasks_completed += 1;
        } else {
            self.tasks_failed += 1;
        }
    }

    pub fn record_message(&mut self, sent: bool) {
        if sent {
            self.messages_sent += 1;
        } else {
            self.messages_received += 1;
        }
    }

    pub fn calculate_success_rate(&self) -> f64 {
        let total_tasks = self.tasks_completed + self.tasks_failed;
        if total_tasks == 0 {
            return 0.0;
        }
        self.tasks_completed as f64 / total_tasks as f64
    }

    pub fn get_performance_score(&self) -> f64 {
        let success_rate = self.calculate_success_rate();
        let activity_score = (self.messages_sent + self.messages_received) as f64 / 100.0;
        let coordination_score = self.coordination_events as f64 / 50.0;

        (success_rate * 0.5) + (activity_score * 0.3) + (coordination_score * 0.2)
    }
}

impl Default for AgentMetrics {
    fn default() -> Self {
        Self::new()
    }
}

/// Spawn a new agent
pub fn spawn(config: AgentConfig) -> Result<AgentContext, String> {
    // Generate unique agent ID
    let agent_id = format!("agent_{}", generate_id());

    // Create agent context
    let mut agent_context = AgentContext::new(agent_id.clone(), config);

    // Initialize agent based on type
    match agent_context.config.agent_type {
        AgentType::AI => initialize_ai_agent(&mut agent_context),
        AgentType::System => initialize_system_agent(&mut agent_context),
        AgentType::Worker => initialize_worker_agent(&mut agent_context),
        AgentType::IDE => initialize_ide_agent(&mut agent_context),
        AgentType::Custom(_) => initialize_custom_agent(&mut agent_context),
    }

    // Run on_create lifecycle hook if present (from mold)
    if let Some(ref lifecycle) = agent_context.config.lifecycle {
        if let Some(ref on_create) = lifecycle.on_create {
            let mut vars = HashMap::new();
            vars.insert("agent_id".to_string(), Value::String(agent_id.clone()));
            if let Err(e) = crate::execute_dal_with_scope(&vars, on_create) {
                log::warn!(
                    "Mold on_create lifecycle hook failed for {}: {}",
                    agent_id,
                    e
                );
                // Don't fail spawn; hook errors are non-fatal
            }
        }
    }

    // Log agent creation
    log::info!("agent: {:?}", {
        let mut data = HashMap::new();
        data.insert("agent_id".to_string(), Value::String(agent_id.clone()));
        data.insert(
            "agent_type".to_string(),
            Value::String(agent_context.config.agent_type.to_string()),
        );
        data.insert(
            "agent_name".to_string(),
            Value::String(agent_context.config.name.clone()),
        );
        data.insert(
            "status".to_string(),
            Value::String(agent_context.status.to_string()),
        );
        data.insert(
            "message".to_string(),
            Value::String("Agent spawned successfully".to_string()),
        );
        data
    });

    {
        let mut r = get_runtime();
        r.agent_contexts
            .insert(agent_context.agent_id.clone(), agent_context.clone());
        r.persist();
    }
    Ok(agent_context)
}

/// Terminate an agent: set status to Terminated, run on_destroy lifecycle hook, persist.
pub fn terminate(agent_id: &str) -> Result<(), String> {
    let on_destroy = {
        let mut r = get_runtime();
        let ctx = r
            .agent_contexts
            .get_mut(agent_id)
            .ok_or_else(|| format!("Agent not found: {}", agent_id))?;
        ctx.update_status(AgentStatus::Terminated);
        let hook = ctx
            .config
            .lifecycle
            .as_ref()
            .and_then(|l| l.on_destroy.clone());
        r.persist();
        hook
    };
    if let Some(snippet) = on_destroy {
        let mut vars = HashMap::new();
        vars.insert("agent_id".to_string(), Value::String(agent_id.to_string()));
        if let Err(e) = crate::execute_dal_with_scope(&vars, &snippet) {
            log::warn!(
                "Mold on_destroy lifecycle hook failed for {}: {}",
                agent_id,
                e
            );
        }
    }
    log::info!("agent: terminated {}", agent_id);
    Ok(())
}

/// Look up an agent context by id (clone).
pub fn get_agent_context(agent_id: &str) -> Option<AgentContext> {
    get_runtime().agent_contexts.get(agent_id).cloned()
}

/// Coordination runtime with integrated persistence.
/// Persistence is ON by default; set DAL_AGENT_RUNTIME_PERSIST=0 to disable.
struct AgentRuntime {
    task_queue: Vec<(String, AgentTask)>,
    message_bus: Vec<(String, AgentMessage)>,
    evolution_store: HashMap<String, HashMap<String, Value>>,
    agent_contexts: HashMap<String, AgentContext>,
    serve_agent_id: Option<String>,
    /// Non-builtin skills registered at runtime (persisted alongside agent state).
    registered_skills: Vec<crate::skills::SkillDefinition>,
    persistence: Box<dyn crate::stdlib::agent_persist::RuntimePersistence>,
}

impl AgentRuntime {
    /// Persist current state. Best-effort: logs on failure but does not panic.
    fn persist(&self) {
        let snapshot = crate::stdlib::agent_persist::AgentRuntimeSnapshot::from_runtime(
            &self.agent_contexts,
            &self.task_queue,
            &self.message_bus,
            &self.evolution_store,
            &self.serve_agent_id,
            &self.registered_skills,
        );
        if let Err(e) = self.persistence.save(&snapshot) {
            log::warn!("Agent runtime persistence save failed: {}", e);
        }
    }
}

fn get_runtime() -> std::sync::MutexGuard<'static, AgentRuntime> {
    static RUNTIME: OnceLock<Mutex<AgentRuntime>> = OnceLock::new();
    RUNTIME
        .get_or_init(|| {
            use crate::stdlib::agent_persist::{create_persistence, PersistConfig};
            let mut config = PersistConfig::from_env();
            if config.is_disabled_by_toml() {
                config.backend = crate::stdlib::agent_persist::PersistBackend::Disabled;
            }
            let persistence = create_persistence(&config).unwrap_or_else(|e| {
                log::warn!(
                    "Failed to create agent persistence ({}). Running without persistence.",
                    e
                );
                Box::new(crate::stdlib::agent_persist::NullPersistence)
            });
            let snapshot = persistence.load().unwrap_or_else(|e| {
                log::warn!(
                    "Failed to load agent runtime snapshot ({}). Starting empty.",
                    e
                );
                crate::stdlib::agent_persist::AgentRuntimeSnapshot::empty()
            });
            let agent_contexts: HashMap<String, AgentContext> = snapshot
                .agent_contexts
                .iter()
                .map(|(k, v)| (k.clone(), v.to_domain()))
                .collect();
            let task_queue: Vec<(String, AgentTask)> = snapshot
                .task_queue
                .iter()
                .map(|(k, v)| (k.clone(), v.to_domain()))
                .collect();
            let message_bus: Vec<(String, AgentMessage)> = snapshot
                .message_bus
                .iter()
                .map(|(k, v)| (k.clone(), v.to_domain()))
                .collect();
            let registered_skills: Vec<crate::skills::SkillDefinition> = snapshot
                .registered_skills
                .iter()
                .map(|dto| dto.to_domain())
                .collect();
            if !registered_skills.is_empty() {
                crate::skills::register_global_skills(registered_skills.clone());
                log::info!(
                    "Restored {} runtime-registered skill(s) from snapshot.",
                    registered_skills.len()
                );
            }
            Mutex::new(AgentRuntime {
                task_queue,
                message_bus,
                evolution_store: snapshot.evolution_store,
                agent_contexts,
                serve_agent_id: snapshot.serve_agent_id,
                registered_skills,
                persistence,
            })
        })
        .lock()
        .unwrap()
}

/// Register skills at runtime. Persisted in the agent runtime snapshot so they survive restarts.
/// Also merges into the global skill registry for immediate use in prompt building.
pub fn register_runtime_skills(skills: Vec<crate::skills::SkillDefinition>) {
    if skills.is_empty() {
        return;
    }
    crate::skills::register_global_skills(skills.clone());
    let mut r = get_runtime();
    for skill in skills {
        if !skill.builtin && !r.registered_skills.iter().any(|s| s.name == skill.name) {
            r.registered_skills.push(skill);
        }
    }
    r.persist();
}

/// Register the agent as the one to serve (used by behavior script before server starts). Call agent::set_serve_agent(agent_id) from DAL.
pub fn set_serve_agent(agent_id: &str) {
    let mut r = get_runtime();
    r.serve_agent_id = Some(agent_id.to_string());
    r.persist();
}

/// Get the agent context for the current serve agent, if the behavior script set one. Used by dal agent serve --behavior.
pub fn get_serve_agent_context() -> Option<AgentContext> {
    let r = get_runtime();
    let id = r.serve_agent_id.clone()?;
    r.agent_contexts.get(&id).cloned()
}

/// Coordinate agent activities. Uses in-memory task queue; tasks are routed to agent_id.
pub fn coordinate(
    agent_id: &str,
    task: AgentTask,
    coordination_type: &str,
) -> Result<bool, String> {
    match coordination_type {
        "task_distribution" | "resource_sharing" | "conflict_resolution" => {
            let mut r = get_runtime();
            r.task_queue.push((agent_id.to_string(), task.clone()));
            r.persist();
            log::info!("agent_coordination: {:?}", {
                let mut data = HashMap::new();
                data.insert("agent_id".to_string(), Value::String(agent_id.to_string()));
                data.insert("task_id".to_string(), Value::String(task.task_id.clone()));
                data.insert(
                    "coordination_type".to_string(),
                    Value::String(coordination_type.to_string()),
                );
                data.insert(
                    "message".to_string(),
                    Value::String(format!("{} completed successfully", coordination_type)),
                );
                data
            });
            Ok(true)
        }
        _ => Err(format!("Unknown coordination type: {}", coordination_type)),
    }
}

/// Returns pending tasks assigned to this agent (and removes them from the queue).
pub fn receive_pending_tasks(agent_id: &str) -> Vec<AgentTask> {
    let mut runtime = get_runtime();
    let (mine, rest): (Vec<_>, Vec<_>) = std::mem::take(&mut runtime.task_queue)
        .into_iter()
        .partition(|(id, _)| id == agent_id);
    runtime.task_queue = rest;
    runtime.persist();
    mine.into_iter().map(|(_, t)| t).collect()
}

/// Send message between agents. Routes via in-memory message bus; receiver can call receive_messages().
pub fn communicate(
    sender_id: &str,
    receiver_id: &str,
    message: AgentMessage,
) -> Result<bool, String> {
    {
        let mut r = get_runtime();
        r.message_bus
            .push((receiver_id.to_string(), message.clone()));
        r.persist();
    }
    log::info!("agent_communication: {:?}", {
        let mut data = HashMap::new();
        data.insert(
            "sender_id".to_string(),
            Value::String(sender_id.to_string()),
        );
        data.insert(
            "receiver_id".to_string(),
            Value::String(receiver_id.to_string()),
        );
        data.insert(
            "message_id".to_string(),
            Value::String(message.message_id.clone()),
        );
        data.insert(
            "message_type".to_string(),
            Value::String(message.message_type.clone()),
        );
        data.insert(
            "message".to_string(),
            Value::String("Message sent successfully".to_string()),
        );
        data
    });

    Ok(true)
}

/// Returns messages for this agent (and removes them from the bus).
pub fn receive_messages(receiver_id: &str) -> Vec<AgentMessage> {
    let mut runtime = get_runtime();
    let (mine, rest): (Vec<_>, Vec<_>) = std::mem::take(&mut runtime.message_bus)
        .into_iter()
        .partition(|(id, _)| id == receiver_id);
    runtime.message_bus = rest;
    runtime.persist();
    mine.into_iter().map(|(_, m)| m).collect()
}

/// Evolve agent through learning. Persists evolution_data to disk; use get_evolution_data() to retrieve.
/// If the agent was spawned from a mold with lifecycle.on_evolve, that DAL snippet is run with `agent_id` and `evolution_data` in scope.
pub fn evolve(agent_id: &str, evolution_data: HashMap<String, Value>) -> Result<bool, String> {
    let on_evolve = {
        let mut r = get_runtime();
        r.evolution_store
            .insert(agent_id.to_string(), evolution_data.clone());
        let hook = r
            .agent_contexts
            .get(agent_id)
            .and_then(|ctx| ctx.config.lifecycle.as_ref())
            .and_then(|l| l.on_evolve.clone());
        r.persist();
        hook
    };
    log::info!("agent_evolution: {:?}", {
        let mut data = HashMap::new();
        data.insert("agent_id".to_string(), Value::String(agent_id.to_string()));
        data.insert(
            "evolution_data_keys".to_string(),
            Value::Int(evolution_data.len() as i64),
        );
        data.insert(
            "message".to_string(),
            Value::String("Agent evolved successfully".to_string()),
        );
        data
    });

    if let Some(snippet) = on_evolve {
        let mut vars = HashMap::new();
        vars.insert("agent_id".to_string(), Value::String(agent_id.to_string()));
        vars.insert("evolution_data".to_string(), Value::Map(evolution_data));
        if let Err(e) = crate::execute_dal_with_scope(&vars, &snippet) {
            log::warn!(
                "Mold on_evolve lifecycle hook failed for {}: {}",
                agent_id,
                e
            );
        }
    }

    Ok(true)
}

/// Returns stored evolution data for an agent, if any.
pub fn get_evolution_data(agent_id: &str) -> Option<HashMap<String, Value>> {
    get_runtime().evolution_store.get(agent_id).cloned()
}

/// Capability registry: when set via register_capabilities(), validation uses it; otherwise built-in defaults.
static CAPABILITY_REGISTRY: Mutex<Option<HashMap<String, Vec<String>>>> = Mutex::new(None);

/// Register capabilities per agent type (e.g. from config/DB). Overrides built-in defaults for validation.
pub fn register_capabilities(agent_type: String, capabilities: Vec<String>) {
    let mut reg = CAPABILITY_REGISTRY.lock().unwrap();
    if reg.is_none() {
        *reg = Some(HashMap::new());
    }
    if let Some(ref mut m) = *reg {
        m.insert(agent_type, capabilities);
    }
}

/// Validate agent capabilities. Uses registry if set (e.g. from config); otherwise built-in per agent type.
pub fn validate_capabilities(
    agent_type: &str,
    required_capabilities: Vec<String>,
) -> Result<bool, String> {
    let agent_type_enum = AgentType::from_string(agent_type)
        .ok_or_else(|| format!("Invalid agent type: {}", agent_type))?;

    let capabilities: Vec<String> = {
        let reg = CAPABILITY_REGISTRY.lock().unwrap();
        if let Some(ref m) = *reg {
            if let Some(caps) = m.get(agent_type) {
                caps.clone()
            } else {
                builtin_capabilities(&agent_type_enum)
                    .into_iter()
                    .map(String::from)
                    .collect()
            }
        } else {
            builtin_capabilities(&agent_type_enum)
                .into_iter()
                .map(String::from)
                .collect()
        }
    };

    let mut missing_capabilities = Vec::new();
    for required_cap in &required_capabilities {
        if !capabilities.contains(required_cap) {
            missing_capabilities.push(required_cap);
        }
    }

    if missing_capabilities.is_empty() {
        log::info!("capability_validation: {:?}", {
            let mut data = HashMap::new();
            data.insert(
                "agent_type".to_string(),
                Value::String(agent_type.to_string()),
            );
            data.insert(
                "required_capabilities".to_string(),
                Value::Int(required_capabilities.len() as i64),
            );
            data.insert(
                "message".to_string(),
                Value::String("All capabilities validated".to_string()),
            );
            data
        });
        Ok(true)
    } else {
        Err(format!("Missing capabilities: {:?}", missing_capabilities))
    }
}

/// Create agent configuration
pub fn create_agent_config(name: String, agent_type: &str, role: String) -> Option<AgentConfig> {
    let agent_type_enum = AgentType::from_string(agent_type)?;
    Some(AgentConfig::new(name, agent_type_enum).with_role(role))
}

/// Create agent task
pub fn create_agent_task(
    task_id: String,
    description: String,
    priority: &str,
) -> Option<AgentTask> {
    let priority_enum = TaskPriority::from_string(priority)?;
    Some(AgentTask {
        task_id,
        description,
        priority: priority_enum,
        status: TaskStatus::Pending,
        assigned_at: chrono::Utc::now().to_rfc3339(),
        completed_at: None,
        dependencies: Vec::new(),
        metadata: HashMap::new(),
    })
}

/// Create agent message
pub fn create_agent_message(
    message_id: String,
    sender_id: String,
    receiver_id: String,
    message_type: String,
    content: Value,
) -> AgentMessage {
    AgentMessage {
        message_id,
        sender_id,
        receiver_id,
        message_type,
        content,
        timestamp: chrono::Utc::now().to_rfc3339(),
        priority: MessagePriority::Normal,
        requires_response: false,
    }
}

// Helper functions

fn builtin_capabilities(agent_type: &AgentType) -> Vec<&'static str> {
    match agent_type {
        AgentType::AI => vec!["analysis", "learning", "communication", "task_execution"],
        AgentType::System => vec!["monitoring", "coordination", "resource_management"],
        AgentType::Worker => vec!["task_execution", "data_processing", "automation"],
        AgentType::IDE => vec![
            "run",
            "read_file",
            "write_file",
            "list_dir",
            "search",
            "fetch_url",
            "dal_check",
            "dal_run",
            "dal_init",
            "show_url",
            "show_content",
        ],
        AgentType::Custom(_) => vec!["custom_processing"],
    }
}

fn generate_id() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos() as u64
}

fn initialize_ai_agent(agent_context: &mut AgentContext) {
    // Initialize AI-specific capabilities
    agent_context.store_memory("ai_model".to_string(), Value::String("gpt-4".to_string()));
    agent_context.store_memory(
        "learning_algorithm".to_string(),
        Value::String("reinforcement".to_string()),
    );
    agent_context.store_memory(
        "communication_protocol".to_string(),
        Value::String("natural_language".to_string()),
    );

    // Set initial capabilities
    agent_context.config.capabilities = vec![
        "analysis".to_string(),
        "learning".to_string(),
        "communication".to_string(),
        "task_execution".to_string(),
        "problem_solving".to_string(),
    ];
}

fn initialize_system_agent(agent_context: &mut AgentContext) {
    // Initialize system-specific capabilities
    agent_context.store_memory(
        "system_role".to_string(),
        Value::String("coordinator".to_string()),
    );
    agent_context.store_memory("monitoring_enabled".to_string(), Value::Bool(true));
    agent_context.store_memory("resource_tracking".to_string(), Value::Bool(true));

    // Set initial capabilities
    agent_context.config.capabilities = vec![
        "monitoring".to_string(),
        "coordination".to_string(),
        "resource_management".to_string(),
        "system_optimization".to_string(),
    ];
}

fn initialize_worker_agent(agent_context: &mut AgentContext) {
    // Initialize worker-specific capabilities
    agent_context.store_memory(
        "worker_type".to_string(),
        Value::String("general".to_string()),
    );
    agent_context.store_memory(
        "automation_level".to_string(),
        Value::String("high".to_string()),
    );
    agent_context.store_memory("task_queue_size".to_string(), Value::Int(100));

    // Set initial capabilities
    agent_context.config.capabilities = vec![
        "task_execution".to_string(),
        "data_processing".to_string(),
        "automation".to_string(),
        "workflow_management".to_string(),
    ];
}

fn initialize_ide_agent(agent_context: &mut AgentContext) {
    agent_context.store_memory(
        "surface".to_string(),
        Value::String("workspace".to_string()),
    );
    agent_context.store_memory(
        "tool_dispatch".to_string(),
        Value::String("model_turn_loop".to_string()),
    );

    if agent_context.config.capabilities.is_empty() {
        agent_context.config.capabilities = builtin_capabilities(&AgentType::IDE)
            .into_iter()
            .map(String::from)
            .collect();
    }
}

fn initialize_custom_agent(agent_context: &mut AgentContext) {
    // Initialize custom agent with basic capabilities
    agent_context.store_memory(
        "custom_type".to_string(),
        Value::String(agent_context.config.agent_type.to_string()),
    );
    agent_context.store_memory("flexibility".to_string(), Value::String("high".to_string()));

    // Set initial capabilities
    agent_context.config.capabilities = vec![
        "custom_processing".to_string(),
        "adaptation".to_string(),
        "flexibility".to_string(),
    ];
}