Skip to main content

gadk_engine/workflow/
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//! `Workflow` and `WorkflowOptions` (the scheduler and persistence modules add impl blocks).
17//! `Workflow` is not a [`Node`](crate::workflow::Node); `WorkflowNode` wraps it.
18
19use std::sync::Arc;
20
21use gadk_agent::{Context, ContextDelta, EventStream, InvocationContext};
22use gadk_session::Session;
23use serde_json::{Map, Value};
24
25use crate::error::{WorkflowError, WorkflowErrorKind};
26use crate::workflow::base_node::compile_schema;
27use crate::workflow::graph::Graph;
28use crate::workflow::route::go_quote;
29use crate::workflow::scheduler::Scheduler;
30use crate::workflow::state::RunState;
31use crate::workflow::validation::{validate_nodes, validate_sub_workflow_names, validate_workflow};
32use crate::workflow::{Edge, START};
33
34/// Construction-time settings for [`Workflow::new`].
35/// Zero values mean "no override / use engine defaults".
36#[derive(Clone, Default)]
37pub struct WorkflowOptions {
38    /// Marks the workflow as a synthetic single-node wrapper created by the runner to drive a
39    /// standalone agent.
40    pub root_wrapper: bool,
41    /// Caps how many graph-scheduled nodes may run concurrently; `None` or `Some(0)` = unlimited.
42    pub max_concurrency: Option<usize>,
43    /// The workflow's state schema.
44    pub state_schema: Option<Value>,
45}
46
47impl WorkflowOptions {
48    /// Marks this workflow as a synthetic single-node wrapper created
49    /// by the runner to drive a standalone agent. A root wrapper's run does not stamp a parent
50    /// namespace prefix onto root contexts.
51    pub fn with_root_wrapper(mut self) -> Self {
52        self.root_wrapper = true;
53        self
54    }
55
56    /// Caps how many graph-scheduled nodes may run concurrently in a single run; nodes beyond the
57    /// cap queue as pending. 0 disables the cap (unlimited). Does not apply to dynamic sub-nodes
58    /// invoked via RunNode.
59    pub fn with_max_concurrency(mut self, n: usize) -> Self {
60        self.max_concurrency = Some(n);
61        self
62    }
63
64    /// Sets the state schema for the workflow.
65    pub fn with_state_schema(mut self, s: Value) -> Self {
66        self.state_schema = Some(s);
67        self
68    }
69}
70
71/// A validated workflow graph.
72pub struct Workflow {
73    /// The validated graph.
74    pub(crate) graph: Arc<Graph>,
75    /// The node-path namespacing name; empty leaves the workflow unnamed.
76    pub(crate) name: String,
77    /// Concurrency cap for graph-scheduled nodes; 0 = unlimited.
78    pub(crate) max_concurrency: usize,
79    /// The raw state schema (compiled and checked by [`Workflow::new`]).
80    #[allow(dead_code)] // never read after construction.
81    pub(crate) state_schema: Option<Value>,
82    /// Marks a synthetic single-node wrapper created by the runner.
83    pub(crate) is_root_wrapper: bool,
84}
85
86impl Workflow {
87    /// Validates `edges` and builds the workflow.
88    pub fn new(
89        name: &str,
90        edges: Vec<Edge>,
91        opts: WorkflowOptions,
92    ) -> Result<Arc<Workflow>, WorkflowError> {
93        validate_nodes(&edges)?;
94        validate_sub_workflow_names(name, &edges)?;
95        // The struct keeps the raw schema (`state_schema: Option<Value>`); it is compiled
96        // here to validate.
97        let compiled_state = compile_schema(opts.state_schema.clone()).map_err(|e| {
98            WorkflowError::new(
99                WorkflowErrorKind::Other,
100                format!(
101                    "resolving state schema for workflow {}: {e}",
102                    go_quote(name)
103                ),
104            )
105        })?;
106        let mut graph = Graph::new(edges);
107        graph.is_root_wrapper = opts.root_wrapper;
108        validate_workflow(&graph, compiled_state.as_deref())?;
109        Ok(Arc::new(Workflow {
110            graph: Arc::new(graph),
111            name: name.to_owned(),
112            max_concurrency: opts.max_concurrency.unwrap_or(0),
113            state_schema: opts.state_schema,
114            is_root_wrapper: opts.root_wrapper,
115        }))
116    }
117
118    /// The node-path namespacing name; empty when anonymous.
119    pub fn name(&self) -> &str {
120        &self.name
121    }
122}
123
124impl Workflow {
125    /// Namespaces a named, non-root-wrapper workflow's node paths
126    /// under `<parent>/<name>@1` and seeds START with the user content's text.
127    pub fn run(self: &Arc<Self>, ctx: InvocationContext) -> EventStream {
128        let c = ctx.into_context();
129        let c = if !self.is_root_wrapper && !self.name.is_empty() {
130            let parent = c.path();
131            let wf_path = if parent.is_empty() {
132                format!("{}@1", self.name)
133            } else {
134                format!("{parent}/{}@1", self.name)
135            };
136            let ancestors = c.output_for_ancestors();
137            c.with_delta(ContextDelta {
138                path: Some(wf_path),
139                run_id: Some("1".to_string()),
140                output_for_ancestors: Some(ancestors),
141                sub_scheduler: Some(None),
142                ..ContextDelta::default()
143            })
144        } else {
145            c
146        };
147        let input = user_input(&c);
148        self.run_node(c, input)
149    }
150
151    /// Runs the graph from START with `input` under `ctx`. One
152    /// scheduler per call, created on the stream's first poll; dropping the stream stops the
153    /// run (every node task is aborted and every node context cancelled).
154    pub fn run_node(self: &Arc<Self>, ctx: Context, input: Value) -> EventStream {
155        let wf = Arc::clone(self);
156        Box::pin(async_stream::stream! {
157            let mut s = Scheduler::new(ctx.clone(), Arc::clone(&wf.graph), wf.max_concurrency);
158            s.workflow_name = wf.name.clone();
159            let input = (!input.is_null()).then_some(input);
160            s.state.ensure_node(START.name()).input = input.clone();
161            s.schedule_node(Arc::clone(&START), input, String::new(), ctx.branch());
162            while let Some(item) = s.next().await {
163                yield item;
164            }
165        })
166    }
167}
168
169impl Workflow {
170    /// Rebuilds the paused run from session history. `Ok(None)` means no interrupt or failure
171    /// history; a non-empty `invocation_id` scopes the scan to that invocation.
172    pub fn reconstruct_run_state(
173        &self,
174        session: &dyn Session,
175        invocation_id: &str,
176    ) -> Result<Option<RunState>, WorkflowError> {
177        crate::workflow::persistence::reconstruct_run_state(self, session, invocation_id)
178    }
179
180    /// Continues a paused run from `state` with `responses`
181    /// (interrupt id → payload). Empty `responses` yields an empty stream.
182    pub fn resume(
183        self: &Arc<Self>,
184        ctx: Context,
185        state: RunState,
186        responses: Map<String, Value>,
187    ) -> EventStream {
188        crate::workflow::resume::resume_stream(Arc::clone(self), ctx, state, responses)
189    }
190}
191
192/// The concatenated text parts of the user content; null without one.
193fn user_input(ctx: &Context) -> Value {
194    match ctx.user_content() {
195        None => Value::Null,
196        Some(uc) => Value::String(uc.parts.iter().map(|p| p.text.as_str()).collect()),
197    }
198}