1mod build;
42mod location;
43mod types;
44
45use std::path::Path;
46use std::sync::Arc;
47
48pub use build::{FunctionNodeFn, ModelResolver, WorkflowRegistry};
49pub use location::SourceLocation;
50pub use types::{
51 ChannelDefinition, CheckpointDefinition, CheckpointStore, Condition, ConditionOp,
52 EdgeDefinition, EdgeSpec, InterruptDefinition, LlmDefinition, NodeDefinition, ReducerKind,
53 RouteDefinition, Targets, WORKFLOW_FORMAT_VERSION, WorkflowDefinition,
54};
55
56use location::LocationIndex;
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct WorkflowIssue {
62 pub path: String,
64 pub location: Option<SourceLocation>,
66 pub message: String,
68}
69
70impl WorkflowIssue {
71 pub fn new(
86 path: impl Into<String>,
87 location: Option<SourceLocation>,
88 message: impl Into<String>,
89 ) -> Self {
90 Self { path: path.into(), location, message: message.into() }
91 }
92}
93
94impl std::fmt::Display for WorkflowIssue {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 if let Some(location) = self.location {
97 write!(f, "{location}: ")?;
98 }
99 if !self.path.is_empty() {
100 write!(f, "{}: ", self.path)?;
101 }
102 f.write_str(&self.message)
103 }
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
121#[error("{}", self.render())]
122#[non_exhaustive]
123pub struct WorkflowError {
124 pub source_name: Option<String>,
126 pub issues: Vec<WorkflowIssue>,
128}
129
130impl WorkflowError {
131 fn render(&self) -> String {
132 let prefix = self.source_name.as_deref().map(|name| format!("{name}:")).unwrap_or_default();
133 let lines: Vec<String> = self
134 .issues
135 .iter()
136 .map(|issue| match (&prefix, issue.location) {
137 (prefix, Some(_)) if !prefix.is_empty() => format!("{prefix}{issue}"),
138 (prefix, _) if !prefix.is_empty() => format!("{prefix} {issue}"),
139 _ => issue.to_string(),
140 })
141 .collect();
142 lines.join("\n")
143 }
144}
145
146impl From<WorkflowError> for crate::GraphError {
147 fn from(error: WorkflowError) -> Self {
148 crate::GraphError::InvalidGraph(error.to_string())
149 }
150}
151
152impl From<WorkflowError> for adk_core::AdkError {
153 fn from(error: WorkflowError) -> Self {
154 crate::GraphError::from(error).into()
155 }
156}
157
158#[derive(Debug, Clone, Default)]
160pub(crate) struct SourceInfo {
161 pub(crate) name: Option<String>,
162 pub(crate) index: Option<Arc<LocationIndex>>,
163 #[cfg_attr(
164 not(feature = "sqlite"),
165 expect(dead_code, reason = "only the sqlite store resolves a path against the file")
166 )]
167 pub(crate) base_dir: Option<std::path::PathBuf>,
168}
169
170impl PartialEq for SourceInfo {
173 fn eq(&self, _: &Self) -> bool {
174 true
175 }
176}
177
178impl SourceInfo {
179 pub(crate) fn error(&self, issues: Vec<(String, String)>) -> WorkflowError {
180 let mut issues: Vec<WorkflowIssue> = issues
181 .into_iter()
182 .map(|(path, message)| WorkflowIssue {
183 location: self.index.as_ref().and_then(|index| index.locate(&path)),
184 path,
185 message,
186 })
187 .collect();
188 issues.sort_by_key(|issue| issue.location.map(|l| (l.line, l.column)));
189 WorkflowError { source_name: self.name.clone(), issues }
190 }
191}
192
193impl WorkflowDefinition {
194 pub fn from_yaml_str(yaml: &str) -> Result<Self, WorkflowError> {
201 Self::parse_yaml(yaml, SourceInfo::default())
202 }
203
204 pub fn from_json_str(json: &str) -> Result<Self, WorkflowError> {
211 Self::parse_json(json, SourceInfo::default())
212 }
213
214 pub fn from_file(path: impl AsRef<Path>) -> Result<Self, WorkflowError> {
222 let path = path.as_ref();
223 let source = SourceInfo {
224 name: Some(path.display().to_string()),
225 index: None,
226 base_dir: path.parent().map(Path::to_path_buf),
227 };
228 let text = std::fs::read_to_string(path).map_err(|error| {
229 source.error(vec![(String::new(), format!("cannot read the workflow file: {error}"))])
230 })?;
231 if path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("json")) {
232 Self::parse_json(&text, source)
233 } else {
234 Self::parse_yaml(&text, source)
235 }
236 }
237
238 pub fn to_yaml_string(&self) -> Result<String, WorkflowError> {
244 serde_saphyr::to_string(self).map_err(|error| {
245 self.source.error(vec![(String::new(), format!("cannot write YAML: {error}"))])
246 })
247 }
248
249 pub fn validate(&self) -> Result<(), WorkflowError> {
257 let issues = validate::issues(self);
258 if issues.is_empty() { Ok(()) } else { Err(self.source.error(issues)) }
259 }
260
261 fn parse_yaml(yaml: &str, mut source: SourceInfo) -> Result<Self, WorkflowError> {
262 let index = Arc::new(LocationIndex::of_yaml(yaml));
263 source.index = Some(index);
264 let mut definition: Self = serde_saphyr::from_str(yaml).map_err(|error| {
265 let location = error
266 .location()
267 .filter(|location| location.line() > 0)
268 .map(|l| SourceLocation { line: l.line() as u32, column: l.column() as u32 });
269 WorkflowError {
270 source_name: source.name.clone(),
271 issues: vec![WorkflowIssue {
272 path: String::new(),
273 location,
274 message: first_line(&error.to_string()),
275 }],
276 }
277 })?;
278 definition.source = source;
279 definition.validate()?;
280 Ok(definition)
281 }
282
283 fn parse_json(json: &str, source: SourceInfo) -> Result<Self, WorkflowError> {
284 let mut definition: Self = serde_json::from_str(json).map_err(|error| WorkflowError {
285 source_name: source.name.clone(),
286 issues: vec![WorkflowIssue {
287 path: String::new(),
288 location: (error.line() > 0).then(|| SourceLocation {
289 line: error.line() as u32,
290 column: error.column() as u32,
291 }),
292 message: error.to_string(),
293 }],
294 })?;
295 definition.source = source;
296 definition.validate()?;
297 Ok(definition)
298 }
299}
300
301fn first_line(message: &str) -> String {
303 message.lines().next().unwrap_or(message).trim().to_string()
304}
305
306pub fn workflow_json_schema() -> serde_json::Value {
318 serde_json::to_value(schemars::schema_for!(WorkflowDefinition)).unwrap_or_default()
319}
320
321mod validate {
322 use std::collections::{BTreeSet, HashSet, VecDeque};
325
326 use super::types::{
327 CheckpointStore, Condition, ConditionOp, EdgeDefinition, EdgeSpec, NodeDefinition,
328 WORKFLOW_FORMAT_VERSION, WorkflowDefinition,
329 };
330
331 pub(super) const START_ID: &str = "START";
332 pub(super) const END_ID: &str = "END";
333
334 type Issues = Vec<(String, String)>;
335
336 pub(super) fn issues(workflow: &WorkflowDefinition) -> Issues {
337 let mut issues = Issues::new();
338 if workflow.version != WORKFLOW_FORMAT_VERSION {
339 issues.push((
340 "version".into(),
341 format!(
342 "version {} is not supported; this release reads version {WORKFLOW_FORMAT_VERSION}",
343 workflow.version
344 ),
345 ));
346 }
347 if workflow.name.trim().is_empty() {
348 issues.push(("name".into(), "the workflow needs a name".into()));
349 }
350 if workflow.nodes.is_empty() {
351 issues.push(("nodes".into(), "the workflow declares no nodes".into()));
352 }
353 for (name, reference) in &workflow.models {
354 if reference.trim().is_empty() {
355 issues.push((format!("models.{name}"), "the model reference is empty".into()));
356 }
357 }
358 for (id, node) in &workflow.nodes {
359 check_node(id, node, &mut issues);
360 }
361
362 let declared: BTreeSet<&str> = workflow.nodes.keys().map(String::as_str).collect();
363 let mut successors: Vec<(&str, &str)> = Vec::new();
364 for (index, edge) in workflow.edges.iter().enumerate() {
365 let path = format!("edges[{index}]");
366 match edge {
367 EdgeDefinition::Chain(ids) => {
368 if ids.len() < 2 {
369 issues.push((path.clone(), "a chain needs at least two node ids".into()));
370 }
371 for (position, id) in ids.iter().enumerate() {
372 let is_first = position == 0;
373 let is_last = position + 1 == ids.len();
374 check_reference(
375 &format!("{path}[{position}]"),
376 id,
377 &declared,
378 is_first,
379 is_last,
380 &mut issues,
381 );
382 }
383 for pair in ids.windows(2) {
384 successors.push((pair[0].as_str(), pair[1].as_str()));
385 }
386 }
387 EdgeDefinition::Edge(spec) => {
388 for target in check_spec(&path, spec, &declared, &mut issues) {
389 successors.push((spec.from.as_str(), target));
390 }
391 }
392 }
393 }
394
395 if !successors.iter().any(|(from, _)| *from == START_ID) {
396 issues.push((
397 "edges".into(),
398 "no edge leaves START; add one such as `- [START, <first node>]`".into(),
399 ));
400 } else {
401 let mut reached: HashSet<&str> = HashSet::from([START_ID]);
402 let mut queue = VecDeque::from([START_ID]);
403 while let Some(node) = queue.pop_front() {
404 for (_, next) in successors.iter().filter(|(from, _)| *from == node) {
405 if reached.insert(next) {
406 queue.push_back(next);
407 }
408 }
409 }
410 for id in &declared {
411 if !reached.contains(id) {
412 issues.push((
413 format!("nodes.{id}"),
414 format!("node '{id}' is unreachable from START; add an edge to it"),
415 ));
416 }
417 }
418 }
419
420 for (field, ids) in [
421 ("interrupt_before", &workflow.interrupt_before),
422 ("interrupt_after", &workflow.interrupt_after),
423 ] {
424 for (index, id) in ids.iter().enumerate() {
425 if !declared.contains(id.as_str()) {
426 issues.push((format!("{field}[{index}]"), unknown_node(id, &declared)));
427 }
428 }
429 }
430
431 let pauses = !workflow.interrupt_before.is_empty()
432 || !workflow.interrupt_after.is_empty()
433 || workflow.nodes.values().any(|node| node.interrupt.is_some());
434 match workflow.checkpoint.store {
435 CheckpointStore::None if pauses => issues.push((
436 "checkpoint.store".into(),
437 "a workflow that pauses needs checkpoints to resume from; use `memory` or `sqlite`"
438 .into(),
439 )),
440 CheckpointStore::Sqlite if workflow.checkpoint.path.is_none() => issues.push((
441 "checkpoint".into(),
442 "a `sqlite` store needs a `path` to the database file".into(),
443 )),
444 CheckpointStore::Memory | CheckpointStore::None
445 if workflow.checkpoint.path.is_some() =>
446 {
447 issues.push((
448 "checkpoint.path".into(),
449 "`path` applies only to the `sqlite` store".into(),
450 ));
451 }
452 _ => {}
453 }
454 if workflow.recursion_limit == Some(0) {
455 issues
456 .push(("recursion_limit".into(), "the recursion limit must be at least 1".into()));
457 }
458 issues
459 }
460
461 fn check_node(id: &str, node: &NodeDefinition, issues: &mut Issues) {
462 let path = format!("nodes.{id}");
463 if !valid_id(id) {
464 issues.push((
465 path.clone(),
466 format!(
467 "'{id}' is not a valid node id; use letters, digits, `_` and `-`, starting \
468 with a letter or `_`, and not START or END"
469 ),
470 ));
471 }
472 let kinds: Vec<&str> = [
473 ("agent", node.agent.is_some()),
474 ("llm", node.llm.is_some()),
475 ("function", node.function.is_some()),
476 ("set", node.set.is_some()),
477 ("action", node.action.is_some()),
478 ("interrupt", node.interrupt.is_some()),
479 ]
480 .into_iter()
481 .filter_map(|(kind, set)| set.then_some(kind))
482 .collect();
483 match kinds.as_slice() {
484 [] => issues.push((
485 path.clone(),
486 "the node has no kind; set one of agent, llm, function, set, action or interrupt"
487 .into(),
488 )),
489 [_] => {}
490 many => issues.push((
491 path.clone(),
492 format!("the node sets {}; set exactly one kind", many.join(" and ")),
493 )),
494 }
495 let runs_agent = node.agent.is_some() || node.llm.is_some();
496 if node.input.is_some() && !runs_agent {
497 issues.push((
498 format!("{path}.input"),
499 "`input` applies only to agent and llm nodes".into(),
500 ));
501 }
502 if node.output_key.is_some() && (node.set.is_some() || node.function.is_some()) {
503 issues.push((
504 format!("{path}.output_key"),
505 "`output_key` does not apply to set and function nodes, which name their own keys"
506 .into(),
507 ));
508 }
509 if node.output_key.as_deref().is_some_and(|key| key.trim().is_empty()) {
510 issues.push((format!("{path}.output_key"), "the output key is empty".into()));
511 }
512 if node.max_attempts == Some(0) {
513 issues
514 .push((format!("{path}.max_attempts"), "a node needs at least one attempt".into()));
515 }
516 if let Some(agent) = &node.agent
517 && agent.trim().is_empty()
518 {
519 issues.push((format!("{path}.agent"), "the agent name is empty".into()));
520 }
521 if let Some(llm) = &node.llm
522 && llm.model.trim().is_empty()
523 {
524 issues.push((format!("{path}.llm.model"), "the model reference is empty".into()));
525 }
526 if let Some(function) = &node.function
527 && function.trim().is_empty()
528 {
529 issues.push((format!("{path}.function"), "the function name is empty".into()));
530 }
531 if let Some(set) = &node.set
532 && set.is_empty()
533 {
534 issues.push((format!("{path}.set"), "`set` names no keys".into()));
535 }
536 if let Some(action) = &node.action
537 && let Err(message) =
538 super::build::action_config(id, action, node.output_key.as_deref())
539 {
540 issues.push((format!("{path}.action"), message));
541 }
542 if let Some(interrupt) = &node.interrupt {
543 if interrupt.message.trim().is_empty() {
544 issues.push((format!("{path}.interrupt.message"), "the message is empty".into()));
545 }
546 if let Some(schema) = &interrupt.response_schema
547 && let Err(error) = jsonschema::validator_for(schema)
548 {
549 issues.push((
550 format!("{path}.interrupt.response_schema"),
551 format!("not a valid JSON Schema: {error}"),
552 ));
553 }
554 }
555 }
556
557 fn check_spec<'a>(
559 path: &str,
560 spec: &'a EdgeSpec,
561 declared: &BTreeSet<&str>,
562 issues: &mut Issues,
563 ) -> Vec<&'a str> {
564 check_reference(&format!("{path}.from"), &spec.from, declared, true, false, issues);
565 let forms = [spec.to.is_some(), !spec.routes.is_empty(), spec.switch.is_some()];
566 let mut targets: Vec<(String, &'a str)> = Vec::new();
567 match forms.iter().filter(|set| **set).count() {
568 0 => issues.push((
569 path.into(),
570 "the edge has no target; set `to`, `routes`, or `switch` with `cases`".into(),
571 )),
572 1 => {}
573 _ => issues.push((path.into(), "set only one of `to`, `routes` and `switch`".into())),
574 }
575 if let Some(to) = &spec.to {
576 let ids = to.ids();
577 if ids.is_empty() {
578 issues.push((format!("{path}.to"), "`to` lists no nodes".into()));
579 }
580 if ids.len() == 1 {
581 targets.push((format!("{path}.to"), ids[0]));
582 } else {
583 for (index, id) in ids.into_iter().enumerate() {
584 targets.push((format!("{path}.to[{index}]"), id));
585 }
586 }
587 if spec.default.is_some() {
588 issues.push((
589 format!("{path}.default"),
590 "`default` applies only to `routes` and `switch`".into(),
591 ));
592 }
593 }
594 if spec.from == START_ID && (!spec.routes.is_empty() || spec.switch.is_some()) {
595 issues.push((
596 format!("{path}.from"),
597 "edges from START cannot be conditional; route from the first node instead".into(),
598 ));
599 }
600 for (index, route) in spec.routes.iter().enumerate() {
601 check_condition(&format!("{path}.routes[{index}].when"), &route.when, issues);
602 targets.push((format!("{path}.routes[{index}].to"), route.to.as_str()));
603 }
604 if let Some(field) = &spec.switch {
605 if field.trim().is_empty() {
606 issues.push((format!("{path}.switch"), "the state path is empty".into()));
607 }
608 if spec.cases.is_empty() {
609 issues.push((format!("{path}.cases"), "`switch` needs `cases`".into()));
610 }
611 }
612 if !spec.cases.is_empty() && spec.switch.is_none() {
613 issues.push((format!("{path}.cases"), "`cases` applies only with `switch`".into()));
614 }
615 for (value, target) in &spec.cases {
616 targets.push((format!("{path}.cases.{value}"), target.as_str()));
617 }
618 if let Some(default) = &spec.default {
619 targets.push((format!("{path}.default"), default.as_str()));
620 }
621 for (target_path, id) in &targets {
622 check_reference(target_path, id, declared, false, true, issues);
623 }
624 targets.into_iter().map(|(_, id)| id).collect()
625 }
626
627 fn check_condition(path: &str, condition: &Condition, issues: &mut Issues) {
628 let comparison =
629 condition.field.is_some() || condition.op.is_some() || condition.value.is_some();
630 let forms =
631 [comparison, condition.all.is_some(), condition.any.is_some(), condition.not.is_some()];
632 match forms.iter().filter(|set| **set).count() {
633 0 => {
634 issues.push((
635 path.into(),
636 "the condition is empty; set `field` and `op`, or `all`, `any` or `not`".into(),
637 ));
638 return;
639 }
640 1 => {}
641 _ => issues.push((
642 path.into(),
643 "set only one of a comparison (`field`, `op`, `value`), `all`, `any` and `not`"
644 .into(),
645 )),
646 }
647 if comparison {
648 match &condition.field {
649 Some(field) if !field.trim().is_empty() => {}
650 _ => issues.push((format!("{path}.field"), "a comparison needs a `field`".into())),
651 }
652 match condition.op {
653 None => issues.push((format!("{path}.op"), "a comparison needs an `op`".into())),
654 Some(op) if op.takes_value() && condition.value.is_none() => issues
655 .push((format!("{path}.value"), format!("`{}` needs a `value`", op_name(op)))),
656 Some(op) if !op.takes_value() && condition.value.is_some() => issues
657 .push((format!("{path}.value"), format!("`{}` takes no `value`", op_name(op)))),
658 Some(ConditionOp::Matches) => {
659 let pattern = condition.value.as_ref().and_then(|value| value.as_str());
660 match pattern.map(regex::Regex::new) {
661 Some(Ok(_)) => {}
662 Some(Err(error)) => issues.push((
663 format!("{path}.value"),
664 format!("not a valid regular expression: {error}"),
665 )),
666 None => issues.push((
667 format!("{path}.value"),
668 "`matches` needs a regular expression string".into(),
669 )),
670 }
671 }
672 Some(_) => {}
673 }
674 if let Some(value) = &condition.value
675 && (value.is_object()
676 || (value.is_array() && condition.op != Some(ConditionOp::In)))
677 {
678 issues.push((
679 format!("{path}.value"),
680 "the value must be a string, number or boolean (a list only for `in`)".into(),
681 ));
682 }
683 }
684 for (key, list) in [("all", &condition.all), ("any", &condition.any)] {
685 if let Some(list) = list {
686 if list.is_empty() {
687 issues.push((format!("{path}.{key}"), format!("`{key}` lists no conditions")));
688 }
689 for (index, inner) in list.iter().enumerate() {
690 check_condition(&format!("{path}.{key}[{index}]"), inner, issues);
691 }
692 }
693 }
694 if let Some(inner) = &condition.not {
695 check_condition(&format!("{path}.not"), inner, issues);
696 }
697 }
698
699 fn op_name(op: ConditionOp) -> String {
700 serde_json::to_value(op)
701 .ok()
702 .and_then(|value| value.as_str().map(str::to_string))
703 .unwrap_or_default()
704 }
705
706 fn check_reference(
707 path: &str,
708 id: &str,
709 declared: &BTreeSet<&str>,
710 may_be_start: bool,
711 may_be_end: bool,
712 issues: &mut Issues,
713 ) {
714 match id {
715 START_ID if may_be_start => {}
716 START_ID => issues.push((path.into(), "START can only begin an edge".into())),
717 END_ID if may_be_end => {}
718 END_ID => issues.push((path.into(), "END can only finish an edge".into())),
719 id if declared.contains(id) => {}
720 id => issues.push((path.into(), unknown_node(id, declared))),
721 }
722 }
723
724 fn unknown_node(id: &str, declared: &BTreeSet<&str>) -> String {
725 let known: Vec<&str> = declared.iter().copied().collect();
726 format!("unknown node '{id}'; declared nodes are {}", known.join(", "))
727 }
728
729 pub(super) fn valid_id(id: &str) -> bool {
730 let mut chars = id.chars();
731 chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
732 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
733 && !matches!(id, START_ID | END_ID | crate::START | crate::END)
734 }
735}