oxify-model 0.1.0

Data models and types for OxiFY workflows, execution, and configuration
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
//! Workflow builder for fluent workflow construction
//!
//! This module provides a builder pattern for constructing workflows
//! with a clean, fluent API.

use crate::{
    ApprovalConfig, Condition, Edge, FormConfig, LlmConfig, LoopConfig, McpConfig, Node, NodeId,
    NodeKind, ParallelConfig, RetryConfig, ScriptConfig, SubWorkflowConfig, SwitchConfig,
    TimeoutConfig, TryCatchConfig, VectorConfig, Workflow,
};

/// Builder for constructing workflows
pub struct WorkflowBuilder {
    workflow: Workflow,
    last_node_id: Option<NodeId>,
}

impl WorkflowBuilder {
    /// Create a new workflow builder
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            workflow: Workflow::new(name.into()),
            last_node_id: None,
        }
    }

    /// Set the workflow description
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.workflow.metadata.description = Some(description.into());
        self
    }

    /// Set the workflow version
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.workflow.metadata.version = version.into();
        self
    }

    /// Add a tag to the workflow
    pub fn tag(mut self, tag: impl Into<String>) -> Self {
        self.workflow.metadata.tags.push(tag.into());
        self
    }

    /// Add multiple tags to the workflow
    pub fn tags(mut self, tags: Vec<String>) -> Self {
        self.workflow.metadata.tags.extend(tags);
        self
    }

    /// Add a start node
    pub fn start(mut self, name: impl Into<String>) -> Self {
        let node = Node::new(name.into(), NodeKind::Start);
        self.last_node_id = Some(node.id);
        self.workflow.add_node(node);
        self
    }

    /// Add an end node
    pub fn end(mut self, name: impl Into<String>) -> Self {
        let node = Node::new(name.into(), NodeKind::End);
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add an LLM node
    pub fn llm(mut self, name: impl Into<String>, config: LlmConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::LLM(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a code execution node
    pub fn code(mut self, name: impl Into<String>, config: ScriptConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Code(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a retriever (vector search) node
    pub fn retriever(mut self, name: impl Into<String>, config: VectorConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Retriever(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add an if-else conditional node
    pub fn if_else(mut self, name: impl Into<String>, condition: Condition) -> Self {
        let node = Node::new(name.into(), NodeKind::IfElse(condition));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a tool (MCP) node
    pub fn tool(mut self, name: impl Into<String>, config: McpConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Tool(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a loop node
    pub fn loop_node(mut self, name: impl Into<String>, config: LoopConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Loop(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a try-catch node
    pub fn try_catch(mut self, name: impl Into<String>, config: TryCatchConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::TryCatch(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a sub-workflow node
    pub fn sub_workflow(mut self, name: impl Into<String>, config: SubWorkflowConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::SubWorkflow(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a switch node
    pub fn switch(mut self, name: impl Into<String>, config: SwitchConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Switch(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a parallel execution node
    pub fn parallel(mut self, name: impl Into<String>, config: ParallelConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Parallel(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add an approval node
    pub fn approval(mut self, name: impl Into<String>, config: ApprovalConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Approval(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a form input node
    pub fn form(mut self, name: impl Into<String>, config: FormConfig) -> Self {
        let node = Node::new(name.into(), NodeKind::Form(config));
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add a custom node (low-level API)
    pub fn node(mut self, node: Node) -> Self {
        let node_id = node.id;
        self.workflow.add_node(node);

        // Auto-connect from last node if exists
        if let Some(from_id) = self.last_node_id {
            self.workflow.add_edge(Edge::new(from_id, node_id));
        }

        self.last_node_id = Some(node_id);
        self
    }

    /// Add an edge between two nodes by their indices (0-based)
    pub fn connect(mut self, from_index: usize, to_index: usize) -> Self {
        if from_index < self.workflow.nodes.len() && to_index < self.workflow.nodes.len() {
            let from_id = self.workflow.nodes[from_index].id;
            let to_id = self.workflow.nodes[to_index].id;
            self.workflow.add_edge(Edge::new(from_id, to_id));
        }
        self
    }

    /// Add an edge between two nodes by their IDs
    pub fn connect_ids(mut self, from_id: NodeId, to_id: NodeId) -> Self {
        self.workflow.add_edge(Edge::new(from_id, to_id));
        self
    }

    /// Get the ID of the last added node
    pub fn last_node_id(&self) -> Option<NodeId> {
        self.last_node_id
    }

    /// Get the ID of a node by its index (0-based)
    pub fn node_id_at(&self, index: usize) -> Option<NodeId> {
        self.workflow.nodes.get(index).map(|n| n.id)
    }

    /// Build the workflow
    pub fn build(self) -> Workflow {
        self.workflow
    }
}

/// Node builder for configuring individual nodes with retry and timeout
pub struct NodeBuilder {
    node: Node,
}

impl NodeBuilder {
    /// Create a new node builder
    pub fn new(name: impl Into<String>, kind: NodeKind) -> Self {
        Self {
            node: Node::new(name.into(), kind),
        }
    }

    /// Set retry configuration
    pub fn retry(mut self, config: RetryConfig) -> Self {
        self.node.retry_config = Some(config);
        self
    }

    /// Set timeout configuration
    pub fn timeout(mut self, config: TimeoutConfig) -> Self {
        self.node.timeout_config = Some(config);
        self
    }

    /// Set node position in visual editor
    pub fn position(mut self, x: f64, y: f64) -> Self {
        self.node.position = Some((x, y));
        self
    }

    /// Build the node
    pub fn build(self) -> Node {
        self.node
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_workflow_builder_basic() {
        let workflow = WorkflowBuilder::new("Test Workflow")
            .description("A test workflow")
            .version("1.0.0")
            .tag("test")
            .start("Start")
            .end("End")
            .build();

        assert_eq!(workflow.metadata.name, "Test Workflow");
        assert_eq!(
            workflow.metadata.description,
            Some("A test workflow".to_string())
        );
        assert_eq!(workflow.metadata.version, "1.0.0");
        assert_eq!(workflow.metadata.tags, vec!["test"]);
        assert_eq!(workflow.nodes.len(), 2);
        assert_eq!(workflow.edges.len(), 1);
    }

    #[test]
    fn test_workflow_builder_with_llm() {
        let llm_config = LlmConfig {
            provider: "openai".to_string(),
            model: "gpt-4".to_string(),
            system_prompt: None,
            prompt_template: "Hello {{input}}".to_string(),
            temperature: Some(0.7),
            max_tokens: Some(100),
            tools: vec![],
            images: vec![],
            extra_params: serde_json::json!({}),
        };

        let workflow = WorkflowBuilder::new("LLM Workflow")
            .start("Start")
            .llm("Generate", llm_config)
            .end("End")
            .build();

        assert_eq!(workflow.nodes.len(), 3);
        assert_eq!(workflow.edges.len(), 2);

        // Check that LLM node exists
        let llm_node = &workflow.nodes[1];
        assert_eq!(llm_node.name, "Generate");
        assert!(matches!(llm_node.kind, NodeKind::LLM(_)));
    }

    #[test]
    fn test_workflow_builder_with_code() {
        let script_config = ScriptConfig {
            runtime: "rust".to_string(),
            code: "println!(\"Hello\");".to_string(),
            inputs: vec![],
            output: "result".to_string(),
        };

        let workflow = WorkflowBuilder::new("Code Workflow")
            .start("Start")
            .code("Execute", script_config)
            .end("End")
            .build();

        assert_eq!(workflow.nodes.len(), 3);
        assert_eq!(workflow.edges.len(), 2);
    }

    #[test]
    fn test_workflow_builder_custom_connections() {
        let workflow = WorkflowBuilder::new("Custom Connections")
            .start("Start")
            .end("End")
            .connect(0, 1) // Connect start to end
            .build();

        assert_eq!(workflow.edges.len(), 2); // Auto-connect + manual connect
    }

    #[test]
    fn test_node_builder() {
        let retry_config = RetryConfig {
            max_retries: 3,
            initial_delay_ms: 1000,
            backoff_multiplier: 2.0,
            max_delay_ms: 30000,
        };

        let timeout_config = TimeoutConfig {
            execution_timeout_ms: 60000,
            idle_timeout_ms: None,
            timeout_action: crate::TimeoutAction::Fail,
        };

        let node = NodeBuilder::new("Test Node", NodeKind::Start)
            .retry(retry_config)
            .timeout(timeout_config)
            .position(100.0, 200.0)
            .build();

        assert_eq!(node.name, "Test Node");
        assert!(node.retry_config.is_some());
        assert!(node.timeout_config.is_some());
        assert_eq!(node.position, Some((100.0, 200.0)));
    }

    #[test]
    fn test_workflow_builder_multiple_tags() {
        let workflow = WorkflowBuilder::new("Tagged Workflow")
            .tags(vec!["tag1".to_string(), "tag2".to_string()])
            .tag("tag3")
            .build();

        assert_eq!(workflow.metadata.tags.len(), 3);
        assert!(workflow.metadata.tags.contains(&"tag1".to_string()));
        assert!(workflow.metadata.tags.contains(&"tag2".to_string()));
        assert!(workflow.metadata.tags.contains(&"tag3".to_string()));
    }

    #[test]
    fn test_workflow_builder_get_node_ids() {
        let builder = WorkflowBuilder::new("Test").start("Start").end("End");

        assert!(builder.last_node_id().is_some());
        assert!(builder.node_id_at(0).is_some());
        assert!(builder.node_id_at(1).is_some());
        assert!(builder.node_id_at(2).is_none());
    }

    #[test]
    fn test_workflow_builder_if_else() {
        use uuid::Uuid;

        let true_branch_id = Uuid::new_v4();
        let false_branch_id = Uuid::new_v4();

        let condition = Condition {
            expression: "{{value}} > 10".to_string(),
            true_branch: true_branch_id,
            false_branch: false_branch_id,
        };

        let workflow = WorkflowBuilder::new("Conditional Workflow")
            .start("Start")
            .if_else("Check Value", condition)
            .end("End")
            .build();

        assert_eq!(workflow.nodes.len(), 3);
        assert!(matches!(workflow.nodes[1].kind, NodeKind::IfElse(_)));
    }

    #[test]
    fn test_workflow_builder_auto_connect() {
        let llm_config = LlmConfig {
            provider: "openai".to_string(),
            model: "gpt-4".to_string(),
            system_prompt: None,
            prompt_template: "test".to_string(),
            temperature: None,
            max_tokens: None,
            tools: vec![],
            images: vec![],
            extra_params: serde_json::json!({}),
        };

        let workflow = WorkflowBuilder::new("Auto Connect Test")
            .start("Start")
            .llm("LLM1", llm_config.clone())
            .llm("LLM2", llm_config)
            .end("End")
            .build();

        // Should have 4 nodes and 3 auto-connected edges
        assert_eq!(workflow.nodes.len(), 4);
        assert_eq!(workflow.edges.len(), 3);
    }
}