modelrelay 6.5.0

Rust SDK for the ModelRelay API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
use std::collections::BTreeMap;

use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::errors::{Error, Result, ValidationError};
use crate::responses::ResponseBuilder;
use crate::types::InputItem;
use crate::workflow::{
    ConditionV1, EdgeV1, ExecutionV1, NodeId, NodeTypeV1, NodeV1, OutputRefV1, WorkflowKind,
    WorkflowSpecV1,
};

// =============================================================================
// Binding Target Validation
// =============================================================================

fn validate_binding_targets_v1(
    node_id: &NodeId,
    input: &[InputItem],
    bindings: &[LlmResponsesBindingV1],
) -> Result<()> {
    let pattern = Regex::new(r"^/input/(\d+)(?:/content/(\d+))?").unwrap();

    for (i, binding) in bindings.iter().enumerate() {
        let to = match &binding.to {
            Some(t) => t,
            None => continue,
        };

        if !to.starts_with("/input/") {
            continue;
        }

        let captures = match pattern.captures(to) {
            Some(c) => c,
            None => continue,
        };

        let msg_index: usize = captures
            .get(1)
            .and_then(|m| m.as_str().parse().ok())
            .unwrap_or(0);

        if msg_index >= input.len() {
            return Err(Error::Validation(ValidationError::new(format!(
                "node \"{}\" binding {}: targets {} but request only has {} messages (indices 0-{}); add placeholder messages or adjust binding target",
                node_id,
                i,
                to,
                input.len(),
                input.len().saturating_sub(1)
            ))));
        }

        if let Some(content_match) = captures.get(2) {
            let content_index: usize = content_match.as_str().parse().unwrap_or(0);
            let content_len = match &input[msg_index] {
                InputItem::Message { content, .. } => content.len(),
            };
            if content_index >= content_len {
                return Err(Error::Validation(ValidationError::new(format!(
                    "node \"{}\" binding {}: targets {} but message {} only has {} content blocks (indices 0-{})",
                    node_id,
                    i,
                    to,
                    msg_index,
                    content_len,
                    content_len.saturating_sub(1)
                ))));
            }
        }
    }

    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LlmResponsesBindingEncodingV1 {
    Json,
    JsonString,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ToolExecutionModeV1 {
    Server,
    Client,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolExecutionV1 {
    pub mode: ToolExecutionModeV1,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct LlmResponsesToolLimitsV1 {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_llm_calls: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tool_calls_per_step: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wait_ttl_ms: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LlmResponsesBindingV1 {
    pub from: NodeId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pointer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_placeholder: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<LlmResponsesBindingEncodingV1>,
}

impl LlmResponsesBindingV1 {
    pub fn json(from: NodeId, pointer: Option<String>, to: impl Into<String>) -> Self {
        Self {
            from,
            pointer,
            to: Some(to.into()),
            to_placeholder: None,
            encoding: None,
        }
    }

    pub fn json_string(from: NodeId, pointer: Option<String>, to: impl Into<String>) -> Self {
        Self {
            from,
            pointer,
            to: Some(to.into()),
            to_placeholder: None,
            encoding: Some(LlmResponsesBindingEncodingV1::JsonString),
        }
    }

    pub fn placeholder(
        from: NodeId,
        pointer: Option<String>,
        placeholder_name: impl Into<String>,
    ) -> Self {
        Self {
            from,
            pointer,
            to: None,
            to_placeholder: Some(placeholder_name.into()),
            encoding: Some(LlmResponsesBindingEncodingV1::JsonString),
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct LlmResponsesNodeOptionsV1 {
    pub stream: Option<bool>,
    pub bindings: Option<Vec<LlmResponsesBindingV1>>,
    pub tool_execution: Option<ToolExecutionV1>,
    pub tool_limits: Option<LlmResponsesToolLimitsV1>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TransformJsonValueV1 {
    pub from: NodeId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pointer: Option<String>,
}

impl TransformJsonValueV1 {
    pub fn new(from: NodeId, pointer: Option<String>) -> Self {
        Self { from, pointer }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TransformJsonInputV1 {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub object: Option<BTreeMap<String, TransformJsonValueV1>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merge: Option<Vec<TransformJsonValueV1>>,
}

impl TransformJsonInputV1 {
    pub fn object(fields: BTreeMap<String, TransformJsonValueV1>) -> Self {
        Self {
            object: Some(fields),
            merge: None,
        }
    }

    pub fn merge(items: Vec<TransformJsonValueV1>) -> Self {
        Self {
            object: None,
            merge: Some(items),
        }
    }

    pub fn validate(&self) -> Result<()> {
        let has_object = self.object.as_ref().map(|m| !m.is_empty()).unwrap_or(false);
        let has_merge = self.merge.as_ref().map(|m| !m.is_empty()).unwrap_or(false);

        match (has_object, has_merge) {
            (true, false) => Ok(()),
            (false, true) => Ok(()),
            (false, false) => Err(Error::Validation(ValidationError::new(
                "transform.json input requires either object or merge",
            ))),
            (true, true) => Err(Error::Validation(ValidationError::new(
                "transform.json input must not set both object and merge",
            ))),
        }
    }

    pub fn validate_map_fanout(&self) -> Result<()> {
        self.validate()?;
        if let Some(ref object) = self.object {
            for (key, value) in object {
                if key.trim().is_empty() {
                    continue;
                }
                if value.from.as_str() != "item" {
                    return Err(Error::Validation(ValidationError::new(format!(
                        "map.fanout transform.json object.{key}.from must be \"item\""
                    ))));
                }
            }
        }
        if let Some(ref merge) = self.merge {
            for (idx, value) in merge.iter().enumerate() {
                if value.from.as_str() != "item" {
                    return Err(Error::Validation(ValidationError::new(format!(
                        "map.fanout transform.json merge[{idx}].from must be \"item\""
                    ))));
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MapFanoutItemsV1 {
    pub from: NodeId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MapFanoutItemBindingV1 {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_placeholder: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<LlmResponsesBindingEncodingV1>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MapFanoutSubNodeV1 {
    pub id: NodeId,
    #[serde(rename = "type")]
    pub node_type: NodeTypeV1,
    pub input: Value,
}

impl MapFanoutSubNodeV1 {
    pub fn llm_responses(
        id: NodeId,
        request: ResponseBuilder,
        options: LlmResponsesNodeOptionsV1,
    ) -> Result<Self> {
        let req = request.payload.into_request();
        req.validate(true)?;

        let mut input = json!({ "request": req });
        if let Some(s) = options.stream {
            input["stream"] = Value::Bool(s);
        }
        if let Some(exec) = options.tool_execution {
            let raw = serde_json::to_value(exec).map_err(|err| {
                Error::Validation(ValidationError::new(format!(
                    "invalid llm.responses tool_execution: {err}"
                )))
            })?;
            input["tool_execution"] = raw;
        }
        if let Some(limits) = options.tool_limits {
            let raw = serde_json::to_value(limits).map_err(|err| {
                Error::Validation(ValidationError::new(format!(
                    "invalid llm.responses tool_limits: {err}"
                )))
            })?;
            input["tool_limits"] = raw;
        }
        if let Some(bs) = options.bindings {
            if !bs.is_empty() {
                let raw = serde_json::to_value(bs).map_err(|err| {
                    Error::Validation(ValidationError::new(format!(
                        "invalid llm.responses bindings: {err}"
                    )))
                })?;
                input["bindings"] = raw;
            }
        }

        Ok(Self {
            id,
            node_type: NodeTypeV1::LlmResponses,
            input,
        })
    }

    pub fn route_switch(
        id: NodeId,
        request: ResponseBuilder,
        options: LlmResponsesNodeOptionsV1,
    ) -> Result<Self> {
        let req = request.payload.into_request();
        req.validate(true)?;

        let mut input = json!({ "request": req });
        if let Some(s) = options.stream {
            input["stream"] = Value::Bool(s);
        }
        if let Some(exec) = options.tool_execution {
            let raw = serde_json::to_value(exec).map_err(|err| {
                Error::Validation(ValidationError::new(format!(
                    "invalid route.switch tool_execution: {err}"
                )))
            })?;
            input["tool_execution"] = raw;
        }
        if let Some(limits) = options.tool_limits {
            let raw = serde_json::to_value(limits).map_err(|err| {
                Error::Validation(ValidationError::new(format!(
                    "invalid route.switch tool_limits: {err}"
                )))
            })?;
            input["tool_limits"] = raw;
        }
        if let Some(bs) = options.bindings {
            if !bs.is_empty() {
                let raw = serde_json::to_value(bs).map_err(|err| {
                    Error::Validation(ValidationError::new(format!(
                        "invalid route.switch bindings: {err}"
                    )))
                })?;
                input["bindings"] = raw;
            }
        }

        Ok(Self {
            id,
            node_type: NodeTypeV1::RouteSwitch,
            input,
        })
    }

    pub fn transform_json(id: NodeId, input: TransformJsonInputV1) -> Result<Self> {
        input.validate()?;
        let raw = serde_json::to_value(&input).map_err(|err| {
            Error::Validation(ValidationError::new(format!(
                "invalid transform.json input: {err}"
            )))
        })?;

        Ok(Self {
            id,
            node_type: NodeTypeV1::TransformJson,
            input: raw,
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MapFanoutInputV1 {
    pub items: MapFanoutItemsV1,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item_bindings: Option<Vec<MapFanoutItemBindingV1>>,
    pub subnode: MapFanoutSubNodeV1,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_parallelism: Option<i64>,
}

impl MapFanoutInputV1 {
    pub fn validate(&self) -> Result<()> {
        match self.subnode.node_type {
            NodeTypeV1::LlmResponses | NodeTypeV1::RouteSwitch => {
                if let Some(bindings) = self.subnode.input.get("bindings") {
                    if bindings.as_array().map(|b| !b.is_empty()).unwrap_or(false) {
                        return Err(Error::Validation(ValidationError::new(
                            "map.fanout subnode bindings are not allowed",
                        )));
                    }
                }
            }
            NodeTypeV1::TransformJson => {
                if self
                    .item_bindings
                    .as_ref()
                    .map(|b| !b.is_empty())
                    .unwrap_or(false)
                {
                    return Err(Error::Validation(ValidationError::new(
                        "map.fanout transform.json cannot use item_bindings",
                    )));
                }
                let input: TransformJsonInputV1 =
                    serde_json::from_value(self.subnode.input.clone()).map_err(|err| {
                        Error::Validation(ValidationError::new(format!(
                            "map.fanout transform.json input must be valid JSON: {err}"
                        )))
                    })?;
                input.validate_map_fanout()?;
            }
            _ => {
                return Err(Error::Validation(ValidationError::new(
                    "unsupported map.fanout subnode type",
                )))
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JoinAnyInputV1 {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub predicate: Option<ConditionV1>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JoinCollectInputV1 {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub predicate: Option<ConditionV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<i64>,
}

#[derive(Clone, Debug, Default)]
pub struct WorkflowBuilderV1 {
    name: Option<String>,
    execution: Option<ExecutionV1>,
    nodes: Vec<NodeV1>,
    edges: Vec<EdgeV1>,
    outputs: Vec<OutputRefV1>,
}

impl WorkflowBuilderV1 {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        let trimmed = name.into();
        let out = trimmed.trim().to_string();
        self.name = if out.is_empty() { None } else { Some(out) };
        self
    }

    #[must_use]
    pub fn execution(mut self, exec: ExecutionV1) -> Self {
        self.execution = Some(exec);
        self
    }

    pub fn llm_responses(
        self,
        id: NodeId,
        request: ResponseBuilder,
        stream: Option<bool>,
    ) -> Result<Self> {
        self.llm_responses_with_options(id, request, stream, None, None, None)
    }

    pub fn llm_responses_with_bindings(
        self,
        id: NodeId,
        request: ResponseBuilder,
        stream: Option<bool>,
        bindings: Option<Vec<LlmResponsesBindingV1>>,
    ) -> Result<Self> {
        self.llm_responses_with_options(id, request, stream, bindings, None, None)
    }

    pub fn llm_responses_with_options(
        mut self,
        id: NodeId,
        request: ResponseBuilder,
        stream: Option<bool>,
        bindings: Option<Vec<LlmResponsesBindingV1>>,
        tool_execution: Option<ToolExecutionV1>,
        tool_limits: Option<LlmResponsesToolLimitsV1>,
    ) -> Result<Self> {
        let req = request.payload.into_request();
        req.validate(true)?;

        if let Some(ref bs) = bindings {
            if !bs.is_empty() {
                validate_binding_targets_v1(&id, &req.input, bs)?;
            }
        }

        let mut input = json!({ "request": req });
        if let Some(s) = stream {
            input["stream"] = Value::Bool(s);
        }
        if let Some(exec) = tool_execution {
            input["tool_execution"] = serde_json::to_value(exec).map_err(|err| {
                Error::Validation(ValidationError::new(format!(
                    "invalid llm.responses tool_execution: {err}"
                )))
            })?;
        }
        if let Some(limits) = tool_limits {
            input["tool_limits"] = serde_json::to_value(limits).map_err(|err| {
                Error::Validation(ValidationError::new(format!(
                    "invalid llm.responses tool_limits: {err}"
                )))
            })?;
        }
        if let Some(bs) = bindings {
            if !bs.is_empty() {
                input["bindings"] = serde_json::to_value(bs).map_err(|err| {
                    Error::Validation(ValidationError::new(format!(
                        "invalid llm.responses bindings: {err}"
                    )))
                })?;
            }
        }

        self.nodes.push(NodeV1 {
            id,
            node_type: NodeTypeV1::LlmResponses,
            input: Some(input),
        });
        Ok(self)
    }

    pub fn route_switch(
        mut self,
        id: NodeId,
        request: ResponseBuilder,
        stream: Option<bool>,
        bindings: Option<Vec<LlmResponsesBindingV1>>,
    ) -> Result<Self> {
        let req = request.payload.into_request();
        req.validate(true)?;

        if let Some(ref bs) = bindings {
            if !bs.is_empty() {
                validate_binding_targets_v1(&id, &req.input, bs)?;
            }
        }

        let mut input = json!({ "request": req });
        if let Some(s) = stream {
            input["stream"] = Value::Bool(s);
        }
        if let Some(bs) = bindings {
            if !bs.is_empty() {
                input["bindings"] = serde_json::to_value(bs).map_err(|err| {
                    Error::Validation(ValidationError::new(format!(
                        "invalid route.switch bindings: {err}"
                    )))
                })?;
            }
        }

        self.nodes.push(NodeV1 {
            id,
            node_type: NodeTypeV1::RouteSwitch,
            input: Some(input),
        });
        Ok(self)
    }

    #[must_use]
    pub fn join_all(mut self, id: NodeId) -> Self {
        self.nodes.push(NodeV1 {
            id,
            node_type: NodeTypeV1::JoinAll,
            input: None,
        });
        self
    }

    pub fn join_any(mut self, id: NodeId, input: Option<JoinAnyInputV1>) -> Result<Self> {
        let raw = match input {
            Some(val) => Some(serde_json::to_value(val).map_err(|err| {
                Error::Validation(ValidationError::new(format!(
                    "invalid join.any input: {err}"
                )))
            })?),
            None => None,
        };
        self.nodes.push(NodeV1 {
            id,
            node_type: NodeTypeV1::JoinAny,
            input: raw,
        });
        Ok(self)
    }

    pub fn join_collect(mut self, id: NodeId, input: JoinCollectInputV1) -> Result<Self> {
        let raw = serde_json::to_value(input).map_err(|err| {
            Error::Validation(ValidationError::new(format!(
                "invalid join.collect input: {err}"
            )))
        })?;
        self.nodes.push(NodeV1 {
            id,
            node_type: NodeTypeV1::JoinCollect,
            input: Some(raw),
        });
        Ok(self)
    }

    pub fn transform_json(mut self, id: NodeId, input: TransformJsonInputV1) -> Result<Self> {
        input.validate()?;
        let raw = serde_json::to_value(input).map_err(|err| {
            Error::Validation(ValidationError::new(format!(
                "invalid transform.json input: {err}"
            )))
        })?;
        self.nodes.push(NodeV1 {
            id,
            node_type: NodeTypeV1::TransformJson,
            input: Some(raw),
        });
        Ok(self)
    }

    pub fn map_fanout(mut self, id: NodeId, input: MapFanoutInputV1) -> Result<Self> {
        input.validate()?;
        let raw = serde_json::to_value(input).map_err(|err| {
            Error::Validation(ValidationError::new(format!(
                "invalid map.fanout input: {err}"
            )))
        })?;
        self.nodes.push(NodeV1 {
            id,
            node_type: NodeTypeV1::MapFanout,
            input: Some(raw),
        });
        Ok(self)
    }

    #[must_use]
    pub fn edge(mut self, from: NodeId, to: NodeId) -> Self {
        self.edges.push(EdgeV1 {
            from,
            to,
            when: None,
        });
        self
    }

    #[must_use]
    pub fn edge_when(mut self, from: NodeId, to: NodeId, when: ConditionV1) -> Self {
        self.edges.push(EdgeV1 {
            from,
            to,
            when: Some(when),
        });
        self
    }

    #[must_use]
    pub fn output(
        mut self,
        name: impl Into<String>,
        from: NodeId,
        pointer: Option<String>,
    ) -> Self {
        self.outputs.push(OutputRefV1 {
            name: name.into(),
            from,
            pointer,
        });
        self
    }

    pub fn build(self) -> Result<WorkflowSpecV1> {
        let mut edges = self.edges;
        edges.sort_by(|a, b| {
            let af = a.from.as_str();
            let bf = b.from.as_str();
            if af != bf {
                return af.cmp(bf);
            }
            let at = a.to.as_str();
            let bt = b.to.as_str();
            if at != bt {
                return at.cmp(bt);
            }
            let aw = a
                .when
                .as_ref()
                .map(|w| serde_json::to_string(w).unwrap_or_default())
                .unwrap_or_default();
            let bw = b
                .when
                .as_ref()
                .map(|w| serde_json::to_string(w).unwrap_or_default())
                .unwrap_or_default();
            aw.cmp(&bw)
        });

        let mut outputs = self.outputs;
        outputs.sort_by(|a, b| {
            let an = a.name.as_str();
            let bn = b.name.as_str();
            if an != bn {
                return an.cmp(bn);
            }
            let af = a.from.as_str();
            let bf = b.from.as_str();
            if af != bf {
                return af.cmp(bf);
            }
            let ap = a.pointer.as_deref().unwrap_or("");
            let bp = b.pointer.as_deref().unwrap_or("");
            ap.cmp(bp)
        });

        Ok(WorkflowSpecV1 {
            kind: WorkflowKind::WorkflowV1,
            name: self.name,
            execution: self.execution,
            nodes: self.nodes,
            edges: if edges.is_empty() { None } else { Some(edges) },
            outputs,
        })
    }
}

pub fn workflow_v1() -> WorkflowBuilderV1 {
    WorkflowBuilderV1::new()
}