gadk_engine/agents/workflow_agent.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 workflow graph as an agent.
17
18use std::sync::Arc;
19
20use futures::StreamExt;
21use gadk_agent::{
22 AfterAgentCallback, Agent, AgentConfig, AgentError, AgentState, AgentType, BeforeAgentCallback,
23 EventStream, InvocationContext,
24};
25use gadk_genai::FunctionResponse;
26use serde_json::{Map, Value};
27
28use crate::tool::utils::function_responses;
29use crate::workflow::{
30 Edge, RunState, WORKFLOW_INPUT_FUNCTION_CALL_NAME, Workflow, WorkflowOptions,
31};
32
33/// The configuration for creating a new workflow agent.
34#[derive(Clone, Default)]
35pub struct WorkflowAgentConfig {
36 /// The agent's (and workflow's) name.
37 pub name: String,
38 /// The agent's description.
39 pub description: String,
40 /// The child agents this agent can delegate to.
41 pub sub_agents: Vec<Arc<dyn Agent>>,
42 /// The workflow graph's edges.
43 pub edges: Vec<Edge>,
44 /// Called sequentially before the agent starts its run.
45 pub before_agent_callbacks: Vec<BeforeAgentCallback>,
46 /// Called sequentially after the agent completes its run.
47 pub after_agent_callbacks: Vec<AfterAgentCallback>,
48}
49
50/// A workflow agent. One returned agent can serve many concurrent sessions: the per-invocation
51/// run state is rebuilt from session event history on a resume turn rather than held on the
52/// agent. A paused workflow resumes on a follow-up turn when the user submits a FunctionResponse
53/// targeting the interrupt id emitted by the paused node.
54pub fn new(cfg: WorkflowAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
55 // A graph that fails validation is reported as-is.
56 let wf = Workflow::new(&cfg.name, cfg.edges.clone(), WorkflowOptions::default())?;
57 gadk_agent::new_with_state(
58 AgentConfig {
59 name: cfg.name.clone(),
60 description: cfg.description.clone(),
61 sub_agents: cfg.sub_agents.clone(),
62 before_agent_callbacks: cfg.before_agent_callbacks.clone(),
63 after_agent_callbacks: cfg.after_agent_callbacks.clone(),
64 run: Some(Arc::new(move |ctx: InvocationContext| run(wf.clone(), ctx))),
65 },
66 // The agent type makes the agent run open an "invoke_workflow <name>" span.
67 AgentState {
68 agent_type: AgentType::WorkflowAgent,
69 config: Some(Arc::new(cfg)),
70 on_before_agent_callback_event: None,
71 live: None,
72 },
73 )
74}
75
76/// Runs `Workflow::resume` when the inbound user content answers a previously emitted input
77/// request, `Workflow::run` on every other turn.
78fn run(workflow: Arc<Workflow>, ctx: InvocationContext) -> EventStream {
79 Box::pin(async_stream::stream! {
80 match detect_resume(&workflow, &ctx) {
81 Err(e) => yield Err(e),
82 Ok(Some((responses, state))) => {
83 // Resume takes the invocation context as a plain `Context`.
84 let mut s = workflow.resume(ctx.clone().into_context(), state, responses);
85 while let Some(item) = s.next().await {
86 yield item;
87 }
88 }
89 Ok(None) => {
90 let mut s = workflow.run(ctx.clone());
91 while let Some(item) = s.next().await {
92 yield item;
93 }
94 }
95 }
96 })
97}
98
99/// A resume turn: the responses keyed by interrupt id, and the reconstructed run state.
100type Resume = (Map<String, Value>, RunState);
101
102/// The responses keyed by interrupt id and the run state reconstructed from session history when
103/// this turn is a resume; `None` for a fresh turn.
104fn detect_resume(
105 workflow: &Workflow,
106 ctx: &InvocationContext,
107) -> Result<Option<Resume>, AgentError> {
108 let frs = function_responses(ctx.user_content());
109 if frs.is_empty() {
110 return Ok(None);
111 }
112 let mut responses = Map::new();
113 for fr in frs {
114 if fr.name != WORKFLOW_INPUT_FUNCTION_CALL_NAME {
115 continue;
116 }
117 responses.insert(fr.id.clone(), decode_workflow_input_response(fr));
118 }
119 if responses.is_empty() {
120 return Ok(None);
121 }
122 // Scope rehydration to this run's invocation (the runner reuses the paused run's id on
123 // resume) so a prior completed run in the same session does not leak in. A bad resume (e.g.
124 // failed schema validation) must fail, not silently fall through to a fresh run.
125 let session = ctx.session();
126 let Some(state) = workflow.reconstruct_run_state(&*session, ctx.invocation_id())? else {
127 return Ok(None);
128 };
129 // The runner has already persisted this turn's answers. Rehydration unwraps and validates
130 // them; the ingress decoder must not replace those values with a differently decoded copy.
131 for ns in state.nodes.values() {
132 for (id, response) in ns.resumed_inputs.iter().flatten() {
133 if responses.contains_key(id) {
134 responses.insert(id.clone(), response.clone());
135 }
136 }
137 }
138 Ok(Some((responses, state)))
139}
140
141/// The user-supplied payload of a FunctionResponse targeting a workflow input request. Three
142/// accepted shapes, in priority order:
143///
144/// 1. `{"response": <value>}`: a string value is parsed as JSON and the result returned (the
145/// string verbatim when it is not valid JSON); any other value is returned as-is.
146/// 2. `{"payload": <any>}`: the value, verbatim.
147/// 3. anything else: the whole response map.
148pub(crate) fn decode_workflow_input_response(fr: &FunctionResponse) -> Value {
149 if let Some(raw) = fr.response.get("response") {
150 if let Value::String(s) = raw {
151 return serde_json::from_str::<Value>(s).unwrap_or_else(|_| Value::String(s.clone()));
152 }
153 return raw.clone();
154 }
155 if let Some(payload) = fr.response.get("payload") {
156 return payload.clone();
157 }
158 Value::Object(fr.response.clone())
159}