Skip to main content

adk_graph/
shape.rs

1//! The static shape of a compiled graph, for workflow observers (spec 3.3 §12, developer
2//! track).
3//!
4//! [`CompiledGraph::shape`] reports every node, every edge and the entry nodes in a
5//! deterministic order, so an observer draws the same graph on every call and a
6//! governed node's [`ToolOrigin`](adk_core::ToolOrigin) binds to a stable declaration.
7//!
8//! # Example
9//!
10//! ```
11//! use adk_graph::edge::{END, START};
12//! use adk_graph::graph::StateGraph;
13//! use adk_graph::node::NodeOutput;
14//! use adk_graph::shape::{EdgeShape, NodeKind};
15//!
16//! let graph = StateGraph::with_channels(&["invoice"])
17//!     .add_node_fn("draft", |_ctx| async { Ok(NodeOutput::new()) })
18//!     .add_edge(START, "draft")
19//!     .add_edge("draft", END)
20//!     .compile()?;
21//!
22//! let shape = graph.shape();
23//! assert_eq!(shape.entry, vec!["draft".to_string()]);
24//! assert_eq!(shape.nodes[0].kind, NodeKind::Function);
25//! assert_eq!(shape.edges, vec![EdgeShape::new("draft", END, false)]);
26//! # Ok::<(), adk_graph::GraphError>(())
27//! ```
28
29use crate::edge::{END, Edge, EdgeTarget, START};
30use crate::governed::GovernedNode;
31use crate::graph::CompiledGraph;
32use adk_core::ToolEffect;
33use serde::{Deserialize, Serialize};
34
35/// What kind of step a node is, as a workflow observer labels it (spec 3.3 §12).
36///
37/// A node reports its own kind through [`Node::kind`](crate::node::Node::kind); a fan-in
38/// node is reported as [`NodeKind::Join`] whatever it runs.
39///
40/// # Example
41///
42/// ```
43/// use adk_graph::shape::NodeKind;
44///
45/// assert_eq!(serde_json::to_value(NodeKind::HttpCall)?, serde_json::json!("httpCall"));
46/// # Ok::<(), serde_json::Error>(())
47/// ```
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase")]
50#[non_exhaustive]
51pub enum NodeKind {
52    /// An [`AgentNode`](crate::node::AgentNode): a model step.
53    ModelStep,
54    /// A function node.
55    Function,
56    /// An HTTP action node.
57    HttpCall,
58    /// A trigger action node.
59    Trigger,
60    /// A set action node.
61    Set,
62    /// A transform action node.
63    Transform,
64    /// A switch action node.
65    Switch,
66    /// A loop action node.
67    Loop,
68    /// A merge action node.
69    Merge,
70    /// A wait action node.
71    Wait,
72    /// A file action node.
73    File,
74    /// A code action node.
75    Code,
76    /// A database action node.
77    Database,
78    /// An email action node.
79    Email,
80    /// A notification action node.
81    Notification,
82    /// An RSS action node.
83    Rss,
84    /// A fan-in node, which waits for its predecessors.
85    Join,
86    /// A [`SubgraphNode`](crate::subgraph::SubgraphNode).
87    Subgraph,
88    /// Any other node.
89    Other,
90}
91
92/// One node of a [`GraphShape`] (spec 3.3 §12).
93///
94/// # Example
95///
96/// ```
97/// use adk_graph::governed::GovernedNode;
98/// use adk_graph::shape::{NodeKind, NodeShape};
99///
100/// let shape = NodeShape {
101///     name: "pay".to_string(),
102///     description: "Charges the customer".to_string(),
103///     kind: NodeKind::HttpCall,
104///     effect: Some(adk_core::ToolEffect::NonIdempotent),
105///     interrupt_before: false,
106///     interrupt_after: false,
107///     governed: Some(GovernedNode::new().with_approval().spending_money()),
108/// };
109/// let json = serde_json::to_value(&shape)?;
110/// assert_eq!(json["governed"]["spendsMoney"], true);
111/// # Ok::<(), serde_json::Error>(())
112/// ```
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "camelCase")]
115pub struct NodeShape {
116    /// The node's name.
117    pub name: String,
118    /// The node's [`description`](crate::node::Node::description).
119    pub description: String,
120    /// What kind of step the node is.
121    pub kind: NodeKind,
122    /// The side effect the node declared with
123    /// [`CompiledGraph::with_node_effect`], if any.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub effect: Option<ToolEffect>,
126    /// Whether the run pauses before the node.
127    pub interrupt_before: bool,
128    /// Whether the run pauses after the node.
129    pub interrupt_after: bool,
130    /// The node's governance, when it opted in with
131    /// [`CompiledGraph::with_governed_node`].
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub governed: Option<GovernedNode>,
134}
135
136/// A governed node of a graph or of a subgraph inside it, from
137/// [`CompiledGraph::governed_shapes`] (spec 3.3 §12).
138///
139/// # Example
140///
141/// ```
142/// use adk_graph::governed::GovernedNode;
143/// use adk_graph::shape::{GovernedShape, NodeKind, NodeShape};
144///
145/// let pay = GovernedShape {
146///     path: vec!["billing".to_string(), "pay".to_string()],
147///     node: NodeShape {
148///         name: "pay".to_string(),
149///         description: String::new(),
150///         kind: NodeKind::HttpCall,
151///         effect: None,
152///         interrupt_before: false,
153///         interrupt_after: false,
154///         governed: Some(GovernedNode::new().with_approval()),
155///     },
156/// };
157/// assert_eq!(pay.path.first().map(String::as_str), Some("billing"));
158/// ```
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(rename_all = "camelCase")]
161pub struct GovernedShape {
162    /// The node names from the graph asked down to the governed node: its first entry is a
163    /// node of that graph, its last the governed node itself.
164    pub path: Vec<String>,
165    /// The governed node's shape entry in the graph that holds it, which its decision's
166    /// [`ToolOrigin`](adk_core::ToolOrigin) binds to.
167    pub node: NodeShape,
168}
169
170/// One edge of a [`GraphShape`]; `to` is [`END`] for an edge that ends a branch.
171///
172/// # Example
173///
174/// ```
175/// use adk_graph::shape::EdgeShape;
176///
177/// let edge = EdgeShape::new("pay", "receipt", false);
178/// assert_eq!(serde_json::to_value(&edge)?["to"], "receipt");
179/// # Ok::<(), serde_json::Error>(())
180/// ```
181#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
182#[serde(rename_all = "camelCase")]
183pub struct EdgeShape {
184    /// The node the edge leaves.
185    pub from: String,
186    /// The node the edge reaches, or [`END`].
187    pub to: String,
188    /// Whether a router chooses this edge at run time.
189    pub conditional: bool,
190}
191
192impl EdgeShape {
193    /// An edge from `from` to `to`.
194    pub fn new(from: impl Into<String>, to: impl Into<String>, conditional: bool) -> Self {
195        Self { from: from.into(), to: to.into(), conditional }
196    }
197}
198
199/// The static shape of a compiled graph (spec 3.3 §12).
200///
201/// Nodes are sorted by name, edges by `(from, to, conditional)` and entry nodes by name,
202/// so equal graphs serialize identically.
203///
204/// # Example
205///
206/// ```
207/// use adk_graph::edge::{END, START};
208/// use adk_graph::graph::StateGraph;
209/// use adk_graph::node::NodeOutput;
210///
211/// let graph = StateGraph::with_channels(&["n"])
212///     .add_node_fn("a", |_ctx| async { Ok(NodeOutput::new()) })
213///     .add_edge(START, "a")
214///     .add_edge("a", END)
215///     .compile()?;
216/// let json = serde_json::to_value(graph.shape())?;
217/// assert_eq!(json["entry"], serde_json::json!(["a"]));
218/// assert_eq!(json["nodes"][0]["interruptBefore"], false);
219/// # Ok::<(), Box<dyn std::error::Error>>(())
220/// ```
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase")]
223pub struct GraphShape {
224    /// Every node, sorted by name.
225    pub nodes: Vec<NodeShape>,
226    /// Every edge, sorted, with each target of a conditional edge listed once.
227    pub edges: Vec<EdgeShape>,
228    /// The nodes a run starts with, sorted.
229    pub entry: Vec<String>,
230}
231
232impl CompiledGraph {
233    /// The graph's nodes, edges and entry nodes, for a workflow observer (spec 3.3 §12).
234    ///
235    /// # Example
236    ///
237    /// ```
238    /// use adk_graph::edge::{END, START};
239    /// use adk_graph::graph::StateGraph;
240    /// use adk_graph::node::NodeOutput;
241    /// use adk_graph::shape::EdgeShape;
242    ///
243    /// let graph = StateGraph::with_channels(&["route"])
244    ///     .add_node_fn("triage", |_ctx| async { Ok(NodeOutput::new()) })
245    ///     .add_node_fn("refund", |_ctx| async { Ok(NodeOutput::new()) })
246    ///     .add_edge(START, "triage")
247    ///     .add_conditional_edges(
248    ///         "triage",
249    ///         |_state| "refund".to_string(),
250    ///         [("refund", "refund"), (END, END)],
251    ///     )
252    ///     .add_edge("refund", END)
253    ///     .compile()?;
254    /// assert_eq!(
255    ///     graph.shape().edges,
256    ///     vec![
257    ///         EdgeShape::new("refund", END, false),
258    ///         EdgeShape::new("triage", END, true),
259    ///         EdgeShape::new("triage", "refund", true),
260    ///     ]
261    /// );
262    /// # Ok::<(), adk_graph::GraphError>(())
263    /// ```
264    pub fn shape(&self) -> GraphShape {
265        let mut names: Vec<&String> = self.nodes.keys().collect();
266        names.sort();
267        let nodes = names.into_iter().filter_map(|name| self.node_shape(name)).collect();
268
269        let mut edges: Vec<EdgeShape> = Vec::new();
270        let target_name = |target: &EdgeTarget| match target {
271            EdgeTarget::Node(name) => name.clone(),
272            EdgeTarget::End => END.to_string(),
273        };
274        for edge in &self.edges {
275            match edge {
276                Edge::Direct { source, target } if source != START => {
277                    edges.push(EdgeShape::new(source.clone(), target_name(target), false));
278                }
279                Edge::Conditional { source, targets, .. } => {
280                    edges.extend(
281                        targets.values().map(|target| {
282                            EdgeShape::new(source.clone(), target_name(target), true)
283                        }),
284                    );
285                }
286                Edge::Direct { .. } | Edge::Entry { .. } => {}
287            }
288        }
289        edges.sort();
290        edges.dedup();
291
292        let mut entry = self.get_entry_nodes();
293        entry.sort();
294        entry.dedup();
295        GraphShape { nodes, edges, entry }
296    }
297
298    /// Every governed node of this graph and of the subgraphs inside it, at any depth, each
299    /// with its path from this graph (spec 3.3 §12).
300    ///
301    /// A governed node inside a subgraph asks for its decision as the graph that holds the
302    /// subgraph, so a workflow observer reads the node's governance and the node of this
303    /// graph it runs under from here. Sorted by path.
304    ///
305    /// # Example
306    ///
307    /// ```
308    /// use std::sync::Arc;
309    /// use adk_graph::edge::{END, START};
310    /// use adk_graph::governed::GovernedNode;
311    /// use adk_graph::graph::StateGraph;
312    /// use adk_graph::node::NodeOutput;
313    /// use adk_graph::subgraph::SubgraphNode;
314    ///
315    /// let billing = StateGraph::with_channels(&["charge"])
316    ///     .add_node_fn("pay", |_ctx| async { Ok(NodeOutput::new()) })
317    ///     .add_edge(START, "pay")
318    ///     .add_edge("pay", END)
319    ///     .compile()?
320    ///     .with_governed_node("pay", GovernedNode::new().spending_money());
321    /// let graph = StateGraph::with_channels(&["charge"])
322    ///     .add_node(SubgraphNode::new("billing", Arc::new(billing)))
323    ///     .add_edge(START, "billing")
324    ///     .add_edge("billing", END)
325    ///     .compile()?;
326    /// let governed = graph.governed_shapes();
327    /// assert_eq!(governed[0].path, vec!["billing".to_string(), "pay".to_string()]);
328    /// assert!(governed[0].node.governed.is_some_and(|node| node.spends_money));
329    /// # Ok::<(), adk_graph::GraphError>(())
330    /// ```
331    pub fn governed_shapes(&self) -> Vec<GovernedShape> {
332        let mut names: Vec<&String> = self.nodes.keys().collect();
333        names.sort();
334        let mut found = Vec::new();
335        for name in names {
336            if self.governed_nodes.contains_key(name)
337                && let Some(node) = self.node_shape(name)
338            {
339                found.push(GovernedShape { path: vec![name.clone()], node });
340            }
341            if let Some(inner) = self.nodes.get(name).and_then(|node| node.subgraph()) {
342                for mut nested in inner.governed_shapes() {
343                    nested.path.insert(0, name.clone());
344                    found.push(nested);
345                }
346            }
347        }
348        found
349    }
350
351    /// The shape entry of one node, or `None` when the graph has no such node.
352    pub(crate) fn node_shape(&self, name: &str) -> Option<NodeShape> {
353        let node = self.nodes.get(name)?;
354        let kind =
355            if self.deferred_configs.contains_key(name) { NodeKind::Join } else { node.kind() };
356        Some(NodeShape {
357            name: name.to_string(),
358            description: node.description().to_string(),
359            kind,
360            effect: self.node_effects.get(name).copied(),
361            interrupt_before: self.interrupt_before.contains(name),
362            interrupt_after: self.interrupt_after.contains(name),
363            governed: self.governed_nodes.get(name).copied(),
364        })
365    }
366}