1use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use std::collections::{HashMap, HashSet};
10
11pub const PROTOCOL_VERSION: u32 = 1;
12pub const NODE_PROTOCOL_SCHEMA: &str =
13 include_str!("../schema/interaction-flow-node.v1.schema.json");
14pub const MAX_STEPS: usize = 64;
15pub const MAX_RESOLVERS: usize = 128;
16pub const MAX_FIELDS_PER_STEP: usize = 64;
17pub const MAX_PRESENTATION_BYTES: usize = 64 * 1024;
18pub const MAX_VALUE_REF_PATH: usize = 32;
19pub const MAX_HANDLER_ARGS: usize = 128;
20pub const MAX_OPTIONS: usize = 1024;
21pub const MAX_TITLE_CHARS: usize = 1024;
22pub const MAX_DESCRIPTION_CHARS: usize = 16 * 1024;
23pub const MAX_CONTENT_CHARS: usize = 64 * 1024;
24pub const MAX_LABEL_CHARS: usize = 1024;
25pub const MAX_UNAVAILABLE_TEXT_CHARS: usize = 4096;
26pub const MAX_MIN_ROWS: u32 = 100;
27
28pub fn definition_target(node_type: &str) -> String {
29 format!("/{node_type}/interaction-flow/definition")
30}
31
32pub fn execute_target(node_type: &str) -> String {
33 format!("/{node_type}/interaction-flow/execute")
34}
35
36pub fn complete_target(node_type: &str) -> String {
37 format!("/{node_type}/interaction-flow/complete")
38}
39
40pub fn submission_target(node_type: &str, retry: bool) -> String {
41 let action = if retry { "retry" } else { "status" };
42 format!("/{node_type}/interaction-flow/submission/{action}")
43}
44
45pub fn close_target(node_type: &str) -> String {
46 format!("/{node_type}/interaction-flow/close")
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase", deny_unknown_fields)]
51pub struct FlowValueRef {
52 pub root: String,
53 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub path: Vec<String>,
55}
56
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58#[serde(
59 tag = "type",
60 rename_all = "camelCase",
61 rename_all_fields = "camelCase",
62 deny_unknown_fields
63)]
64pub enum FlowArgument {
65 Value { value: Value },
66 Ref { value_ref: FlowValueRef },
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "camelCase")]
71pub enum FlowRenderer {
72 TypedForm,
73 #[serde(skip)]
77 CustomConnectMdx,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase", deny_unknown_fields)]
82pub struct FlowPresentation {
83 pub renderer: FlowRenderer,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub title: Option<String>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub description: Option<String>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub content: Option<String>,
90}
91
92#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase", deny_unknown_fields)]
94pub struct FlowForm {
95 #[serde(default)]
96 pub fields: Vec<FlowFormField>,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(rename_all = "camelCase")]
101pub enum FlowFieldValueType {
102 String,
103 Boolean,
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase")]
108pub enum FlowFieldControl {
109 Text,
110 Password,
111 LongText,
112 Select,
113 Boolean,
114}
115
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase", deny_unknown_fields)]
118pub struct FlowFormField {
119 pub var: String,
120 pub value_type: FlowFieldValueType,
121 pub control: FlowFieldControl,
122 #[serde(default)]
123 pub required: bool,
124 #[serde(default)]
125 pub repeat: bool,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub label: Option<String>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub default_value: Option<Value>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub default_value_ref: Option<FlowValueRef>,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub options: Option<Vec<Value>>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub options_ref: Option<FlowValueRef>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub option_unavailable_text: Option<String>,
138 #[serde(default)]
139 pub read_only: bool,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub min_rows: Option<u32>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(
146 tag = "type",
147 rename_all = "camelCase",
148 rename_all_fields = "camelCase",
149 deny_unknown_fields
150)]
151pub enum FlowTransition {
152 Step { step_id: String },
153 Dynamic { value_ref: FlowValueRef },
154 Finish,
155}
156
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase", deny_unknown_fields)]
159pub struct FlowHandler {
160 pub operation: String,
161 #[serde(default)]
162 pub args: Vec<FlowArgument>,
163}
164
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166#[serde(rename_all = "camelCase", deny_unknown_fields)]
167pub struct FlowValueResolver {
168 pub output_var: String,
169 pub handler: FlowHandler,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(rename_all = "camelCase")]
174pub enum ExternalAuthCompletionMode {
175 Callback,
176 Poll,
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
180#[serde(
181 tag = "type",
182 rename_all = "camelCase",
183 rename_all_fields = "camelCase",
184 deny_unknown_fields
185)]
186pub enum FlowStepContent {
187 Form {
188 presentation: FlowPresentation,
189 form: FlowForm,
190 #[serde(default)]
191 render_refs: Vec<FlowValueRef>,
192 },
193 ExternalAuth {
194 presentation: FlowPresentation,
195 authorization_url_ref: FlowValueRef,
196 completion_mode: ExternalAuthCompletionMode,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 poll_after_ms: Option<u64>,
199 },
200}
201
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203#[serde(rename_all = "camelCase", deny_unknown_fields)]
204pub struct InteractionFlowStep {
205 pub id: String,
206 pub content: FlowStepContent,
207 pub transition: FlowTransition,
208}
209
210#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
211#[serde(rename_all = "camelCase", deny_unknown_fields)]
212pub struct FlowLifecycleHandlers {
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub complete: Option<FlowHandler>,
215 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub cancel: Option<FlowHandler>,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub expire: Option<FlowHandler>,
219}
220
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase", deny_unknown_fields)]
223pub struct InteractionFlowDefinition {
224 pub protocol_version: u32,
225 pub flow_id: String,
226 pub start_step_id: String,
227 pub steps: HashMap<String, InteractionFlowStep>,
228 #[serde(default)]
229 pub resolvers: HashMap<String, FlowValueResolver>,
230 #[serde(default)]
231 pub lifecycle: FlowLifecycleHandlers,
232}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub struct FlowValidationError {
236 message: String,
237}
238
239impl FlowValidationError {
240 fn new(message: impl Into<String>) -> Self {
241 Self {
242 message: message.into(),
243 }
244 }
245}
246
247impl std::fmt::Display for FlowValidationError {
248 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 formatter.write_str(&self.message)
250 }
251}
252
253impl std::error::Error for FlowValidationError {}
254
255impl InteractionFlowDefinition {
256 pub fn validate(&self) -> Result<(), FlowValidationError> {
257 if self.protocol_version != PROTOCOL_VERSION {
258 return Err(FlowValidationError::new(
259 "unsupported interaction-flow protocol version",
260 ));
261 }
262 require_identifier("flow id", &self.flow_id)?;
263 require_identifier("start step id", &self.start_step_id)?;
264 if self.steps.is_empty() || self.steps.len() > MAX_STEPS {
265 return Err(FlowValidationError::new(
266 "interaction-flow step count is out of bounds",
267 ));
268 }
269 if self.resolvers.len() > MAX_RESOLVERS {
270 return Err(FlowValidationError::new(
271 "interaction-flow resolver count is out of bounds",
272 ));
273 }
274 if !self.steps.contains_key(&self.start_step_id) {
275 return Err(FlowValidationError::new(
276 "interaction-flow start step does not exist",
277 ));
278 }
279
280 let mut inputs = HashSet::new();
281 let mut input_shapes = HashMap::new();
282 for (step_key, step) in &self.steps {
283 require_identifier("step id", step_key)?;
284 if step.id != *step_key {
285 return Err(FlowValidationError::new(
286 "interaction-flow step key/id mismatch",
287 ));
288 }
289 validate_presentation(step.presentation())?;
290 if let FlowStepContent::Form { form, .. } = &step.content {
291 if form.fields.len() > MAX_FIELDS_PER_STEP {
292 return Err(FlowValidationError::new(
293 "interaction-flow field count is out of bounds",
294 ));
295 }
296 let mut step_inputs = HashSet::new();
297 for field in &form.fields {
298 require_variable("input variable", &field.var)?;
299 if is_builtin(&field.var) || !step_inputs.insert(field.var.as_str()) {
300 return Err(FlowValidationError::new(format!(
301 "duplicate or reserved interaction-flow input variable: {}",
302 field.var
303 )));
304 }
305 inputs.insert(field.var.as_str());
306 validate_field_shape(field)?;
307 if let Some((value_type, repeat)) = input_shapes.get(&field.var) {
308 if *value_type != field.value_type || *repeat != field.repeat {
309 return Err(FlowValidationError::new(format!(
310 "interaction-flow input changes value type or cardinality across steps: {}",
311 field.var
312 )));
313 }
314 } else {
315 input_shapes.insert(field.var.clone(), (field.value_type, field.repeat));
316 }
317 }
318 }
319 }
320
321 for (name, resolver) in &self.resolvers {
322 require_variable("resolver output", name)?;
323 if resolver.output_var != *name {
324 return Err(FlowValidationError::new(
325 "interaction-flow resolver key/output mismatch",
326 ));
327 }
328 if is_builtin(name) || inputs.contains(name.as_str()) {
329 return Err(FlowValidationError::new(format!(
330 "duplicate or reserved interaction-flow resolver output: {name}"
331 )));
332 }
333 }
334
335 let known = |name: &str| {
336 is_builtin(name) || inputs.contains(name) || self.resolvers.contains_key(name)
337 };
338 for step in self.steps.values() {
339 match &step.transition {
340 FlowTransition::Step { step_id } if !self.steps.contains_key(step_id) => {
341 return Err(FlowValidationError::new(format!(
342 "unknown interaction-flow step: {step_id}"
343 )));
344 }
345 FlowTransition::Dynamic { value_ref } => {
346 validate_ref(value_ref, &known)?;
347 if !self.resolvers.contains_key(&value_ref.root) {
348 return Err(FlowValidationError::new(
349 "dynamic interaction-flow transition must be resolver-backed",
350 ));
351 }
352 }
353 _ => {}
354 }
355 match &step.content {
356 FlowStepContent::Form {
357 form, render_refs, ..
358 } => {
359 for value_ref in render_refs {
360 validate_ref(value_ref, &known)?;
361 }
362 for field in &form.fields {
363 for value_ref in
364 [field.default_value_ref.as_ref(), field.options_ref.as_ref()]
365 .into_iter()
366 .flatten()
367 {
368 validate_ref(value_ref, &known)?;
369 }
370 }
371 }
372 FlowStepContent::ExternalAuth {
373 authorization_url_ref,
374 poll_after_ms,
375 completion_mode,
376 ..
377 } => {
378 validate_ref(authorization_url_ref, &known)?;
379 if matches!(completion_mode, ExternalAuthCompletionMode::Poll)
380 && poll_after_ms.is_none_or(|value| !(250..=60_000).contains(&value))
381 {
382 return Err(FlowValidationError::new(
383 "polling external-auth steps require pollAfterMs between 250 and 60000",
384 ));
385 }
386 }
387 }
388 }
389
390 for resolver in self.resolvers.values() {
391 validate_handler(&resolver.handler, &known)?;
392 }
393 for handler in [
394 self.lifecycle.complete.as_ref(),
395 self.lifecycle.cancel.as_ref(),
396 self.lifecycle.expire.as_ref(),
397 ]
398 .into_iter()
399 .flatten()
400 {
401 validate_handler(handler, &known)?;
402 }
403 validate_resolver_graph(&self.resolvers)
404 }
405}
406
407impl InteractionFlowStep {
408 pub fn presentation(&self) -> &FlowPresentation {
409 match &self.content {
410 FlowStepContent::Form { presentation, .. }
411 | FlowStepContent::ExternalAuth { presentation, .. } => presentation,
412 }
413 }
414}
415
416fn validate_presentation(presentation: &FlowPresentation) -> Result<(), FlowValidationError> {
417 if presentation
418 .title
419 .as_ref()
420 .is_some_and(|value| value.chars().count() > MAX_TITLE_CHARS)
421 || presentation
422 .description
423 .as_ref()
424 .is_some_and(|value| value.chars().count() > MAX_DESCRIPTION_CHARS)
425 || presentation
426 .content
427 .as_ref()
428 .is_some_and(|value| value.chars().count() > MAX_CONTENT_CHARS)
429 {
430 return Err(FlowValidationError::new(
431 "interaction-flow presentation field is too large",
432 ));
433 }
434 let total = presentation.title.as_deref().unwrap_or_default().len()
435 + presentation
436 .description
437 .as_deref()
438 .unwrap_or_default()
439 .len()
440 + presentation.content.as_deref().unwrap_or_default().len();
441 if total > MAX_PRESENTATION_BYTES {
442 return Err(FlowValidationError::new(
443 "interaction-flow presentation is too large",
444 ));
445 }
446 if matches!(presentation.renderer, FlowRenderer::CustomConnectMdx)
447 && presentation.content.as_deref().is_none_or(str::is_empty)
448 {
449 return Err(FlowValidationError::new(
450 "custom-connect presentation requires content",
451 ));
452 }
453 Ok(())
454}
455
456fn validate_field_shape(field: &FlowFormField) -> Result<(), FlowValidationError> {
457 if field
458 .label
459 .as_ref()
460 .is_some_and(|value| value.chars().count() > MAX_LABEL_CHARS)
461 || field
462 .option_unavailable_text
463 .as_ref()
464 .is_some_and(|value| value.chars().count() > MAX_UNAVAILABLE_TEXT_CHARS)
465 || field
466 .min_rows
467 .is_some_and(|value| value == 0 || value > MAX_MIN_ROWS)
468 || field
469 .options
470 .as_ref()
471 .is_some_and(|options| options.len() > MAX_OPTIONS)
472 {
473 return Err(FlowValidationError::new(format!(
474 "interaction-flow field metadata is out of bounds: {}",
475 field.var
476 )));
477 }
478 let compatible = matches!(
479 (field.value_type, field.control),
480 (FlowFieldValueType::String, FlowFieldControl::Text)
481 | (FlowFieldValueType::String, FlowFieldControl::Password)
482 | (FlowFieldValueType::String, FlowFieldControl::LongText)
483 | (FlowFieldValueType::String, FlowFieldControl::Select)
484 | (FlowFieldValueType::Boolean, FlowFieldControl::Boolean)
485 );
486 if !compatible {
487 return Err(FlowValidationError::new(format!(
488 "interaction-flow field has incompatible value type and control: {}",
489 field.var
490 )));
491 }
492 if field.repeat
493 && !matches!(
494 field.control,
495 FlowFieldControl::Text | FlowFieldControl::Password | FlowFieldControl::LongText
496 )
497 {
498 return Err(FlowValidationError::new(format!(
499 "interaction-flow field control cannot repeat: {}",
500 field.var
501 )));
502 }
503 if field.default_value.is_some() && field.default_value_ref.is_some() {
504 return Err(FlowValidationError::new(format!(
505 "interaction-flow field has two default sources: {}",
506 field.var
507 )));
508 }
509 if matches!(field.control, FlowFieldControl::Password)
510 && (field.default_value.is_some() || field.default_value_ref.is_some() || field.read_only)
511 {
512 return Err(FlowValidationError::new(format!(
513 "interaction-flow password fields cannot have defaults or be read-only: {}",
514 field.var
515 )));
516 }
517 if field.options.is_some() && field.options_ref.is_some() {
518 return Err(FlowValidationError::new(format!(
519 "interaction-flow field has two option sources: {}",
520 field.var
521 )));
522 }
523 if matches!(field.control, FlowFieldControl::Select)
524 && field.options.is_none()
525 && field.options_ref.is_none()
526 {
527 return Err(FlowValidationError::new(format!(
528 "interaction-flow select field requires options: {}",
529 field.var
530 )));
531 }
532 if !matches!(field.control, FlowFieldControl::Select)
533 && (field.options.is_some()
534 || field.options_ref.is_some()
535 || field.option_unavailable_text.is_some())
536 {
537 return Err(FlowValidationError::new(format!(
538 "interaction-flow options require a select control: {}",
539 field.var
540 )));
541 }
542 if field.min_rows.is_some() && !matches!(field.control, FlowFieldControl::LongText) {
543 return Err(FlowValidationError::new(format!(
544 "interaction-flow minRows requires a long-text control: {}",
545 field.var
546 )));
547 }
548 if let Some(default) = &field.default_value {
549 validate_static_default(field, default)?;
550 if let Some(options) = &field.options {
551 let selected = if field.repeat {
552 default.as_array().map(Vec::as_slice).unwrap_or_default()
553 } else {
554 std::slice::from_ref(default)
555 };
556 if selected.iter().any(|selected| {
557 !options
558 .iter()
559 .any(|option| option_value(option) == Some(selected))
560 }) {
561 return Err(FlowValidationError::new(format!(
562 "interaction-flow default is not in static options: {}",
563 field.var
564 )));
565 }
566 }
567 }
568 if let Some(options) = &field.options {
569 for option in options {
570 let value = option_value(option).ok_or_else(|| {
571 FlowValidationError::new(format!(
572 "interaction-flow option has an invalid shape: {}",
573 field.var
574 ))
575 })?;
576 validate_static_scalar(field, value, "option")?;
577 }
578 }
579 Ok(())
580}
581
582fn validate_static_default(
583 field: &FlowFormField,
584 value: &Value,
585) -> Result<(), FlowValidationError> {
586 if field.repeat {
587 let values = value.as_array().ok_or_else(|| {
588 FlowValidationError::new(format!(
589 "interaction-flow repeat default must be an array: {}",
590 field.var
591 ))
592 })?;
593 for value in values {
594 validate_static_scalar(field, value, "default")?;
595 }
596 } else {
597 validate_static_scalar(field, value, "default")?;
598 }
599 Ok(())
600}
601
602fn validate_static_scalar(
603 field: &FlowFormField,
604 value: &Value,
605 kind: &str,
606) -> Result<(), FlowValidationError> {
607 let valid = match field.value_type {
608 FlowFieldValueType::String => value.is_string(),
609 FlowFieldValueType::Boolean => value.is_boolean(),
610 };
611 if !valid {
612 return Err(FlowValidationError::new(format!(
613 "interaction-flow {kind} has the wrong type: {}",
614 field.var
615 )));
616 }
617 Ok(())
618}
619
620fn option_value(option: &Value) -> Option<&Value> {
621 let Value::Object(object) = option else {
622 return Some(option);
623 };
624 if object.get("label").is_some_and(|label| !label.is_string()) {
625 return None;
626 }
627 object.get("value")
628}
629
630fn validate_handler(
631 handler: &FlowHandler,
632 known: &impl Fn(&str) -> bool,
633) -> Result<(), FlowValidationError> {
634 require_identifier("handler operation", &handler.operation)?;
635 if handler.args.len() > MAX_HANDLER_ARGS {
636 return Err(FlowValidationError::new(
637 "interaction-flow handler argument count is out of bounds",
638 ));
639 }
640 for argument in &handler.args {
641 if let FlowArgument::Ref { value_ref } = argument {
642 validate_ref(value_ref, known)?;
643 }
644 }
645 Ok(())
646}
647
648fn validate_ref(
649 value_ref: &FlowValueRef,
650 known: &impl Fn(&str) -> bool,
651) -> Result<(), FlowValidationError> {
652 require_variable("value reference", &value_ref.root)?;
653 if !known(&value_ref.root)
654 || value_ref.path.len() > MAX_VALUE_REF_PATH
655 || value_ref.path.iter().any(|part| !is_identifier(part))
656 {
657 return Err(FlowValidationError::new(format!(
658 "unknown or invalid interaction-flow value reference: {}",
659 value_ref.root
660 )));
661 }
662 Ok(())
663}
664
665fn validate_resolver_graph(
666 resolvers: &HashMap<String, FlowValueResolver>,
667) -> Result<(), FlowValidationError> {
668 fn visit<'a>(
669 name: &'a str,
670 resolvers: &'a HashMap<String, FlowValueResolver>,
671 visiting: &mut HashSet<&'a str>,
672 visited: &mut HashSet<&'a str>,
673 ) -> Result<(), FlowValidationError> {
674 if visited.contains(name) {
675 return Ok(());
676 }
677 if !visiting.insert(name) {
678 return Err(FlowValidationError::new(
679 "interaction-flow resolver dependency cycle",
680 ));
681 }
682 let resolver = resolvers
683 .get(name)
684 .ok_or_else(|| FlowValidationError::new("interaction-flow resolver is missing"))?;
685 for dependency in resolver
686 .handler
687 .args
688 .iter()
689 .filter_map(|argument| match argument {
690 FlowArgument::Ref { value_ref } if resolvers.contains_key(&value_ref.root) => {
691 Some(value_ref.root.as_str())
692 }
693 _ => None,
694 })
695 {
696 visit(dependency, resolvers, visiting, visited)?;
697 }
698 visiting.remove(name);
699 visited.insert(name);
700 Ok(())
701 }
702
703 let mut visiting = HashSet::new();
704 let mut visited = HashSet::new();
705 for name in resolvers.keys() {
706 visit(name, resolvers, &mut visiting, &mut visited)?;
707 }
708 Ok(())
709}
710
711fn require_identifier(kind: &str, value: &str) -> Result<(), FlowValidationError> {
712 if value.is_empty()
713 || value.len() > 128
714 || !value.chars().all(|character| {
715 character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.' | '/')
716 })
717 {
718 return Err(FlowValidationError::new(format!(
719 "invalid interaction-flow {kind}: {value}"
720 )));
721 }
722 Ok(())
723}
724
725fn require_variable(kind: &str, value: &str) -> Result<(), FlowValidationError> {
726 let Some(name) = value.strip_prefix('$') else {
727 return Err(FlowValidationError::new(format!(
728 "invalid interaction-flow {kind}: {value}"
729 )));
730 };
731 if name.is_empty()
732 || name.len() > 127
733 || !name
734 .chars()
735 .next()
736 .is_some_and(|character| character.is_ascii_alphabetic() || character == '_')
737 || !name
738 .chars()
739 .all(|character| character.is_ascii_alphanumeric() || character == '_')
740 {
741 return Err(FlowValidationError::new(format!(
742 "invalid interaction-flow {kind}: {value}"
743 )));
744 }
745 Ok(())
746}
747
748fn is_identifier(value: &str) -> bool {
749 !value.is_empty()
750 && value.len() <= 128
751 && value
752 .chars()
753 .next()
754 .is_some_and(|character| character.is_ascii_alphabetic() || character == '_')
755 && value
756 .chars()
757 .all(|character| character.is_ascii_alphanumeric() || character == '_')
758}
759
760fn is_builtin(value: &str) -> bool {
761 matches!(value, "$env" | "$context")
762}
763
764#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
765#[serde(rename_all = "camelCase", deny_unknown_fields)]
766pub struct FlowDefinitionRequest {
767 pub flow_id: String,
768 #[serde(default, skip_serializing_if = "Option::is_none")]
769 pub subject_id: Option<String>,
770}
771
772#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
773#[serde(rename_all = "camelCase", deny_unknown_fields)]
774pub struct FlowDefinitionResponse {
775 pub definition_revision: String,
776 pub source_session_id: String,
777 pub definition: InteractionFlowDefinition,
778}
779
780#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
781#[serde(rename_all = "camelCase", deny_unknown_fields)]
782pub struct FlowExecuteRequest {
783 pub flow_id: String,
784 pub source_session_id: String,
785 pub definition_revision: String,
786 pub operation: String,
787 pub operation_id: String,
788 #[serde(default)]
789 pub args: Vec<Value>,
790}
791
792#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
793#[serde(rename_all = "camelCase")]
794pub struct FlowExecuteResponse {
795 pub data: Value,
796}
797
798#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
801#[serde(rename_all = "camelCase", deny_unknown_fields)]
802pub struct FlowSubmissionRequest {
803 pub flow_id: String,
804 pub submission_id: String,
805 pub owner: String,
806}
807
808#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
809#[serde(rename_all = "camelCase", deny_unknown_fields)]
810pub struct FlowCompleteRequest {
811 pub submission: FlowSubmissionRequest,
812 pub source_session_id: String,
813 pub definition_revision: String,
814 pub operation: String,
815 #[serde(default)]
816 pub args: Vec<Value>,
817}
818
819#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
822#[serde(tag = "status", rename_all = "camelCase", deny_unknown_fields)]
823pub enum FlowSubmissionResponse {
824 NotFound {},
825 Accepted {},
826 Completed { result: Value },
827}
828
829#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
830#[serde(rename_all = "camelCase")]
831pub enum FlowCloseReason {
832 Completed,
833 Cancelled,
834 Expired,
835 StartFailed,
836}
837
838#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
839#[serde(rename_all = "camelCase", deny_unknown_fields)]
840pub struct FlowCloseRequest {
841 pub flow_id: String,
842 pub source_session_id: String,
843 pub operation_id: String,
844 pub reason: FlowCloseReason,
845}
846
847#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
848#[serde(rename_all = "camelCase")]
849pub struct FlowCloseResponse {
850 pub closed: bool,
851}
852
853#[cfg(test)]
854mod tests {
855 use super::*;
856 use serde_json::json;
857
858 fn definition() -> InteractionFlowDefinition {
859 InteractionFlowDefinition {
860 protocol_version: PROTOCOL_VERSION,
861 flow_id: "provider.connect".into(),
862 start_step_id: "credentials".into(),
863 steps: HashMap::from([(
864 "credentials".into(),
865 InteractionFlowStep {
866 id: "credentials".into(),
867 content: FlowStepContent::Form {
868 presentation: FlowPresentation {
869 renderer: FlowRenderer::TypedForm,
870 title: Some("Connect".into()),
871 description: None,
872 content: None,
873 },
874 form: FlowForm {
875 fields: vec![FlowFormField {
876 var: "$host".into(),
877 value_type: FlowFieldValueType::String,
878 control: FlowFieldControl::Text,
879 required: true,
880 repeat: false,
881 label: Some("Host".into()),
882 default_value: None,
883 default_value_ref: None,
884 options: None,
885 options_ref: None,
886 option_unavailable_text: None,
887 read_only: false,
888 min_rows: None,
889 }],
890 },
891 render_refs: Vec::new(),
892 },
893 transition: FlowTransition::Finish,
894 },
895 )]),
896 resolvers: HashMap::new(),
897 lifecycle: FlowLifecycleHandlers {
898 complete: Some(FlowHandler {
899 operation: "provider.save".into(),
900 args: vec![FlowArgument::Ref {
901 value_ref: FlowValueRef {
902 root: "$host".into(),
903 path: Vec::new(),
904 },
905 }],
906 }),
907 ..FlowLifecycleHandlers::default()
908 },
909 }
910 }
911
912 #[test]
913 fn canonical_definition_round_trips_and_validates() {
914 let definition = definition();
915 definition.validate().unwrap();
916 let value = serde_json::to_value(&definition).unwrap();
917 assert_eq!(value["lifecycle"]["complete"]["operation"], "provider.save");
918 assert!(value.to_string().contains("\"type\":\"ref\""));
919 assert_eq!(
920 serde_json::from_value::<InteractionFlowDefinition>(value).unwrap(),
921 definition
922 );
923 }
924
925 #[test]
926 fn dependencies_are_inferred_from_typed_arguments_and_cycles_are_rejected() {
927 let mut definition = definition();
928 definition.resolvers.insert(
929 "$a".into(),
930 FlowValueResolver {
931 output_var: "$a".into(),
932 handler: FlowHandler {
933 operation: "resolve.a".into(),
934 args: vec![FlowArgument::Ref {
935 value_ref: FlowValueRef {
936 root: "$b".into(),
937 path: Vec::new(),
938 },
939 }],
940 },
941 },
942 );
943 definition.resolvers.insert(
944 "$b".into(),
945 FlowValueResolver {
946 output_var: "$b".into(),
947 handler: FlowHandler {
948 operation: "resolve.b".into(),
949 args: vec![FlowArgument::Ref {
950 value_ref: FlowValueRef {
951 root: "$a".into(),
952 path: Vec::new(),
953 },
954 }],
955 },
956 },
957 );
958 assert!(definition
959 .validate()
960 .unwrap_err()
961 .to_string()
962 .contains("cycle"));
963 }
964
965 #[test]
966 fn node_routes_and_requests_do_not_accept_routing_identity() {
967 assert_eq!(
968 definition_target("camera"),
969 "/camera/interaction-flow/definition"
970 );
971 assert_eq!(execute_target("camera"), "/camera/interaction-flow/execute");
972 assert_eq!(close_target("camera"), "/camera/interaction-flow/close");
973 let request = serde_json::from_value::<FlowExecuteRequest>(json!({
974 "flowId": "provider.connect",
975 "sourceSessionId": "source-1",
976 "definitionRevision": "sha256:abc",
977 "operation": "provider.discover",
978 "operationId": "operation-1",
979 "args": [],
980 "nodeId": "untrusted"
981 }));
982 assert!(request.is_err());
983 }
984
985 #[test]
986 fn node_renderer_is_typed_form_only_on_the_wire() {
987 let mut definition = definition();
988 let step = definition.steps.get_mut("credentials").unwrap();
989 let FlowStepContent::Form { presentation, .. } = &mut step.content else {
990 unreachable!();
991 };
992 presentation.renderer = FlowRenderer::CustomConnectMdx;
993 assert!(serde_json::to_value(definition).is_err());
994 }
995
996 #[test]
997 fn input_shape_is_stable_across_steps_and_passwords_are_user_owned() {
998 let mut invalid_definition = definition();
999 invalid_definition.steps.insert(
1000 "second".into(),
1001 InteractionFlowStep {
1002 id: "second".into(),
1003 content: FlowStepContent::Form {
1004 presentation: FlowPresentation {
1005 renderer: FlowRenderer::TypedForm,
1006 title: None,
1007 description: None,
1008 content: None,
1009 },
1010 form: FlowForm {
1011 fields: vec![FlowFormField {
1012 var: "$host".into(),
1013 value_type: FlowFieldValueType::Boolean,
1014 control: FlowFieldControl::Boolean,
1015 required: true,
1016 repeat: false,
1017 label: None,
1018 default_value: None,
1019 default_value_ref: None,
1020 options: None,
1021 options_ref: None,
1022 option_unavailable_text: None,
1023 read_only: false,
1024 min_rows: None,
1025 }],
1026 },
1027 render_refs: Vec::new(),
1028 },
1029 transition: FlowTransition::Finish,
1030 },
1031 );
1032 assert!(invalid_definition.validate().is_err());
1033
1034 let mut definition = definition();
1035 let step = definition.steps.get_mut("credentials").unwrap();
1036 let FlowStepContent::Form { form, .. } = &mut step.content else {
1037 unreachable!();
1038 };
1039 let field = form.fields.first_mut().unwrap();
1040 field.control = FlowFieldControl::Password;
1041 field.default_value = Some(json!("not-allowed"));
1042 assert!(definition.validate().is_err());
1043 }
1044
1045 #[test]
1046 fn durable_submission_contract_is_typed_and_closed() {
1047 assert_eq!(
1048 complete_target("camera"),
1049 "/camera/interaction-flow/complete"
1050 );
1051 assert_eq!(
1052 submission_target("camera", false),
1053 "/camera/interaction-flow/submission/status"
1054 );
1055 assert_eq!(
1056 submission_target("camera", true),
1057 "/camera/interaction-flow/submission/retry"
1058 );
1059 let mut fixture: Value = serde_json::from_str(include_str!(
1060 "../fixtures/interaction-flow-node.conformance.json"
1061 ))
1062 .unwrap();
1063 let complete: FlowCompleteRequest =
1064 serde_json::from_value(fixture["completeRequest"].clone()).unwrap();
1065 assert_eq!(
1066 serde_json::to_value(&complete.submission).unwrap(),
1067 fixture["submissionRequest"]
1068 );
1069 let schema: Value = serde_json::from_str(NODE_PROTOCOL_SCHEMA).unwrap();
1070 let validator = jsonschema::validator_for(&schema).unwrap();
1071 for response in [
1072 json!({"status":"notFound"}),
1073 json!({"status":"accepted"}),
1074 json!({"status":"completed","result":{"id":"saved"}}),
1075 ] {
1076 let typed: FlowSubmissionResponse = serde_json::from_value(response.clone()).unwrap();
1077 assert_eq!(serde_json::to_value(typed).unwrap(), response);
1078 fixture["submissionResponse"] = response;
1079 assert!(validator.is_valid(&fixture));
1080 }
1081 for response in [
1082 json!({"status":"accepted","material":{"password":"secret"}}),
1083 json!({"status":"running"}),
1084 ] {
1085 assert!(serde_json::from_value::<FlowSubmissionResponse>(response.clone()).is_err());
1086 fixture["submissionResponse"] = response;
1087 assert!(!validator.is_valid(&fixture));
1088 }
1089 fixture["submissionResponse"] = json!({"status":"accepted"});
1090 fixture["completeRequest"]["target"] = json!("/arbitrary");
1091 assert!(
1092 serde_json::from_value::<FlowCompleteRequest>(fixture["completeRequest"].clone())
1093 .is_err()
1094 );
1095 assert!(!validator.is_valid(&fixture));
1096 }
1097
1098 #[test]
1099 fn conformance_fixture_matches_the_published_node_schema() {
1100 let schema: Value = serde_json::from_str(NODE_PROTOCOL_SCHEMA).unwrap();
1101 let fixture: Value = serde_json::from_str(include_str!(
1102 "../fixtures/interaction-flow-node.conformance.json"
1103 ))
1104 .unwrap();
1105 let validator = jsonschema::validator_for(&schema).unwrap();
1106 let errors = validator
1107 .iter_errors(&fixture)
1108 .map(|error| error.to_string())
1109 .collect::<Vec<_>>();
1110 assert!(errors.is_empty(), "fixture failed: {errors:?}");
1111 }
1112}