Skip to main content

gadk_engine/workflow/nodes/
workflow.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! `WorkflowNode`: a graph node that runs a nested workflow.
17
18use std::any::Any;
19use std::collections::HashMap;
20use std::sync::Arc;
21
22use futures::StreamExt;
23use gadk_agent::{AgentError, Context, EventStream};
24use gadk_session::Event;
25use serde_json::Value;
26
27use crate::error::{WorkflowError, WorkflowErrorKind};
28use crate::workflow::persistence::{
29    completed_delegated_output, graph_history_event, own_event_node_name,
30};
31use crate::workflow::route::go_quote;
32use crate::workflow::scheduler::{build_nodes_by_name, child_event_output, wf_error};
33use crate::workflow::{BaseNode, Edge, Node, NodeConfig, Workflow, WorkflowOptions};
34
35/// A graph node that runs a nested workflow.
36pub struct WorkflowNode {
37    pub(crate) base: BaseNode,
38    pub(crate) sub_workflow: Arc<Workflow>,
39}
40
41impl WorkflowNode {
42    /// Builds the nested workflow named `name` from `edges`.
43    pub fn new(name: &str, edges: Vec<Edge>) -> Result<Arc<WorkflowNode>, WorkflowError> {
44        let wf = Workflow::new(name, edges, WorkflowOptions::default())?;
45        Ok(Arc::new(WorkflowNode {
46            base: BaseNode::new(name, "", NodeConfig::default()),
47            sub_workflow: wf,
48        }))
49    }
50}
51
52impl Node for WorkflowNode {
53    fn name(&self) -> &str {
54        self.base.name()
55    }
56    fn description(&self) -> &str {
57        self.base.description()
58    }
59    fn config(&self) -> &NodeConfig {
60        self.base.config()
61    }
62    fn input_schema(&self) -> Option<&Value> {
63        self.base.input_schema()
64    }
65    fn output_schema(&self) -> Option<&Value> {
66        self.base.output_schema()
67    }
68    fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
69        self.base.validate_input(v)
70    }
71    fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
72        self.base.validate_output(v)
73    }
74    /// Runs the nested workflow, forwarding its events with the output stripped, then yields the
75    /// single terminal output as this node's output.
76    fn run(&self, ctx: Context, input: Value) -> EventStream {
77        let sub = Arc::clone(&self.sub_workflow);
78        let terminals = sub.graph.terminal_node_names();
79        let nodes_by_name = build_nodes_by_name(&sub.graph);
80        Box::pin(async_stream::stream! {
81            let mut terminal_outputs: HashMap<String, Value> = HashMap::new();
82            let mut pending_err: Option<AgentError> = None;
83            // The guard lives in the stream state: dropping the stream cancels the nested run.
84            let (sub_ctx, guard) = ctx.with_agent_cancel();
85            let mut events = sub.run_node(sub_ctx.clone(), input);
86            while let Some(item) = events.next().await {
87                let mut ev = match item {
88                    Err(e) => {
89                        pending_err = Some(e); // the last error wins
90                        // Keep draining so the nested scheduler unwinds.
91                        guard.cancel();
92                        continue;
93                    }
94                    Ok(ev) => ev,
95                };
96                if let (Some(out), Some(info)) = (child_event_output(&ev), ev.node_info.as_ref()) {
97                    for seg in info.path.split('/') {
98                        let n = seg.split('@').next().unwrap_or(seg);
99                        if terminals.contains(n) {
100                            terminal_outputs.insert(n.to_string(), out);
101                            break;
102                        }
103                    }
104                } else if let Some(out) = completed_delegated_output(&ev) {
105                    let owner = own_event_node_name(&graph_history_event(&ev, sub.name()), &nodes_by_name);
106                    if terminals.contains(&owner) && !out.is_null() {
107                        terminal_outputs.insert(owner, out);
108                    }
109                }
110                // Forward with the output stripped: the terminal output is re-emitted below.
111                ev.output = None;
112                yield Ok(ev);
113            }
114            if let Some(e) = pending_err {
115                yield Err(e);
116                return;
117            }
118            if terminal_outputs.len() > 1 {
119                yield Err(wf_error(
120                    WorkflowErrorKind::MultipleOutputs,
121                    format!(
122                        ": sub-workflow {} has {} terminal nodes producing output; a workflow must have at most one terminal output",
123                        go_quote(sub.name()),
124                        terminal_outputs.len()
125                    ),
126                ));
127                return;
128            }
129            if let Some(out) = terminal_outputs.into_values().next() {
130                let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
131                ev.output = Some(out);
132                yield Ok(ev);
133            }
134        })
135    }
136    fn as_any(&self) -> &dyn Any {
137        self
138    }
139}