Skip to main content

gadk_engine/workflow/
base_node.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//! `BaseNode`: the identity, configuration and schemas shared by every node kind.
17
18use std::sync::Arc;
19
20use gadk_agent::AgentError;
21use gadk_session::Event;
22use serde_json::Value;
23
24use crate::error::{WorkflowError, WorkflowErrorKind};
25use crate::tool::utils::CompiledSchema;
26use crate::workflow::route::go_quote;
27use crate::workflow::validation::default_validate_input;
28use crate::workflow::{Node, NodeConfig};
29
30/// The identity, configuration and schemas shared by every node kind. Custom node types hold a
31/// `BaseNode` and delegate the [`Node`] metadata methods to it.
32#[derive(Clone)]
33pub struct BaseNode {
34    name: String,
35    description: String,
36    config: NodeConfig,
37    input: Option<Arc<CompiledSchema>>,
38    output: Option<Arc<CompiledSchema>>,
39}
40
41/// Compiles an optional JSON schema.
42pub(crate) fn compile_schema(schema: Option<Value>) -> Result<Option<Arc<CompiledSchema>>, String> {
43    match schema {
44        None => Ok(None),
45        Some(v) => CompiledSchema::new(v).map(|c| Some(Arc::new(c))),
46    }
47}
48
49impl BaseNode {
50    /// Builds a `BaseNode` from already-compiled schemas.
51    pub(crate) fn from_compiled(
52        name: &str,
53        description: &str,
54        cfg: NodeConfig,
55        input: Option<Arc<CompiledSchema>>,
56        output: Option<Arc<CompiledSchema>>,
57    ) -> Self {
58        Self {
59            name: name.to_owned(),
60            description: description.to_owned(),
61            config: cfg,
62            input,
63            output,
64        }
65    }
66
67    /// A `BaseNode` with the given identity, configuration, and JSON schemas. Fails when a schema
68    /// does not compile.
69    pub fn with_schemas(
70        name: &str,
71        description: &str,
72        input: Option<Value>,
73        output: Option<Value>,
74        cfg: NodeConfig,
75    ) -> Result<Self, WorkflowError> {
76        let input = compile_schema(input).map_err(|e| {
77            WorkflowError::new(
78                WorkflowErrorKind::Other,
79                format!("resolving input schema for node {}: {e}", go_quote(name)),
80            )
81        })?;
82        let output = compile_schema(output).map_err(|e| {
83            WorkflowError::new(
84                WorkflowErrorKind::Other,
85                format!("resolving output schema for node {}: {e}", go_quote(name)),
86            )
87        })?;
88        Ok(Self::from_compiled(name, description, cfg, input, output))
89    }
90
91    /// A `BaseNode` with no schemas.
92    pub fn new(name: &str, description: &str, cfg: NodeConfig) -> Self {
93        Self::from_compiled(name, description, cfg, None, None)
94    }
95
96    /// The node's name.
97    pub fn name(&self) -> &str {
98        &self.name
99    }
100
101    /// The node's human-readable description.
102    pub fn description(&self) -> &str {
103        &self.description
104    }
105
106    /// The node's configuration.
107    pub fn config(&self) -> &NodeConfig {
108        &self.config
109    }
110
111    /// The node's input validation schema.
112    pub fn input_schema(&self) -> Option<&Value> {
113        self.input.as_deref().map(CompiledSchema::schema)
114    }
115
116    /// The node's output validation schema.
117    pub fn output_schema(&self) -> Option<&Value> {
118        self.output.as_deref().map(CompiledSchema::schema)
119    }
120
121    /// The compiled input schema.
122    pub(crate) fn input_compiled(&self) -> Option<&CompiledSchema> {
123        self.input.as_deref()
124    }
125
126    /// The compiled output schema.
127    pub(crate) fn output_compiled(&self) -> Option<&CompiledSchema> {
128        self.output.as_deref()
129    }
130
131    /// Validates and coerces the input using the node's input schema. The error message is the
132    /// raw validator text.
133    pub fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
134        default_validate_input(v, self.input_compiled())
135            .map_err(|m| WorkflowError::new(WorkflowErrorKind::InputValidation, m))
136    }
137
138    /// Validates the output against the node's output schema. The error message is the raw
139    /// validator text.
140    pub fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
141        default_validate_output(v, self.output_compiled())
142            .map_err(|m| WorkflowError::new(WorkflowErrorKind::OutputValidation, m))
143    }
144}
145
146/// The default output validation: a missing schema or a null output passes. When direct
147/// validation fails on model text (a string), `project_text_onto_schema` retries via the schema;
148/// on total failure the original error wins.
149pub(crate) fn default_validate_output(
150    out: Value,
151    schema: Option<&CompiledSchema>,
152) -> Result<Value, String> {
153    let Some(schema) = schema else { return Ok(out) };
154    if out.is_null() {
155        return Ok(out);
156    }
157    let err = match schema.validate(&out) {
158        Ok(()) => return Ok(out),
159        Err(e) => e,
160    };
161    if let Value::String(text) = &out
162        && let Some(v) = project_text_onto_schema(text, schema)
163    {
164        return Ok(v);
165    }
166    Err(err)
167}
168
169/// Output validation for a `Content` output: validates the content's JSON form, then falls back
170/// to projecting the concatenated non-thought text parts onto the schema. Test-only: node outputs
171/// are `Value`s (synthesized agent output is a string), so no production path carries a
172/// `Content` output.
173#[cfg(test)]
174pub(crate) fn default_validate_content_output(
175    content: &gadk_genai::Content,
176    schema: Option<&CompiledSchema>,
177) -> Result<Value, String> {
178    let v = serde_json::to_value(content).map_err(|e| e.to_string())?;
179    let Some(schema) = schema else { return Ok(v) };
180    let err = match schema.validate(&v) {
181        Ok(()) => return Ok(v),
182        Err(e) => e,
183    };
184    let text: String = content
185        .parts
186        .iter()
187        .filter(|p| !p.text.is_empty() && !p.thought)
188        .map(|p| p.text.as_str())
189        .collect();
190    project_text_onto_schema(&text, schema).ok_or(err)
191}
192
193/// Returns the text directly for a string schema (after re-validating so per-string constraints
194/// still apply), otherwise JSON-parses and re-validates. `None` when no valid value can be
195/// produced.
196fn project_text_onto_schema(s: &str, schema: &CompiledSchema) -> Option<Value> {
197    if root_schema_is_string(schema) {
198        let v = Value::String(s.to_owned());
199        return schema.validate(&v).ok().map(|()| v);
200    }
201    if s.trim().is_empty() {
202        return None;
203    }
204    let parsed: Value = serde_json::from_str(s).ok()?;
205    schema.validate(&parsed).ok().map(|()| parsed)
206}
207
208/// Whether the root permits the "string" type, via a single `"type"` or a `"type"` array.
209fn root_schema_is_string(schema: &CompiledSchema) -> bool {
210    match schema.schema().get("type") {
211        Some(Value::String(t)) => t == "string",
212        Some(Value::Array(ts)) => ts.iter().any(|t| t == "string"),
213        _ => false,
214    }
215}
216
217/// Runs `n.validate_output` on `out` and, on success, stamps the validated value back onto
218/// `ev.output` when it rode there. The error matches both the `NodeFailed` and the
219/// `OutputValidation` kinds.
220pub(crate) fn validate_and_stamp_output(
221    n: &dyn Node,
222    out: Value,
223    ev: &mut Event,
224) -> Result<Value, AgentError> {
225    let validated = n.validate_output(out).map_err(|e| {
226        let msg = format!(
227            "{}: output validation failed for node {}: {}",
228            WorkflowError::sentinel_text(WorkflowErrorKind::NodeFailed),
229            go_quote(n.name()),
230            e
231        );
232        AgentError::from(
233            WorkflowError::new(WorkflowErrorKind::OutputValidation, msg).with_source(e.into()),
234        )
235    })?;
236    if ev.output.is_some() {
237        ev.output = Some(validated.clone());
238    }
239    Ok(validated)
240}