1use std::any::Any;
19use std::future::Future;
20use std::sync::Arc;
21
22use futures::future::BoxFuture;
23use gadk_agent::{AgentError, Context, EventStream, InvocationContext};
24use gadk_genai::{Content, Part};
25use gadk_session::Event;
26use schemars::JsonSchema;
27use serde::Serialize;
28use serde::de::DeserializeOwned;
29use serde_json::{Map, Value, json};
30
31use crate::error::{WorkflowError, WorkflowErrorKind};
32use crate::tool::utils::{CompiledSchema, convert_with_schema, infer_schema};
33use crate::workflow::nodes::dynamic::{EmitMsg, make_emit};
34use crate::workflow::route::go_quote;
35use crate::workflow::scheduler::is_kind;
36use crate::workflow::{BaseNode, Node, NodeConfig};
37
38pub type Emit = Arc<dyn Fn(Event) -> BoxFuture<'static, Result<(), AgentError>> + Send + Sync>;
41
42pub(crate) enum FnOutput {
44 Event(Box<Event>),
45 Content(Content),
46 Value(Option<Value>),
47}
48
49type PlainFn =
50 Arc<dyn Fn(Context, Value) -> BoxFuture<'static, Result<FnOutput, AgentError>> + Send + Sync>;
51type EmittingFn = Arc<
52 dyn Fn(Context, Value, Emit) -> BoxFuture<'static, Result<Option<Value>, AgentError>>
53 + Send
54 + Sync,
55>;
56
57enum Body {
58 Plain(PlainFn),
59 Emitting(EmittingFn),
60}
61
62pub struct FunctionNode {
64 base: BaseNode,
65 body: Body,
66 state_field_names: Option<Vec<String>>,
67}
68
69pub(crate) enum Step<T> {
71 Emit(EmitMsg),
72 Done(T),
73}
74
75pub(crate) enum CoerceError {
77 Validation(String),
78 Conversion(String),
79}
80
81pub(crate) fn short_type_name<T>() -> &'static str {
83 let full = std::any::type_name::<T>();
84 full.rsplit("::").next().unwrap_or(full)
85}
86
87pub(crate) fn zero_input<In: DeserializeOwned + JsonSchema>() -> Result<In, String> {
90 if let Ok(v) = serde_json::from_value::<In>(Value::Null) {
91 return Ok(v);
92 }
93 serde_json::from_value::<In>(zero_from_schema(&infer_schema::<In>())).map_err(|e| e.to_string())
94}
95
96fn zero_from_schema(schema: &Value) -> Value {
97 let types: Vec<&str> = match schema.get("type") {
98 Some(Value::String(t)) => vec![t.as_str()],
99 Some(Value::Array(ts)) => ts.iter().filter_map(Value::as_str).collect(),
100 _ => Vec::new(),
101 };
102 if types.contains(&"null") {
103 return Value::Null;
104 }
105 match types.first().copied() {
106 Some("string") => json!(""),
107 Some("integer") | Some("number") => json!(0),
108 Some("boolean") => json!(false),
109 Some("array") => json!([]),
110 Some("object") => Value::Object(
111 schema
112 .get("properties")
113 .and_then(Value::as_object)
114 .map(|p| {
115 p.iter()
116 .map(|(k, s)| (k.clone(), zero_from_schema(s)))
117 .collect()
118 })
119 .unwrap_or_default(),
120 ),
121 _ => Value::Null,
122 }
123}
124
125pub(crate) fn coerce_input<In: DeserializeOwned + JsonSchema>(
128 input: Value,
129 schema: Option<&CompiledSchema>,
130) -> Result<In, CoerceError> {
131 if input.is_null() {
132 return zero_input::<In>().map_err(CoerceError::Conversion);
133 }
134 if let Some(s) = schema {
135 s.validate(&input).map_err(CoerceError::Validation)?;
136 }
137 convert_with_schema::<Value, In>(&input, None).map_err(CoerceError::Conversion)
138}
139
140fn function_input_error<In>(name: &str, e: CoerceError) -> AgentError {
141 match e {
142 CoerceError::Validation(e) => AgentError::other(format!(
143 "function node {name}: validation failed for input *{}: {e}",
144 short_type_name::<In>()
145 )),
146 CoerceError::Conversion(e) => AgentError::other(format!(
147 "new function node: invalid input type, expected *{}: {e}",
148 short_type_name::<In>()
149 )),
150 }
151}
152
153pub(crate) fn to_fn_output<Out: Serialize + 'static>(out: Out) -> Result<FnOutput, AgentError> {
156 let any: Box<dyn Any> = Box::new(out);
157 let any = match any.downcast::<Event>() {
158 Ok(ev) => return Ok(FnOutput::Event(ev)),
159 Err(a) => a,
160 };
161 let any = match any.downcast::<Content>() {
162 Ok(c) => return Ok(FnOutput::Content(*c)),
163 Err(a) => a,
164 };
165 let Ok(out) = any.downcast::<Out>() else {
166 return Err(AgentError::other("function node: output type mismatch"));
167 };
168 let v = serde_json::to_value(*out)
169 .map_err(|e| AgentError::other(format!("function node: marshal output: {e}")))?;
170 Ok(FnOutput::Value((!v.is_null()).then_some(v)))
171}
172
173fn compile(
175 schema: Option<Value>,
176 what: &str,
177) -> Result<Option<Arc<CompiledSchema>>, WorkflowError> {
178 schema
179 .map(|s| {
180 CompiledSchema::new(s).map(Arc::new).map_err(|e| {
181 WorkflowError::new(
182 WorkflowErrorKind::Other,
183 format!("resolving {what} schema: {e}"),
184 )
185 })
186 })
187 .transpose()
188}
189
190fn new_plain<In, Out, F, Fut>(
192 name: &str,
193 f: F,
194 in_schema: Option<Arc<CompiledSchema>>,
195 out_schema: Option<Arc<CompiledSchema>>,
196 cfg: NodeConfig,
197) -> Arc<dyn Node>
198where
199 In: DeserializeOwned + JsonSchema + Send + 'static,
200 Out: Serialize + Send + 'static,
201 F: Fn(Context, In) -> Fut + Send + Sync + 'static,
202 Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
203{
204 let base = BaseNode::from_compiled(name, "", cfg, in_schema.clone(), out_schema);
205 let f = Arc::new(f);
206 let node_name = name.to_string();
207 let body: PlainFn = Arc::new(move |ctx, input| {
208 let (f, schema, name) = (Arc::clone(&f), in_schema.clone(), node_name.clone());
209 Box::pin(async move {
210 let typed: In = coerce_input(input, schema.as_deref())
211 .map_err(|e| function_input_error::<In>(&name, e))?;
212 to_fn_output(f(ctx, typed).await?)
213 })
214 });
215 Arc::new(FunctionNode {
216 base,
217 body: Body::Plain(body),
218 state_field_names: None,
219 })
220}
221
222fn new_emitting<In, Out, F, Fut>(
224 name: &str,
225 f: F,
226 in_schema: Option<Arc<CompiledSchema>>,
227 out_schema: Option<Arc<CompiledSchema>>,
228 cfg: NodeConfig,
229) -> Arc<dyn Node>
230where
231 In: DeserializeOwned + JsonSchema + Send + 'static,
232 Out: Serialize + Send + 'static,
233 F: Fn(Context, In, Emit) -> Fut + Send + Sync + 'static,
234 Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
235{
236 let base = BaseNode::from_compiled(name, "", cfg, in_schema.clone(), out_schema);
237 let f = Arc::new(f);
238 let node_name = name.to_string();
239 let body: EmittingFn = Arc::new(move |ctx, input, emit| {
240 let (f, schema, name) = (Arc::clone(&f), in_schema.clone(), node_name.clone());
241 Box::pin(async move {
242 let typed: In = coerce_input(input, schema.as_deref())
243 .map_err(|e| function_input_error::<In>(&name, e))?;
244 let out = f(ctx, typed, emit).await?;
245 let v = serde_json::to_value(out)
246 .map_err(|e| AgentError::other(format!("function node: marshal output: {e}")))?;
247 Ok((!v.is_null()).then_some(v))
248 })
249 });
250 Arc::new(FunctionNode {
251 base,
252 body: Body::Emitting(body),
253 state_field_names: None,
254 })
255}
256
257pub fn function_node<In, Out, F, Fut>(name: &str, f: F, cfg: NodeConfig) -> Arc<dyn Node>
259where
260 In: DeserializeOwned + JsonSchema + Send + 'static,
261 Out: Serialize + Send + 'static,
262 F: Fn(Context, In) -> Fut + Send + Sync + 'static,
263 Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
264{
265 new_plain::<In, Out, F, Fut>(name, f, None, None, cfg)
266}
267
268pub fn function_node_with_schema<In, Out, F, Fut>(
270 name: &str,
271 f: F,
272 input: Option<Value>,
273 output: Option<Value>,
274 cfg: NodeConfig,
275) -> Result<Arc<dyn Node>, WorkflowError>
276where
277 In: DeserializeOwned + JsonSchema + Send + 'static,
278 Out: Serialize + Send + 'static,
279 F: Fn(Context, In) -> Fut + Send + Sync + 'static,
280 Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
281{
282 let in_schema = compile(input, "input")?;
283 let out_schema = compile(output, "output")?;
284 Ok(new_plain::<In, Out, F, Fut>(
285 name, f, in_schema, out_schema, cfg,
286 ))
287}
288
289pub fn emitting_function_node<In, Out, F, Fut>(name: &str, f: F, cfg: NodeConfig) -> Arc<dyn Node>
292where
293 In: DeserializeOwned + JsonSchema + Send + 'static,
294 Out: Serialize + Send + 'static,
295 F: Fn(Context, In, Emit) -> Fut + Send + Sync + 'static,
296 Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
297{
298 new_emitting::<In, Out, F, Fut>(name, f, None, None, cfg)
299}
300
301pub fn emitting_function_node_with_schema<In, Out, F, Fut>(
303 name: &str,
304 f: F,
305 input: Option<Value>,
306 output: Option<Value>,
307 cfg: NodeConfig,
308) -> Result<Arc<dyn Node>, WorkflowError>
309where
310 In: DeserializeOwned + JsonSchema + Send + 'static,
311 Out: Serialize + Send + 'static,
312 F: Fn(Context, In, Emit) -> Fut + Send + Sync + 'static,
313 Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
314{
315 let in_schema = compile(input, "input")?;
316 let out_schema = compile(output, "output")?;
317 Ok(new_emitting::<In, Out, F, Fut>(
318 name, f, in_schema, out_schema, cfg,
319 ))
320}
321
322fn struct_field_names<T: DeserializeOwned>() -> Option<&'static [&'static str]> {
326 struct Probe(Option<&'static [&'static str]>);
327
328 #[derive(Debug)]
329 struct Stop;
330 impl std::fmt::Display for Stop {
331 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332 f.write_str("probe")
333 }
334 }
335 impl std::error::Error for Stop {}
336 impl serde::de::Error for Stop {
337 fn custom<M: std::fmt::Display>(_: M) -> Self {
338 Stop
339 }
340 }
341
342 impl<'de> serde::Deserializer<'de> for &mut Probe {
343 type Error = Stop;
344 fn deserialize_any<V: serde::de::Visitor<'de>>(self, _: V) -> Result<V::Value, Stop> {
345 Err(Stop)
346 }
347 fn deserialize_struct<V: serde::de::Visitor<'de>>(
348 self,
349 _name: &'static str,
350 fields: &'static [&'static str],
351 _: V,
352 ) -> Result<V::Value, Stop> {
353 self.0 = Some(fields);
354 Err(Stop)
355 }
356 serde::forward_to_deserialize_any! {
357 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
358 option unit unit_struct newtype_struct seq tuple tuple_struct map enum identifier
359 ignored_any
360 }
361 }
362
363 let mut probe = Probe(None);
364 let _ = T::deserialize(&mut probe);
365 probe.0
366}
367
368const NODE_INPUT_FIELD: &str = "node_input";
370
371pub fn function_node_from_state<Params, Out, F, Fut>(
376 name: &str,
377 f: F,
378 cfg: NodeConfig,
379) -> Result<Arc<dyn Node>, WorkflowError>
380where
381 Params: DeserializeOwned + JsonSchema + Send + 'static,
382 Out: Serialize + JsonSchema + Send + 'static,
383 F: Fn(InvocationContext, Params) -> Fut + Send + Sync + 'static,
384 Fut: Future<Output = Result<Out, AgentError>> + Send + 'static,
385{
386 let other = |m: String| WorkflowError::new(WorkflowErrorKind::Other, m);
387 let schema = infer_schema::<Params>();
388 let fields = match struct_field_names::<Params>() {
389 Some(f) if schema.get("type") == Some(&json!("object")) => f,
390 _ => return Err(other("params must be a struct type".into())),
391 };
392 let properties = schema
393 .get("properties")
394 .and_then(Value::as_object)
395 .cloned()
396 .unwrap_or_default();
397 let mut field_schemas: Vec<(String, Option<Arc<CompiledSchema>>)> = Vec::new();
399 for field in fields {
400 let compiled = compile(properties.get(*field).cloned(), "input")?;
401 field_schemas.push(((*field).to_string(), compiled));
402 }
403 let has_node_input = fields.contains(&NODE_INPUT_FIELD);
404 let state_field_names: Vec<String> = fields
405 .iter()
406 .filter(|f| **f != NODE_INPUT_FIELD)
407 .map(|f| (*f).to_string())
408 .collect();
409 let in_schema = if has_node_input {
410 compile(properties.get(NODE_INPUT_FIELD).cloned(), "input")?
411 } else {
412 None
413 };
414 let out_schema = compile(Some(infer_schema::<Out>()), "output")?;
415 let f = Arc::new(f);
416 let field_schemas = Arc::new(field_schemas);
417 let body: PlainFn = Arc::new(move |ctx: Context, input: Value| {
418 let (f, field_schemas) = (Arc::clone(&f), Arc::clone(&field_schemas));
419 Box::pin(async move {
420 let session = ctx.session();
421 let mut state_map = Map::new();
422 for (key, schema) in field_schemas.iter() {
423 let val = if key == NODE_INPUT_FIELD {
424 input.clone()
425 } else {
426 session.state().get(key).map_err(|e| {
427 AgentError::other(format!(
428 "missing state value for required field {} (state key {}): {e}",
429 go_quote(key),
430 go_quote(key)
431 ))
432 })?
433 };
434 if let Some(s) = schema
435 && let Err(e) = s.validate(&val)
436 {
437 return Err(AgentError::other(if key == NODE_INPUT_FIELD {
438 format!(
439 "new function node from state: invalid input type for node_input: {e}"
440 )
441 } else {
442 format!(
443 "failed to convert state value to field {}: {e}",
444 go_quote(key)
445 )
446 }));
447 }
448 state_map.insert(key.clone(), val);
449 }
450 let params: Params = serde_json::from_value(Value::Object(state_map)).map_err(|e| {
451 AgentError::other(format!("failed to convert state to Params: {e}"))
452 })?;
453 to_fn_output(f(ctx.as_invocation().clone(), params).await?)
454 })
455 });
456 Ok(Arc::new(FunctionNode {
457 base: BaseNode::from_compiled(name, "", cfg, in_schema, out_schema),
458 body: Body::Plain(body),
459 state_field_names: Some(state_field_names),
460 }))
461}
462
463impl Node for FunctionNode {
464 fn name(&self) -> &str {
465 self.base.name()
466 }
467 fn description(&self) -> &str {
468 self.base.description()
469 }
470 fn config(&self) -> &NodeConfig {
471 self.base.config()
472 }
473 fn input_schema(&self) -> Option<&Value> {
474 self.base.input_schema()
475 }
476 fn output_schema(&self) -> Option<&Value> {
477 self.base.output_schema()
478 }
479 fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
480 self.base.validate_input(v)
481 }
482 fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
483 self.base.validate_output(v)
484 }
485 fn state_field_names(&self) -> Option<&[String]> {
486 self.state_field_names.as_deref()
487 }
488 fn run(&self, ctx: Context, input: Value) -> EventStream {
491 match &self.body {
492 Body::Plain(f) => {
493 let f = Arc::clone(f);
494 Box::pin(async_stream::stream! {
495 match f(ctx.clone(), input).await {
496 Err(e) => yield Err(e),
497 Ok(FnOutput::Event(mut ev)) => {
498 if ev.invocation_id.is_empty() {
499 ev.invocation_id = ctx.invocation_id().to_string();
500 }
501 yield Ok(*ev);
502 }
503 Ok(FnOutput::Content(c)) => {
504 let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
505 ev.response.content = Some(c);
506 yield Ok(ev);
507 }
508 Ok(FnOutput::Value(v)) => {
509 let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
510 ev.output = v;
511 yield Ok(ev);
512 }
513 }
514 })
515 }
516 Body::Emitting(f) => {
517 let f = Arc::clone(f);
518 Box::pin(async_stream::stream! {
519 let (emit, mut rx) = make_emit(&ctx);
522 let mut body = Box::pin(f(ctx.clone(), input, emit));
523 let result = loop {
524 let step = tokio::select! {
525 biased;
526 Some(msg) = rx.recv() => Step::Emit(msg),
527 r = &mut body => Step::Done(r),
528 };
529 match step {
530 Step::Emit(msg) => {
531 let (ev, ack) = msg.into_parts();
532 yield Ok(ev);
533 let _ = ack.send(());
534 }
535 Step::Done(r) => break r,
536 }
537 };
538 match result {
539 Err(e) if is_kind(&e, WorkflowErrorKind::NodeInterrupted) => {}
540 Err(e) => yield Err(e),
541 Ok(None) => {}
542 Ok(Some(out)) => {
543 let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
544 if let Value::String(s) = &out {
545 ev.response.content = Some(Content {
546 parts: vec![Part::from_text(s.clone())],
547 ..Content::default()
548 });
549 }
550 ev.output = Some(out);
551 yield Ok(ev);
552 }
553 }
554 })
555 }
556 }
557 }
558 fn as_any(&self) -> &dyn Any {
559 self
560 }
561}