1use std::collections::HashMap;
8use std::sync::Arc;
9
10use adk_action::{ActionNodeConfig, SwitchNodeConfig, TriggerNodeConfig};
11use serde::{Deserialize, Serialize};
12
13use crate::action::ActionNodeExecutor;
14use crate::action::switch::evaluate_switch_conditions;
15use crate::edge::{END, EdgeTarget};
16use crate::error::{GraphError, Result};
17use crate::graph::StateGraph;
18use crate::node::Node;
19use crate::state::StateSchema;
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct WorkflowEdge {
27 pub from: String,
29 pub to: String,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
33 pub condition: Option<String>,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub from_port: Option<String>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub to_port: Option<String>,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub struct WorkflowCondition {
46 pub id: String,
48 pub expression: String,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub description: Option<String>,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
60#[serde(rename_all = "camelCase")]
61pub struct WorkflowSchema {
62 pub edges: Vec<WorkflowEdge>,
64 #[serde(default)]
66 pub conditions: Vec<WorkflowCondition>,
67 #[serde(default)]
69 pub action_nodes: HashMap<String, ActionNodeConfig>,
70 #[serde(default)]
72 pub agent_nodes: Vec<String>,
73}
74
75impl WorkflowSchema {
76 pub fn from_json(json: &str) -> Result<Self> {
78 serde_json::from_str(json)
79 .map_err(|e| GraphError::InvalidGraph(format!("invalid workflow JSON: {e}")))
80 }
81
82 pub fn build_graph(&self, name: &str) -> Result<crate::agent::GraphAgent> {
90 let schema = StateSchema::simple(&["input", "output", "messages"]);
91 let mut graph = StateGraph::new(schema);
92
93 for (node_id, config) in &self.action_nodes {
95 let executor = ActionNodeExecutor::new(config.clone());
96 debug_assert_eq!(
98 executor.name(),
99 node_id,
100 "ActionNodeExecutor name must match node ID"
101 );
102 graph.nodes.insert(node_id.clone(), Arc::new(executor));
103 }
104
105 let condition_map: HashMap<&str, &WorkflowCondition> =
107 self.conditions.iter().map(|c| (c.id.as_str(), c)).collect();
108
109 let mut conditional_groups: HashMap<String, Vec<&WorkflowEdge>> = HashMap::new();
111 let mut direct_edges: Vec<&WorkflowEdge> = Vec::new();
112
113 for edge in &self.edges {
114 if edge.condition.is_some() {
115 conditional_groups.entry(edge.from.clone()).or_default().push(edge);
116 } else {
117 direct_edges.push(edge);
118 }
119 }
120
121 for edge in &direct_edges {
123 graph = graph.add_edge(&edge.from, &edge.to);
124 }
125
126 for (node_id, config) in &self.action_nodes {
128 if let ActionNodeConfig::Switch(switch_config) = config {
129 graph = register_switch_conditional_edges(graph, node_id, switch_config);
130 }
131 }
132
133 for (source, edges) in &conditional_groups {
135 if let Some(ActionNodeConfig::Switch(_)) = self.action_nodes.get(source) {
137 continue;
138 }
139
140 let mut targets_map: HashMap<String, EdgeTarget> = HashMap::new();
142 let mut condition_expressions: Vec<(String, String)> = Vec::new();
143
144 for edge in edges {
145 if let Some(cond_id) = &edge.condition {
146 let target = if edge.to == END {
147 EdgeTarget::End
148 } else {
149 EdgeTarget::Node(edge.to.clone())
150 };
151 targets_map.insert(edge.to.clone(), target);
152
153 if let Some(cond) = condition_map.get(cond_id.as_str()) {
154 condition_expressions.push((cond.expression.clone(), edge.to.clone()));
155 }
156 }
157 }
158
159 let router_expressions = condition_expressions.clone();
160 let default_target = END.to_string();
161
162 let router = Arc::new(move |state: &crate::state::State| -> String {
163 for (expr, target) in &router_expressions {
164 let resolved = adk_action::interpolate_variables(expr, state);
165 let trimmed = resolved.trim().to_lowercase();
166 if !trimmed.is_empty() && trimmed != "false" && trimmed != "0" {
167 return target.clone();
168 }
169 }
170 default_target.clone()
171 });
172
173 graph.edges.push(crate::edge::Edge::Conditional {
174 source: source.clone(),
175 router,
176 targets: targets_map,
177 });
178 }
179
180 let compiled = graph.compile()?;
181 Ok(crate::agent::GraphAgent::from_graph(name, compiled))
182 }
183
184 pub fn trigger_configs(&self) -> Vec<TriggerNodeConfig> {
188 self.action_nodes
189 .values()
190 .filter_map(|config| {
191 if let ActionNodeConfig::Trigger(trigger) = config {
192 Some(trigger.clone())
193 } else {
194 None
195 }
196 })
197 .collect()
198 }
199
200 #[cfg(feature = "action-trigger")]
205 pub fn build_trigger_runtime(
206 &self,
207 graph: Arc<crate::agent::GraphAgent>,
208 ) -> crate::action::trigger_runtime::TriggerRuntime {
209 let triggers = self.trigger_configs();
210 crate::action::trigger_runtime::TriggerRuntime::new(graph, triggers)
211 }
212}
213
214fn register_switch_conditional_edges(
219 mut graph: StateGraph,
220 node_id: &str,
221 switch_config: &SwitchNodeConfig,
222) -> StateGraph {
223 let conditions = switch_config.conditions.clone();
224 let eval_mode = switch_config.evaluation_mode.clone();
225 let default_branch = switch_config.default_branch.clone();
226
227 let mut targets_map: HashMap<String, EdgeTarget> = HashMap::new();
229 for condition in &conditions {
230 targets_map
231 .insert(condition.output_port.clone(), EdgeTarget::Node(condition.output_port.clone()));
232 }
233 if let Some(ref default) = default_branch {
234 let target =
235 if default == END { EdgeTarget::End } else { EdgeTarget::Node(default.clone()) };
236 targets_map.insert(default.clone(), target);
237 }
238 targets_map.insert(END.to_string(), EdgeTarget::End);
240
241 let router = Arc::new(move |state: &crate::state::State| -> String {
242 match evaluate_switch_conditions(&conditions, state, &eval_mode, default_branch.as_deref())
243 {
244 Ok(ports) => ports.into_iter().next().unwrap_or_else(|| END.to_string()),
245 Err(_) => END.to_string(),
246 }
247 });
248
249 graph.edges.push(crate::edge::Edge::Conditional {
250 source: node_id.to_string(),
251 router,
252 targets: targets_map,
253 });
254
255 graph
256}