-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp.txt
More file actions
3848 lines (3439 loc) · 139 KB
/
temp.txt
File metadata and controls
3848 lines (3439 loc) · 139 KB
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
We are trying to extend the dagger library attached below to also have a third way of executing flows. The first is essentially running a DAG through a static workflow. The second is a dynamic DAG where agents can add or nodes can add other nodes to the DAG execution. The last is a completely autonomous pub/sub based system. I am attaching the code to the DAG library along with where we stand with the current pub/sub agent implementation and also we have. One second. Also we have. Also The below is attached the design document.
Dagger Lib
```
//! Dagger - A library for executing directed acyclic graphs (DAGs) with custom actions.
//!
//! This library provides a way to define and execute DAGs with custom actions. It supports
//! loading graph definitions from YAML files, validating the graph structure, and executing
//! custom actions associated with each node in the graph.
use anyhow::anyhow;
use anyhow::{Error, Result};
use petgraph::visit::IntoNodeReferences;
pub mod any;
pub use any::*;
use async_trait::async_trait;
use chrono::NaiveDateTime;
use cuid2;
use petgraph::algo::is_cyclic_directed;
use petgraph::graph::{DiGraph, NodeIndex};
use petgraph::visit::EdgeRef;
use petgraph::visit::Topo;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::Read;
use std::sync::Arc;
use std::sync::RwLock;
use tokio::sync::oneshot;
mod pubsubagent;
// use tokio::sync::RwLock;
use serde_json::error::Error as JsonError;
use tokio::time::{sleep, timeout, Duration};
use tracing::{debug, error, info, trace, warn, Level}; // Assuming you're using Tokio for async runtime // Add at top with other imports
// Add these imports at the top with other imports
use serde::de::Error as SerdeError;
use std::io::Error as IoError;
#[macro_export]
macro_rules! register_action {
($executor:expr, $action_name:expr, $action_func:path) => {{
struct Action;
#[async_trait::async_trait]
impl NodeAction for Action {
fn name(&self) -> String {
$action_name.to_string()
}
async fn execute(
&self,
executor: &mut DagExecutor,
node: &Node,
cache: &Cache,
) -> Result<()> {
$action_func(executor, node, cache).await
}
fn schema(&self) -> serde_json::Value {
serde_json::json!({
"name": $action_name,
"description": "Manually registered action",
"parameters": { "type": "object", "properties": {} },
"returns": { "type": "object" }
})
}
}
$executor.register_action(Arc::new(Action));
}};
}
/// Specifies how to execute a workflow
#[derive(Debug, Clone)]
pub enum WorkflowSpec {
/// Execute a static, pre-loaded DAG by name
Static { name: String },
/// Start an agent-driven flow with a given task
Agent { task: String },
}
/// Configuration for retry behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RetryStrategy {
/// Exponential backoff with configurable parameters
Exponential {
initial_delay_secs: u64,
max_delay_secs: u64,
multiplier: f64,
},
/// Linear backoff with fixed delay
Linear { delay_secs: u64 },
/// No delay between retries
Immediate,
}
impl Default for RetryStrategy {
fn default() -> Self {
Self::Exponential {
initial_delay_secs: 2,
max_delay_secs: 60,
multiplier: 2.0,
}
}
}
/// Configuration for DAG execution behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DagConfig {
/// Maximum number of retry attempts
pub max_attempts: Option<u8>,
/// What to do when a node fails
pub on_failure: OnFailure,
/// Maximum runtime in seconds
pub timeout_seconds: Option<u64>,
/// How long to wait for human input (None = indefinite)
pub human_wait_minutes: Option<u32>,
/// What to do when human input times out
pub human_timeout_action: HumanTimeoutAction,
/// Maximum tokens allowed
pub max_tokens: Option<u64>,
/// Maximum iterations allowed
pub max_iterations: Option<u32>,
/// How often to trigger human review (in iterations)
pub review_frequency: Option<u32>,
/// Retry strategy configuration
pub retry_strategy: RetryStrategy,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OnFailure {
Continue,
Pause,
Stop,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HumanTimeoutAction {
Autopilot,
Pause,
}
impl Default for DagConfig {
fn default() -> Self {
Self {
max_attempts: Some(3),
on_failure: OnFailure::Pause,
timeout_seconds: Some(3600),
human_wait_minutes: None,
human_timeout_action: HumanTimeoutAction::Pause,
max_tokens: None,
max_iterations: Some(50),
review_frequency: Some(5),
retry_strategy: RetryStrategy::default(),
}
}
}
impl DagConfig {
/// Validates configuration values
pub fn validate(&self) -> Result<(), Error> {
// Validate max_attempts
if let Some(attempts) = self.max_attempts {
if attempts == 0 {
return Err(anyhow!("max_attempts must be greater than 0"));
}
}
// Validate timeout_seconds
if let Some(timeout) = self.timeout_seconds {
if timeout == 0 {
return Err(anyhow!("timeout_seconds must be greater than 0"));
}
if timeout > 86400 {
// 24 hours
return Err(anyhow!("timeout_seconds cannot exceed 24 hours"));
}
}
// Validate human_wait_minutes
if let Some(wait) = self.human_wait_minutes {
if wait > 1440 {
// 24 hours
return Err(anyhow!("human_wait_minutes cannot exceed 24 hours"));
}
}
// Validate max_iterations
if let Some(iterations) = self.max_iterations {
if iterations == 0 {
return Err(anyhow!("max_iterations must be greater than 0"));
}
if iterations > 1000 {
return Err(anyhow!("max_iterations cannot exceed 1000"));
}
}
// Validate review_frequency
if let Some(freq) = self.review_frequency {
if freq == 0 {
return Err(anyhow!("review_frequency must be greater than 0"));
}
}
Ok(())
}
/// Merges two configurations, with override_with taking precedence
pub fn merge(base: &Self, override_with: &Self) -> Result<Self, Error> {
let merged = Self {
max_attempts: override_with.max_attempts.or(base.max_attempts),
on_failure: override_with.on_failure.clone(),
timeout_seconds: override_with.timeout_seconds.or(base.timeout_seconds),
human_wait_minutes: override_with.human_wait_minutes.or(base.human_wait_minutes),
human_timeout_action: override_with.human_timeout_action.clone(),
max_tokens: override_with.max_tokens.or(base.max_tokens),
max_iterations: override_with.max_iterations.or(base.max_iterations),
review_frequency: override_with.review_frequency.or(base.review_frequency),
retry_strategy: override_with.retry_strategy.clone(),
};
// Validate merged configuration
merged.validate()?;
Ok(merged)
}
}
/// Metadata about a DAG's execution state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DagMetadata {
pub status: String,
pub task: String,
}
/// Represents a graph of nodes.
#[derive(Debug, Deserialize)]
pub struct Graph {
/// The nodes in the graph.
pub nodes: Vec<Node>,
pub name: String,
pub description: String,
pub instructions: Option<Vec<String>>,
pub tags: Vec<String>,
pub author: String,
pub version: String,
pub signature: String,
pub config: Option<DagConfig>,
}
/// A trait for converting values between Rust types and `DynAny` enum.
pub trait Convertible {
/// Converts a Rust type to a `DynAny` enum.
fn to_value(&self) -> DynAny;
/// Converts a `DynAny` enum to a Rust type.
fn from_value(value: &DynAny) -> Option<Self>
where
Self: Sized;
}
/// An input or output field of a node.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct IField {
/// The name of the field.
pub name: String,
/// The description of the field.
pub description: Option<String>,
/// The data type of the field.
// pub data_type: String, // Changed to String for simplicity in this example
/// The reference to another node's output.
pub reference: String,
// pub default: Option<DynAny>,
}
/// An input or output field of a node.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct OField {
/// The name of the field.
pub name: String,
/// The description of the field.
pub description: Option<String>,
}
/// A node in the graph.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct Node {
/// The unique identifier of the node.
///
pub id: String,
/// The dependencies of the node (other nodes that must be executed before this node).
pub dependencies: Vec<String>,
/// The inputs of the node.
pub inputs: Vec<IField>,
/// The outputs of the node.
pub outputs: Vec<OField>,
/// The action to be executed by the node.
pub action: String,
/// The failure action to be executed if the node's action fails.
pub failure: String,
/// The on-failure behavior (continue or terminate).
pub onfailure: bool,
/// The description of the node.
pub description: String,
/// The timeout for the node's action in seconds.
pub timeout: u64,
/// The number of times to retry the node's action if it fails.
pub try_count: u8,
pub instructions: Option<Vec<String>>,
}
/// Type alias for a cache of input and output values.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SerializableData {
pub value: String,
}
// Update your cache to use the new SerializableData
pub type Cache = RwLock<HashMap<String, HashMap<String, SerializableData>>>;
pub fn serialize_cache_to_json(cache: &Cache) -> Result<String> {
let cache_read = cache
.read()
.map_err(|e| anyhow!("Failed to acquire cache read lock: {}", e))?;
let serialized_cache: HashMap<String, HashMap<String, String>> = cache_read
.iter()
.map(|(node_id, category_map)| {
let serialized_category: HashMap<String, String> = category_map
.iter()
.map(|(output_name, data)| (output_name.clone(), data.value.clone()))
.collect();
(node_id.clone(), serialized_category)
})
.collect();
serde_json::to_string(&serialized_cache)
.map_err(|e| anyhow!("Failed to serialize cache to JSON: {}", e))
}
pub fn serialize_cache_to_prettyjson(cache: &Cache) -> Result<String> {
let cache_read = cache.read().unwrap();
let serialized_cache: HashMap<String, HashMap<String, String>> = cache_read
.iter()
.map(|(node_id, category_map)| {
let serialized_category: HashMap<String, String> = category_map
.iter()
.map(|(output_name, data)| (output_name.clone(), data.value.clone()))
.collect();
(node_id.clone(), serialized_category)
})
.collect();
// Convert to JSON string
serde_json::to_string_pretty(&serialized_cache)
.map_err(|e| anyhow::anyhow!(format!("Serialization error: {}", e)))
}
/// Function to load the cache from JSON
/// Function to load the cache from JSON
pub fn load_cache_from_json(json_data: &str) -> Result<Cache> {
// Create a new cache instance
let cache = Cache::new(HashMap::new());
// Deserialize the JSON string into a HashMap
let parsed_cache: HashMap<String, HashMap<String, SerializableData>> =
serde_json::from_str(json_data)
.map_err(|e| anyhow::anyhow!(format!("Deserialization error: {}", e)))?;
// Lock the cache for writing
{
let mut cache_write = cache.write().unwrap();
*cache_write = parsed_cache;
}
Ok(cache)
}
// pub fn insert_value<T: IntoAny + 'static>(cache: &Cache, category: String, key: String, value: T) {
// let mut cache_write = cache.write().unwrap();
// let category_map = cache_write.entry(category).or_insert_with(HashMap::new);
// category_map.insert(key, Box::new(value));
// }
pub fn insert_value<T>(cache: &Cache, node_id: &str, output_name: &str, value: T) -> Result<()>
where
T: Serialize + std::fmt::Debug,
{
let mut cache_write = cache
.write()
.map_err(|e| anyhow!("Failed to acquire cache write lock: {}", e))?;
// Try to convert the value to a string representation
let serialized_value = match serde_json::to_string(&value) {
Ok(json_str) => {
// For simple string values, remove the quotes
if json_str.starts_with('"') && json_str.ends_with('"') {
json_str[1..json_str.len() - 1].to_string()
} else {
json_str
}
}
Err(e) => return Err(anyhow!("Failed to serialize value: {}", e)),
};
// Store the serialized value in the cache
cache_write
.entry(node_id.to_string())
.or_insert_with(HashMap::new)
.insert(
output_name.to_string(),
SerializableData {
value: serialized_value,
},
);
Ok(())
}
pub fn generate_node_id(action_name: &str) -> String {
let timestamp = chrono::Utc::now().timestamp_millis() % 1_000_000; // Last 6 digits
format!("{}_{}", action_name, timestamp)
}
pub fn get_input<T: for<'de> Deserialize<'de>>(
cache: &Cache,
node_id: &str,
key: &str,
) -> Result<T> {
let cache_read = cache
.read()
.map_err(|e| anyhow!("Failed to acquire cache read lock: {}", e))?;
let node_map = cache_read
.get(node_id)
.ok_or_else(|| anyhow!("Node '{}' not found in cache", node_id))?;
let serialized_value = node_map
.get(key)
.ok_or_else(|| anyhow!("Key '{}' not found for node '{}'", key, node_id))?;
serde_json::from_str(&serialized_value.value).map_err(|e| {
anyhow!(
"Failed to deserialize value for node '{}', key '{}': {}",
node_id,
key,
e
)
})
}
pub fn parse_input_from_name<T: for<'de> Deserialize<'de>>(
cache: &Cache,
input_name: String,
inputs: &[IField],
) -> Result<T> {
let input = inputs
.iter()
.find(|input| input.name == input_name)
.ok_or_else(|| anyhow::anyhow!("Input not found: {}", input_name))?;
let parts: Vec<&str> = input.reference.split('.').collect();
if parts.len() != 2 {
return Err(anyhow::anyhow!(
"Invalid reference format: {}",
input.reference
));
}
let node_id = parts[0];
let output_name = parts[1];
let cache_read = cache.read().unwrap();
let category_map = cache_read
.get(node_id)
.ok_or_else(|| anyhow::anyhow!("Node not found: {}", node_id))?;
let serialized_value = category_map
.get(output_name)
.ok_or_else(|| anyhow::anyhow!("Output not found: {}", output_name))?;
serde_json::from_str(&serialized_value.value)
.map_err(|e| anyhow::anyhow!("Deserialization error: {}", e))
}
pub fn get_global_input<T: for<'de> Deserialize<'de>>(
cache: &Cache,
dag_name: &str,
key: &str,
) -> Result<T> {
let cache_read = cache.read().unwrap();
let dag_map = cache_read
.get(dag_name)
.ok_or_else(|| anyhow!("DAG '{}' not found", dag_name))?;
let serialized_value = dag_map
.get(key)
.ok_or_else(|| anyhow!("Key '{}' not found", key))?;
serde_json::from_str(&serialized_value.value)
.map_err(|e| anyhow!("Deserialization error: {}", e))
}
pub fn insert_global_value<T: Serialize>(
cache: &Cache,
dag_name: &str,
key: &str,
value: T,
) -> Result<()> {
let mut cache_write = cache.write().unwrap();
let dag_map = cache_write
.entry(dag_name.to_string())
.or_insert_with(HashMap::new);
dag_map.insert(
key.to_string(),
SerializableData {
value: serde_json::to_string(&value)?,
},
);
Ok(())
}
pub fn append_global_value<T: Serialize + for<'de> Deserialize<'de>>(
cache: &Cache,
dag_name: &str,
key: &str,
value: T,
) -> Result<()> {
let mut cache_write = cache.write().unwrap();
let dag_map = cache_write
.entry(dag_name.to_string())
.or_insert_with(HashMap::new);
let existing: Vec<T> = dag_map
.get(key)
.map(|v| serde_json::from_str(&v.value).unwrap_or(vec![]))
.unwrap_or(vec![]);
let mut updated = existing;
updated.push(value);
dag_map.insert(
key.to_string(),
SerializableData {
value: serde_json::to_string(&updated)?,
},
);
Ok(())
}
/// A trait for custom actions associated with nodes.
#[async_trait]
pub trait NodeAction: Send + Sync {
/// Returns the name of the action.
fn name(&self) -> String;
/// Executes the action with the given node and inputs, and returns the outputs.
async fn execute(&self, executor: &mut DagExecutor, node: &Node, cache: &Cache) -> Result<()>;
fn schema(&self) -> Value;
}
// Add ExecutionTree type definition before DagExecutor
pub type ExecutionTree = DiGraph<NodeSnapshot, ExecutionEdge>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeSnapshot {
pub node_id: String,
pub outcome: NodeExecutionOutcome,
pub cache_ref: String,
pub timestamp: NaiveDateTime,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionEdge {
pub parent: String,
pub label: String,
}
#[derive(Debug, thiserror::Error)]
pub enum DagError {
#[error("Lock error: {0}")]
LockError(String),
#[error("Node not found: {0}")]
NodeNotFound(String),
#[error("Action not found: {0}")]
ActionNotFound(String),
#[error("Serialization error: {0}")]
SerializationError(#[from] serde_json::Error),
#[error("Database error: {0}")]
DatabaseError(#[from] sled::Error),
#[error("Validation error: {0}")]
ValidationError(String),
#[error("Execution error: {0}")]
ExecutionError(String),
#[error("Invalid graph: {0}")]
InvalidGraph(String),
#[error("Cancelled")]
Cancelled,
#[error("Action not registered: {0}")]
ActionNotRegistered(String),
#[error("Invalid state: {0}")]
InvalidState(String),
#[error("Dependency not found: {0}")]
DependencyNotFound(String),
#[error("Node already exists: {0}")]
NodeAlreadyExists(String),
#[error("Unknown database error occurred")]
UnknownDatabaseError,
}
type ActionRegistry = Arc<RwLock<HashMap<String, Arc<dyn NodeAction>>>>;
/// The main executor for DAGs.
pub struct DagExecutor {
/// A registry of custom actions.
pub function_registry: ActionRegistry,
/// The graphs to be executed.
pub graphs: Arc<RwLock<HashMap<String, Graph>>>,
/// The prebuilt DAGs.
pub prebuilt_dags:
Arc<RwLock<HashMap<String, (DiGraph<Node, ()>, HashMap<String, NodeIndex>)>>>,
pub config: DagConfig,
pub sled_db: sled::Db,
pub stopped: Arc<RwLock<bool>>,
pub paused: Arc<RwLock<bool>>,
pub start_time: NaiveDateTime,
pub tree: Arc<RwLock<HashMap<String, ExecutionTree>>>,
/// Track bootstrapped agent DAGs
pub bootstrapped_agents: Arc<RwLock<HashSet<String>>>,
}
impl DagExecutor {
/// Creates a new `DagExecutor` with optional configuration
pub fn new(
config: Option<DagConfig>,
registry: ActionRegistry,
sled_path: &str,
) -> Result<Self, Error> {
let sled_db = sled::open(sled_path)?;
Ok(DagExecutor {
function_registry: registry,
graphs: Arc::new(RwLock::new(HashMap::new())),
prebuilt_dags: Arc::new(RwLock::new(HashMap::new())),
config: config.unwrap_or_default(),
sled_db,
stopped: Arc::new(RwLock::new(false)),
paused: Arc::new(RwLock::new(false)),
start_time: chrono::Local::now().naive_local(),
tree: Arc::new(RwLock::new(HashMap::new())),
bootstrapped_agents: Arc::new(RwLock::new(HashSet::new())),
})
}
/// Registers a custom action with the `DagExecutor`.
pub fn register_action(&mut self, action: Arc<dyn NodeAction>) -> Result<(), DagError> {
let mut registry = self
.function_registry
.write()
.map_err(|e| DagError::LockError(e.to_string()))?;
info!("Registered action: {:#?}", action.name());
registry.insert(action.name(), action);
Ok(())
}
pub fn get_tool_schemas(&self) -> Vec<Value> {
let registry = self.function_registry.read().unwrap();
registry.values().map(|action| action.schema()).collect()
}
/// Loads a graph definition from a YAML file with proper config merging
pub fn load_yaml_file(&mut self, file_path: &str) -> Result<(), Error> {
let mut file = File::open(file_path)
.map_err(|e| anyhow!("Failed to open file {}: {}", file_path, e))?;
let mut yaml_content = String::new();
file.read_to_string(&mut yaml_content)
.map_err(|e| anyhow!("Failed to read file {}: {}", file_path, e))?;
let mut graph: Graph = serde_yaml::from_str(&yaml_content)
.map_err(|e| anyhow!("Failed to parse YAML file {}: {}", file_path, e))?;
// Merge and validate configurations
if let Some(graph_config) = &graph.config {
let merged_config = DagConfig::merge(&self.config, graph_config)?;
graph.config = Some(merged_config);
}
// Build DAG
let (dag, node_indices) = self.build_dag_internal(&graph)?;
let name = graph.name.clone();
// Acquire write locks and update both structures atomically
let mut graphs = self
.graphs
.write()
.map_err(|e| anyhow!("Failed to acquire graphs write lock: {}", e))?;
let mut dags = self
.prebuilt_dags
.write()
.map_err(|e| anyhow!("Failed to acquire DAGs write lock: {}", e))?;
graphs.insert(name.clone(), graph);
dags.insert(name, (dag, node_indices));
Ok(())
}
// extend above to load all yaml files in a directory
pub fn load_yaml_dir(&mut self, dir_path: &str) {
match std::fs::read_dir(dir_path) {
Ok(entries) => {
for entry in entries {
match entry {
Ok(entry) => {
if let Ok(file_type) = entry.file_type() {
if file_type.is_file() {
if let Some(file_path) = entry.path().to_str() {
self.load_yaml_file(file_path);
} else {
error!(
"Failed to convert file path to string: {:?}",
entry.path()
);
}
}
} else {
error!(
"Failed to determine file type for entry: {:?}",
entry.path()
);
}
}
Err(e) => {
error!("Error reading directory entry: {}", e);
}
}
}
}
Err(e) => {
error!("Failed to read directory {}: {}", dir_path, e);
}
}
}
/// Executes the DAG and returns a `DagExecutionReport`.
pub async fn execute_dag(
&mut self,
spec: WorkflowSpec,
cache: &Cache,
cancel_rx: oneshot::Receiver<()>,
) -> Result<DagExecutionReport, DagError> {
match spec {
WorkflowSpec::Static { name } => {
// Get read lock to access prebuilt DAG
let prebuilt_dag = {
let dags = self
.prebuilt_dags
.read()
.map_err(|e| DagError::LockError(e.to_string()))?;
dags.get(&name)
.ok_or_else(|| {
DagError::NodeNotFound(format!("Graph '{}' not found", name))
})?
.clone()
};
let (dag, _) = prebuilt_dag;
if dag.node_count() == 0 {
return Err(DagError::InvalidGraph(format!(
"Graph '{}' contains no nodes",
name
)));
}
self.start_time = chrono::Local::now().naive_local();
tokio::select! {
result = execute_dag_async(self, &dag, cache) => {
let (report, needs_human_check) = result;
if needs_human_check {
self.add_node(&name, format!("human_check_{}", cuid2::create_id()),
"human_interrupt".to_string(), vec![])?;
}
Ok(report)
},
_ = cancel_rx => Err(DagError::Cancelled),
}
}
WorkflowSpec::Agent { task } => {
// Verify supervisor action is registered first
{
let registry = self.function_registry.read().unwrap();
if !registry.contains_key("supervisor_step") {
return Err(DagError::ActionNotFound("supervisor_step".to_string()));
}
info!("Supervisor action registered");
} // registry lock is dropped here
// Attempt to bootstrap agent DAG if not already done
let needs_bootstrap = {
let mut bootstrapped = self
.bootstrapped_agents
.write()
.map_err(|e| DagError::LockError(e.to_string()))?;
if !bootstrapped.contains(&task) {
bootstrapped.insert(task.clone());
true
} else {
false
}
};
if needs_bootstrap {
// Bootstrap agent DAG with write lock
let mut dags = self
.prebuilt_dags
.write()
.map_err(|e| DagError::LockError(e.to_string()))?;
if !dags.contains_key(&task) {
// Create bootstrap graph
let graph = Graph {
name: task.clone(),
nodes: vec![Node {
id: "supervisor_start".to_string(),
action: "supervisor_step".to_string(),
dependencies: Vec::new(),
inputs: Vec::new(),
outputs: Vec::new(),
failure: String::new(),
onfailure: true,
description: "Supervisor node".to_string(),
timeout: self.config.timeout_seconds.unwrap_or(3600),
try_count: self.config.max_attempts.unwrap_or(3),
instructions: None,
}],
description: format!("Agent-driven DAG for task: {}", task),
instructions: None,
tags: vec!["agent".to_string()],
author: "system".to_string(),
version: "1.0".to_string(),
signature: "auto-generated".to_string(),
config: Some(self.config.clone()),
};
let (mut dag, indices) = self
.build_dag_internal(&graph)
.map_err(|e| DagError::InvalidGraph(e.to_string()))?;
self.graphs.write().unwrap().insert(task.clone(), graph);
dags.insert(task.clone(), (dag, indices));
}
}
// Get DAG with read lock
let (dag, _) = {
let dags = self
.prebuilt_dags
.read()
.map_err(|e| DagError::LockError(e.to_string()))?;
dags.get(&task)
.ok_or_else(|| {
DagError::NodeNotFound(format!("Agent DAG '{}' not found", task))
})?
.clone()
};
self.start_time = chrono::Local::now().naive_local();
// Record active DAG in Sled
let active_tree = self.sled_db.open_tree("active")?;
active_tree.insert(
task.as_bytes(),
serde_json::to_vec(&DagMetadata {
status: "Running".to_string(),
task: task.clone(),
})?,
)?;
tokio::select! {
result = execute_dag_async(self, &dag, cache) => {
let (report, needs_human_check) = result;
if needs_human_check {
self.add_node(&task, format!("human_check_{}", cuid2::create_id()),
"human_interrupt".to_string(), vec![])?;
}
Ok(report)
},
_ = cancel_rx => Err(DagError::Cancelled),
}
}
}
}
fn build_dag_internal(
&self,
graph: &Graph,
) -> Result<(DiGraph<Node, ()>, HashMap<String, NodeIndex>), Error> {
let mut dag = DiGraph::<Node, ()>::new();
let mut node_indices = HashMap::new();
for node in &graph.nodes {
let node_index = dag.add_node(node.clone());
node_indices.insert(node.id.clone(), node_index);
}
validate_dag_structure(&dag)?;
validate_node_dependencies(&graph.nodes, &node_indices)?;
validate_node_actions(self, &graph.nodes)?;
// validate_io_data_types(&graph.nodes)?;
for node in &graph.nodes {
let dependent_node_index = node_indices[&node.id];
for dependency_id in &node.dependencies {
let dependency_node_index = node_indices[dependency_id];
dag.add_edge(dependency_node_index, dependent_node_index, ());
}
}
Ok((dag, node_indices))
}
pub fn list_dags(&self) -> Result<Vec<(String, String)>> {
let graphs = self
.graphs
.read()
.map_err(|e| anyhow!("Failed to acquire graphs read lock: {}", e))?;
Ok(graphs
.iter()
.map(|(name, graph)| (name.clone(), graph.description.clone()))
.collect())
}
pub fn list_dag_filtered_tag(&self, filter: &str) -> Result<Vec<(String, String)>> {
let graphs = self
.graphs
.read()
.map_err(|e| anyhow!("Failed to acquire graphs read lock: {}", e))?;
Ok(graphs
.iter()
.filter(|(_, graph)| graph.tags.iter().any(|tag| tag.contains(filter)))
.map(|(name, graph)| (name.clone(), graph.description.clone()))
.collect())
}
pub fn list_dag_multiple_tags(&self, tags: Vec<String>) -> Result<Vec<(String, String)>> {
let graphs = self
.graphs
.read()
.map_err(|e| anyhow!("Failed to acquire graphs read lock: {}", e))?;
Ok(graphs
.iter()
.filter(|(_, graph)| tags.iter().all(|tag| graph.tags.contains(tag)))
.map(|(name, graph)| (name.clone(), graph.description.clone()))
.collect())
}
pub fn list_dags_metadata(&self) -> Result<Vec<(String, String, String, String, String)>> {
let graphs = self
.graphs
.read()
.map_err(|e| anyhow!("Failed to acquire graphs read lock: {}", e))?;
Ok(graphs
.iter()
.map(|(name, graph)| {
(
name.clone(),
graph.description.clone(),
graph.author.clone(),
graph.version.clone(),
graph.signature.clone(),
)
})
.collect())
}
/// Saves only changed cache entries since last save
pub fn save_cache(&self, dag_id: &str, cache: &Cache) -> Result<(), DagError> {
let start = std::time::Instant::now();
let cache_read = cache.read().map_err(|e| {
DagError::LockError(format!("Failed to acquire cache read lock: {}", e))
})?;
// Get last saved state from Sled
let cache_tree = self.sled_db.open_tree("cache")?;
let previous_state: HashMap<String, HashMap<String, SerializableData>> =
match cache_tree.get(dag_id.as_bytes())? {
Some(compressed) => zstd::decode_all(&compressed[..])