Skip to main content

conductor/models/
workflow_def.rs

1// Copyright {{.Year}} Conductor OSS
2// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
3
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6
7/// Workflow timeout policy.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
10pub enum WorkflowTimeoutPolicy {
11    /// Timeout the workflow.
12    #[default]
13    TimeOutWf,
14    /// Alert only.
15    AlertOnly,
16}
17
18/// Task type in a workflow.
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
21pub enum TaskType {
22    /// Simple task executed by a worker.
23    #[default]
24    Simple,
25    /// Dynamic task.
26    Dynamic,
27    /// Fork task for parallel execution.
28    ForkJoin,
29    /// Fork dynamic task.
30    ForkJoinDynamic,
31    /// Decision task (deprecated, use Switch).
32    Decision,
33    /// Switch task for branching.
34    Switch,
35    /// Join task.
36    Join,
37    /// Do-while loop task.
38    DoWhile,
39    /// Subworkflow task.
40    SubWorkflow,
41    /// Event task.
42    Event,
43    /// Wait task.
44    Wait,
45    /// Human task.
46    Human,
47    /// User defined task.
48    UserDefined,
49    /// HTTP task.
50    Http,
51    /// HTTP Poll task.
52    #[serde(rename = "HTTP_POLL")]
53    HttpPoll,
54    /// Lambda task.
55    Lambda,
56    /// Inline task (JavaScript).
57    Inline,
58    /// Exclusive join task.
59    ExclusiveJoin,
60    /// Terminate task.
61    Terminate,
62    /// Kafka publish task.
63    KafkaPublish,
64    /// JSON JQ transform task.
65    JsonJqTransform,
66    /// Set variable task.
67    SetVariable,
68    /// Start workflow task.
69    StartWorkflow,
70    /// Wait for webhook task.
71    #[serde(rename = "WAIT_FOR_WEBHOOK")]
72    WaitForWebhook,
73    /// LLM text complete task.
74    #[serde(rename = "LLM_TEXT_COMPLETE")]
75    LlmTextComplete,
76    /// LLM chat complete task.
77    #[serde(rename = "LLM_CHAT_COMPLETE")]
78    LlmChatComplete,
79    /// LLM generate embeddings task.
80    #[serde(rename = "LLM_GENERATE_EMBEDDINGS")]
81    LlmGenerateEmbeddings,
82    /// LLM index text task.
83    #[serde(rename = "LLM_INDEX_TEXT")]
84    LlmIndexText,
85    /// LLM index document task.
86    #[serde(rename = "LLM_INDEX_DOCUMENT")]
87    LlmIndexDocument,
88    /// LLM search index task.
89    #[serde(rename = "LLM_SEARCH_INDEX")]
90    LlmSearchIndex,
91    /// LLM query embeddings task.
92    #[serde(rename = "LLM_GET_EMBEDDINGS")]
93    LlmGetEmbeddings,
94    /// LLM store embeddings task.
95    #[serde(rename = "LLM_STORE_EMBEDDINGS")]
96    LlmStoreEmbeddings,
97    /// Search a vector database using a pre-computed embedding vector (as opposed to
98    /// [`TaskType::LlmSearchIndex`], which searches by query text).
99    #[serde(rename = "LLM_SEARCH_EMBEDDINGS")]
100    LlmSearchEmbeddings,
101    /// Generate an image using an LLM provider.
102    #[serde(rename = "GENERATE_IMAGE")]
103    GenerateImage,
104    /// Generate audio (text-to-speech) using an LLM provider.
105    #[serde(rename = "GENERATE_AUDIO")]
106    GenerateAudio,
107    /// List available tools from an MCP (Model Context Protocol) server.
108    #[serde(rename = "LIST_MCP_TOOLS")]
109    ListMcpTools,
110    /// Call a tool on an MCP server.
111    #[serde(rename = "CALL_MCP_TOOL")]
112    CallMcpTool,
113    /// Get document task.
114    #[serde(rename = "GET_DOCUMENT")]
115    GetDocument,
116    /// No-op task.
117    Noop,
118    /// Update task (Orkes) -- update another task's status/output within a workflow.
119    #[serde(rename = "UPDATE_TASK")]
120    UpdateTask,
121    /// Get workflow task (Orkes) -- fetch a workflow's state from within a workflow.
122    #[serde(rename = "GET_WORKFLOW")]
123    GetWorkflow,
124    /// Update secret task (Orkes).
125    #[serde(rename = "UPDATE_SECRET")]
126    UpdateSecret,
127    /// Publish metric task (Orkes).
128    #[serde(rename = "PUBLISH_METRIC")]
129    PublishMetric,
130    /// Query processor task (Orkes).
131    #[serde(rename = "QUERY_PROCESSOR")]
132    QueryProcessor,
133    /// JDBC task (Orkes).
134    Jdbc,
135    /// Business rule task (Orkes).
136    #[serde(rename = "BUSINESS_RULE")]
137    BusinessRule,
138    /// AWS Lambda task (Orkes).
139    #[serde(rename = "AWS_LAMBDA")]
140    AwsLambda,
141    /// `OpsGenie` task (Orkes).
142    #[serde(rename = "OPS_GENIE")]
143    OpsGenie,
144    /// `SendGrid` email task (Orkes).
145    Sendgrid,
146    /// Wait until task (Orkes).
147    #[serde(rename = "WAIT_UNTIL")]
148    WaitUntil,
149    /// MCP remote task (Orkes).
150    #[serde(rename = "MCP_REMOTE")]
151    McpRemote,
152    /// Start workflow batch task (Orkes).
153    #[serde(rename = "START_WORKFLOW_BATCH")]
154    StartWorkflowBatch,
155    /// Unrecognized task type from the server.
156    #[serde(other)]
157    Other,
158}
159
160/// A task definition within a workflow.
161#[derive(Debug, Clone, Default, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase")]
163pub struct WorkflowTask {
164    /// Task name.
165    pub name: String,
166
167    /// Task reference name (unique within workflow).
168    pub task_reference_name: String,
169
170    /// Task type.
171    #[serde(rename = "type")]
172    pub task_type: TaskType,
173
174    /// Input parameters.
175    #[serde(default)]
176    pub input_parameters: HashMap<String, serde_json::Value>,
177
178    /// Description.
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub description: Option<String>,
181
182    /// Dynamic task name (for dynamic tasks).
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub dynamic_task_name_param: Option<String>,
185
186    /// Case value (for switch tasks).
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub case_value_param: Option<String>,
189
190    /// Case expression (for switch tasks).
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub case_expression: Option<String>,
193
194    /// Script expression (for inline tasks).
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub script_expression: Option<String>,
197
198    /// Decision cases (for switch tasks).
199    #[serde(default)]
200    pub decision_cases: HashMap<String, Vec<WorkflowTask>>,
201
202    /// Dynamic fork tasks param (for `fork_join_dynamic`).
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub dynamic_fork_tasks_param: Option<String>,
205
206    /// Dynamic fork tasks input param name.
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub dynamic_fork_tasks_input_param_name: Option<String>,
209
210    /// Default case (for switch tasks).
211    #[serde(default)]
212    pub default_case: Vec<WorkflowTask>,
213
214    /// Fork tasks (for `fork_join`).
215    #[serde(default)]
216    pub fork_tasks: Vec<Vec<WorkflowTask>>,
217
218    /// Start delay seconds.
219    #[serde(default)]
220    pub start_delay: i32,
221
222    /// Subworkflow param (for subworkflow tasks).
223    #[serde(skip_serializing_if = "Option::is_none")]
224    pub sub_workflow_param: Option<SubWorkflowParams>,
225
226    /// Join on (for join tasks).
227    #[serde(default)]
228    pub join_on: Vec<String>,
229
230    /// Sink (for event tasks).
231    #[serde(skip_serializing_if = "Option::is_none")]
232    pub sink: Option<String>,
233
234    /// Optional task flag.
235    #[serde(default)]
236    pub optional: bool,
237
238    /// Async complete flag (for wait tasks).
239    #[serde(default)]
240    pub async_complete: bool,
241
242    /// Default exclusive join task (for `exclusive_join`).
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub default_exclusive_join_task: Option<Vec<String>>,
245
246    /// Loop condition (for `do_while`).
247    #[serde(skip_serializing_if = "Option::is_none")]
248    pub loop_condition: Option<String>,
249
250    /// Loop over (for `do_while`).
251    #[serde(default)]
252    pub loop_over: Vec<WorkflowTask>,
253
254    /// Retry count.
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub retry_count: Option<i32>,
257
258    /// Evaluator type (for inline tasks).
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub evaluator_type: Option<String>,
261
262    /// Expression (for inline tasks).
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub expression: Option<String>,
265
266    /// Rate limited flag.
267    #[serde(default)]
268    pub rate_limited: bool,
269
270    /// Join on script (for join tasks with custom script).
271    #[serde(skip_serializing_if = "Option::is_none")]
272    pub join_on_script: Option<String>,
273
274    /// State change configuration (for audit events).
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub on_state_change: Option<StateChangeConfig>,
277
278    /// Inline task definition (for embedded task defs).
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub task_definition: Option<EmbeddedTaskDef>,
281}
282
283/// Configuration for state change events on tasks.
284#[derive(Debug, Clone, Default, Serialize, Deserialize)]
285#[serde(rename_all = "camelCase")]
286pub struct StateChangeConfig {
287    /// Event types to trigger on.
288    #[serde(default)]
289    pub event_type: Vec<StateChangeEventType>,
290
291    /// Events to dispatch.
292    #[serde(default)]
293    pub events: Vec<StateChangeEvent>,
294}
295
296impl StateChangeConfig {
297    /// Create a new state change config.
298    #[must_use]
299    pub fn new() -> Self {
300        Self::default()
301    }
302
303    /// Add an event type.
304    #[must_use]
305    pub fn on_event(mut self, event_type: StateChangeEventType) -> Self {
306        self.event_type.push(event_type);
307        self
308    }
309
310    /// Add an event to dispatch.
311    #[must_use]
312    pub fn with_event(mut self, event: StateChangeEvent) -> Self {
313        self.events.push(event);
314        self
315    }
316}
317
318/// State change event types.
319#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
320#[serde(rename_all = "camelCase")]
321pub enum StateChangeEventType {
322    /// On task scheduled.
323    OnScheduled,
324    /// On task started.
325    OnStart,
326    /// On task failed.
327    OnFailed,
328    /// On task completed.
329    OnCompleted,
330    /// On task cancelled.
331    OnCancelled,
332}
333
334/// Event to dispatch on state change.
335#[derive(Debug, Clone, Default, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337pub struct StateChangeEvent {
338    /// Task type to dispatch (task name).
339    #[serde(rename = "type")]
340    pub event_type: String,
341
342    /// Payload for the task.
343    #[serde(default)]
344    pub payload: HashMap<String, serde_json::Value>,
345}
346
347impl StateChangeEvent {
348    /// Create a new state change event.
349    pub fn new(task_type: impl Into<String>) -> Self {
350        Self {
351            event_type: task_type.into(),
352            payload: HashMap::new(),
353        }
354    }
355
356    /// Add a payload parameter.
357    #[must_use]
358    pub fn with_payload(
359        mut self,
360        key: impl Into<String>,
361        value: impl Into<serde_json::Value>,
362    ) -> Self {
363        self.payload.insert(key.into(), value.into());
364        self
365    }
366}
367
368/// Embedded task definition (for inline task defs in workflow tasks).
369#[derive(Debug, Clone, Default, Serialize, Deserialize)]
370#[serde(rename_all = "camelCase")]
371pub struct EmbeddedTaskDef {
372    /// Task name.
373    #[serde(default)]
374    pub name: String,
375
376    /// Retry count.
377    #[serde(default)]
378    pub retry_count: i32,
379
380    /// Timeout seconds.
381    #[serde(default)]
382    pub timeout_seconds: i64,
383
384    /// Response timeout seconds.
385    #[serde(default)]
386    pub response_timeout_seconds: i64,
387}
388
389impl EmbeddedTaskDef {
390    /// Create a new embedded task def.
391    pub fn new(name: impl Into<String>) -> Self {
392        Self {
393            name: name.into(),
394            ..Default::default()
395        }
396    }
397
398    /// Set retry count.
399    #[must_use]
400    pub fn with_retry_count(mut self, count: i32) -> Self {
401        self.retry_count = count;
402        self
403    }
404
405    /// Set timeout.
406    #[must_use]
407    pub fn with_timeout(mut self, seconds: i64) -> Self {
408        self.timeout_seconds = seconds;
409        self
410    }
411}
412
413impl WorkflowTask {
414    /// Create a simple task.
415    pub fn simple(name: impl Into<String>, task_ref_name: impl Into<String>) -> Self {
416        Self {
417            name: name.into(),
418            task_reference_name: task_ref_name.into(),
419            task_type: TaskType::Simple,
420            ..Default::default()
421        }
422    }
423
424    /// Create a subworkflow task.
425    pub fn sub_workflow(
426        task_ref_name: impl Into<String>,
427        workflow_name: impl Into<String>,
428    ) -> Self {
429        Self {
430            name: "sub_workflow".to_owned(),
431            task_reference_name: task_ref_name.into(),
432            task_type: TaskType::SubWorkflow,
433            sub_workflow_param: Some(SubWorkflowParams {
434                name: workflow_name.into(),
435                version: None,
436                task_to_domain: HashMap::new(),
437            }),
438            ..Default::default()
439        }
440    }
441
442    /// Create a wait task.
443    pub fn wait(task_ref_name: impl Into<String>) -> Self {
444        Self {
445            name: "wait".to_owned(),
446            task_reference_name: task_ref_name.into(),
447            task_type: TaskType::Wait,
448            ..Default::default()
449        }
450    }
451
452    /// Create an HTTP task.
453    pub fn http(task_ref_name: impl Into<String>, uri: impl Into<String>) -> Self {
454        let http_request = serde_json::json!({
455            "uri": uri.into(),
456            "method": "GET"
457        });
458
459        let mut input = HashMap::new();
460        input.insert("http_request".to_owned(), http_request);
461
462        Self {
463            name: "http".to_owned(),
464            task_reference_name: task_ref_name.into(),
465            task_type: TaskType::Http,
466            input_parameters: input,
467            ..Default::default()
468        }
469    }
470
471    /// Create a `LIST_MCP_TOOLS` task — lists available tools from an MCP server.
472    pub fn list_mcp_tools(
473        task_ref_name: impl Into<String>,
474        mcp_server: impl Into<String>,
475        headers: Option<HashMap<String, String>>,
476    ) -> Self {
477        let mut input = HashMap::new();
478        input.insert(
479            "mcpServer".to_owned(),
480            serde_json::Value::String(mcp_server.into()),
481        );
482        if let Some(headers) = headers {
483            input.insert(
484                "headers".to_owned(),
485                serde_json::to_value(headers).unwrap_or_default(),
486            );
487        }
488
489        Self {
490            name: "list_mcp_tools".to_owned(),
491            task_reference_name: task_ref_name.into(),
492            task_type: TaskType::ListMcpTools,
493            input_parameters: input,
494            ..Default::default()
495        }
496    }
497
498    /// Create an inline JavaScript task.
499    pub fn inline(task_ref_name: impl Into<String>, script: impl Into<String>) -> Self {
500        let mut input = HashMap::new();
501        input.insert(
502            "expression".to_owned(),
503            serde_json::Value::String(script.into()),
504        );
505        input.insert(
506            "evaluatorType".to_owned(),
507            serde_json::Value::String("graaljs".to_owned()),
508        );
509
510        Self {
511            name: "inline".to_owned(),
512            task_reference_name: task_ref_name.into(),
513            task_type: TaskType::Inline,
514            input_parameters: input,
515            ..Default::default()
516        }
517    }
518
519    /// Set input parameters.
520    #[must_use]
521    pub fn with_input(mut self, input: HashMap<String, serde_json::Value>) -> Self {
522        self.input_parameters = input;
523        self
524    }
525
526    /// Add a single input parameter.
527    #[must_use]
528    pub fn with_input_param(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
529        self.input_parameters.insert(
530            key.into(),
531            serde_json::to_value(value).unwrap_or(serde_json::Value::Null),
532        );
533        self
534    }
535
536    /// Set description.
537    #[must_use]
538    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
539        self.description = Some(desc.into());
540        self
541    }
542
543    /// Mark as optional.
544    #[must_use]
545    pub fn optional(mut self) -> Self {
546        self.optional = true;
547        self
548    }
549
550    /// Create a switch (decision) task with JavaScript expression.
551    pub fn switch(task_ref_name: impl Into<String>, case_expression: impl Into<String>) -> Self {
552        Self {
553            name: "switch".to_owned(),
554            task_reference_name: task_ref_name.into(),
555            task_type: TaskType::Switch,
556            expression: Some(case_expression.into()),
557            evaluator_type: Some("javascript".to_owned()),
558            ..Default::default()
559        }
560    }
561
562    /// Create a switch (decision) task with `value_param` evaluator.
563    ///
564    /// Use this for simple value expressions like ${workflow.input.choice}
565    /// The `evaluator_type` is set to "value-param" which directly evaluates the expression.
566    pub fn switch_value_param(
567        task_ref_name: impl Into<String>,
568        case_expression: impl Into<String>,
569    ) -> Self {
570        Self {
571            name: "switch".to_owned(),
572            task_reference_name: task_ref_name.into(),
573            task_type: TaskType::Switch,
574            expression: Some(case_expression.into()),
575            evaluator_type: Some("value-param".to_owned()),
576            ..Default::default()
577        }
578    }
579
580    /// Add a switch case.
581    #[must_use]
582    pub fn with_switch_case(
583        mut self,
584        case_value: impl Into<String>,
585        tasks: Vec<WorkflowTask>,
586    ) -> Self {
587        self.decision_cases.insert(case_value.into(), tasks);
588        self
589    }
590
591    /// Set default case for switch.
592    #[must_use]
593    pub fn with_default_case(mut self, tasks: Vec<WorkflowTask>) -> Self {
594        self.default_case = tasks;
595        self
596    }
597
598    /// Create a fork task for parallel execution.
599    pub fn fork(task_ref_name: impl Into<String>, branches: Vec<Vec<WorkflowTask>>) -> Self {
600        Self {
601            name: "fork".to_owned(),
602            task_reference_name: task_ref_name.into(),
603            task_type: TaskType::ForkJoin,
604            fork_tasks: branches,
605            ..Default::default()
606        }
607    }
608
609    /// Create a join task.
610    pub fn join(task_ref_name: impl Into<String>, join_on: Vec<String>) -> Self {
611        Self {
612            name: "join".to_owned(),
613            task_reference_name: task_ref_name.into(),
614            task_type: TaskType::Join,
615            join_on,
616            ..Default::default()
617        }
618    }
619
620    /// Create a set variable task.
621    pub fn set_variable(task_ref_name: impl Into<String>) -> Self {
622        Self {
623            name: "set_variable".to_owned(),
624            task_reference_name: task_ref_name.into(),
625            task_type: TaskType::SetVariable,
626            ..Default::default()
627        }
628    }
629
630    /// Create a terminate task.
631    pub fn terminate(task_ref_name: impl Into<String>, status: impl Into<String>) -> Self {
632        let mut input = HashMap::new();
633        input.insert(
634            "terminationStatus".to_owned(),
635            serde_json::Value::String(status.into()),
636        );
637
638        Self {
639            name: "terminate".to_owned(),
640            task_reference_name: task_ref_name.into(),
641            task_type: TaskType::Terminate,
642            input_parameters: input,
643            ..Default::default()
644        }
645    }
646
647    /// Set termination reason.
648    #[must_use]
649    pub fn with_termination_reason(mut self, reason: impl Into<String>) -> Self {
650        self.input_parameters.insert(
651            "terminationReason".to_owned(),
652            serde_json::Value::String(reason.into()),
653        );
654        self
655    }
656
657    /// Create a JSON JQ transform task.
658    pub fn json_jq_transform(task_ref_name: impl Into<String>, query: impl Into<String>) -> Self {
659        let mut input = HashMap::new();
660        input.insert(
661            "queryExpression".to_owned(),
662            serde_json::Value::String(query.into()),
663        );
664
665        Self {
666            name: "json_jq_transform".to_owned(),
667            task_reference_name: task_ref_name.into(),
668            task_type: TaskType::JsonJqTransform,
669            input_parameters: input,
670            ..Default::default()
671        }
672    }
673
674    /// Create a wait task with duration.
675    pub fn wait_duration(task_ref_name: impl Into<String>, duration: impl Into<String>) -> Self {
676        let mut input = HashMap::new();
677        input.insert(
678            "duration".to_owned(),
679            serde_json::Value::String(duration.into()),
680        );
681
682        Self {
683            name: "wait".to_owned(),
684            task_reference_name: task_ref_name.into(),
685            task_type: TaskType::Wait,
686            input_parameters: input,
687            ..Default::default()
688        }
689    }
690
691    /// Create an event task.
692    pub fn event(task_ref_name: impl Into<String>, sink: impl Into<String>) -> Self {
693        Self {
694            name: "event".to_owned(),
695            task_reference_name: task_ref_name.into(),
696            task_type: TaskType::Event,
697            sink: Some(sink.into()),
698            ..Default::default()
699        }
700    }
701
702    /// Create a do-while loop task.
703    pub fn do_while(
704        task_ref_name: impl Into<String>,
705        loop_condition: impl Into<String>,
706        loop_tasks: Vec<WorkflowTask>,
707    ) -> Self {
708        Self {
709            name: "do_while".to_owned(),
710            task_reference_name: task_ref_name.into(),
711            task_type: TaskType::DoWhile,
712            loop_condition: Some(loop_condition.into()),
713            loop_over: loop_tasks,
714            ..Default::default()
715        }
716    }
717
718    /// Create a human task.
719    pub fn human(task_ref_name: impl Into<String>) -> Self {
720        Self {
721            name: "human".to_owned(),
722            task_reference_name: task_ref_name.into(),
723            task_type: TaskType::Human,
724            ..Default::default()
725        }
726    }
727
728    /// Set async complete (for wait tasks).
729    #[must_use]
730    pub fn async_complete(mut self) -> Self {
731        self.async_complete = true;
732        self
733    }
734
735    /// Set start delay in seconds.
736    #[must_use]
737    pub fn with_start_delay(mut self, seconds: i32) -> Self {
738        self.start_delay = seconds;
739        self
740    }
741
742    /// Set state change configuration for audit events.
743    #[must_use]
744    pub fn with_state_change(mut self, config: StateChangeConfig) -> Self {
745        self.on_state_change = Some(config);
746        self
747    }
748
749    /// Set embedded task definition.
750    #[must_use]
751    pub fn with_task_definition(mut self, task_def: EmbeddedTaskDef) -> Self {
752        self.task_definition = Some(task_def);
753        self
754    }
755
756    /// Create a join task with custom script.
757    pub fn join_with_script(
758        task_ref_name: impl Into<String>,
759        join_on: Vec<String>,
760        script: impl Into<String>,
761    ) -> Self {
762        Self {
763            name: "join".to_owned(),
764            task_reference_name: task_ref_name.into(),
765            task_type: TaskType::Join,
766            join_on,
767            join_on_script: Some(script.into()),
768            ..Default::default()
769        }
770    }
771
772    /// Create an HTTP Poll task.
773    pub fn http_poll(task_ref_name: impl Into<String>, uri: impl Into<String>) -> Self {
774        let http_request = serde_json::json!({
775            "uri": uri.into(),
776            "method": "GET",
777            "pollingStrategy": "FIXED",
778            "pollingInterval": 1000
779        });
780
781        let mut input = HashMap::new();
782        input.insert("http_request".to_owned(), http_request);
783
784        Self {
785            name: "http_poll".to_owned(),
786            task_reference_name: task_ref_name.into(),
787            task_type: TaskType::HttpPoll,
788            input_parameters: input,
789            ..Default::default()
790        }
791    }
792
793    /// Set polling strategy (FIXED, `LINEAR_BACKOFF`, or `EXPONENTIAL_BACKOFF`).
794    #[must_use]
795    pub fn with_polling_strategy(mut self, strategy: impl Into<String>) -> Self {
796        if let Some(req) = self.input_parameters.get_mut("http_request") {
797            req["pollingStrategy"] = serde_json::json!(strategy.into());
798        }
799        self
800    }
801
802    /// Set polling interval in seconds.
803    #[must_use]
804    pub fn with_polling_interval(mut self, interval_secs: i64) -> Self {
805        if let Some(req) = self.input_parameters.get_mut("http_request") {
806            req["pollingInterval"] = serde_json::json!(interval_secs);
807        }
808        self
809    }
810
811    /// Set termination condition script for HTTP Poll.
812    #[must_use]
813    pub fn with_termination_condition(mut self, script: impl Into<String>) -> Self {
814        if let Some(req) = self.input_parameters.get_mut("http_request") {
815            req["terminationCondition"] = serde_json::json!(script.into());
816        }
817        self
818    }
819
820    /// Create a wait for webhook task.
821    pub fn wait_for_webhook(task_ref_name: impl Into<String>) -> Self {
822        Self {
823            name: "wait_for_webhook".to_owned(),
824            task_reference_name: task_ref_name.into(),
825            task_type: TaskType::WaitForWebhook,
826            ..Default::default()
827        }
828    }
829
830    /// Set webhook matches configuration.
831    #[must_use]
832    pub fn with_matches(mut self, matches: HashMap<String, String>) -> Self {
833        let matches_value: HashMap<String, serde_json::Value> = matches
834            .into_iter()
835            .map(|(k, v)| (k, serde_json::json!(v)))
836            .collect();
837        self.input_parameters
838            .insert("matches".to_owned(), serde_json::json!(matches_value));
839        self
840    }
841
842    /// Create an LLM text complete task.
843    pub fn llm_text_complete(
844        task_ref_name: impl Into<String>,
845        llm_provider: impl Into<String>,
846        model: impl Into<String>,
847        prompt_name: impl Into<String>,
848    ) -> Self {
849        let mut input = HashMap::new();
850        input.insert(
851            "llmProvider".to_owned(),
852            serde_json::json!(llm_provider.into()),
853        );
854        input.insert("model".to_owned(), serde_json::json!(model.into()));
855        input.insert(
856            "promptName".to_owned(),
857            serde_json::json!(prompt_name.into()),
858        );
859
860        Self {
861            name: "llm_text_complete".to_owned(),
862            task_reference_name: task_ref_name.into(),
863            task_type: TaskType::LlmTextComplete,
864            input_parameters: input,
865            ..Default::default()
866        }
867    }
868
869    /// Create an LLM chat complete task.
870    pub fn llm_chat_complete(
871        task_ref_name: impl Into<String>,
872        llm_provider: impl Into<String>,
873        model: impl Into<String>,
874    ) -> Self {
875        let mut input = HashMap::new();
876        input.insert(
877            "llmProvider".to_owned(),
878            serde_json::json!(llm_provider.into()),
879        );
880        input.insert("model".to_owned(), serde_json::json!(model.into()));
881        input.insert("messages".to_owned(), serde_json::json!([]));
882
883        Self {
884            name: "llm_chat_complete".to_owned(),
885            task_reference_name: task_ref_name.into(),
886            task_type: TaskType::LlmChatComplete,
887            input_parameters: input,
888            ..Default::default()
889        }
890    }
891
892    /// Set instructions template for LLM tasks.
893    #[must_use]
894    pub fn with_instructions_template(mut self, template_name: impl Into<String>) -> Self {
895        self.input_parameters.insert(
896            "instructionsTemplate".to_owned(),
897            serde_json::json!(template_name.into()),
898        );
899        self
900    }
901
902    /// Set messages for chat complete.
903    #[must_use]
904    pub fn with_messages(mut self, messages: Vec<ChatMessage>) -> Self {
905        self.input_parameters.insert(
906            "messages".to_owned(),
907            serde_json::to_value(messages).unwrap_or_default(),
908        );
909        self
910    }
911
912    /// Set temperature for LLM tasks.
913    #[must_use]
914    pub fn with_temperature(mut self, temp: f32) -> Self {
915        self.input_parameters
916            .insert("temperature".to_owned(), serde_json::json!(temp));
917        self
918    }
919
920    /// Set max tokens for LLM tasks.
921    #[must_use]
922    pub fn with_max_tokens(mut self, tokens: i32) -> Self {
923        self.input_parameters
924            .insert("maxTokens".to_owned(), serde_json::json!(tokens));
925        self
926    }
927
928    /// Set `top_p` for LLM tasks.
929    #[must_use]
930    pub fn with_top_p(mut self, top_p: f32) -> Self {
931        self.input_parameters
932            .insert("topP".to_owned(), serde_json::json!(top_p));
933        self
934    }
935
936    /// Set prompt variables for LLM tasks.
937    #[must_use]
938    pub fn with_prompt_variables(mut self, variables: HashMap<String, serde_json::Value>) -> Self {
939        self.input_parameters
940            .insert("promptVariables".to_owned(), serde_json::json!(variables));
941        self
942    }
943
944    /// Add a single prompt variable.
945    #[must_use]
946    pub fn with_prompt_variable(
947        mut self,
948        key: impl Into<String>,
949        value: impl Into<serde_json::Value>,
950    ) -> Self {
951        let vars = self
952            .input_parameters
953            .entry("promptVariables".to_owned())
954            .or_insert_with(|| serde_json::json!({}));
955        if let serde_json::Value::Object(map) = vars {
956            map.insert(key.into(), value.into());
957        }
958        self
959    }
960
961    /// Create an LLM generate embeddings task.
962    pub fn llm_generate_embeddings(
963        task_ref_name: impl Into<String>,
964        llm_provider: impl Into<String>,
965        model: impl Into<String>,
966        text: impl Into<String>,
967    ) -> Self {
968        let mut input = HashMap::new();
969        input.insert(
970            "llmProvider".to_owned(),
971            serde_json::json!(llm_provider.into()),
972        );
973        input.insert("model".to_owned(), serde_json::json!(model.into()));
974        input.insert("text".to_owned(), serde_json::json!(text.into()));
975
976        Self {
977            name: "llm_generate_embeddings".to_owned(),
978            task_reference_name: task_ref_name.into(),
979            task_type: TaskType::LlmGenerateEmbeddings,
980            input_parameters: input,
981            ..Default::default()
982        }
983    }
984
985    /// Create an LLM search index task.
986    pub fn llm_search_index(
987        task_ref_name: impl Into<String>,
988        vector_db: impl Into<String>,
989        index: impl Into<String>,
990        query: impl Into<String>,
991    ) -> Self {
992        let mut input = HashMap::new();
993        input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
994        input.insert("index".to_owned(), serde_json::json!(index.into()));
995        input.insert("query".to_owned(), serde_json::json!(query.into()));
996
997        Self {
998            name: "llm_search_index".to_owned(),
999            task_reference_name: task_ref_name.into(),
1000            task_type: TaskType::LlmSearchIndex,
1001            input_parameters: input,
1002            ..Default::default()
1003        }
1004    }
1005
1006    /// Create an LLM search-by-embedding task -- searches a vector database using a
1007    /// pre-computed embedding vector, as opposed to [`WorkflowTask::llm_search_index`], which
1008    /// searches by query text.
1009    pub fn llm_search_embeddings(
1010        task_ref_name: impl Into<String>,
1011        vector_db: impl Into<String>,
1012        index: impl Into<String>,
1013        embeddings: Vec<f64>,
1014    ) -> Self {
1015        let mut input = HashMap::new();
1016        input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
1017        input.insert("index".to_owned(), serde_json::json!(index.into()));
1018        input.insert("embeddings".to_owned(), serde_json::json!(embeddings));
1019        input.insert("maxResults".to_owned(), serde_json::json!(1));
1020
1021        Self {
1022            name: "llm_search_embeddings".to_owned(),
1023            task_reference_name: task_ref_name.into(),
1024            task_type: TaskType::LlmSearchEmbeddings,
1025            input_parameters: input,
1026            ..Default::default()
1027        }
1028    }
1029
1030    /// Create an image-generation task.
1031    pub fn generate_image(
1032        task_ref_name: impl Into<String>,
1033        llm_provider: impl Into<String>,
1034        model: impl Into<String>,
1035        prompt: impl Into<String>,
1036    ) -> Self {
1037        let mut input = HashMap::new();
1038        input.insert(
1039            "llmProvider".to_owned(),
1040            serde_json::json!(llm_provider.into()),
1041        );
1042        input.insert("model".to_owned(), serde_json::json!(model.into()));
1043        input.insert("prompt".to_owned(), serde_json::json!(prompt.into()));
1044        input.insert("width".to_owned(), serde_json::json!(1024));
1045        input.insert("height".to_owned(), serde_json::json!(1024));
1046        input.insert("n".to_owned(), serde_json::json!(1));
1047        input.insert("outputFormat".to_owned(), serde_json::json!("png"));
1048
1049        Self {
1050            name: "generate_image".to_owned(),
1051            task_reference_name: task_ref_name.into(),
1052            task_type: TaskType::GenerateImage,
1053            input_parameters: input,
1054            ..Default::default()
1055        }
1056    }
1057
1058    /// Create an audio-generation (text-to-speech) task.
1059    pub fn generate_audio(
1060        task_ref_name: impl Into<String>,
1061        llm_provider: impl Into<String>,
1062        model: impl Into<String>,
1063    ) -> Self {
1064        let mut input = HashMap::new();
1065        input.insert(
1066            "llmProvider".to_owned(),
1067            serde_json::json!(llm_provider.into()),
1068        );
1069        input.insert("model".to_owned(), serde_json::json!(model.into()));
1070        input.insert("n".to_owned(), serde_json::json!(1));
1071
1072        Self {
1073            name: "generate_audio".to_owned(),
1074            task_reference_name: task_ref_name.into(),
1075            task_type: TaskType::GenerateAudio,
1076            input_parameters: input,
1077            ..Default::default()
1078        }
1079    }
1080
1081    /// Set namespace for vector DB tasks.
1082    #[must_use]
1083    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
1084        self.input_parameters
1085            .insert("namespace".to_owned(), serde_json::json!(namespace.into()));
1086        self
1087    }
1088
1089    /// Set max results for search tasks.
1090    #[must_use]
1091    pub fn with_max_results(mut self, max: i32) -> Self {
1092        self.input_parameters
1093            .insert("maxResults".to_owned(), serde_json::json!(max));
1094        self
1095    }
1096
1097    /// Set embedding model for vector DB tasks.
1098    #[must_use]
1099    pub fn with_embedding_model(
1100        mut self,
1101        provider: impl Into<String>,
1102        model: impl Into<String>,
1103    ) -> Self {
1104        self.input_parameters.insert(
1105            "embeddingModelProvider".to_owned(),
1106            serde_json::json!(provider.into()),
1107        );
1108        self.input_parameters
1109            .insert("embeddingModel".to_owned(), serde_json::json!(model.into()));
1110        self
1111    }
1112
1113    /// Set embedding vector dimensions, for [`WorkflowTask::llm_search_embeddings`].
1114    #[must_use]
1115    pub fn with_dimensions(mut self, dimensions: i32) -> Self {
1116        self.input_parameters
1117            .insert("dimensions".to_owned(), serde_json::json!(dimensions));
1118        self
1119    }
1120
1121    /// Set the number of outputs to generate, for [`WorkflowTask::generate_image`]/
1122    /// [`WorkflowTask::generate_audio`].
1123    #[must_use]
1124    pub fn with_n(mut self, n: i32) -> Self {
1125        self.input_parameters
1126            .insert("n".to_owned(), serde_json::json!(n));
1127        self
1128    }
1129
1130    /// Override the default `1024`x`1024` size, for [`WorkflowTask::generate_image`].
1131    #[must_use]
1132    pub fn with_image_dimensions(mut self, width: i32, height: i32) -> Self {
1133        self.input_parameters
1134            .insert("width".to_owned(), serde_json::json!(width));
1135        self.input_parameters
1136            .insert("height".to_owned(), serde_json::json!(height));
1137        self
1138    }
1139
1140    /// Set a size specification (e.g. `"1024x1024"`), as an alternative to
1141    /// [`WorkflowTask::with_image_dimensions`], for [`WorkflowTask::generate_image`].
1142    #[must_use]
1143    pub fn with_size(mut self, size: impl Into<String>) -> Self {
1144        self.input_parameters
1145            .insert("size".to_owned(), serde_json::json!(size.into()));
1146        self
1147    }
1148
1149    /// Set image style (e.g. `"natural"`, `"vivid"`), for [`WorkflowTask::generate_image`].
1150    #[must_use]
1151    pub fn with_style(mut self, style: impl Into<String>) -> Self {
1152        self.input_parameters
1153            .insert("style".to_owned(), serde_json::json!(style.into()));
1154        self
1155    }
1156
1157    /// Set the image weight parameter, for [`WorkflowTask::generate_image`].
1158    #[must_use]
1159    pub fn with_weight(mut self, weight: f64) -> Self {
1160        self.input_parameters
1161            .insert("weight".to_owned(), serde_json::json!(weight));
1162        self
1163    }
1164
1165    /// Override the default `"png"` output format, for [`WorkflowTask::generate_image`].
1166    #[must_use]
1167    pub fn with_output_format(mut self, format: impl Into<String>) -> Self {
1168        self.input_parameters
1169            .insert("outputFormat".to_owned(), serde_json::json!(format.into()));
1170        self
1171    }
1172
1173    /// Set the text to convert to speech, for [`WorkflowTask::generate_audio`].
1174    #[must_use]
1175    pub fn with_text(mut self, text: impl Into<String>) -> Self {
1176        self.input_parameters
1177            .insert("text".to_owned(), serde_json::json!(text.into()));
1178        self
1179    }
1180
1181    /// Set the voice, for [`WorkflowTask::generate_audio`].
1182    #[must_use]
1183    pub fn with_voice(mut self, voice: impl Into<String>) -> Self {
1184        self.input_parameters
1185            .insert("voice".to_owned(), serde_json::json!(voice.into()));
1186        self
1187    }
1188
1189    /// Set the speech speed multiplier, for [`WorkflowTask::generate_audio`].
1190    #[must_use]
1191    pub fn with_speed(mut self, speed: f64) -> Self {
1192        self.input_parameters
1193            .insert("speed".to_owned(), serde_json::json!(speed));
1194        self
1195    }
1196
1197    /// Set the audio response format (e.g. `"mp3"`, `"wav"`), for
1198    /// [`WorkflowTask::generate_audio`].
1199    #[must_use]
1200    pub fn with_response_format(mut self, format: impl Into<String>) -> Self {
1201        self.input_parameters.insert(
1202            "responseFormat".to_owned(),
1203            serde_json::json!(format.into()),
1204        );
1205        self
1206    }
1207
1208    /// Set an alternative prompt, for [`WorkflowTask::generate_audio`].
1209    #[must_use]
1210    pub fn with_prompt(mut self, prompt: impl Into<String>) -> Self {
1211        self.input_parameters
1212            .insert("prompt".to_owned(), serde_json::json!(prompt.into()));
1213        self
1214    }
1215
1216    /// Create an LLM index text task.
1217    pub fn llm_index_text(
1218        task_ref_name: impl Into<String>,
1219        vector_db: impl Into<String>,
1220        index: impl Into<String>,
1221        text: impl Into<String>,
1222        doc_id: impl Into<String>,
1223    ) -> Self {
1224        let mut input = HashMap::new();
1225        input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
1226        input.insert("index".to_owned(), serde_json::json!(index.into()));
1227        input.insert("text".to_owned(), serde_json::json!(text.into()));
1228        input.insert("docId".to_owned(), serde_json::json!(doc_id.into()));
1229
1230        Self {
1231            name: "llm_index_text".to_owned(),
1232            task_reference_name: task_ref_name.into(),
1233            task_type: TaskType::LlmIndexText,
1234            input_parameters: input,
1235            ..Default::default()
1236        }
1237    }
1238
1239    /// Create an LLM index document task.
1240    pub fn llm_index_document(
1241        task_ref_name: impl Into<String>,
1242        vector_db: impl Into<String>,
1243        index: impl Into<String>,
1244        url: impl Into<String>,
1245        doc_id: impl Into<String>,
1246    ) -> Self {
1247        let mut input = HashMap::new();
1248        input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
1249        input.insert("index".to_owned(), serde_json::json!(index.into()));
1250        input.insert("url".to_owned(), serde_json::json!(url.into()));
1251        input.insert("docId".to_owned(), serde_json::json!(doc_id.into()));
1252
1253        Self {
1254            name: "llm_index_document".to_owned(),
1255            task_reference_name: task_ref_name.into(),
1256            task_type: TaskType::LlmIndexDocument,
1257            input_parameters: input,
1258            ..Default::default()
1259        }
1260    }
1261
1262    /// Set media type for document tasks.
1263    #[must_use]
1264    pub fn with_media_type(mut self, media_type: impl Into<String>) -> Self {
1265        self.input_parameters
1266            .insert("mediaType".to_owned(), serde_json::json!(media_type.into()));
1267        self
1268    }
1269
1270    /// Set metadata for indexing tasks.
1271    #[must_use]
1272    pub fn with_metadata(mut self, metadata: HashMap<String, String>) -> Self {
1273        self.input_parameters
1274            .insert("metadata".to_owned(), serde_json::json!(metadata));
1275        self
1276    }
1277
1278    /// Create a dynamic task.
1279    pub fn dynamic(task_ref_name: impl Into<String>, dynamic_task_name: impl Into<String>) -> Self {
1280        let mut input = HashMap::new();
1281        input.insert(
1282            "dynamicTaskName".to_owned(),
1283            serde_json::json!(dynamic_task_name.into()),
1284        );
1285
1286        Self {
1287            name: "dynamic".to_owned(),
1288            task_reference_name: task_ref_name.into(),
1289            task_type: TaskType::Dynamic,
1290            input_parameters: input,
1291            dynamic_task_name_param: Some("dynamicTaskName".to_owned()),
1292            ..Default::default()
1293        }
1294    }
1295
1296    /// Create a get document task.
1297    pub fn get_document(task_ref_name: impl Into<String>, url: impl Into<String>) -> Self {
1298        let mut input = HashMap::new();
1299        input.insert("url".to_owned(), serde_json::json!(url.into()));
1300
1301        Self {
1302            name: "get_document".to_owned(),
1303            task_reference_name: task_ref_name.into(),
1304            task_type: TaskType::GetDocument,
1305            input_parameters: input,
1306            ..Default::default()
1307        }
1308    }
1309}
1310
1311/// Chat message for LLM chat complete.
1312#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1313#[serde(rename_all = "camelCase")]
1314pub struct ChatMessage {
1315    /// Role (user, assistant, system).
1316    pub role: String,
1317
1318    /// Message content.
1319    pub message: String,
1320}
1321
1322impl ChatMessage {
1323    /// Create a user message.
1324    pub fn user(message: impl Into<String>) -> Self {
1325        Self {
1326            role: "user".to_owned(),
1327            message: message.into(),
1328        }
1329    }
1330
1331    /// Create an assistant message.
1332    pub fn assistant(message: impl Into<String>) -> Self {
1333        Self {
1334            role: "assistant".to_owned(),
1335            message: message.into(),
1336        }
1337    }
1338
1339    /// Create a system message.
1340    pub fn system(message: impl Into<String>) -> Self {
1341        Self {
1342            role: "system".to_owned(),
1343            message: message.into(),
1344        }
1345    }
1346}
1347
1348/// Subworkflow parameters.
1349#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1350#[serde(rename_all = "camelCase")]
1351pub struct SubWorkflowParams {
1352    /// Subworkflow name.
1353    pub name: String,
1354
1355    /// Subworkflow version.
1356    #[serde(skip_serializing_if = "Option::is_none")]
1357    pub version: Option<i32>,
1358
1359    /// Task to domain mapping.
1360    #[serde(default)]
1361    pub task_to_domain: HashMap<String, String>,
1362}
1363
1364/// Workflow definition.
1365#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1366#[serde(rename_all = "camelCase")]
1367pub struct WorkflowDef {
1368    /// Workflow name.
1369    pub name: String,
1370
1371    /// Workflow description.
1372    #[serde(skip_serializing_if = "Option::is_none")]
1373    pub description: Option<String>,
1374
1375    /// Workflow version.
1376    #[serde(default = "default_version")]
1377    pub version: i32,
1378
1379    /// Tasks in the workflow.
1380    #[serde(default)]
1381    pub tasks: Vec<WorkflowTask>,
1382
1383    /// Input parameters.
1384    #[serde(default)]
1385    pub input_parameters: Vec<String>,
1386
1387    /// Output parameters.
1388    #[serde(default)]
1389    pub output_parameters: HashMap<String, serde_json::Value>,
1390
1391    /// Failure workflow name.
1392    #[serde(skip_serializing_if = "Option::is_none")]
1393    pub failure_workflow: Option<String>,
1394
1395    /// Schema version.
1396    #[serde(default = "default_schema_version")]
1397    pub schema_version: i32,
1398
1399    /// Restartable flag.
1400    #[serde(default = "default_true")]
1401    pub restartable: bool,
1402
1403    /// Workflow status listener enabled.
1404    #[serde(default)]
1405    pub workflow_status_listener_enabled: bool,
1406
1407    /// Owner email.
1408    #[serde(skip_serializing_if = "Option::is_none")]
1409    pub owner_email: Option<String>,
1410
1411    /// Timeout policy.
1412    #[serde(default)]
1413    pub timeout_policy: WorkflowTimeoutPolicy,
1414
1415    /// Timeout in seconds.
1416    #[serde(default)]
1417    pub timeout_seconds: i64,
1418
1419    /// Variables.
1420    #[serde(default)]
1421    pub variables: HashMap<String, serde_json::Value>,
1422
1423    /// Input template.
1424    #[serde(default)]
1425    pub input_template: HashMap<String, serde_json::Value>,
1426
1427    /// Created by.
1428    #[serde(skip_serializing_if = "Option::is_none")]
1429    pub created_by: Option<String>,
1430
1431    /// Update time.
1432    #[serde(skip_serializing_if = "Option::is_none")]
1433    pub update_time: Option<i64>,
1434
1435    /// Create time.
1436    #[serde(skip_serializing_if = "Option::is_none")]
1437    pub create_time: Option<i64>,
1438}
1439
1440fn default_version() -> i32 {
1441    1
1442}
1443
1444fn default_schema_version() -> i32 {
1445    2
1446}
1447
1448fn default_true() -> bool {
1449    true
1450}
1451
1452impl WorkflowDef {
1453    /// Create a new workflow definition.
1454    pub fn new(name: impl Into<String>) -> Self {
1455        Self {
1456            name: name.into(),
1457            version: 1,
1458            schema_version: 2,
1459            restartable: true,
1460            ..Default::default()
1461        }
1462    }
1463
1464    /// Set description.
1465    #[must_use]
1466    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
1467        self.description = Some(desc.into());
1468        self
1469    }
1470
1471    /// Set version.
1472    #[must_use]
1473    pub fn with_version(mut self, version: i32) -> Self {
1474        self.version = version;
1475        self
1476    }
1477
1478    /// Add a task to the workflow.
1479    #[must_use]
1480    pub fn with_task(mut self, task: WorkflowTask) -> Self {
1481        self.tasks.push(task);
1482        self
1483    }
1484
1485    /// Set tasks.
1486    #[must_use]
1487    pub fn with_tasks(mut self, tasks: Vec<WorkflowTask>) -> Self {
1488        self.tasks = tasks;
1489        self
1490    }
1491
1492    /// Set input parameters.
1493    #[must_use]
1494    pub fn with_input_parameters(mut self, params: Vec<String>) -> Self {
1495        self.input_parameters = params;
1496        self
1497    }
1498
1499    /// Set output parameters.
1500    #[must_use]
1501    pub fn with_output_parameters(mut self, params: HashMap<String, serde_json::Value>) -> Self {
1502        self.output_parameters = params;
1503        self
1504    }
1505
1506    /// Add an output parameter.
1507    #[must_use]
1508    pub fn with_output_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1509        self.output_parameters
1510            .insert(key.into(), serde_json::Value::String(value.into()));
1511        self
1512    }
1513
1514    /// Set failure workflow.
1515    #[must_use]
1516    pub fn with_failure_workflow(mut self, name: impl Into<String>) -> Self {
1517        self.failure_workflow = Some(name.into());
1518        self
1519    }
1520
1521    /// Set timeout.
1522    #[must_use]
1523    pub fn with_timeout(mut self, seconds: i64, policy: WorkflowTimeoutPolicy) -> Self {
1524        self.timeout_seconds = seconds;
1525        self.timeout_policy = policy;
1526        self
1527    }
1528
1529    /// Set owner email.
1530    #[must_use]
1531    pub fn with_owner(mut self, email: impl Into<String>) -> Self {
1532        self.owner_email = Some(email.into());
1533        self
1534    }
1535}
1536
1537#[cfg(test)]
1538mod tests {
1539    use super::*;
1540
1541    #[test]
1542    fn test_workflow_def_builder() {
1543        let wf = WorkflowDef::new("my_workflow")
1544            .with_description("Test workflow")
1545            .with_version(1)
1546            .with_task(WorkflowTask::simple("task1", "task1_ref"))
1547            .with_task(WorkflowTask::simple("task2", "task2_ref"));
1548
1549        assert_eq!(wf.name, "my_workflow");
1550        assert_eq!(wf.description, Some("Test workflow".to_owned()));
1551        assert_eq!(wf.tasks.len(), 2);
1552    }
1553
1554    #[test]
1555    fn test_workflow_task_builder() {
1556        let task = WorkflowTask::simple("my_task", "my_task_ref")
1557            .with_input_param("name", "value")
1558            .with_description("A simple task");
1559
1560        assert_eq!(task.name, "my_task");
1561        assert_eq!(task.task_reference_name, "my_task_ref");
1562        assert_eq!(task.task_type, TaskType::Simple);
1563        assert!(task.input_parameters.contains_key("name"));
1564    }
1565
1566    #[test]
1567    fn test_workflow_def_serialization() {
1568        let wf = WorkflowDef::new("test").with_task(WorkflowTask::simple("t1", "t1_ref"));
1569
1570        let json = serde_json::to_string(&wf).unwrap();
1571        assert!(json.contains("\"name\":\"test\""));
1572        assert!(json.contains("\"tasks\":["));
1573    }
1574
1575    #[test]
1576    fn test_llm_search_embeddings_task_builder() {
1577        let task = WorkflowTask::llm_search_embeddings(
1578            "search_ref",
1579            "pinecone_db",
1580            "my_index",
1581            vec![0.1, 0.2, 0.3],
1582        )
1583        .with_namespace("my_namespace")
1584        .with_dimensions(3)
1585        .with_embedding_model("openai", "text-embedding-3-small");
1586
1587        assert_eq!(task.task_type, TaskType::LlmSearchEmbeddings);
1588        assert_eq!(
1589            task.input_parameters.get("vectorDB"),
1590            Some(&serde_json::json!("pinecone_db"))
1591        );
1592        assert_eq!(
1593            task.input_parameters.get("embeddings"),
1594            Some(&serde_json::json!([0.1, 0.2, 0.3]))
1595        );
1596        assert_eq!(
1597            task.input_parameters.get("maxResults"),
1598            Some(&serde_json::json!(1))
1599        );
1600        assert_eq!(
1601            task.input_parameters.get("namespace"),
1602            Some(&serde_json::json!("my_namespace"))
1603        );
1604        assert_eq!(
1605            task.input_parameters.get("dimensions"),
1606            Some(&serde_json::json!(3))
1607        );
1608        assert_eq!(
1609            task.input_parameters.get("embeddingModel"),
1610            Some(&serde_json::json!("text-embedding-3-small"))
1611        );
1612    }
1613
1614    #[test]
1615    fn test_generate_image_task_builder_has_python_matching_defaults() {
1616        let task = WorkflowTask::generate_image("img_ref", "openai", "dall-e-3", "a cat");
1617
1618        assert_eq!(task.task_type, TaskType::GenerateImage);
1619        assert_eq!(
1620            task.input_parameters.get("prompt"),
1621            Some(&serde_json::json!("a cat"))
1622        );
1623        assert_eq!(
1624            task.input_parameters.get("width"),
1625            Some(&serde_json::json!(1024))
1626        );
1627        assert_eq!(
1628            task.input_parameters.get("height"),
1629            Some(&serde_json::json!(1024))
1630        );
1631        assert_eq!(task.input_parameters.get("n"), Some(&serde_json::json!(1)));
1632        assert_eq!(
1633            task.input_parameters.get("outputFormat"),
1634            Some(&serde_json::json!("png"))
1635        );
1636    }
1637
1638    #[test]
1639    fn test_generate_image_task_builder_overrides() {
1640        let task = WorkflowTask::generate_image("img_ref", "openai", "dall-e-3", "a cat")
1641            .with_image_dimensions(512, 512)
1642            .with_size("512x512")
1643            .with_style("vivid")
1644            .with_weight(0.5)
1645            .with_n(2)
1646            .with_output_format("jpg");
1647
1648        assert_eq!(
1649            task.input_parameters.get("width"),
1650            Some(&serde_json::json!(512))
1651        );
1652        assert_eq!(
1653            task.input_parameters.get("size"),
1654            Some(&serde_json::json!("512x512"))
1655        );
1656        assert_eq!(
1657            task.input_parameters.get("style"),
1658            Some(&serde_json::json!("vivid"))
1659        );
1660        assert_eq!(
1661            task.input_parameters.get("weight"),
1662            Some(&serde_json::json!(0.5))
1663        );
1664        assert_eq!(task.input_parameters.get("n"), Some(&serde_json::json!(2)));
1665        assert_eq!(
1666            task.input_parameters.get("outputFormat"),
1667            Some(&serde_json::json!("jpg"))
1668        );
1669    }
1670
1671    #[test]
1672    fn test_generate_audio_task_builder() {
1673        let task = WorkflowTask::generate_audio("audio_ref", "openai", "tts-1")
1674            .with_text("hello world")
1675            .with_voice("alloy")
1676            .with_speed(1.5)
1677            .with_response_format("mp3")
1678            .with_prompt("an alternative prompt");
1679
1680        assert_eq!(task.task_type, TaskType::GenerateAudio);
1681        assert_eq!(task.input_parameters.get("n"), Some(&serde_json::json!(1)));
1682        assert_eq!(
1683            task.input_parameters.get("text"),
1684            Some(&serde_json::json!("hello world"))
1685        );
1686        assert_eq!(
1687            task.input_parameters.get("voice"),
1688            Some(&serde_json::json!("alloy"))
1689        );
1690        assert_eq!(
1691            task.input_parameters.get("speed"),
1692            Some(&serde_json::json!(1.5))
1693        );
1694        assert_eq!(
1695            task.input_parameters.get("responseFormat"),
1696            Some(&serde_json::json!("mp3"))
1697        );
1698        assert_eq!(
1699            task.input_parameters.get("prompt"),
1700            Some(&serde_json::json!("an alternative prompt"))
1701        );
1702    }
1703
1704    #[test]
1705    fn test_list_mcp_tools_task_builder() {
1706        let task = WorkflowTask::list_mcp_tools("list_tools", "http://localhost:3001/mcp", None);
1707        assert_eq!(task.task_type, TaskType::ListMcpTools);
1708        assert_eq!(
1709            task.input_parameters.get("mcpServer"),
1710            Some(&serde_json::Value::String(
1711                "http://localhost:3001/mcp".to_owned()
1712            ))
1713        );
1714        assert!(!task.input_parameters.contains_key("headers"));
1715    }
1716
1717    #[test]
1718    fn test_list_mcp_tools_task_includes_headers_when_given() {
1719        let mut headers = HashMap::new();
1720        headers.insert("Authorization".to_owned(), "Bearer x".to_owned());
1721        let task = WorkflowTask::list_mcp_tools("list_tools", "http://mcp", Some(headers));
1722        assert_eq!(
1723            task.input_parameters.get("headers"),
1724            Some(&serde_json::json!({"Authorization": "Bearer x"}))
1725        );
1726    }
1727
1728    #[test]
1729    fn test_list_mcp_tools_and_call_mcp_tool_wire_strings() {
1730        assert_eq!(
1731            serde_json::to_string(&TaskType::ListMcpTools).unwrap(),
1732            "\"LIST_MCP_TOOLS\""
1733        );
1734        assert_eq!(
1735            serde_json::to_string(&TaskType::CallMcpTool).unwrap(),
1736            "\"CALL_MCP_TOOL\""
1737        );
1738    }
1739}