Skip to main content

gadk_engine/workflow/nodes/
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//! `AgentNode`: a graph node that runs an agent.
17
18use std::any::Any;
19use std::sync::Arc;
20
21use futures::StreamExt;
22use gadk_agent::{Agent, AgentError, Context, ContextDelta, EventStream, Mode};
23use gadk_genai::{Content, Schema};
24use gadk_session::{Event, EventActions, NodeInfo};
25use serde_json::{Map, Value, json};
26
27use crate::error::{WorkflowError, WorkflowErrorKind};
28use crate::llm::mode::{resolve_mode, with_bound_mode};
29use crate::llm::node_wrapper::run_llm_agent_as_node;
30use crate::llm::output_schema_binding::with_bound_output_schema;
31use crate::llm::processors::go_json_marshal;
32use crate::llm::state::reveal;
33use crate::workflow::base_node::compile_schema;
34use crate::workflow::model_output_schema::model_output_schema;
35use crate::workflow::route::go_quote;
36use crate::workflow::scheduler::message_text;
37use crate::workflow::{BaseNode, Node, NodeConfig};
38
39/// A graph node that runs an agent.
40pub struct AgentNode {
41    pub(crate) base: BaseNode,
42    pub(crate) agent: Arc<dyn Agent>,
43    /// The output schema in the form the model is asked to answer with, or `None`. `run` binds it
44    /// per invocation ([`crate::llm::output_schema_binding::with_bound_output_schema`]) rather than
45    /// setting it on the agent.
46    pub(crate) model_output_schema: Option<Schema>,
47}
48
49impl AgentNode {
50    /// A node running `agent` with no declared schemas: both are the empty schema `{}`.
51    pub fn new(agent: Arc<dyn Agent>, cfg: NodeConfig) -> Result<Arc<AgentNode>, WorkflowError> {
52        Self::with_schemas(agent, None, None, cfg)
53    }
54
55    /// A node running `agent` with the given input and output schemas. A missing schema is the
56    /// empty schema `{}`.
57    pub fn with_schemas(
58        agent: Arc<dyn Agent>,
59        input: Option<Value>,
60        output: Option<Value>,
61        mut cfg: NodeConfig,
62    ) -> Result<Arc<AgentNode>, WorkflowError> {
63        let input = compile_schema(Some(input.unwrap_or_else(|| json!({})))).map_err(|e| {
64            WorkflowError::new(
65                WorkflowErrorKind::Other,
66                format!(
67                    "resolving input schema for agent {}: {e}",
68                    go_quote(agent.name())
69                ),
70            )
71        })?;
72        let output = output.unwrap_or_else(|| json!({}));
73        let model_output_schema = model_output_schema(Some(&output));
74        let output = compile_schema(Some(output)).map_err(|e| {
75            WorkflowError::new(
76                WorkflowErrorKind::Other,
77                format!(
78                    "resolving output schema for agent {}: {e}",
79                    go_quote(agent.name())
80                ),
81            )
82        })?;
83        // The wrapped agent's run already emits an invoke_agent span.
84        cfg.emits_own_span = true;
85        let base = BaseNode::from_compiled(agent.name(), agent.description(), cfg, input, output);
86        Ok(Arc::new(AgentNode {
87            base,
88            agent,
89            model_output_schema,
90        }))
91    }
92
93    /// The wrapped agent.
94    pub fn agent(&self) -> &Arc<dyn Agent> {
95        &self.agent
96    }
97}
98
99impl Node for AgentNode {
100    fn name(&self) -> &str {
101        self.base.name()
102    }
103    fn description(&self) -> &str {
104        self.base.description()
105    }
106    fn config(&self) -> &NodeConfig {
107        self.base.config()
108    }
109    fn input_schema(&self) -> Option<&Value> {
110        self.base.input_schema()
111    }
112    fn output_schema(&self) -> Option<&Value> {
113        self.base.output_schema()
114    }
115    fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
116        self.base.validate_input(v)
117    }
118    fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
119        self.base.validate_output(v)
120    }
121    /// Runs the agent on a fresh invocation context over the node's
122    /// (input as user content, agent replaced, branch and isolation scope inherited); an
123    /// undeclared LlmAgent mode binds to single_turn. Own final model text becomes the output
124    /// (except for task-mode agents), and events are stamped with the ctx isolation scope.
125    fn run(&self, ctx: Context, input: Value) -> EventStream {
126        let agent = Arc::clone(self.agent());
127        let model_output_schema = self.model_output_schema.clone();
128        Box::pin(async_stream::stream! {
129            let user_content = match node_input_to_content(&input) {
130                Ok(c) => c,
131                Err(e) => {
132                    yield Err(e);
133                    return;
134                }
135            };
136            let declared_mode: Option<Mode> = reveal(agent.as_ref()).map(|s| s.cfg.mode);
137            // A fresh agent context over the node's invocation: the Context-level fields reset,
138            // agent and user content replaced, the end flag copied from the node's context.
139            let mut delta = ContextDelta {
140                agent: Some(Arc::clone(&agent)),
141                user_content: Some(user_content),
142                path: Some(String::new()),
143                run_id: Some(String::new()),
144                sub_scheduler: Some(None),
145                output_for_ancestors: Some(Vec::new()),
146                resumed_inputs: Some(Arc::new(Map::new())),
147                // function_call_id is cleared by fresh_end_flag; Some("") would mint a UUID.
148                tool_confirmation: Some(None),
149                actions: Some(Arc::new(parking_lot::Mutex::new(EventActions::default()))),
150                fresh_end_flag: true,
151                ..ContextDelta::default()
152            };
153            if let Some(declared) = declared_mode {
154                // A graph node is a one-shot placement: an undeclared mode runs single_turn,
155                // bound under this agent's own key.
156                let mode = resolve_mode(declared, Mode::SingleTurn);
157                let bound = with_bound_mode(ctx.as_invocation(), agent.name(), agent.agent_state(), mode);
158                // Offer the node's output shape to the model. Each request decides whether to
159                // use it, against the mode bound for it and the agent's own setup. A `None`
160                // schema is still bound, so this placement clears one an outer placement bound.
161                let bound = with_bound_output_schema(
162                    &bound,
163                    agent.name(),
164                    agent.agent_state(),
165                    model_output_schema.clone(),
166                );
167                delta.bound_modes = Some(bound.bound_modes().clone());
168            }
169            let ex_ctx = ctx.with_delta(delta);
170            // An LLM agent runs through its node entry point.
171            let mut events = if declared_mode.is_some() {
172                run_llm_agent_as_node(ex_ctx, Arc::clone(&agent), input)
173            } else {
174                agent.run(ex_ctx.as_invocation().clone())
175            };
176            // Task-mode LlmAgents set their output through the task run, not model text.
177            let synthesize = declared_mode != Some(Mode::Task);
178            let scope = ctx.isolation_scope();
179            while let Some(item) = events.next().await {
180                let mut ev = match item {
181                    Ok(ev) => ev,
182                    Err(e) => {
183                        yield Err(e);
184                        return;
185                    }
186                };
187                // A composite agent yields one final response per sub-agent (each a distinct
188                // author); synthesizing all of them would trip the one-output-per-node rule.
189                if synthesize && is_own_agent_event(&ev, agent.name()) {
190                    synthesize_agent_output(&mut ev);
191                }
192                // Tag the event for scope filtering (the direct agent-wrapper path).
193                if !scope.is_empty() && ev.isolation_scope.is_empty() {
194                    ev.isolation_scope = scope.clone();
195                }
196                yield Ok(ev);
197            }
198        })
199    }
200    fn as_any(&self) -> &dyn Any {
201        self
202    }
203}
204
205/// A final model response without output gets the concatenated
206/// model text as output (empty text is an empty `""` output) and `node_info.message_as_output`.
207/// Long-running-tool events are a pause, not a completion, and are left untouched.
208pub(crate) fn synthesize_agent_output(ev: &mut Event) {
209    if ev.output.is_some() || !ev.is_final_response() || !ev.long_running_tool_ids.is_empty() {
210        return;
211    }
212    if let Some(text) = message_text(ev) {
213        ev.output = Some(Value::String(text));
214        ev.node_info
215            .get_or_insert_with(NodeInfo::default)
216            .message_as_output = true;
217    }
218}
219
220/// Whether the event is the node agent's own: un-authored events count as its own.
221pub(crate) fn is_own_agent_event(ev: &Event, node_agent_name: &str) -> bool {
222    ev.author.is_empty() || ev.author == node_agent_name
223}
224
225/// The user content for a node's input: null → none; a string → user text; anything else → its
226/// compact JSON text (keys sorted, `<`, `>` and `&` written as Unicode escapes, as
227/// `go_json_marshal` writes it) as user text. Marshaling a `Value` cannot fail, so
228/// the error branch is unreachable; the `Result` is kept for the signature.
229pub(crate) fn node_input_to_content(input: &Value) -> Result<Option<Content>, AgentError> {
230    match input {
231        Value::Null => Ok(None),
232        Value::String(s) => Ok(Some(Content::from_text(s.clone(), "user"))),
233        other => Ok(Some(Content::from_text(go_json_marshal(other), "user"))),
234    }
235}