Skip to main content

gadk_engine/workflow/nodes/
dynamic.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//! A node whose body schedules children at run time with
17//! [`run_node`](fn@crate::workflow::run_node).
18
19use std::any::Any;
20use std::future::Future;
21use std::marker::PhantomData;
22use std::sync::Arc;
23
24use gadk_agent::{AgentError, Context, ContextDelta, DynamicSubScheduler, EventStream};
25use gadk_session::{Event, NodeInfo};
26use schemars::JsonSchema;
27use serde::Serialize;
28use serde::de::DeserializeOwned;
29use serde_json::Value;
30use tokio::sync::{mpsc, oneshot};
31
32use crate::error::{WorkflowError, WorkflowErrorKind};
33use crate::tool::utils::CompiledSchema;
34use crate::workflow::dynamic_scheduler::new_dynamic_sub_scheduler;
35use crate::workflow::failure_inventory::publish_failure_inventory;
36use crate::workflow::nodes::function::{CoerceError, Step, coerce_input, short_type_name};
37use crate::workflow::persistence::{WORKFLOW_DELEGATED_OUTPUT_KEY, WORKFLOW_NODE_COMPLETED_KEY};
38use crate::workflow::route::go_quote;
39use crate::workflow::scheduler::is_kind;
40use crate::workflow::{BaseNode, Emit, Node, NodeConfig};
41
42/// One emitted event awaiting the consumer.
43pub(crate) struct EmitMsg {
44    ev: Box<Event>,
45    ack: oneshot::Sender<()>,
46}
47
48impl EmitMsg {
49    /// The event and the acknowledgement to fire once the consumer has resumed.
50    pub(crate) fn into_parts(self) -> (Event, oneshot::Sender<()>) {
51        (*self.ev, self.ack)
52    }
53}
54
55/// Creates the emit handed to the node body, and the receiver its events arrive on. The returned
56/// emit resolves after the node's stream yielded the event and the consumer polled again. It
57/// fails with `AgentError::Cancelled` once the context is cancelled or the stream (the receiver)
58/// is gone; a dropped stream also drops the body future.
59pub(crate) fn make_emit(ctx: &Context) -> (Emit, mpsc::Receiver<EmitMsg>) {
60    let (tx, rx) = mpsc::channel::<EmitMsg>(1);
61    let token = ctx.cancellation_token().clone();
62    let emit: Emit = Arc::new(move |ev: Event| {
63        let (tx, token) = (tx.clone(), token.clone());
64        Box::pin(async move {
65            if token.is_cancelled() {
66                return Err(AgentError::Cancelled);
67            }
68            let (ack, done) = oneshot::channel();
69            if tx
70                .send(EmitMsg {
71                    ev: Box::new(ev),
72                    ack,
73                })
74                .await
75                .is_err()
76            {
77                return Err(AgentError::Cancelled);
78            }
79            done.await.map_err(|_| AgentError::Cancelled)
80        })
81    });
82    (emit, rx)
83}
84
85/// A node whose body takes an `In`, orchestrates children and returns an `Out`.
86struct DynamicNode<In, Out, F> {
87    base: BaseNode,
88    f: Arc<F>,
89    input_schema: Option<Arc<CompiledSchema>>,
90    _types: PhantomData<fn(In) -> Out>,
91}
92
93/// `rerun_on_resume` defaults to `Some(true)`.
94fn apply_dynamic_defaults(mut cfg: NodeConfig) -> NodeConfig {
95    if cfg.rerun_on_resume.is_none() {
96        cfg.rerun_on_resume = Some(true);
97    }
98    cfg
99}
100
101fn compile(
102    schema: Option<Value>,
103    what: &str,
104) -> Result<Option<Arc<CompiledSchema>>, WorkflowError> {
105    schema
106        .map(|s| {
107            CompiledSchema::new(s).map(Arc::new).map_err(|e| {
108                WorkflowError::new(
109                    WorkflowErrorKind::Other,
110                    format!("resolving {what} schema: {e}"),
111                )
112            })
113        })
114        .transpose()
115}
116
117/// Builds a dynamic node from already-compiled schemas.
118fn new_dynamic<In, Out, F, Fut>(
119    name: &str,
120    f: F,
121    input_schema: Option<Arc<CompiledSchema>>,
122    output_schema: Option<Arc<CompiledSchema>>,
123    cfg: NodeConfig,
124) -> Arc<dyn Node>
125where
126    In: DeserializeOwned + JsonSchema + Send + 'static,
127    Out: Serialize + Send + 'static,
128    F: Fn(Context, In, Emit) -> Fut + Send + Sync + 'static,
129    Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
130{
131    Arc::new(DynamicNode::<In, Out, F> {
132        base: BaseNode::from_compiled(name, "", cfg, input_schema.clone(), output_schema),
133        f: Arc::new(f),
134        input_schema,
135        _types: PhantomData,
136    })
137}
138
139/// A node whose body orchestrates children with `run_node`. Its `rerun_on_resume` defaults to
140/// true.
141pub fn dynamic_node<In, Out, F, Fut>(name: &str, f: F, cfg: NodeConfig) -> Arc<dyn Node>
142where
143    In: DeserializeOwned + JsonSchema + Send + 'static,
144    Out: Serialize + Send + 'static,
145    F: Fn(Context, In, Emit) -> Fut + Send + Sync + 'static,
146    Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
147{
148    new_dynamic::<In, Out, F, Fut>(name, f, None, None, apply_dynamic_defaults(cfg))
149}
150
151/// As [`dynamic_node`], with input and output schemas.
152pub fn dynamic_node_with_schema<In, Out, F, Fut>(
153    name: &str,
154    f: F,
155    input: Option<Value>,
156    output: Option<Value>,
157    cfg: NodeConfig,
158) -> Result<Arc<dyn Node>, WorkflowError>
159where
160    In: DeserializeOwned + JsonSchema + Send + 'static,
161    Out: Serialize + Send + 'static,
162    F: Fn(Context, In, Emit) -> Fut + Send + Sync + 'static,
163    Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
164{
165    let input_schema = compile(input, "input")?;
166    let output_schema = compile(output, "output")?;
167    Ok(new_dynamic::<In, Out, F, Fut>(
168        name,
169        f,
170        input_schema,
171        output_schema,
172        apply_dynamic_defaults(cfg),
173    ))
174}
175
176impl<In, Out, F, Fut> Node for DynamicNode<In, Out, F>
177where
178    In: DeserializeOwned + JsonSchema + Send + 'static,
179    Out: Serialize + Send + 'static,
180    F: Fn(Context, In, Emit) -> Fut + Send + Sync + 'static,
181    Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
182{
183    fn name(&self) -> &str {
184        self.base.name()
185    }
186    fn description(&self) -> &str {
187        self.base.description()
188    }
189    fn config(&self) -> &NodeConfig {
190        self.base.config()
191    }
192    fn input_schema(&self) -> Option<&Value> {
193        self.base.input_schema()
194    }
195    fn output_schema(&self) -> Option<&Value> {
196        self.base.output_schema()
197    }
198    fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
199        self.base.validate_input(v)
200    }
201    fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
202        self.base.validate_output(v)
203    }
204    /// Runs the body with an emit and a sub-scheduler for its children.
205    fn run(&self, ctx: Context, input: Value) -> EventStream {
206        let (f, schema, name) = (
207            Arc::clone(&self.f),
208            self.input_schema.clone(),
209            self.base.name().to_string(),
210        );
211        let waits = self.base.config().wait_for_output == Some(true);
212        // The data address of the Arc holding this node: equal to its node_producer_key.
213        let self_key = std::ptr::from_ref(self).cast::<()>() as usize;
214        Box::pin(async_stream::stream! {
215            let typed: In = match coerce_input(input, schema.as_deref()) {
216                Ok(v) => v,
217                Err(CoerceError::Validation(e) | CoerceError::Conversion(e)) => {
218                    yield Err(AgentError::other(format!(
219                        "dynamic node {}: invalid input type, expected {}: {e}",
220                        go_quote(&name),
221                        short_type_name::<In>()
222                    )));
223                    return;
224                }
225            };
226            let (emit, mut rx) = make_emit(&ctx);
227            // The parent path of the children: the context's path, or the node's name at the top.
228            let parent_path = {
229                let p = ctx.path();
230                if p.is_empty() { name.clone() } else { p }
231            };
232            let sub = new_dynamic_sub_scheduler(ctx.clone(), parent_path.clone(), Arc::clone(&emit));
233            let orchestrator_ctx = ctx.with_delta(ContextDelta {
234                run_id: Some(String::new()),
235                sub_scheduler: Some(Some(Arc::clone(&sub) as Arc<dyn DynamicSubScheduler>)),
236                output_for_ancestors: Some(sub.output_for_ancestors()),
237                ..ContextDelta::default()
238            });
239            let mut body = Box::pin(f(orchestrator_ctx, typed, emit));
240            let result = loop {
241                let step = tokio::select! {
242                    biased;
243                    Some(msg) = rx.recv() => Step::Emit(msg),
244                    r = &mut body => Step::Done(r),
245                };
246                match step {
247                    Step::Emit(msg) => {
248                        let (ev, ack) = msg.into_parts();
249                        yield Ok(ev);
250                        let _ = ack.send(());
251                    }
252                    Step::Done(r) => break r,
253                }
254            };
255            drop(body);
256            match result {
257                Err(e) => {
258                    if is_kind(&e, WorkflowErrorKind::NodeWaitingForOutput) {
259                        yield Err(e);
260                    } else if !is_kind(&e, WorkflowErrorKind::NodeInterrupted) {
261                        publish_failure_inventory(self_key, &sub.child_failures());
262                        yield Err(e);
263                    }
264                }
265                Ok(out) => {
266                    if let Some(value) = sub.delegated_output() {
267                        if !(value.is_null() && waits) {
268                            let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
269                            ev.node_info = Some(NodeInfo { path: parent_path.clone(), ..NodeInfo::default() });
270                            ev.response.custom_metadata.insert(WORKFLOW_NODE_COMPLETED_KEY.into(), Value::Bool(true));
271                            ev.response.custom_metadata.insert(WORKFLOW_DELEGATED_OUTPUT_KEY.into(), value);
272                            yield Ok(ev);
273                        }
274                    } else {
275                        match serde_json::to_value(out) {
276                            Err(e) => yield Err(AgentError::other(format!(
277                                "dynamic node {}: marshal output: {e}",
278                                go_quote(&name)
279                            ))),
280                            Ok(Value::Null) => {}
281                            Ok(v) => {
282                                let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
283                                ev.output = Some(v);
284                                ev.node_info = Some(NodeInfo { path: parent_path.clone(), ..NodeInfo::default() });
285                                yield Ok(ev);
286                            }
287                        }
288                    }
289                }
290            }
291        })
292    }
293    fn as_any(&self) -> &dyn Any {
294        self
295    }
296}