1use indexmap::IndexMap;
39use serde::{Deserialize, Serialize};
40
41use crate::source_map::DocPath;
42use crate::validate::{Diagnostic, suggest};
43use crate::value::{Value, ValueType};
44
45pub const FORMAT_VERSION: &str = "1";
47
48#[derive(Debug, thiserror::Error)]
50#[non_exhaustive]
51pub enum DocumentError {
52 #[error("invalid JSON workflow document: {0}")]
53 Json(#[from] serde_json::Error),
54 #[error("invalid YAML workflow document: {0}")]
57 Yaml(String),
58 #[error("invalid node `{id}`: {message}")]
59 Node { id: String, message: String },
60 #[error("{path}: {message}")]
62 Field { path: String, message: String },
63}
64
65#[derive(Clone, Debug, Default, Serialize)]
67pub struct Workflow {
68 pub version: String,
70 pub name: Option<String>,
71 pub description: Option<String>,
72 pub env: Vec<VariableDecl>,
74 pub conversation: Vec<VariableDecl>,
76 pub graph: GraphDoc,
77}
78
79#[derive(Clone, Debug, Serialize, Deserialize)]
81pub struct VariableDecl {
82 pub name: String,
83 #[serde(rename = "type", alias = "value_type", default = "any_type")]
84 pub ty: ValueType,
85 #[serde(default)]
86 pub value: Option<Value>,
87 #[serde(default)]
88 pub description: Option<String>,
89}
90
91fn any_type() -> ValueType {
92 ValueType::Any
93}
94
95#[derive(Clone, Debug, Default, Serialize)]
97pub struct GraphDoc {
98 pub nodes: Vec<NodeDoc>,
99 pub edges: Vec<EdgeDoc>,
100}
101
102#[derive(Clone, Debug)]
108pub struct NodeDoc {
109 pub id: String,
110 pub kind: String,
112 pub title: Option<String>,
113 pub parent: Option<String>,
115 pub policy: NodePolicy,
116 pub config: serde_json::Map<String, serde_json::Value>,
118 pub strict: bool,
122}
123
124impl NodeDoc {
125 pub fn new(id: impl Into<String>, kind: impl Into<String>, config: serde_json::Value) -> Self {
127 let config = match config {
128 serde_json::Value::Object(map) => map,
129 _ => serde_json::Map::new(),
130 };
131 Self {
132 id: id.into(),
133 kind: kind.into(),
134 title: None,
135 parent: None,
136 policy: NodePolicy::default(),
137 config,
138 strict: true,
139 }
140 }
141
142 pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
144 self.parent = Some(parent.into());
145 self
146 }
147
148 pub fn with_policy(mut self, policy: NodePolicy) -> Self {
150 self.policy = policy;
151 self
152 }
153
154 pub fn parse_config<T: serde::de::DeserializeOwned>(&self) -> Result<T, DocumentError> {
156 parse_config_at(&self.config)
157 .map_err(|(path, e)| DocumentError::Node { id: self.id.clone(), message: with_field(&path, &e) })
158 }
159
160 pub fn label(&self) -> &str {
162 self.title.as_deref().unwrap_or(&self.id)
163 }
164}
165
166pub(crate) fn parse_config_at<T: serde::de::DeserializeOwned>(
171 config: &serde_json::Map<String, serde_json::Value>,
172) -> Result<T, (String, serde_json::Error)> {
173 let value = serde_json::Value::Object(config.clone());
174 T::deserialize(&value).map_err(|e| (crate::value_path::error_path_text(&value, &e), e))
175}
176
177fn with_field(path: &str, error: &serde_json::Error) -> String {
178 if path == "." { error.to_string() } else { format!("{path}: {error}") }
179}
180
181#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
183pub struct NodePolicy {
184 #[serde(default)]
185 pub on_error: ErrorStrategy,
186 #[serde(default)]
187 pub retry: RetryPolicy,
188 #[serde(default)]
190 pub timeout_ms: Option<u64>,
191}
192
193#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
195#[serde(tag = "strategy", rename_all = "kebab-case")]
196#[non_exhaustive]
197pub enum ErrorStrategy {
198 #[default]
200 Fail,
201 FailBranch,
204 DefaultValue {
206 #[serde(default)]
207 values: IndexMap<String, Value>,
208 },
209}
210
211#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
213pub struct RetryPolicy {
214 #[serde(default)]
215 pub max_retries: u32,
216 #[serde(default)]
218 pub interval_ms: u64,
219 #[serde(default = "one")]
221 pub backoff: f64,
222}
223
224fn one() -> f64 {
225 1.0
226}
227
228impl Default for RetryPolicy {
229 fn default() -> Self {
230 Self { max_retries: 0, interval_ms: 0, backoff: 1.0 }
231 }
232}
233
234impl RetryPolicy {
235 pub fn delay_ms(&self, attempt: u32) -> u64 {
237 let factor = self.backoff.max(1.0).powi(i32::try_from(attempt.saturating_sub(1)).unwrap_or(i32::MAX));
238 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::cast_precision_loss)]
239 let ms = (self.interval_ms as f64 * factor).min(3_600_000.0) as u64;
240 ms
241 }
242}
243
244#[derive(Clone, Debug, Serialize, Deserialize)]
246pub struct EdgeDoc {
247 #[serde(default)]
248 pub id: Option<String>,
249 pub source: String,
250 pub target: String,
251 #[serde(default, alias = "sourceHandle", alias = "source_handle", skip_serializing_if = "Option::is_none")]
252 pub handle: Option<String>,
253}
254
255impl EdgeDoc {
256 pub fn new(source: impl Into<String>, target: impl Into<String>) -> Self {
257 Self { id: None, source: source.into(), target: target.into(), handle: None }
258 }
259
260 pub fn with_handle(mut self, handle: impl Into<String>) -> Self {
261 self.handle = Some(handle.into());
262 self
263 }
264}
265
266impl Workflow {
267 pub fn from_json(text: &str) -> Result<Self, DocumentError> {
269 let raw: serde_json::Value = serde_json::from_str(text)?;
270 Self::from_value(raw)
271 }
272
273 #[cfg(feature = "yaml")]
275 pub fn from_yaml(text: &str) -> Result<Self, DocumentError> {
276 let raw = crate::yaml::to_value(text, true).map_err(|e| DocumentError::Yaml(e.to_string()))?;
278 Self::from_value(raw)
279 }
280
281 pub fn parse(text: &str) -> Result<Self, DocumentError> {
283 let first = text.trim_start().chars().next();
284 if matches!(first, Some('{')) {
285 return Self::from_json(text);
286 }
287 #[cfg(feature = "yaml")]
288 {
289 Self::from_yaml(text)
290 }
291 #[cfg(not(feature = "yaml"))]
292 {
293 Self::from_json(text)
294 }
295 }
296
297 pub fn from_value(raw: serde_json::Value) -> Result<Self, DocumentError> {
300 let decoded = decode(raw);
301 match decoded.diagnostics.into_iter().find(Diagnostic::is_error) {
302 None => Ok(decoded.workflow),
303 Some(d) => {
304 let message = match &d.suggestion {
305 Some(s) => format!("{}; did you mean `{s}`?", d.message),
306 None => d.message,
307 };
308 Err(match d.node {
309 Some(id) => DocumentError::Node { id, message },
310 None => DocumentError::Field { path: d.path.to_string(), message },
311 })
312 }
313 }
314 }
315}
316
317pub(crate) struct Decoded {
320 pub workflow: Workflow,
321 pub node_paths: Vec<DocPath>,
323 pub edge_paths: Vec<DocPath>,
325 pub diagnostics: Vec<Diagnostic>,
326}
327
328struct KeyRules<'a> {
330 what: &'a str,
331 known: &'a [&'a str],
332 deprecated: &'a [(&'a str, &'a str)],
334 reserved: &'a [&'a str],
336}
337
338const TOP_LEVEL: KeyRules<'static> = KeyRules {
339 what: "the document",
340 known: &["version", "name", "description", "env", "conversation", "graph"],
341 deprecated: &[("environment_variables", "env"), ("conversation_variables", "conversation")],
342 reserved: &["imports", "inputs", "outputs", "triggers", "metadata", "requires", "subgraphs"],
343};
344
345const GRAPH_KEYS: KeyRules<'static> =
346 KeyRules { what: "`graph`", known: &["nodes", "edges"], deprecated: &[], reserved: &[] };
347
348const NODE_KEYS: KeyRules<'static> = KeyRules {
350 what: "a node",
351 known: &[],
352 deprecated: &[
353 ("parentId", "parent"),
354 ("container_id", "parent"),
355 ("iteration_id", "parent"),
356 ("loop_id", "parent"),
357 ("error_strategy", "on_error"),
358 ("default_value", "on_error"),
359 ("retry_config", "retry"),
360 ],
361 reserved: &["disabled", "cache", "metadata"],
362};
363
364pub const COMMON_NODE_FIELDS: &[&str] = &["id", "type", "title", "parent", "retry", "timeout_ms", "on_error"];
366
367pub const RESERVED_NODE_FIELDS: &[&str] = NODE_KEYS.reserved;
369
370const EDGE_KEYS: KeyRules<'static> = KeyRules {
371 what: "an edge",
372 known: &["id", "source", "target", "handle"],
373 deprecated: &[("sourceHandle", "handle"), ("source_handle", "handle")],
374 reserved: &[],
375};
376
377const DECL_KEYS: KeyRules<'static> = KeyRules {
378 what: "a variable declaration",
379 known: &["name", "type", "value", "description"],
380 deprecated: &[("value_type", "type")],
381 reserved: &[],
382};
383
384const RETRY_KEYS: KeyRules<'static> =
385 KeyRules { what: "`retry`", known: &["max_retries", "interval_ms", "backoff"], deprecated: &[], reserved: &[] };
386
387const ON_ERROR_KEYS: KeyRules<'static> =
388 KeyRules { what: "`on_error`", known: &["strategy", "values"], deprecated: &[], reserved: &[] };
389
390const STRATEGIES: &[&str] = &["fail", "fail-branch", "default-value"];
391
392const BUILDER_KEYS: &[&str] = &[
394 "desc",
395 "selected",
396 "position",
397 "positionAbsolute",
398 "width",
399 "height",
400 "sourcePosition",
401 "targetPosition",
402 "zIndex",
403 "isInIteration",
404 "isInLoop",
405];
406
407pub fn is_extension_key(key: &str) -> bool {
409 key.starts_with("x-")
410}
411
412fn check_keys(
416 obj: &serde_json::Map<String, serde_json::Value>,
417 path: &DocPath,
418 rules: &KeyRules<'_>,
419 unknown_is_error: bool,
420 out: &mut Vec<Diagnostic>,
421) {
422 for key in obj.keys() {
423 let key_path = path.key(key);
424 if is_extension_key(key) || rules.known.contains(&key.as_str()) {
425 continue;
426 }
427 if let Some((_, new)) = rules.deprecated.iter().find(|(old, _)| old == key) {
428 out.push(
429 Diagnostic::warning("deprecated", key_path, format!("`{key}` in {} is deprecated", rules.what))
430 .at_key()
431 .with_suggestion(Some((*new).to_owned())),
432 );
433 } else if rules.reserved.contains(&key.as_str()) {
434 out.push(
435 Diagnostic::error(
436 "reserved-field",
437 key_path,
438 format!("`{key}` in {} is reserved for a future version of the format", rules.what),
439 )
440 .at_key()
441 .with_help("keys starting with `x-` are free for tools and ignored"),
442 );
443 } else if unknown_is_error {
444 out.push(
445 Diagnostic::error("unknown-field", key_path, format!("unknown field `{key}` in {}", rules.what))
446 .at_key()
447 .with_suggestion(suggest(key, rules.known.iter().copied()))
448 .with_help(format!("expected one of: {}", rules.known.join(", "))),
449 );
450 }
451 }
452}
453
454pub(crate) fn decode(raw: serde_json::Value) -> Decoded {
456 let mut out = Vec::new();
457 let mut decoded = Decoded {
458 workflow: Workflow { version: FORMAT_VERSION.to_owned(), ..Workflow::default() },
459 node_paths: Vec::new(),
460 edge_paths: Vec::new(),
461 diagnostics: Vec::new(),
462 };
463 let serde_json::Value::Object(mut root) = raw else {
464 out.push(Diagnostic::error("invalid-value", DocPath::root(), "a workflow document must be an object"));
465 decoded.diagnostics = out;
466 return decoded;
467 };
468 let import = matches!(root.get("workflow"), Some(serde_json::Value::Object(_))) || root.contains_key("app");
470 let strict = !import;
471 let mut inner_keys = std::collections::HashSet::new();
472 if let Some(serde_json::Value::Object(inner)) = root.remove("workflow") {
473 for (k, v) in inner {
474 if !root.contains_key(&k) {
475 inner_keys.insert(k.clone());
476 root.insert(k, v);
477 }
478 }
479 }
480 let at = |key: &str| {
481 if inner_keys.contains(key) { DocPath::root().key("workflow").key(key) } else { DocPath::root().key(key) }
482 };
483 if strict {
484 check_keys(&root, &DocPath::root(), &TOP_LEVEL, true, &mut out);
485 }
486
487 let wf = &mut decoded.workflow;
488 if strict {
489 wf.version = check_version(root.get("version"), &at("version"), &mut out);
490 } else if let Some(v) = str_field(&root, "version") {
491 wf.version = v;
492 }
493 let app = root.get("app").and_then(|a| a.as_object());
494 wf.name =
495 text_field(&root, "name", &at("name"), strict, &mut out).or_else(|| app.and_then(|a| str_field(a, "name")));
496 wf.description = text_field(&root, "description", &at("description"), strict, &mut out)
497 .or_else(|| app.and_then(|a| str_field(a, "description")));
498
499 for (field, legacy) in [("env", "environment_variables"), ("conversation", "conversation_variables")] {
500 let (key, raw) = match root.remove(field) {
501 Some(v) => (field, Some(v)),
502 None => (legacy, root.remove(legacy)),
503 };
504 let decls = decode_decls(raw, &at(key), strict, &mut out);
505 if field == "env" {
506 wf.env = decls;
507 } else {
508 wf.conversation = decls;
509 }
510 }
511
512 let graph_path = at("graph");
513 let graph = match root.remove("graph") {
514 Some(serde_json::Value::Object(g)) => g,
515 Some(_) => {
516 out.push(Diagnostic::error(
517 "invalid-value",
518 graph_path,
519 "`graph` must be an object with `nodes` and `edges`",
520 ));
521 decoded.diagnostics = out;
522 return decoded;
523 }
524 None => {
525 out.push(
526 Diagnostic::error("missing-field", DocPath::root(), "missing `graph`")
527 .with_help("a workflow needs `graph: {nodes: [...], edges: [...]}`"),
528 );
529 decoded.diagnostics = out;
530 return decoded;
531 }
532 };
533 if strict {
534 check_keys(&graph, &graph_path, &GRAPH_KEYS, true, &mut out);
535 }
536 for (i, raw) in list_field(&graph, "nodes", &graph_path, &mut out).into_iter().enumerate() {
537 let path = graph_path.key("nodes").index(i);
538 if let Some(doc) = NodeDoc::decode(raw, &path, strict, &mut out) {
539 wf.graph.nodes.push(doc);
540 decoded.node_paths.push(path);
541 }
542 }
543 for (i, raw) in list_field(&graph, "edges", &graph_path, &mut out).into_iter().enumerate() {
544 let path = graph_path.key("edges").index(i);
545 if let Some(edge) = decode_edge(raw, &path, strict, &mut out) {
546 wf.graph.edges.push(edge);
547 decoded.edge_paths.push(path);
548 }
549 }
550 decoded.diagnostics = out;
551 decoded
552}
553
554fn check_version(raw: Option<&serde_json::Value>, path: &DocPath, out: &mut Vec<Diagnostic>) -> String {
556 match raw {
557 None => FORMAT_VERSION.to_owned(),
558 Some(serde_json::Value::String(s)) if s == FORMAT_VERSION => s.clone(),
559 Some(serde_json::Value::Number(n)) if n.as_u64() == Some(1) => FORMAT_VERSION.to_owned(),
560 Some(other) => {
561 let shown = other.as_str().map_or_else(|| other.to_string(), str::to_owned);
562 out.push(
563 Diagnostic::error(
564 "unsupported-version",
565 path.clone(),
566 format!("unsupported document version `{shown}`; this build reads version \"{FORMAT_VERSION}\""),
567 )
568 .with_help("newer documents need a newer graphrt"),
569 );
570 shown
571 }
572 }
573}
574
575fn str_field(map: &serde_json::Map<String, serde_json::Value>, key: &str) -> Option<String> {
576 map.get(key).and_then(|v| v.as_str()).map(str::to_owned)
577}
578
579fn text_field(
581 map: &serde_json::Map<String, serde_json::Value>,
582 key: &str,
583 path: &DocPath,
584 strict: bool,
585 out: &mut Vec<Diagnostic>,
586) -> Option<String> {
587 match map.get(key) {
588 None | Some(serde_json::Value::Null) => None,
589 Some(serde_json::Value::String(s)) => Some(s.clone()),
590 Some(_) => {
591 if strict {
592 out.push(Diagnostic::error("invalid-value", path.clone(), format!("`{key}` must be a string")));
593 }
594 None
595 }
596 }
597}
598
599fn list_field(
601 map: &serde_json::Map<String, serde_json::Value>,
602 key: &str,
603 parent: &DocPath,
604 out: &mut Vec<Diagnostic>,
605) -> Vec<serde_json::Value> {
606 match map.get(key) {
607 None | Some(serde_json::Value::Null) => Vec::new(),
608 Some(serde_json::Value::Array(items)) => items.clone(),
609 Some(_) => {
610 out.push(Diagnostic::error("invalid-value", parent.key(key), format!("`{key}` must be a list")));
611 Vec::new()
612 }
613 }
614}
615
616fn decode_decls(
617 raw: Option<serde_json::Value>,
618 path: &DocPath,
619 strict: bool,
620 out: &mut Vec<Diagnostic>,
621) -> Vec<VariableDecl> {
622 let items = match raw {
623 None | Some(serde_json::Value::Null) => return Vec::new(),
624 Some(serde_json::Value::Array(items)) => items,
625 Some(_) => {
626 out.push(Diagnostic::error("invalid-value", path.clone(), "variable declarations must be a list"));
627 return Vec::new();
628 }
629 };
630 let mut decls: Vec<VariableDecl> = Vec::with_capacity(items.len());
631 for (i, item) in items.into_iter().enumerate() {
632 let item_path = path.index(i);
633 if strict && let serde_json::Value::Object(obj) = &item {
634 check_keys(obj, &item_path, &DECL_KEYS, true, out);
635 }
636 match serde_json::from_value::<VariableDecl>(item) {
637 Ok(decl) => {
638 if decls.iter().any(|d| d.name == decl.name) {
639 out.push(Diagnostic::error(
640 "duplicate-variable",
641 item_path.key("name"),
642 format!("variable `{}` is declared twice", decl.name),
643 ));
644 }
645 decls.push(decl);
646 }
647 Err(e) => {
648 out.push(Diagnostic::error("invalid-value", item_path, format!("invalid variable declaration: {e}")))
649 }
650 }
651 }
652 decls
653}
654
655fn decode_edge(raw: serde_json::Value, path: &DocPath, strict: bool, out: &mut Vec<Diagnostic>) -> Option<EdgeDoc> {
656 let serde_json::Value::Object(mut obj) = raw else {
657 out.push(Diagnostic::error("invalid-value", path.clone(), "an edge must be an object `{source, target}`"));
658 return None;
659 };
660 if strict {
661 check_keys(&obj, path, &EDGE_KEYS, true, out);
662 }
663 obj.retain(|k, _| !is_extension_key(k));
664 let mut ok = true;
665 for end in ["source", "target"] {
666 match obj.get(end) {
667 Some(serde_json::Value::String(s)) if !s.is_empty() => {}
668 Some(_) => {
669 out.push(Diagnostic::error("invalid-value", path.key(end), format!("edge `{end}` must be a node id")));
670 ok = false;
671 }
672 None => {
673 out.push(Diagnostic::error("missing-field", path.clone(), format!("edge is missing `{end}`")));
674 ok = false;
675 }
676 }
677 }
678 if !ok {
679 return None;
680 }
681 match serde_json::from_value::<EdgeDoc>(serde_json::Value::Object(obj)) {
682 Ok(edge) => Some(edge),
683 Err(e) => {
684 out.push(Diagnostic::error("invalid-value", path.clone(), format!("invalid edge: {e}")));
685 None
686 }
687 }
688}
689
690const POLICY_KEYS: &[&str] = &["on_error", "error_strategy", "default_value", "retry", "retry_config", "timeout_ms"];
692
693impl NodeDoc {
694 pub fn from_raw(raw: serde_json::Value) -> Result<Option<Self>, DocumentError> {
696 let mut out = Vec::new();
697 let doc = Self::decode(raw, &DocPath::root(), true, &mut out);
698 match out.into_iter().find(Diagnostic::is_error) {
699 Some(d) => Err(DocumentError::Node {
700 id: d.node.unwrap_or_else(|| "<node>".to_owned()),
701 message: match d.suggestion {
702 Some(s) => format!("{}; did you mean `{s}`?", d.message),
703 None => d.message,
704 },
705 }),
706 None => Ok(doc),
707 }
708 }
709
710 fn decode(raw: serde_json::Value, path: &DocPath, strict_doc: bool, out: &mut Vec<Diagnostic>) -> Option<Self> {
713 let serde_json::Value::Object(mut obj) = raw else {
714 out.push(Diagnostic::error("invalid-value", path.clone(), "a node must be an object `{id, type, ...}`"));
715 return None;
716 };
717 let id = match obj.remove("id") {
718 Some(serde_json::Value::String(s)) if !s.is_empty() => s,
719 Some(_) => {
720 out.push(Diagnostic::error("invalid-value", path.key("id"), "node `id` must be a non-empty string"));
721 return None;
722 }
723 None => {
724 out.push(Diagnostic::error("missing-field", path.clone(), "node is missing `id`"));
725 return None;
726 }
727 };
728 let wrapped = matches!(obj.get("data"), Some(serde_json::Value::Object(_)));
729 let strict = strict_doc && !wrapped;
730 if strict {
731 let before = out.len();
732 check_keys(&obj, path, &NODE_KEYS, false, out);
733 for d in out.iter_mut().skip(before) {
734 d.node = Some(id.clone());
735 }
736 }
737 let legacy_parent = obj.remove("parentId").and_then(as_string);
738 let mut parent = obj.remove("parent").and_then(as_string).or(legacy_parent);
739 if let Some(serde_json::Value::Object(data)) = obj.remove("data") {
741 for (k, v) in data {
742 obj.insert(k, v);
743 }
744 }
745 for key in ["container_id", "iteration_id", "loop_id"] {
746 let v = obj.remove(key).and_then(as_string);
747 if parent.is_none() {
748 parent = v;
749 }
750 }
751 let kind = match obj.remove("type") {
752 Some(serde_json::Value::String(s)) if !s.is_empty() => s,
753 Some(_) => {
754 out.push(
755 Diagnostic::error("invalid-value", path.key("type"), "node `type` must be a non-empty string")
756 .with_node(&id),
757 );
758 return None;
759 }
760 None => {
761 out.push(Diagnostic::error("missing-field", path.clone(), "node is missing `type`").with_node(&id));
762 return None;
763 }
764 };
765 if kind == "custom-note" || kind == "note" {
766 return None;
767 }
768 let title = match obj.remove("title") {
769 Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s),
770 None | Some(serde_json::Value::Null | serde_json::Value::String(_)) => None,
771 Some(_) => {
772 if strict {
773 out.push(
774 Diagnostic::error("invalid-value", path.key("title"), "node `title` must be a string")
775 .with_node(&id),
776 );
777 }
778 None
779 }
780 };
781 let policy = extract_policy(&id, &mut obj, path, strict, out);
782 for k in BUILDER_KEYS {
783 obj.remove(*k);
784 }
785 obj.retain(|k, _| !is_extension_key(k));
786 Some(Self { id, kind, title, parent, policy, config: obj, strict })
787 }
788}
789
790fn as_string(v: serde_json::Value) -> Option<String> {
791 match v {
792 serde_json::Value::String(s) if !s.is_empty() => Some(s),
793 _ => None,
794 }
795}
796
797fn extract_policy(
798 id: &str,
799 obj: &mut serde_json::Map<String, serde_json::Value>,
800 path: &DocPath,
801 strict: bool,
802 out: &mut Vec<Diagnostic>,
803) -> NodePolicy {
804 let mut policy = NodePolicy::default();
805 let mut push = |d: Diagnostic| out.push(d.with_node(id));
806
807 if let Some(v) = obj.remove("on_error") {
808 let at = path.key("on_error");
809 if let serde_json::Value::Object(map) = &v
810 && strict
811 {
812 let mut found = Vec::new();
813 check_keys(map, &at, &ON_ERROR_KEYS, true, &mut found);
814 found.into_iter().for_each(&mut push);
815 }
816 let strategy = v.get("strategy").and_then(serde_json::Value::as_str).map(str::to_owned);
817 match (&strategy, serde_json::from_value::<ErrorStrategy>(v)) {
818 (_, Ok(s)) => policy.on_error = s,
819 (Some(name), Err(_)) if !STRATEGIES.contains(&name.as_str()) => push(
820 Diagnostic::error("invalid-value", at.key("strategy"), format!("unknown `on_error` strategy `{name}`"))
821 .with_suggestion(suggest(name, STRATEGIES.iter().copied()))
822 .with_help("expected `fail`, `fail-branch` or `default-value`"),
823 ),
824 (_, Err(e)) => push(
825 Diagnostic::error("invalid-value", at, format!("invalid `on_error`: {e}"))
826 .with_help("expected `{strategy: fail | fail-branch | default-value, values: {...}}`"),
827 ),
828 }
829 } else if let Some(serde_json::Value::String(strategy)) = obj.remove("error_strategy") {
830 policy.on_error = match strategy.as_str() {
831 "fail-branch" => ErrorStrategy::FailBranch,
832 "" | "none" | "fail" => ErrorStrategy::Fail,
833 "default-value" => {
834 let values = match obj.remove("default_value") {
836 Some(serde_json::Value::Array(items)) => items
837 .into_iter()
838 .filter_map(|item| {
839 let key = item.get("key")?.as_str()?.to_owned();
840 let declared = item.get("type").and_then(|t| t.as_str()).unwrap_or("any").to_owned();
841 let value = item.get("value").cloned().unwrap_or(serde_json::Value::Null);
842 Some((key, default_value(&declared, value)))
843 })
844 .collect(),
845 Some(serde_json::Value::Object(map)) => {
846 map.into_iter().map(|(k, v)| (k, Value::from_json(v))).collect()
847 }
848 _ => IndexMap::new(),
849 };
850 ErrorStrategy::DefaultValue { values }
851 }
852 other => {
853 push(
854 Diagnostic::error(
855 "invalid-value",
856 path.key("error_strategy"),
857 format!("unknown error_strategy `{other}` (expected `fail`, `fail-branch` or `default-value`)"),
858 )
859 .with_suggestion(suggest(other, STRATEGIES.iter().copied())),
860 );
861 ErrorStrategy::Fail
862 }
863 };
864 }
865 obj.remove("default_value");
866
867 if let Some(v) = obj.remove("retry") {
868 let at = path.key("retry");
869 if let serde_json::Value::Object(map) = &v
870 && strict
871 {
872 let mut found = Vec::new();
873 check_keys(map, &at, &RETRY_KEYS, true, &mut found);
874 found.into_iter().for_each(&mut push);
875 }
876 match serde_json::from_value(v) {
877 Ok(retry) => policy.retry = retry,
878 Err(e) => push(Diagnostic::error("invalid-value", at, format!("invalid `retry`: {e}"))),
879 }
880 } else if let Some(serde_json::Value::Object(cfg)) = obj.remove("retry_config") {
881 let enabled = cfg.get("retry_enabled").and_then(serde_json::Value::as_bool).unwrap_or(false);
882 if enabled {
883 policy.retry.max_retries = cfg
884 .get("max_retries")
885 .and_then(serde_json::Value::as_u64)
886 .and_then(|n| u32::try_from(n).ok())
887 .unwrap_or(0);
888 policy.retry.interval_ms = cfg.get("retry_interval").and_then(serde_json::Value::as_u64).unwrap_or(0);
889 }
890 }
891 match obj.remove("timeout_ms") {
892 None | Some(serde_json::Value::Null) => {}
893 Some(v) => match v.as_u64() {
894 Some(ms) => policy.timeout_ms = Some(ms),
895 None => push(Diagnostic::error(
896 "invalid-value",
897 path.key("timeout_ms"),
898 format!("timeout_ms must be a non-negative integer number of milliseconds, got {v}"),
899 )),
900 },
901 }
902 for k in POLICY_KEYS {
903 obj.remove(*k);
904 }
905 policy
906}
907
908fn default_value(declared: &str, value: serde_json::Value) -> Value {
910 match (declared, value) {
911 ("string", v) => Value::from_json(v),
912 (_, serde_json::Value::String(s)) => match serde_json::from_str::<serde_json::Value>(&s) {
913 Ok(parsed) => Value::from_json(parsed),
914 Err(_) => Value::from(s),
915 },
916 (_, v) => Value::from_json(v),
917 }
918}
919
920#[cfg(test)]
921mod tests {
922 use super::*;
923
924 #[test]
925 fn parses_flat_layout() {
926 let doc = Workflow::from_json(
927 r#"{"graph":{"nodes":[{"id":"s","type":"start","variables":[]},
928 {"id":"h","type":"http-request","retry":{"max_retries":2,"interval_ms":10},"timeout_ms":500}],
929 "edges":[{"source":"s","target":"h"}]}}"#,
930 );
931 let doc = doc.unwrap();
932 assert_eq!(doc.graph.nodes.len(), 2);
933 let h = &doc.graph.nodes[1];
934 assert_eq!(h.policy.retry.max_retries, 2);
935 assert_eq!(h.policy.timeout_ms, Some(500));
936 assert!(!h.config.contains_key("retry"));
937 }
938
939 #[test]
940 fn parses_data_wrapper_layout() {
941 let doc = Workflow::from_json(
942 r#"{"workflow":{"environment_variables":[{"name":"K","value_type":"secret","value":"x"}],
943 "graph":{"nodes":[
944 {"id":"a","type":"custom","data":{"type":"llm","title":"LLM","error_strategy":"default-value",
945 "default_value":[{"key":"n","type":"number","value":"42"}],
946 "retry_config":{"retry_enabled":true,"max_retries":3,"retry_interval":100}}},
947 {"id":"b","type":"custom","parentId":"it","data":{"type":"code"}},
948 {"id":"note","type":"custom-note","data":{"type":"custom-note"}}],
949 "edges":[{"source":"a","target":"b","sourceHandle":"source"}]}}}"#,
950 );
951 let doc = doc.unwrap();
952 assert_eq!(doc.env.len(), 1);
953 assert_eq!(doc.env[0].ty, ValueType::Secret);
954 assert_eq!(doc.graph.nodes.len(), 2);
955 let a = &doc.graph.nodes[0];
956 assert_eq!(a.kind, "llm");
957 assert_eq!(a.title.as_deref(), Some("LLM"));
958 assert_eq!(a.policy.retry.max_retries, 3);
959 match &a.policy.on_error {
960 ErrorStrategy::DefaultValue { values } => assert_eq!(values.get("n"), Some(&Value::Int(42))),
961 other => panic!("unexpected {other:?}"),
962 }
963 assert_eq!(doc.graph.nodes[1].parent.as_deref(), Some("it"));
964 assert_eq!(doc.graph.edges[0].handle.as_deref(), Some("source"));
965 }
966
967 #[test]
968 fn backoff_delay() {
969 let p = RetryPolicy { max_retries: 3, interval_ms: 100, backoff: 2.0 };
970 assert_eq!(p.delay_ms(1), 100);
971 assert_eq!(p.delay_ms(3), 400);
972 }
973
974 #[cfg(feature = "yaml")]
975 #[test]
976 fn parses_yaml() {
977 let doc = Workflow::parse("graph:\n nodes:\n - {id: s, type: start}\n edges: []\n");
978 assert!(matches!(doc, Ok(d) if d.graph.nodes.len() == 1));
979 }
980
981 #[cfg(feature = "yaml")]
982 #[test]
983 fn yaml_uses_strict_booleans() {
984 let doc = Workflow::parse("graph:\n nodes:\n - {id: s, type: start, label: n, flag: true}\n").unwrap();
985 let cfg = &doc.graph.nodes[0].config;
986 assert_eq!(cfg.get("label"), Some(&serde_json::json!("n")));
987 assert_eq!(cfg.get("flag"), Some(&serde_json::json!(true)));
988 }
989}
990
991impl Serialize for NodeDoc {
992 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
993 use serde::ser::{Error as _, SerializeMap};
994 let mut map = serializer.serialize_map(None)?;
995 map.serialize_entry("id", &self.id)?;
996 map.serialize_entry("type", &self.kind)?;
997 if let Some(title) = &self.title {
998 map.serialize_entry("title", title)?;
999 }
1000 if let Some(parent) = &self.parent {
1001 map.serialize_entry("parent", parent)?;
1002 }
1003 if self.policy.on_error != ErrorStrategy::Fail {
1004 map.serialize_entry("on_error", &self.policy.on_error)?;
1005 }
1006 if self.policy.retry != RetryPolicy::default() {
1007 map.serialize_entry("retry", &self.policy.retry)?;
1008 }
1009 if let Some(ms) = self.policy.timeout_ms {
1010 map.serialize_entry("timeout_ms", &ms)?;
1011 }
1012 for (key, value) in &self.config {
1013 if matches!(key.as_str(), "id" | "type" | "title" | "parent") || POLICY_KEYS.contains(&key.as_str()) {
1014 return Err(S::Error::custom(format!("node `{}`: config key `{key}` is reserved", self.id)));
1015 }
1016 map.serialize_entry(key, value)?;
1017 }
1018 map.end()
1019 }
1020}
1021
1022impl Workflow {
1023 pub fn to_json(&self) -> Result<String, DocumentError> {
1025 Ok(serde_json::to_string(self)?)
1026 }
1027
1028 pub fn canonical_graph_json(&self) -> Result<String, DocumentError> {
1031 let value = serde_json::to_value(&self.graph)?;
1032 Ok(serde_json::to_string(&canonicalize(value))?)
1033 }
1034}
1035
1036fn canonicalize(value: serde_json::Value) -> serde_json::Value {
1038 match value {
1039 serde_json::Value::Object(map) => {
1040 let mut entries: Vec<(String, serde_json::Value)> = map.into_iter().collect();
1041 entries.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1042 serde_json::Value::Object(entries.into_iter().map(|(k, v)| (k, canonicalize(v))).collect())
1043 }
1044 serde_json::Value::Array(items) => serde_json::Value::Array(items.into_iter().map(canonicalize).collect()),
1045 other => other,
1046 }
1047}
1048
1049#[cfg(test)]
1050mod roundtrip_tests {
1051 use super::*;
1052
1053 const DOC: &str = r#"{"name":"demo","env":[{"name":"K","type":"secret"}],"graph":{"nodes":[
1054 {"id":"s","type":"start","variables":[]},
1055 {"id":"h","type":"custom","data":{"type":"http-request","title":"Call","url":"https://x",
1056 "error_strategy":"default-value","default_value":{"body":"none"},
1057 "retry_config":{"retry_enabled":true,"max_retries":2,"retry_interval":10},"timeout_ms":500}},
1058 {"id":"b","type":"code","parentId":"it"}],
1059 "edges":[{"source":"s","target":"h","sourceHandle":"source"}]}}"#;
1060
1061 #[test]
1062 fn workflow_round_trips() {
1063 let a = Workflow::from_json(DOC).unwrap();
1064 let text = a.to_json().unwrap();
1065 let b = Workflow::from_json(&text).unwrap();
1066 assert_eq!(text, b.to_json().unwrap());
1067 let h = &b.graph.nodes[1];
1068 assert_eq!(h.kind, "http-request");
1069 assert_eq!(h.title.as_deref(), Some("Call"));
1070 assert_eq!(h.policy, a.graph.nodes[1].policy);
1071 assert_eq!(h.policy.timeout_ms, Some(500));
1072 assert_eq!(h.config.get("url"), Some(&serde_json::json!("https://x")));
1073 assert!(!h.config.contains_key("config"));
1074 assert_eq!(b.graph.nodes[2].parent.as_deref(), Some("it"));
1075 assert_eq!(a.canonical_graph_json().unwrap(), b.canonical_graph_json().unwrap());
1076 }
1077
1078 #[test]
1079 fn canonical_json_ignores_key_order() {
1080 let a = Workflow::from_json(r#"{"graph":{"nodes":[{"id":"s","type":"start","x":1,"y":2}],"edges":[]}}"#);
1081 let b = Workflow::from_json(r#"{"graph":{"nodes":[{"y":2,"x":1,"type":"start","id":"s"}],"edges":[]}}"#);
1082 assert_eq!(a.unwrap().canonical_graph_json().unwrap(), b.unwrap().canonical_graph_json().unwrap());
1083 }
1084
1085 #[test]
1086 fn typos_are_errors() {
1087 let bad_strategy = r#"{"graph":{"nodes":[{"id":"s","type":"start","error_strategy":"fail-brnch"}]}}"#;
1088 assert!(matches!(Workflow::from_json(bad_strategy), Err(DocumentError::Node { .. })));
1089 let bad_timeout = r#"{"graph":{"nodes":[{"id":"s","type":"start","timeout_ms":"5s"}]}}"#;
1090 assert!(matches!(Workflow::from_json(bad_timeout), Err(DocumentError::Node { .. })));
1091 let none = r#"{"graph":{"nodes":[{"id":"s","type":"start","error_strategy":"none"}]}}"#;
1092 assert!(Workflow::from_json(none).is_ok());
1093 }
1094}