1use std::collections::HashMap;
2use std::error::Error as StdError;
3use std::str::FromStr;
4use std::sync::Arc;
5use std::time::Duration;
6
7use crate::component_api::node::{ExecCtx as ComponentExecCtx, TenantCtx as ComponentTenantCtx};
8use anyhow::{Context, Result, anyhow, bail};
9use chrono::{DateTime, SecondsFormat, Utc};
10use indexmap::IndexMap;
11use parking_lot::RwLock;
12use serde::{Deserialize, Serialize};
13use serde_json::{Map as JsonMap, Value, json};
14use tokio::task;
15
16use super::mocks::MockLayer;
17use super::templating::{TemplateOptions, render_template_value};
18use crate::config::{FlowRetryConfig, HostConfig};
19use crate::pack::{FlowDescriptor, PackRuntime};
20use crate::runner::approval_token;
21use crate::runner::invocation::{InvocationMeta, build_invocation_envelope_as};
22use crate::telemetry::{
23 FlowSpanAttributes, RolloutIds, annotate_span, backoff_delay_ms, set_flow_context,
24};
25#[cfg(feature = "fault-injection")]
26use crate::testing::fault_injection::{FaultContext, FaultPoint, maybe_fail};
27use crate::validate::{
28 ValidationConfig, ValidationIssue, ValidationMode, validate_component_envelope,
29 validate_tool_envelope,
30};
31use greentic_flow::SLOT_SCHEMA_METADATA_KEY;
32use greentic_types::{Flow, Node, NodeId, Routing};
33
34const SLOT_EXTRACTOR_COMPONENT_ID: &str = "ai.greentic.component-slot-extractor";
38
39pub trait CrossPackResolver: Send + Sync {
46 fn invoke(
47 &self,
48 provider_id: &str,
49 provider_type: Option<&str>,
50 op: &str,
51 input: &[u8],
52 tenant: &str,
53 team: Option<&str>,
54 ) -> Result<Value>;
55}
56
57pub struct FlowEngine {
58 packs: Vec<Arc<PackRuntime>>,
59 flows: Vec<FlowDescriptor>,
60 flow_sources: HashMap<FlowKey, usize>,
61 messaging_provider_pack_ids: std::collections::HashSet<String>,
68 flow_cache: RwLock<HashMap<FlowKey, HostFlow>>,
69 default_env: String,
70 validation: ValidationConfig,
71 cross_pack_resolver: Option<Arc<dyn CrossPackResolver>>,
72 rollout_ids: RolloutIds,
77 remote_dispatch_handler: Option<Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>>,
80 approval_dispatch_handler:
89 Option<Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>>,
90 operala_node_handler: Option<Arc<dyn crate::runner::operala_node::OperalaNodeHandler>>,
98 #[cfg(feature = "agentic-worker")]
101 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch,
102 #[cfg(feature = "agentic-worker")]
103 agent_node_handler: Option<Arc<dyn crate::runner::agent_node::AgentNodeHandler>>,
104 #[cfg(feature = "agentic-worker")]
105 graph_node_handler: Option<Arc<dyn crate::runner::graph_node::GraphNodeHandler>>,
106 #[cfg(feature = "agentic-worker")]
111 mcp_tool_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
112 #[cfg(feature = "agentic-worker")]
120 mcp_secrets: Option<crate::secrets::DynSecretsManager>,
121 #[cfg(feature = "agentic-worker")]
135 a2a_sources: RwLock<HashMap<(String, String), Arc<greentic_aw_runtime::A2aToolSource>>>,
136 #[cfg(feature = "agentic-worker")]
140 ext_artifact_port: Option<crate::host::ExtArtifactPort>,
141}
142
143#[derive(Clone, Debug, PartialEq, Eq, Hash)]
144struct FlowKey {
145 pack_id: String,
146 flow_id: String,
147}
148
149#[derive(Clone, Debug, Serialize, Deserialize)]
150pub struct FlowSnapshot {
151 pub pack_id: String,
152 pub flow_id: String,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub next_flow: Option<String>,
155 pub next_node: String,
156 #[serde(default)]
163 pub awaiting_submit: bool,
164 pub state: ExecutionState,
165}
166
167#[derive(Clone, Debug)]
168pub struct FlowWait {
169 pub reason: Option<String>,
170 pub snapshot: FlowSnapshot,
171}
172
173#[derive(Clone, Debug)]
174pub enum FlowStatus {
175 Completed,
176 Waiting(Box<FlowWait>),
177}
178
179#[derive(Clone, Debug)]
180pub struct FlowExecution {
181 pub output: Value,
182 pub status: FlowStatus,
183 pub node_outputs: JsonMap<String, Value>,
187}
188
189#[derive(Clone, Debug)]
190struct HostFlow {
191 id: String,
192 start: Option<NodeId>,
193 nodes: IndexMap<NodeId, HostNode>,
194 vars_init: JsonMap<String, Value>,
195 #[allow(dead_code)]
202 required_vars: Vec<String>,
203 slot_schema: Option<Value>,
206}
207
208#[derive(Clone, Debug)]
209pub struct HostNode {
210 kind: NodeKind,
211 pub component: String,
213 component_id: String,
214 operation_name: Option<String>,
215 operation_in_mapping: Option<String>,
216 payload_expr: Value,
217 routing: Routing,
218 vars_out: Option<JsonMap<String, Value>>,
223 response_timeout_secs: Option<u64>,
228}
229
230impl HostNode {
231 pub fn component_id(&self) -> &str {
232 &self.component_id
233 }
234
235 pub fn operation_name(&self) -> Option<&str> {
236 self.operation_name.as_deref()
237 }
238
239 pub fn operation_in_mapping(&self) -> Option<&str> {
240 self.operation_in_mapping.as_deref()
241 }
242
243 pub(crate) fn is_approval(&self) -> bool {
245 matches!(self.kind, NodeKind::ApprovalCall { .. })
246 }
247
248 pub(crate) fn agent_ref(&self) -> Option<&str> {
252 match &self.kind {
253 NodeKind::DwAgent { agent_id, .. } => Some(agent_id.as_str()),
254 NodeKind::DwAgentGraph { graph_id } => Some(graph_id.as_str()),
255 NodeKind::OperalaCall { target } | NodeKind::AgenticCall { target } => {
256 Some(target.as_str())
257 }
258 _ => None,
259 }
260 .map(str::trim)
261 .filter(|id| !id.is_empty())
262 }
263
264 pub(crate) fn response_timeout_secs(&self) -> Option<u64> {
266 self.response_timeout_secs
267 }
268
269 pub(crate) fn is_agentic(&self) -> bool {
273 matches!(
274 self.kind,
275 NodeKind::DwAgent { .. }
276 | NodeKind::DwAgentGraph { .. }
277 | NodeKind::OperalaCall { .. }
278 | NodeKind::AgenticCall { .. }
279 )
280 }
281}
282
283#[cfg(test)]
284impl HostNode {
285 pub(crate) fn for_test(component_id: &str, operation_name: Option<&str>) -> Self {
291 HostNode {
292 kind: NodeKind::Exec {
293 target_component: component_id.to_string(),
294 },
295 component: component_id.to_string(),
296 component_id: component_id.to_string(),
297 operation_name: operation_name.map(str::to_string),
298 operation_in_mapping: None,
299 payload_expr: Value::Null,
300 routing: Routing::End,
301 vars_out: None,
302 response_timeout_secs: None,
303 }
304 }
305
306 pub(crate) fn for_test_approval(target: &str) -> Self {
308 HostNode {
309 kind: NodeKind::ApprovalCall {
310 target: target.to_string(),
311 },
312 ..Self::for_test("approval.call", Some(target))
313 }
314 }
315
316 pub(crate) fn with_response_timeout(mut self, secs: u64) -> Self {
318 self.response_timeout_secs = Some(secs);
319 self
320 }
321
322 pub(crate) fn for_test_dw_agent(agent_id: &str) -> Self {
324 HostNode {
325 kind: NodeKind::DwAgent {
326 agent_id: agent_id.to_string(),
327 conversational: false,
328 },
329 ..Self::for_test("dw.agent", Some(agent_id))
330 }
331 }
332}
333
334#[derive(Clone, Debug)]
335enum NodeKind {
336 Exec {
337 target_component: String,
338 },
339 PackComponent {
340 component_ref: String,
341 },
342 ProviderInvoke,
343 FlowCall,
344 FlowGoto,
358 BuiltinEmit {
359 kind: EmitKind,
360 },
361 BuiltinStateGet,
362 BuiltinStateSet,
363 VarSet {
367 name: String,
368 value: Value,
369 },
370 Wait,
371 DwAgent {
372 agent_id: String,
373 conversational: bool,
376 },
377 DwAgentGraph {
378 graph_id: String,
379 },
380 SorlaCall {
384 target: String,
385 },
386 OperalaCall {
389 target: String,
390 },
391 AgenticCall {
396 target: String,
397 },
398 TelcoXCall {
403 target: String,
404 },
405 ApprovalCall {
410 target: String,
411 },
412 Mcp {
422 server_id: String,
423 tool: String,
424 },
425 A2a {
437 agent_id: String,
438 },
439 MediaCreate,
444}
445
446impl NodeKind {
447 fn performs_external_effect(&self) -> bool {
470 matches!(
471 self,
472 NodeKind::ProviderInvoke
473 | NodeKind::FlowCall
474 | NodeKind::DwAgent { .. }
475 | NodeKind::DwAgentGraph { .. }
476 | NodeKind::SorlaCall { .. }
477 | NodeKind::OperalaCall { .. }
478 | NodeKind::AgenticCall { .. }
479 | NodeKind::TelcoXCall { .. }
480 | NodeKind::ApprovalCall { .. }
481 | NodeKind::Mcp { .. }
482 | NodeKind::A2a { .. }
483 | NodeKind::MediaCreate
484 )
485 }
486
487 fn may_have_partial_effect_on_failure(&self) -> bool {
495 !matches!(self, NodeKind::FlowCall) && self.performs_external_effect()
496 }
497}
498
499fn terminal_after_effects(err: anyhow::Error, effects_performed: bool) -> anyhow::Error {
511 if !effects_performed || is_after_effects_failure(&err) {
512 return err;
513 }
514 tracing::warn!(
515 error = %format!("{err:#}"),
516 "flow failed after an earlier node performed an external effect; the turn is not re-run"
517 );
518 terminal_flow_error_from_after_effects(err)
522}
523
524#[derive(Clone, Debug)]
525enum EmitKind {
526 Log,
527 Response,
528 Other(String),
529}
530
531struct ComponentOverrides<'a> {
532 component: Option<&'a str>,
533 operation: Option<&'a str>,
534}
535
536struct ComponentCall {
537 component_ref: String,
538 operation: String,
539 input: Value,
540 config: Value,
541 has_error_route: bool,
545}
546
547struct FlowFailure {
556 error: anyhow::Error,
557 node_outputs: JsonMap<String, Value>,
558}
559
560impl From<anyhow::Error> for FlowFailure {
561 fn from(error: anyhow::Error) -> Self {
562 Self {
563 error,
564 node_outputs: JsonMap::new(),
565 }
566 }
567}
568
569impl FlowExecution {
570 fn completed(output: Value, node_outputs: JsonMap<String, Value>) -> Self {
571 Self {
572 output,
573 status: FlowStatus::Completed,
574 node_outputs,
575 }
576 }
577
578 fn waiting(output: Value, wait: FlowWait, node_outputs: JsonMap<String, Value>) -> Self {
579 Self {
580 output,
581 status: FlowStatus::Waiting(Box::new(wait)),
582 node_outputs,
583 }
584 }
585}
586
587const USER_FACING_FLOW_FAILURE_KEY: &str = "runner.flow.execution_failed";
613
614pub(crate) const APPROVAL_RUNTIME: &str = "approval";
618
619fn user_facing_flow_failure_text_for(locale: &str) -> String {
631 let text = crate::runner::i18n::resolve_message(
632 USER_FACING_FLOW_FAILURE_KEY,
633 crate::runner::i18n::FLOW_EXECUTION_FAILED_EN,
634 locale,
635 );
636 if text.trim().is_empty() {
637 return crate::runner::i18n::FLOW_EXECUTION_FAILED_EN.to_string();
638 }
639 text
640}
641
642fn user_facing_flow_failure_text(entry: &Value) -> String {
668 let locale = activity_locale(entry)
669 .map(str::to_owned)
670 .unwrap_or_else(|| crate::runner::i18n::select_locale(None));
671 user_facing_flow_failure_text_for(&locale)
672}
673
674fn surfaced_failure_execution(
678 input: &Value,
679 flow_id: &str,
680 err: &anyhow::Error,
681 node_outputs: JsonMap<String, Value>,
682) -> FlowExecution {
683 FlowExecution::completed(
684 json!({
685 "text": user_facing_flow_failure_text(input),
686 "metadata": {
689 "error_kind": "flow_execution_failed",
690 "error_message": err.to_string(),
691 "flow_id": flow_id,
692 }
693 }),
694 node_outputs,
695 )
696}
697
698impl FlowEngine {
699 pub async fn new(packs: Vec<Arc<PackRuntime>>, config: Arc<HostConfig>) -> Result<Self> {
700 let mut flow_sources: HashMap<FlowKey, usize> = HashMap::new();
701 let mut messaging_provider_pack_ids: std::collections::HashSet<String> =
702 std::collections::HashSet::new();
703 let mut descriptors = Vec::new();
704 let mut bindings = HashMap::new();
705 for pack in &config.pack_bindings {
706 bindings.insert(pack.pack_id.clone(), pack.flows.clone());
707 }
708 let enforce_bindings = !bindings.is_empty();
709 for (idx, pack) in packs.iter().enumerate() {
710 let pack_id = pack.metadata().pack_id.clone();
711 if enforce_bindings && !bindings.contains_key(&pack_id) {
712 bail!("no gtbind entries found for pack {}", pack_id);
713 }
714 let declares_messaging_provider = pack
718 .provider_registry_optional()
719 .ok()
720 .flatten()
721 .map(|registry| {
722 registry
723 .operator_metadata()
724 .iter()
725 .any(|meta| meta.provider_type.starts_with("messaging."))
726 })
727 .unwrap_or(false);
728 if declares_messaging_provider {
729 messaging_provider_pack_ids.insert(pack_id.clone());
730 }
731 let flows = pack.list_flows().await?;
732 let allowed = bindings.get(&pack_id).map(|flows| {
733 flows
734 .iter()
735 .cloned()
736 .collect::<std::collections::HashSet<_>>()
737 });
738 let mut seen = std::collections::HashSet::new();
739 for flow in flows {
740 if let Some(ref allow) = allowed
741 && !allow.contains(&flow.id)
742 {
743 continue;
744 }
745 seen.insert(flow.id.clone());
746 tracing::info!(
747 flow_id = %flow.id,
748 flow_type = %flow.flow_type,
749 pack_id = %flow.pack_id,
750 pack_index = idx,
751 "registered flow"
752 );
753 if let Ok(flow_ir) = pack.load_flow(&flow.id) {
754 for node in flow_ir.nodes.values() {
755 config
756 .secrets_policy
757 .register_flow_secret_refs(&node.input.mapping);
758 config
759 .secrets_policy
760 .register_flow_secret_refs(&node.output.mapping);
761 }
762 }
763 flow_sources.insert(
764 FlowKey {
765 pack_id: flow.pack_id.clone(),
766 flow_id: flow.id.clone(),
767 },
768 idx,
769 );
770 descriptors.retain(|existing: &FlowDescriptor| {
771 !(existing.id == flow.id && existing.pack_id == flow.pack_id)
772 });
773 descriptors.push(flow);
774 }
775 if let Some(allow) = allowed {
776 let missing = allow.difference(&seen).cloned().collect::<Vec<_>>();
777 if !missing.is_empty() {
778 bail!(
779 "gtbind flow ids missing in pack {}: {}",
780 pack_id,
781 missing.join(", ")
782 );
783 }
784 }
785 }
786
787 let mut flow_map = HashMap::new();
788 for flow in &descriptors {
789 let pack_id = flow.pack_id.clone();
790 if let Some(&pack_idx) = flow_sources.get(&FlowKey {
791 pack_id: pack_id.clone(),
792 flow_id: flow.id.clone(),
793 }) {
794 let pack_clone = Arc::clone(&packs[pack_idx]);
795 let flow_id = flow.id.clone();
796 let task_flow_id = flow_id.clone();
797 match task::spawn_blocking(move || pack_clone.load_flow(&task_flow_id)).await {
798 Ok(Ok(loaded_flow)) => {
799 flow_map.insert(
800 FlowKey {
801 pack_id: pack_id.clone(),
802 flow_id,
803 },
804 HostFlow::from(loaded_flow),
805 );
806 }
807 Ok(Err(err)) => {
808 tracing::warn!(flow_id = %flow.id, error = %err, "failed to load flow metadata");
809 }
810 Err(err) => {
811 tracing::warn!(flow_id = %flow.id, error = %err, "join error loading flow metadata");
812 }
813 }
814 }
815 }
816
817 Ok(Self {
818 packs,
819 flows: descriptors,
820 flow_sources,
821 messaging_provider_pack_ids,
822 flow_cache: RwLock::new(flow_map),
823 default_env: crate::config::greentic_env_or_local(),
824 validation: config.validation.clone(),
825 cross_pack_resolver: None,
826 approval_dispatch_handler: None,
827 remote_dispatch_handler: None,
828 rollout_ids: RolloutIds::default(),
829 operala_node_handler: None,
830 #[cfg(feature = "agentic-worker")]
831 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
832 #[cfg(feature = "agentic-worker")]
833 agent_node_handler: None,
834 #[cfg(feature = "agentic-worker")]
835 graph_node_handler: None,
836 #[cfg(feature = "agentic-worker")]
837 mcp_tool_source: crate::runner::mcp_node::source_from_env(),
838 #[cfg(feature = "agentic-worker")]
839 mcp_secrets: None,
840 #[cfg(feature = "agentic-worker")]
841 a2a_sources: RwLock::new(HashMap::new()),
842 #[cfg(feature = "agentic-worker")]
843 ext_artifact_port: None,
844 })
845 }
846
847 pub fn with_rollout_ids(mut self, rollout_ids: RolloutIds) -> Self {
853 self.rollout_ids = rollout_ids;
854 self
855 }
856
857 pub fn rollout_ids(&self) -> &RolloutIds {
861 &self.rollout_ids
862 }
863
864 #[cfg(feature = "agentic-worker")]
877 pub(crate) fn mcp_credential_unit(&self) -> Option<&str> {
878 self.rollout_ids.bundle_id.as_deref()
879 }
880
881 #[cfg(feature = "agentic-worker")]
895 pub fn with_mcp_source(
896 mut self,
897 source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
898 ) -> Self {
899 if let Some(source) = source {
900 self.mcp_tool_source = Some(source);
901 }
902 self
903 }
904
905 #[cfg(feature = "agentic-worker")]
911 pub fn with_mcp_secrets(mut self, secrets: Option<crate::secrets::DynSecretsManager>) -> Self {
912 if let Some(secrets) = secrets {
913 self.mcp_secrets = Some(secrets);
914 }
915 self
916 }
917
918 #[cfg(feature = "agentic-worker")]
923 fn mcp_secrets_for_dispatch(&self) -> Option<crate::secrets::DynSecretsManager> {
924 let requested = std::env::var("SECRETS_BACKEND").ok();
925 crate::runner::mcp_node::aw::choose_mcp_secrets(
926 requested.as_deref(),
927 crate::runner::mcp_node::aw::secrets_from_env(),
928 self.mcp_secrets.as_ref(),
929 )
930 }
931
932 pub fn set_cross_pack_resolver(&mut self, resolver: Arc<dyn CrossPackResolver>) {
935 self.cross_pack_resolver = Some(resolver);
936 }
937
938 pub fn set_remote_dispatch_handler(
942 &mut self,
943 handler: Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
944 ) {
945 self.remote_dispatch_handler = Some(handler);
946 }
947
948 pub fn set_approval_dispatch_handler(
953 &mut self,
954 handler: Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
955 ) {
956 self.approval_dispatch_handler = Some(handler);
957 }
958
959 fn dispatch_handler_for(
962 &self,
963 runtime: &str,
964 ) -> Option<&Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>> {
965 if runtime == APPROVAL_RUNTIME {
966 self.approval_dispatch_handler
967 .as_ref()
968 .or(self.remote_dispatch_handler.as_ref())
969 } else {
970 self.remote_dispatch_handler.as_ref()
971 }
972 }
973
974 #[cfg(feature = "agentic-worker")]
981 fn remote_dispatch_configured(&self) -> bool {
982 self.remote_dispatch_handler.is_some()
983 }
984
985 pub fn set_operala_node_handler(
993 &mut self,
994 handler: Arc<dyn crate::runner::operala_node::OperalaNodeHandler>,
995 ) {
996 self.operala_node_handler = Some(handler);
997 }
998
999 #[cfg(feature = "agentic-worker")]
1002 pub fn set_agent_node_handler(
1003 &mut self,
1004 handler: Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
1005 ) {
1006 self.agent_node_handler = Some(handler);
1007 }
1008
1009 #[cfg(feature = "agentic-worker")]
1013 pub fn set_ext_artifact_port(&mut self, port: Option<crate::host::ExtArtifactPort>) {
1014 self.ext_artifact_port = port;
1015 }
1016
1017 #[cfg(feature = "agentic-worker")]
1023 pub fn set_graph_node_handler(
1024 &mut self,
1025 handler: Arc<dyn crate::runner::graph_node::GraphNodeHandler>,
1026 ) {
1027 self.graph_node_handler = Some(handler);
1028 }
1029
1030 #[cfg(feature = "agentic-worker")]
1043 pub fn set_dw_agent_dispatch(&mut self, mode: crate::runner::agent_node::DwAgentDispatch) {
1044 self.dw_agent_dispatch = mode;
1045 }
1046
1047 async fn get_or_load_flow(&self, pack_id: &str, flow_id: &str) -> Result<HostFlow> {
1048 let key = FlowKey {
1049 pack_id: pack_id.to_string(),
1050 flow_id: flow_id.to_string(),
1051 };
1052 if let Some(flow) = self.flow_cache.read().get(&key).cloned() {
1053 return Ok(flow);
1054 }
1055
1056 let pack_idx = *self
1057 .flow_sources
1058 .get(&key)
1059 .ok_or_else(|| {
1062 terminal_flow_error(format!("flow {pack_id}:{flow_id} not registered"))
1063 })?;
1064 let pack = Arc::clone(&self.packs[pack_idx]);
1065 let flow_id_owned = flow_id.to_string();
1066 let task_flow_id = flow_id_owned.clone();
1067 let flow = task::spawn_blocking(move || pack.load_flow(&task_flow_id))
1068 .await
1069 .context("failed to join flow metadata task")??;
1070 let host_flow = HostFlow::from(flow);
1071 self.flow_cache.write().insert(
1072 FlowKey {
1073 pack_id: pack_id.to_string(),
1074 flow_id: flow_id_owned.clone(),
1075 },
1076 host_flow.clone(),
1077 );
1078 Ok(host_flow)
1079 }
1080
1081 fn flow_execute_span(&self, ctx: &FlowContext<'_>) -> tracing::Span {
1088 let span = tracing::info_span!(
1089 "flow.execute",
1090 tenant = tracing::field::Empty,
1091 flow_id = tracing::field::Empty,
1092 node_id = tracing::field::Empty,
1093 tool = tracing::field::Empty,
1094 action = tracing::field::Empty
1095 );
1096 annotate_span(
1097 &span,
1098 &FlowSpanAttributes {
1099 tenant: ctx.tenant,
1100 flow_id: ctx.flow_id,
1101 node_id: ctx.node_id,
1102 tool: ctx.tool,
1103 action: ctx.action,
1104 },
1105 );
1106 set_flow_context(
1107 &span,
1108 &self.default_env,
1109 ctx.tenant,
1110 ctx.flow_id,
1111 ctx.node_id,
1112 ctx.provider_id,
1113 ctx.session_id,
1114 ctx.pack_id,
1115 &self.rollout_ids,
1116 );
1117 span
1118 }
1119
1120 pub async fn execute(&self, ctx: FlowContext<'_>, input: Value) -> Result<FlowExecution> {
1121 self.execute_with_entry(ctx, input, None).await
1122 }
1123
1124 async fn execute_propagating_failure(
1129 &self,
1130 ctx: FlowContext<'_>,
1131 input: Value,
1132 ) -> Result<FlowExecution> {
1133 self.execute_with_options(ctx, input, None, false).await
1134 }
1135
1136 pub async fn execute_from(
1153 &self,
1154 ctx: FlowContext<'_>,
1155 input: Value,
1156 entry_node: &str,
1157 ) -> Result<FlowExecution> {
1158 self.execute_with_entry(ctx, input, Some(entry_node.to_string()))
1159 .await
1160 }
1161
1162 async fn execute_with_entry(
1163 &self,
1164 ctx: FlowContext<'_>,
1165 input: Value,
1166 entry_node: Option<String>,
1167 ) -> Result<FlowExecution> {
1168 self.execute_with_options(ctx, input, entry_node, true)
1169 .await
1170 }
1171
1172 async fn execute_with_options(
1176 &self,
1177 ctx: FlowContext<'_>,
1178 input: Value,
1179 entry_node: Option<String>,
1180 surface_failures: bool,
1181 ) -> Result<FlowExecution> {
1182 if let Some(node) = entry_node.as_deref() {
1188 let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
1189 let node_id = NodeId::from_str(node)
1190 .with_context(|| format!("invalid entry node id `{node}`"))?;
1191 if !flow_ir.nodes.contains_key(&node_id) {
1192 return Err(terminal_flow_error(format!(
1193 "flow {} has no node `{}`",
1194 ctx.flow_id, node
1195 )));
1196 }
1197 }
1198 let span = self.flow_execute_span(&ctx);
1199 let retry_config = ctx.retry_config;
1200 let original_input = input;
1201 let mut ctx = ctx;
1202 let metric_tenant = ctx.tenant.to_string();
1203 let metric_flow_id = ctx.flow_id.to_string();
1204 let started = std::time::Instant::now();
1205 let observer = ctx.observer;
1206 let mut surfaced_failure = false;
1209 let surfaced_ref = &mut surfaced_failure;
1210 let result = async move {
1211 let mut attempt = 0u32;
1212 loop {
1213 attempt += 1;
1214 ctx.attempt = attempt;
1215 if let Some(observer) = ctx.observer {
1216 observer.on_flow_attempt(ctx.flow_id, attempt);
1217 }
1218 #[cfg(feature = "fault-injection")]
1219 {
1220 let fault_ctx = FaultContext {
1221 pack_id: ctx.pack_id,
1222 flow_id: ctx.flow_id,
1223 node_id: ctx.node_id,
1224 attempt: ctx.attempt,
1225 };
1226 maybe_fail(FaultPoint::Timeout, fault_ctx).map_err(injected_error)?;
1227 }
1228 match self
1229 .execute_once(&ctx, original_input.clone(), entry_node.clone())
1230 .await
1231 {
1232 Ok(value) => return Ok(value),
1233 Err(FlowFailure {
1234 error: err,
1235 node_outputs,
1236 }) => {
1237 if attempt >= retry_config.max_attempts || !should_retry(&err) {
1238 if surface_failures && ctx.session_id.is_some() {
1243 *surfaced_ref = true;
1244 return Ok(surfaced_failure_execution(
1245 &original_input,
1246 ctx.flow_id,
1247 &err,
1248 node_outputs,
1249 ));
1250 }
1251 return Err(err);
1252 }
1253 let delay = backoff_delay_ms(retry_config.base_delay_ms, attempt - 1);
1254 tracing::warn!(
1255 tenant = ctx.tenant,
1256 flow_id = ctx.flow_id,
1257 attempt,
1258 max_attempts = retry_config.max_attempts,
1259 delay_ms = delay,
1260 error = %err,
1261 "transient flow execution failure, backing off"
1262 );
1263 tokio::time::sleep(Duration::from_millis(delay)).await;
1264 }
1265 }
1266 }
1267 }
1268 .instrument(span)
1269 .await;
1270 if let Some(observer) = observer {
1271 observer.on_flow_exit(&metric_flow_id);
1272 }
1273 let status = if result.is_ok() && !surfaced_failure {
1274 "ok"
1275 } else {
1276 "err"
1277 };
1278 let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
1279 crate::metrics::record_flow_execution(&metric_tenant, &metric_flow_id, status, duration_ms);
1280 result
1281 }
1282
1283 pub async fn resume(
1284 &self,
1285 ctx: FlowContext<'_>,
1286 snapshot: FlowSnapshot,
1287 input: Value,
1288 ) -> Result<FlowExecution> {
1289 self.resume_with_options(ctx, snapshot, input, false).await
1290 }
1291
1292 pub async fn resume_surfacing_failures(
1301 &self,
1302 ctx: FlowContext<'_>,
1303 snapshot: FlowSnapshot,
1304 input: Value,
1305 ) -> Result<FlowExecution> {
1306 self.resume_with_options(ctx, snapshot, input, true).await
1307 }
1308
1309 async fn resume_with_options(
1310 &self,
1311 ctx: FlowContext<'_>,
1312 snapshot: FlowSnapshot,
1313 input: Value,
1314 surface_after_effects: bool,
1315 ) -> Result<FlowExecution> {
1316 if snapshot.pack_id != ctx.pack_id {
1317 return Err(terminal_flow_error(format!(
1318 "snapshot pack {} does not match requested {}",
1319 snapshot.pack_id, ctx.pack_id
1320 )));
1321 }
1322 let resume_flow = snapshot
1323 .next_flow
1324 .clone()
1325 .unwrap_or_else(|| snapshot.flow_id.clone());
1326 let flow_ir = self.get_or_load_flow(ctx.pack_id, &resume_flow).await?;
1327 let pending_card_answers = pending_from_snapshot(&snapshot, &input);
1330 let resumed_at = resumed_card_node(&snapshot);
1331 let mut state = snapshot.state;
1332 state.resumed_at = resumed_at;
1333 state.reset_redirect_count();
1337 state.replace_input(input.clone());
1347 let surfaced_input = surface_after_effects.then(|| input.clone());
1348 state.pending_card_answers = pending_card_answers;
1352 state.entry = input;
1353 let span = self.flow_execute_span(&ctx);
1354 let result = self
1355 .drive_flow(&ctx, flow_ir, state, Some(snapshot.next_node), resume_flow)
1356 .instrument(span)
1357 .await;
1358 match result {
1359 Ok(execution) => Ok(execution),
1360 Err(failure) => match surfaced_input {
1361 Some(input)
1362 if ctx.session_id.is_some() && is_after_effects_failure(&failure.error) =>
1363 {
1364 tracing::warn!(
1365 error = %format!("{:#}", failure.error),
1366 flow_id = ctx.flow_id,
1367 "resumed flow failed after an effect; surfacing the failure and clearing the park"
1368 );
1369 Ok(surfaced_failure_execution(
1370 &input,
1371 ctx.flow_id,
1372 &failure.error,
1373 failure.node_outputs,
1374 ))
1375 }
1376 _ => Err(failure.error),
1377 },
1378 }
1379 }
1380
1381 async fn execute_once(
1382 &self,
1383 ctx: &FlowContext<'_>,
1384 input: Value,
1385 entry_node: Option<String>,
1386 ) -> Result<FlowExecution, FlowFailure> {
1387 let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
1388 let mut state = ExecutionState::new(input);
1389 let missing = seed_vars_and_collect_missing_required(
1390 &flow_ir.vars_init,
1391 &flow_ir.required_vars,
1392 &mut state.vars,
1393 );
1394 if !missing.is_empty() {
1395 let label = crate::runner::i18n::resolve_message(
1398 "runner.flow.required_var_missing",
1399 "required flow variable not provided",
1400 "en",
1401 );
1402 return Err(terminal_flow_error(format!("{label}: {}", missing.join(", "))).into());
1403 }
1404 self.drive_flow(ctx, flow_ir, state, entry_node, ctx.flow_id.to_string())
1405 .await
1406 }
1407
1408 async fn drive_flow(
1413 &self,
1414 ctx: &FlowContext<'_>,
1415 flow_ir: HostFlow,
1416 state: ExecutionState,
1417 resume_from: Option<String>,
1418 current_flow_id: String,
1419 ) -> Result<FlowExecution, FlowFailure> {
1420 let mut effects_performed = false;
1421 self.drive_flow_tracked(
1422 ctx,
1423 flow_ir,
1424 state,
1425 resume_from,
1426 current_flow_id,
1427 &mut effects_performed,
1428 )
1429 .await
1430 .map_err(|failure| FlowFailure {
1431 error: terminal_after_effects(failure.error, effects_performed),
1432 node_outputs: failure.node_outputs,
1433 })
1434 }
1435
1436 async fn drive_flow_tracked(
1437 &self,
1438 ctx: &FlowContext<'_>,
1439 mut flow_ir: HostFlow,
1440 mut state: ExecutionState,
1441 resume_from: Option<String>,
1442 mut current_flow_id: String,
1443 effects_performed: &mut bool,
1444 ) -> Result<FlowExecution, FlowFailure> {
1445 let mut current = match resume_from {
1446 Some(node) => NodeId::from_str(&node)
1447 .with_context(|| format!("invalid resume node id `{node}`"))?,
1448 None => flow_ir
1449 .start
1450 .clone()
1451 .or_else(|| flow_ir.nodes.keys().next().cloned())
1452 .ok_or_else(|| {
1453 terminal_flow_error(format!("flow {} has no start node", flow_ir.id))
1454 })?,
1455 };
1456
1457 let mut steps_run: usize = 0;
1458 loop {
1459 steps_run += 1;
1460 check_step_budget(steps_run, flow_ir.id.as_str())?;
1461 let step_ctx = FlowContext {
1462 tenant: ctx.tenant,
1463 pack_id: ctx.pack_id,
1464 flow_id: current_flow_id.as_str(),
1465 node_id: ctx.node_id,
1466 tool: ctx.tool,
1467 action: ctx.action,
1468 session_id: ctx.session_id,
1469 provider_id: ctx.provider_id,
1470 reply_scope: ctx.reply_scope,
1471 retry_config: ctx.retry_config,
1472 attempt: ctx.attempt,
1473 observer: ctx.observer,
1474 mocks: ctx.mocks,
1475 caller: ctx.caller,
1478 };
1479 let node = flow_ir
1480 .nodes
1481 .get(¤t)
1482 .with_context(|| format!("node {} not found", current.as_str()))?;
1483
1484 let payload_template = node.payload_expr.clone();
1485 let prev = state
1486 .last_output
1487 .as_ref()
1488 .cloned()
1489 .unwrap_or_else(|| Value::Object(JsonMap::new()));
1490 let ctx_value = template_context(&state, prev);
1491 #[cfg(feature = "fault-injection")]
1492 {
1493 let fault_ctx = FaultContext {
1494 pack_id: ctx.pack_id,
1495 flow_id: ctx.flow_id,
1496 node_id: Some(current.as_str()),
1497 attempt: ctx.attempt,
1498 };
1499 maybe_fail(FaultPoint::TemplateRender, fault_ctx).map_err(injected_error)?;
1500 }
1501 let mut payload =
1502 render_template_value(&payload_template, &ctx_value, TemplateOptions::default())
1503 .context("failed to render node input template")?;
1504 let node_id = current.clone();
1505
1506 if let NodeKind::Exec { target_component } = &node.kind
1511 && target_component == SLOT_EXTRACTOR_COMPONENT_ID
1512 && let Some(schema) = flow_ir.slot_schema.as_ref()
1513 && let Some(map) = payload.as_object_mut()
1514 {
1515 let input = map.entry("input").or_insert(Value::Null);
1516 inject_slot_definitions(input, schema, step_ctx.flow_id, node_id.as_str());
1517 }
1518
1519 let observed_payload = payload.clone();
1520 let event = NodeEvent {
1521 context: &step_ctx,
1522 node_id: node_id.as_str(),
1523 node,
1524 payload: &observed_payload,
1525 };
1526 if let Some(observer) = step_ctx.observer {
1527 observer.on_node_start(&event);
1528 }
1529 let dispatch = self
1530 .dispatch_node(
1531 &step_ctx,
1532 node_id.as_str(),
1533 node,
1534 &mut state,
1535 payload,
1536 &event,
1537 )
1538 .await;
1539 let DispatchOutcome {
1540 mut output,
1541 control,
1542 } = match dispatch {
1543 Ok(outcome) => outcome,
1544 Err(err) => {
1545 if let Some(observer) = step_ctx.observer {
1546 observer.on_node_error(&event, err.as_ref());
1547 }
1548 if node.kind.may_have_partial_effect_on_failure() && !is_pre_effect_error(&err)
1567 {
1568 *effects_performed = true;
1569 }
1570 return Err(FlowFailure {
1571 error: err,
1572 node_outputs: state.outputs_map(),
1573 });
1574 }
1575 };
1576
1577 if node.kind.performs_external_effect() {
1578 *effects_performed = true;
1579 }
1580 let owned_the_submit =
1581 attach_pending_card_answers(&mut state, node_id.as_str(), node, &mut output);
1582 state.note_created_artifacts(std::mem::take(&mut output.created));
1583 state.record_node_output(node_id.clone().into(), output.clone());
1584 state.last_output = Some(output.payload.clone());
1585 if let Some(bindings) = node.vars_out.as_ref() {
1589 let ctx = template_context(&state, output.payload.clone());
1590 for (var_name, template) in bindings.iter() {
1591 let rendered = render_template_value(
1592 template,
1593 &ctx,
1594 TemplateOptions {
1595 allow_pointer: true,
1596 },
1597 )
1598 .with_context(|| format!("failed to render vars_out binding `{var_name}`"))?;
1599 state.vars.insert(var_name.clone(), rendered);
1600 }
1601 }
1602 if let Some(observer) = step_ctx.observer {
1603 observer.on_node_end(&event, &output.payload);
1604 }
1605
1606 match control {
1607 NodeControl::Continue => {
1608 enum NextDecision {
1609 Next(NodeId),
1610 End,
1611 Wait,
1612 }
1613 let decision = match &node.routing {
1614 Routing::Next { node_id } => NextDecision::Next(node_id.clone()),
1615 Routing::End | Routing::Reply => NextDecision::End,
1616 Routing::Branch { on_status, default } => {
1617 match branch_target(on_status, default.as_ref(), &output) {
1618 Some(target) => NextDecision::Next(target),
1619 None => NextDecision::End,
1620 }
1621 }
1622 Routing::Custom(raw) => {
1623 match evaluate_custom_routing(raw, &output, &state, &flow_ir, &node_id)
1624 {
1625 CustomRoutingDecision::Next(nid) => NextDecision::Next(nid),
1626 CustomRoutingDecision::End => NextDecision::End,
1627 CustomRoutingDecision::Wait => NextDecision::Wait,
1628 }
1629 }
1630 };
1631
1632 if owned_the_submit {
1641 consume_routing_action(&mut state.entry);
1642 }
1643 state.resumed_at = None;
1645
1646 match decision {
1647 NextDecision::Next(n) => current = n,
1648 NextDecision::End => {
1649 let node_outputs = state.outputs_map();
1650 let failure = state.first_unhandled_failure(&flow_ir);
1651 let final_output = state.finalize_with(Some(output.payload.clone()));
1652 return Ok(FlowExecution::completed(
1653 lift_node_error(final_output, failure.as_ref()),
1654 node_outputs,
1655 ));
1656 }
1657 NextDecision::Wait => {
1658 let mut snapshot_state = state.clone();
1663 snapshot_state.clear_egress();
1664 let snapshot = FlowSnapshot {
1665 pack_id: step_ctx.pack_id.to_string(),
1666 flow_id: step_ctx.flow_id.to_string(),
1667 next_flow: (current_flow_id != step_ctx.flow_id)
1668 .then_some(current_flow_id.clone()),
1669 next_node: node_id.as_str().to_string(),
1670 awaiting_submit: true,
1671 state: snapshot_state,
1672 };
1673 let node_outputs = state.outputs_map();
1674 let output_value = state.finalize_with(Some(output.payload.clone()));
1675 return Ok(FlowExecution::waiting(
1676 output_value,
1677 FlowWait {
1678 reason: Some(format!(
1679 "awaiting user submit at node `{}`",
1680 node_id.as_str()
1681 )),
1682 snapshot,
1683 },
1684 node_outputs,
1685 ));
1686 }
1687 }
1688 }
1689 NodeControl::Wait { reason } => {
1690 let next: Option<NodeId> = match &node.routing {
1691 Routing::Next { node_id } => Some(node_id.clone()),
1692 Routing::End | Routing::Reply => None,
1693 Routing::Branch { on_status, default } => {
1694 branch_target(on_status, default.as_ref(), &output)
1695 }
1696 Routing::Custom(raw) => {
1697 match evaluate_custom_routing(raw, &output, &state, &flow_ir, &node_id)
1698 {
1699 CustomRoutingDecision::Next(nid) => Some(nid),
1700 CustomRoutingDecision::End | CustomRoutingDecision::Wait => None,
1705 }
1706 }
1707 };
1708 let resume_target = next.ok_or_else(|| {
1709 anyhow!(
1710 "session.wait node {} requires a non-empty route",
1711 current.as_str()
1712 )
1713 })?;
1714 let mut snapshot_state = state.clone();
1715 snapshot_state.clear_egress();
1716 let snapshot = FlowSnapshot {
1717 pack_id: step_ctx.pack_id.to_string(),
1718 flow_id: step_ctx.flow_id.to_string(),
1719 next_flow: (current_flow_id != step_ctx.flow_id)
1720 .then_some(current_flow_id.clone()),
1721 next_node: resume_target.as_str().to_string(),
1722 awaiting_submit: false,
1723 state: snapshot_state,
1724 };
1725 let node_outputs = state.outputs_map();
1726 let output_value = state.clone().finalize_with(None);
1727 return Ok(FlowExecution::waiting(
1728 output_value,
1729 FlowWait { reason, snapshot },
1730 node_outputs,
1731 ));
1732 }
1733 NodeControl::LoopHere { reason } => {
1734 let mut snapshot_state = state.clone();
1739 snapshot_state.clear_egress();
1740 let snapshot = FlowSnapshot {
1741 pack_id: step_ctx.pack_id.to_string(),
1742 flow_id: step_ctx.flow_id.to_string(),
1743 next_flow: (current_flow_id != step_ctx.flow_id)
1744 .then_some(current_flow_id.clone()),
1745 next_node: node_id.as_str().to_string(),
1746 awaiting_submit: false,
1747 state: snapshot_state,
1748 };
1749 let node_outputs = state.outputs_map();
1750 let rendered = rendered_park(&output.payload);
1756 let output_value = state.finalize_with(Some(rendered));
1757 return Ok(FlowExecution::waiting(
1758 output_value,
1759 FlowWait { reason, snapshot },
1760 node_outputs,
1761 ));
1762 }
1763 NodeControl::AwaitHere {
1764 reason,
1765 correlation_id: _,
1766 } => {
1767 let mut snapshot_state = state.clone();
1783 snapshot_state.clear_egress();
1784 let snapshot = FlowSnapshot {
1785 pack_id: step_ctx.pack_id.to_string(),
1786 flow_id: step_ctx.flow_id.to_string(),
1787 next_flow: (current_flow_id != step_ctx.flow_id)
1788 .then_some(current_flow_id.clone()),
1789 next_node: node_id.as_str().to_string(), awaiting_submit: false,
1791 state: snapshot_state,
1792 };
1793 let node_outputs = state.outputs_map();
1794 let output_value = state.clone().finalize_with(None);
1798 return Ok(FlowExecution::waiting(
1799 output_value,
1800 FlowWait { reason, snapshot },
1801 node_outputs,
1802 ));
1803 }
1804 NodeControl::Jump(jump) => {
1805 let jump_target = self.apply_jump(&step_ctx, &mut state, jump).await?;
1806 flow_ir = jump_target.flow;
1807 current_flow_id = jump_target.flow_id;
1808 current = jump_target.node_id;
1809 }
1810 NodeControl::Respond {
1811 text,
1812 card_cbor,
1813 needs_user,
1814 } => {
1815 let response = json!({
1816 "text": text,
1817 "card_cbor": card_cbor,
1818 "needs_user": needs_user,
1819 });
1820 state.push_egress(response);
1821 let node_outputs = state.outputs_map();
1822 let failure = state.first_unhandled_failure(&flow_ir);
1823 let final_output = state.finalize_with(None);
1824 return Ok(FlowExecution::completed(
1825 lift_node_error(final_output, failure.as_ref()),
1826 node_outputs,
1827 ));
1828 }
1829 }
1830 }
1831 }
1832
1833 async fn dispatch_node(
1834 &self,
1835 ctx: &FlowContext<'_>,
1836 node_id: &str,
1837 node: &HostNode,
1838 state: &mut ExecutionState,
1839 mut payload: Value,
1840 event: &NodeEvent<'_>,
1841 ) -> Result<DispatchOutcome> {
1842 inject_card_locale(&mut payload, &state.entry);
1843 inject_card_route(&mut payload, &state.entry, node);
1844 match &node.kind {
1845 NodeKind::Exec { target_component } => self
1846 .execute_component_exec(
1847 ctx,
1848 node_id,
1849 node,
1850 payload,
1851 event,
1852 ComponentOverrides {
1853 component: Some(target_component.as_str()),
1854 operation: node.operation_name.as_deref(),
1855 },
1856 )
1857 .await
1858 .and_then(component_dispatch_outcome),
1859 NodeKind::PackComponent { component_ref } => self
1860 .execute_component_call(ctx, node_id, node, payload, component_ref.as_str(), event)
1861 .await
1862 .and_then(component_dispatch_outcome),
1863 NodeKind::FlowCall => self
1864 .execute_flow_call(ctx, payload)
1865 .await
1866 .map(DispatchOutcome::complete),
1867 NodeKind::FlowGoto => execute_flow_goto(payload),
1868 NodeKind::ProviderInvoke => self
1869 .execute_provider_invoke(ctx, node_id, state, payload, event)
1870 .await
1871 .map(DispatchOutcome::complete),
1872 NodeKind::BuiltinEmit { kind } => {
1873 match kind {
1874 EmitKind::Log | EmitKind::Response => {}
1875 EmitKind::Other(component) => {
1876 tracing::debug!(%component, "handling emit.* as builtin");
1877 }
1878 }
1879 state.push_egress(payload.clone());
1880 Ok(DispatchOutcome::complete(NodeOutput::new(payload)))
1881 }
1882 NodeKind::BuiltinStateGet => self
1883 .execute_state_get(ctx, payload)
1884 .await
1885 .map(DispatchOutcome::complete),
1886 NodeKind::BuiltinStateSet => self
1887 .execute_state_set(ctx, payload)
1888 .await
1889 .map(DispatchOutcome::complete),
1890 NodeKind::VarSet { name, value } => {
1891 if name.trim().is_empty() {
1892 tracing::warn!(
1893 node_id = %node_id,
1894 "var_set node has an empty variable name; skipping write"
1895 );
1896 return Ok(DispatchOutcome::complete(NodeOutput::new(
1897 serde_json::json!({ "ok": true }),
1898 )));
1899 }
1900 let prev = state.last_output.clone().unwrap_or(Value::Null);
1901 let ctx_val = template_context(state, prev);
1902 let rendered = render_template_value(
1903 value,
1904 &ctx_val,
1905 TemplateOptions {
1906 allow_pointer: true,
1907 },
1908 )
1909 .context("failed to render var_set value")?;
1910 state.vars.insert(name.clone(), rendered);
1911 Ok(DispatchOutcome::complete(NodeOutput::new(
1912 serde_json::json!({ "ok": true }),
1913 )))
1914 }
1915 NodeKind::Wait => {
1916 let reason = extract_wait_reason(&payload);
1917 Ok(DispatchOutcome::wait(NodeOutput::new(payload), reason))
1918 }
1919 NodeKind::DwAgent {
1920 agent_id,
1921 conversational,
1922 } => {
1923 #[cfg(feature = "agentic-worker")]
1924 match self.dw_agent_dispatch {
1925 crate::runner::agent_node::DwAgentDispatch::Nats => {
1926 if *conversational {
1927 let is_agent_response = state.entry.get("ok").is_some();
1943 if is_agent_response && state.take_agent_await(node_id) {
1944 let ok = state
1954 .entry
1955 .get("ok")
1956 .and_then(Value::as_bool)
1957 .unwrap_or(false);
1958 if !ok {
1959 let (_reply, payload) =
1971 agent_error_envelope_reply(&state.entry);
1972 let (error_code, error_message) =
1976 agent_error_log_fields(&state.entry);
1977 tracing::warn!(
1978 agent_id = %agent_id,
1979 error_code = %error_code,
1980 error = %error_message,
1981 "conversational dw.agent (nats) response was an error/timeout envelope; surfacing and re-parking without bumping the park-loop cap"
1982 );
1983 let output = NodeOutput::new(payload);
1984 Ok(DispatchOutcome::with_control(
1985 output,
1986 NodeControl::LoopHere {
1987 reason: Some(format!(
1988 "conversational dw.agent `{agent_id}` (nats) awaiting next user message after error response"
1989 )),
1990 },
1991 ))
1992 } else {
1993 let agent_out =
1994 state.entry.get("output").cloned().unwrap_or(Value::Null);
1995 let output = NodeOutput::new(agent_out.clone());
1996 let ended = agent_out
1997 .get("terminated_by")
1998 .and_then(serde_json::Value::as_str)
1999 == Some("conversation_ended");
2000 if ended {
2001 state.reset_park_turns(node_id);
2002 Ok(DispatchOutcome::complete(output))
2003 } else {
2004 let turns = state.bump_park_turns(node_id);
2005 if turns >= MAX_PARK_TURNS {
2006 tracing::warn!(
2007 agent_id = %agent_id,
2008 turns,
2009 "conversational dw.agent (nats) hit park-loop cap ({MAX_PARK_TURNS}); force-advancing to successor"
2010 );
2011 state.reset_park_turns(node_id);
2016 Ok(DispatchOutcome::complete(output))
2017 } else {
2018 Ok(DispatchOutcome::with_control(
2019 output,
2020 NodeControl::LoopHere {
2021 reason: Some(format!(
2022 "conversational dw.agent `{agent_id}` (nats) awaiting next user message"
2023 )),
2024 },
2025 ))
2026 }
2027 }
2028 }
2029 } else {
2030 state.mark_agent_await(node_id);
2042 let remote_payload =
2043 serde_json::json!({ "await": true, "input": payload });
2044 self.execute_remote_dispatch(
2045 ctx,
2046 "agentic",
2047 agent_id,
2048 remote_payload,
2049 true,
2050 )
2051 .await
2052 }
2053 } else {
2054 let remote_payload =
2057 serde_json::json!({ "await": true, "input": payload });
2058 self.execute_remote_dispatch(
2059 ctx,
2060 "agentic",
2061 agent_id,
2062 remote_payload,
2063 false,
2064 )
2065 .await
2066 }
2067 }
2068 crate::runner::agent_node::DwAgentDispatch::InProcess => {
2069 let resume_payload = (state.take_tool_await(node_id)
2075 && is_card_submit(&state.entry))
2076 .then(|| state.entry.clone());
2077 let output = self
2078 .execute_dw_agent(
2079 ctx,
2080 agent_id,
2081 payload,
2082 *conversational,
2083 resume_payload.as_ref(),
2084 )
2085 .await?;
2086 if awaiting_tool_input(&output.payload) {
2087 state.mark_tool_await(node_id);
2093 Ok(DispatchOutcome::with_control(
2094 output,
2095 NodeControl::LoopHere {
2096 reason: Some(format!(
2097 "dw.agent `{agent_id}` awaiting the user on a flow tool"
2098 )),
2099 },
2100 ))
2101 } else if *conversational {
2102 let ended = output
2103 .payload
2104 .get("terminated_by")
2105 .and_then(serde_json::Value::as_str)
2106 == Some("conversation_ended");
2107 if ended {
2108 state.reset_park_turns(node_id);
2109 Ok(DispatchOutcome::complete(output))
2110 } else {
2111 let turns = state.bump_park_turns(node_id);
2112 if turns >= MAX_PARK_TURNS {
2113 tracing::warn!(
2114 agent_id = %agent_id,
2115 turns,
2116 "conversational dw.agent hit park-loop cap ({MAX_PARK_TURNS}); force-advancing to successor"
2117 );
2118 state.reset_park_turns(node_id);
2123 Ok(DispatchOutcome::complete(output))
2124 } else {
2125 Ok(DispatchOutcome::with_control(
2126 output,
2127 NodeControl::LoopHere {
2128 reason: Some(format!(
2129 "conversational dw.agent `{agent_id}` awaiting next user message"
2130 )),
2131 },
2132 ))
2133 }
2134 }
2135 } else {
2136 Ok(DispatchOutcome::complete(output))
2137 }
2138 }
2139 }
2140 #[cfg(not(feature = "agentic-worker"))]
2141 {
2142 self.execute_dw_agent(ctx, agent_id, payload, *conversational, None)
2143 .await
2144 .map(DispatchOutcome::complete)
2145 }
2146 }
2147 NodeKind::DwAgentGraph { graph_id } => self
2148 .execute_dw_agent_graph(ctx, graph_id, payload)
2149 .await
2150 .map(DispatchOutcome::complete),
2151 NodeKind::SorlaCall { target } => {
2152 self.execute_sorla_call(
2153 ctx,
2154 node_id,
2155 target,
2156 payload,
2157 node_has_error_route(&node.routing),
2158 )
2159 .await
2160 }
2161 NodeKind::OperalaCall { target } => {
2162 self.execute_operala_call(ctx, target, payload).await
2163 }
2164 NodeKind::AgenticCall { target } => {
2165 self.execute_agentic_call(ctx, target, payload).await
2166 }
2167 NodeKind::TelcoXCall { target } => {
2168 self.execute_telco_x_call(ctx, target, payload).await
2169 }
2170 NodeKind::ApprovalCall { target } => {
2171 self.execute_approval_call(ctx, node_id, target, payload, state)
2172 .await
2173 }
2174 NodeKind::Mcp { server_id, tool } => self
2175 .execute_mcp(
2176 ctx,
2177 server_id,
2178 tool,
2179 payload,
2180 node_has_error_route(&node.routing),
2181 )
2182 .await
2183 .map(DispatchOutcome::complete),
2184 NodeKind::A2a { agent_id } => self
2185 .execute_a2a(ctx, agent_id, payload, node_has_error_route(&node.routing))
2186 .await
2187 .map(DispatchOutcome::complete),
2188 NodeKind::MediaCreate => self
2189 .execute_media_create(ctx, payload, node_has_error_route(&node.routing))
2190 .await
2191 .map(DispatchOutcome::complete),
2192 }
2193 }
2194
2195 #[cfg(feature = "agentic-worker")]
2202 async fn execute_media_create(
2203 &self,
2204 ctx: &FlowContext<'_>,
2205 payload: Value,
2206 has_error_route: bool,
2207 ) -> Result<NodeOutput> {
2208 let result = crate::runner::media_node::create(
2209 &payload,
2210 ctx.tenant,
2211 self.ext_artifact_port.as_ref(),
2212 )
2213 .await;
2214 Ok(media_node_output(
2215 bind_node_result(&payload, result.clone()),
2216 &result,
2217 has_error_route,
2218 ))
2219 }
2220
2221 #[cfg(not(feature = "agentic-worker"))]
2224 async fn execute_media_create(
2225 &self,
2226 _ctx: &FlowContext<'_>,
2227 _payload: Value,
2228 _has_error_route: bool,
2229 ) -> Result<NodeOutput> {
2230 Ok(NodeOutput::new(json!({
2231 "ok": false,
2232 "error": {
2233 "code": "artifact_unavailable",
2234 "message": "media.create requires the agentic-worker feature"
2235 }
2236 })))
2237 }
2238
2239 #[cfg(feature = "agentic-worker")]
2240 async fn execute_dw_agent(
2241 &self,
2242 ctx: &FlowContext<'_>,
2243 agent_id: &str,
2244 payload: Value,
2245 conversational: bool,
2246 resume_payload: Option<&Value>,
2247 ) -> Result<NodeOutput> {
2248 let handler = self
2249 .agent_node_handler
2250 .as_ref()
2251 .context("DwAgent node dispatched but no AgentNodeHandler configured on FlowEngine")
2252 .map_err(pre_effect)?;
2253 let session_owned = crate::runner::nested_flow::agent_session_for(ctx.session_id)
2258 .map_err(anyhow::Error::msg)
2259 .map_err(pre_effect)?;
2260 let session_id = session_owned.as_str();
2261 let started = std::time::Instant::now();
2262 let mut result = handler
2263 .execute_with_resume(
2264 ctx.tenant,
2265 &self.default_env,
2266 agent_id,
2267 session_id,
2268 &payload,
2269 conversational,
2270 ctx.caller,
2273 resume_payload,
2274 )
2275 .await?;
2276 if let Value::Object(map) = &mut result {
2280 map.insert(
2281 "duration_ms".into(),
2282 Value::from(started.elapsed().as_millis() as u64),
2283 );
2284 }
2285 Ok(NodeOutput::new(result))
2286 }
2287
2288 #[cfg(not(feature = "agentic-worker"))]
2289 async fn execute_dw_agent(
2290 &self,
2291 _ctx: &FlowContext<'_>,
2292 agent_id: &str,
2293 _payload: Value,
2294 _conversational: bool,
2295 _resume_payload: Option<&Value>,
2296 ) -> Result<NodeOutput> {
2297 anyhow::bail!(
2298 "DwAgent node '{agent_id}' cannot run: this build was compiled without the \
2299 `agentic-worker` feature. Rebuild with --features agentic-worker."
2300 )
2301 }
2302
2303 #[cfg(feature = "agentic-worker")]
2324 async fn execute_sorla_call(
2325 &self,
2326 ctx: &FlowContext<'_>,
2327 node_id: &str,
2328 target: &str,
2329 payload: Value,
2330 has_error_route: bool,
2331 ) -> Result<DispatchOutcome> {
2332 let caller = format!("flow:{}/{node_id}", ctx.flow_id);
2336 let http_result = match self.mcp_secrets_for_dispatch() {
2337 Some(secrets) => {
2338 crate::runner::sorla_node::execute_sorla_http(
2339 &*secrets,
2340 ctx.tenant,
2341 self.mcp_credential_unit(),
2342 target,
2343 &payload,
2344 &caller,
2345 )
2346 .await
2347 }
2348 None => Ok(None),
2351 };
2352 match http_result {
2353 Ok(Some(result)) => {
2354 let bound = match payload.get("output").and_then(Value::as_str) {
2355 Some(key) if !key.is_empty() => json!({ key: result.clone() }),
2356 _ => result.clone(),
2357 };
2358 Ok(DispatchOutcome::complete(mcp_node_output(
2359 bound,
2360 &result,
2361 has_error_route,
2362 )))
2363 }
2364 Ok(None) if self.remote_dispatch_configured() => {
2365 self.execute_remote_dispatch(ctx, "sorla", target, payload, false)
2366 .await
2367 }
2368 Ok(None) => sorla_failure(
2369 format!(
2370 "sorla_route_missing: no route document for SoR `{target}` and no NATS configured"
2371 ),
2372 has_error_route,
2373 ),
2374 Err(e) => sorla_failure(e, has_error_route),
2375 }
2376 }
2377
2378 #[cfg(not(feature = "agentic-worker"))]
2386 async fn execute_sorla_call(
2387 &self,
2388 ctx: &FlowContext<'_>,
2389 _node_id: &str,
2390 target: &str,
2391 payload: Value,
2392 _has_error_route: bool,
2393 ) -> Result<DispatchOutcome> {
2394 self.execute_remote_dispatch(ctx, "sorla", target, payload, false)
2395 .await
2396 }
2397
2398 async fn execute_operala_call(
2408 &self,
2409 ctx: &FlowContext<'_>,
2410 target: &str,
2411 payload: Value,
2412 ) -> Result<DispatchOutcome> {
2413 if let Some(handler) = self.operala_node_handler.as_ref() {
2414 let raw_operation = payload
2419 .get("operation")
2420 .and_then(Value::as_str)
2421 .unwrap_or_default();
2422 let operation = if raw_operation.eq_ignore_ascii_case("invoke") {
2423 "run"
2424 } else {
2425 raw_operation
2426 };
2427 let inner_input = payload.get("input").cloned().unwrap_or(Value::Null);
2428 let session_id = ctx.session_id.unwrap_or("");
2429 let result = handler
2430 .execute(
2431 ctx.tenant,
2432 &self.default_env,
2433 target,
2434 operation,
2435 session_id,
2436 &inner_input,
2437 )
2438 .await?;
2439 return Ok(DispatchOutcome::complete(NodeOutput::new(result)));
2440 }
2441 self.execute_remote_dispatch(ctx, "operala", target, payload, false)
2442 .await
2443 }
2444
2445 async fn execute_agentic_call(
2450 &self,
2451 ctx: &FlowContext<'_>,
2452 target: &str,
2453 payload: Value,
2454 ) -> Result<DispatchOutcome> {
2455 self.execute_remote_dispatch(ctx, "agentic", target, payload, false)
2456 .await
2457 }
2458
2459 async fn execute_telco_x_call(
2463 &self,
2464 ctx: &FlowContext<'_>,
2465 target: &str,
2466 payload: Value,
2467 ) -> Result<DispatchOutcome> {
2468 self.execute_remote_dispatch(ctx, "telco-x", target, payload, false)
2469 .await
2470 }
2471
2472 async fn execute_approval_call(
2485 &self,
2486 ctx: &FlowContext<'_>,
2487 node_id: &str,
2488 target: &str,
2489 payload: Value,
2490 state: &mut ExecutionState,
2491 ) -> Result<DispatchOutcome> {
2492 if let Some(parked) = state.take_approval_await(node_id) {
2493 if entry_is_approval_response(&state.entry) {
2494 if response_authenticates(&state.entry, &parked) {
2495 let mut response = state.entry.clone();
2498 approval_token::strip_from_response(&mut response);
2499 let outcome = approval_outcome_from_entry(&response);
2500 let output =
2501 NodeOutput::with_meta(response, serde_json::json!({ "outcome": outcome }));
2502 return Ok(DispatchOutcome::complete(output));
2503 }
2504 tracing::warn!(
2510 node_id,
2511 "refusing approval response: its decision_token is missing or does not match the one this gate was issued; the gate stays parked"
2512 );
2513 }
2514 state.mark_approval_await(node_id, parked);
2520 return Ok(DispatchOutcome::await_here(
2521 NodeOutput::new(serde_json::json!({ "pending": true })),
2522 Some("awaiting approval decision".to_string()),
2523 String::new(),
2524 ));
2525 }
2526
2527 let input = payload.get("input").cloned().unwrap_or(Value::Null);
2528 if !approval_requires_human(&input) {
2529 let output = NodeOutput::with_meta(
2530 serde_json::json!({
2531 "ok": true,
2532 "output": { "decision": "approved", "auto": true },
2533 "error": serde_json::Value::Null,
2534 }),
2535 serde_json::json!({ "outcome": "approved" }),
2536 );
2537 return Ok(DispatchOutcome::complete(output));
2538 }
2539
2540 let issued = approval_token::issue();
2550 let outcome = self
2551 .execute_remote_dispatch_with_token(
2552 ctx,
2553 APPROVAL_RUNTIME,
2554 target,
2555 payload,
2556 true,
2557 Some(issued.token),
2558 )
2559 .await?;
2560 if let NodeControl::AwaitHere { correlation_id, .. } = &outcome.control {
2561 state.mark_approval_await(
2562 node_id,
2563 ParkedApproval {
2564 correlation_id: Some(correlation_id.clone()).filter(|id| !id.is_empty()),
2565 token_fingerprint: Some(issued.fingerprint),
2566 },
2567 );
2568 }
2569 Ok(outcome)
2570 }
2571
2572 #[cfg(feature = "agentic-worker")]
2590 async fn execute_mcp(
2591 &self,
2592 ctx: &FlowContext<'_>,
2593 server_id: &str,
2594 tool: &str,
2595 payload: Value,
2596 has_error_route: bool,
2597 ) -> Result<NodeOutput> {
2598 let payload_server = crate::runner::mcp_node::str_field(&payload, "server");
2602 let payload_tool = crate::runner::mcp_node::str_field(&payload, "tool");
2603 let server_id = payload_server.as_deref().unwrap_or(server_id);
2604 let tool = payload_tool.as_deref().unwrap_or(tool);
2605
2606 let arguments = payload
2608 .get("arguments")
2609 .cloned()
2610 .unwrap_or_else(|| Value::Object(JsonMap::new()));
2611
2612 let pack_routes = self
2617 .packs
2618 .iter()
2619 .find(|pack| pack.metadata().pack_id == ctx.pack_id)
2620 .and_then(|pack| pack.mcp_routes());
2621
2622 let auth_team = pack_routes
2629 .and_then(|routes| routes.get(server_id))
2630 .and_then(|route| route.auth_team.as_deref());
2631
2632 let secrets = self.mcp_secrets_for_dispatch();
2637 let result = crate::runner::mcp_node::aw::invoke_with_secrets(
2638 self.mcp_tool_source.as_ref(),
2639 pack_routes,
2640 secrets.as_ref(),
2641 ctx.tenant,
2642 &self.default_env,
2643 auth_team,
2644 self.mcp_credential_unit(),
2645 server_id,
2646 tool,
2647 &arguments,
2648 )
2649 .await;
2650
2651 Ok(mcp_node_output(
2652 bind_node_result(&payload, result.clone()),
2653 &result,
2654 has_error_route,
2655 ))
2656 }
2657
2658 #[cfg(not(feature = "agentic-worker"))]
2662 async fn execute_mcp(
2663 &self,
2664 _ctx: &FlowContext<'_>,
2665 server_id: &str,
2666 tool: &str,
2667 _payload: Value,
2668 _has_error_route: bool,
2669 ) -> Result<NodeOutput> {
2670 Ok(NodeOutput::new(json!({
2671 "error": format!(
2672 "mcp node '{server_id}/{tool}' requires the agentic-worker feature (MCP runtime not compiled in)"
2673 )
2674 })))
2675 }
2676
2677 #[cfg(feature = "agentic-worker")]
2680 fn a2a_source_for(
2681 &self,
2682 tenant: &str,
2683 pack: &Arc<PackRuntime>,
2684 ) -> Option<Arc<greentic_aw_runtime::A2aToolSource>> {
2685 let key = (tenant.to_string(), pack.metadata().pack_id.to_string());
2686 if let Some(cached) = self.a2a_sources.read().get(&key) {
2687 return Some(Arc::clone(cached));
2688 }
2689 let secrets = self.mcp_secrets_for_dispatch();
2693 let source = crate::runner::a2a_node::aw::source_for_pack(
2694 pack,
2695 tenant,
2696 secrets,
2697 self.mcp_credential_unit(),
2698 )?;
2699 let mut sources = self.a2a_sources.write();
2702 let entry = sources.entry(key).or_insert(source);
2703 Some(Arc::clone(entry))
2704 }
2705
2706 #[cfg(feature = "agentic-worker")]
2728 async fn execute_a2a(
2729 &self,
2730 ctx: &FlowContext<'_>,
2731 agent_id: &str,
2732 payload: Value,
2733 has_error_route: bool,
2734 ) -> Result<NodeOutput> {
2735 let payload_agent = crate::runner::a2a_node::agent_from_payload(&payload);
2736 let agent_id = payload_agent.as_deref().unwrap_or(agent_id);
2737
2738 let pack = self.pack_for_flow(ctx).map_err(pre_effect)?;
2739 let pack_id = pack.metadata().pack_id.to_string();
2740
2741 let answer = crate::runner::a2a_node::answer_from_payload(&payload);
2745 let blank_message = Value::String(String::new());
2748 let message = payload
2749 .get("message")
2750 .filter(|value| !is_blank(value))
2751 .or_else(|| answer.as_ref().map(|_| &blank_message));
2752 let Some(message) = message else {
2753 let result = greentic_aw_runtime::a2a_source::call_error_value(
2754 agent_id,
2755 "a2a node has no `message` to send (expected a non-empty `message` field \
2756 in the node's config)",
2757 );
2758 tracing::warn!(agent = agent_id, "a2a node has no message configured");
2759 return Ok(a2a_node_output(
2760 bind_node_result(&payload, result.clone()),
2761 &result,
2762 has_error_route,
2763 ));
2764 };
2765
2766 let card_submit_to = crate::runner::a2a_node::card_submit_target(&payload);
2767 let source = self.a2a_source_for(ctx.tenant, pack);
2768 let store = pack.state_store_handle();
2769 let state_ctx = self.state_tenant_ctx(ctx).ok();
2772
2773 let result = crate::runner::a2a_node::aw::invoke(
2774 crate::runner::a2a_node::aw::A2aCall {
2775 source: source.as_ref(),
2776 store: store.as_ref(),
2777 state_ctx: state_ctx.as_ref(),
2778 flow_id: ctx.flow_id,
2783 session_id: ctx.session_id.filter(|hint| !hint.is_empty()),
2784 tenant: ctx.tenant,
2785 env: &self.default_env,
2786 pack_id: &pack_id,
2787 want_card: crate::runner::a2a_node::wants_card(&payload),
2788 answer,
2789 card_submit_to: card_submit_to.as_deref(),
2790 },
2791 agent_id,
2792 message,
2793 )
2794 .await;
2795
2796 Ok(a2a_node_output(
2797 bind_node_result(&payload, result.clone()),
2798 &result,
2799 has_error_route,
2800 ))
2801 }
2802
2803 #[cfg(not(feature = "agentic-worker"))]
2808 async fn execute_a2a(
2809 &self,
2810 _ctx: &FlowContext<'_>,
2811 agent_id: &str,
2812 _payload: Value,
2813 _has_error_route: bool,
2814 ) -> Result<NodeOutput> {
2815 Ok(NodeOutput::new(json!({
2816 "status": "error",
2817 "agent": agent_id,
2818 "error": format!(
2819 "a2a node '{agent_id}' requires the agentic-worker feature (the A2A client is \
2820 not compiled in)"
2821 )
2822 })))
2823 }
2824
2825 async fn execute_remote_dispatch(
2854 &self,
2855 ctx: &FlowContext<'_>,
2856 runtime: &str,
2857 target: &str,
2858 payload: Value,
2859 resume_at_self: bool,
2860 ) -> Result<DispatchOutcome> {
2861 self.execute_remote_dispatch_with_token(ctx, runtime, target, payload, resume_at_self, None)
2862 .await
2863 }
2864
2865 async fn execute_remote_dispatch_with_token(
2869 &self,
2870 ctx: &FlowContext<'_>,
2871 runtime: &str,
2872 target: &str,
2873 payload: Value,
2874 resume_at_self: bool,
2875 decision_token: Option<String>,
2876 ) -> Result<DispatchOutcome> {
2877 let handler = self
2878 .dispatch_handler_for(runtime)
2879 .with_context(|| {
2880 format!("{runtime}.call node dispatched but no RemoteDispatchHandler configured")
2881 })
2882 .map_err(pre_effect)?;
2883
2884 let await_mode = payload
2885 .get("await")
2886 .and_then(Value::as_bool)
2887 .unwrap_or(true);
2888 let operation = payload
2889 .get("operation")
2890 .and_then(Value::as_str)
2891 .unwrap_or_default()
2892 .to_string();
2893 let deadline_ms = payload.get("deadline_ms").and_then(Value::as_u64);
2894 let inner_input = payload.get("input").cloned().unwrap_or(Value::Null);
2895
2896 let raw_hint = ctx.session_id.unwrap_or_default();
2906 let bare_hint =
2909 crate::runner::runtime_session_resumer::parse_correlation(raw_hint).bare_hint;
2910 let mut correlation_id =
2920 format!("{}::pack={}::flow={}", bare_hint, ctx.pack_id, ctx.flow_id);
2921 if let Some(scope) = ctx.reply_scope {
2922 crate::runner::runtime_session_resumer::push_scope_markers(&mut correlation_id, scope);
2923 }
2924 if runtime == APPROVAL_RUNTIME {
2936 correlation_id.push_str(crate::runner::runtime_session_resumer::NONCE_HINT_MARKER);
2937 correlation_id.push_str(&crate::runner::runtime_session_resumer::new_dispatch_nonce());
2938 }
2939 let mode = if await_mode {
2940 greentic_types::DispatchMode::Await
2941 } else {
2942 greentic_types::DispatchMode::FireAndForget
2943 };
2944
2945 let action = handler
2946 .dispatch(crate::runner::remote_dispatch::RemoteDispatch {
2947 tenant: ctx.tenant.to_string(),
2948 env: self.default_env.clone(),
2949 runtime: runtime.to_string(),
2950 target: target.to_string(),
2951 operation,
2952 mode,
2953 correlation_id: correlation_id.clone(),
2954 input: inner_input,
2955 deadline_ms,
2956 decision_token,
2957 })
2958 .await?;
2959
2960 match action {
2961 crate::runner::remote_dispatch::RemoteDispatchAction::AwaitingResponse {
2962 correlation_id,
2963 } => {
2964 let reason = format!("await-runtime:{correlation_id}");
2965 let output = NodeOutput::new(serde_json::json!({
2966 "pending": true,
2967 "correlation_id": correlation_id.clone(),
2968 }));
2969 if resume_at_self {
2970 Ok(DispatchOutcome::await_here(
2971 output,
2972 Some(reason),
2973 correlation_id,
2974 ))
2975 } else {
2976 Ok(DispatchOutcome::wait(output, Some(reason)))
2977 }
2978 }
2979 crate::runner::remote_dispatch::RemoteDispatchAction::Dispatched => {
2980 let output = NodeOutput::new(serde_json::json!({
2981 "dispatched": true,
2982 "correlation_id": correlation_id,
2983 }));
2984 Ok(DispatchOutcome::complete(output))
2985 }
2986 }
2987 }
2988
2989 #[cfg(feature = "agentic-worker")]
2996 async fn execute_dw_agent_graph(
2997 &self,
2998 ctx: &FlowContext<'_>,
2999 graph_id: &str,
3000 payload: Value,
3001 ) -> Result<NodeOutput> {
3002 let handler = self
3003 .graph_node_handler
3004 .as_ref()
3005 .context(
3006 "DwAgentGraph node dispatched but no GraphNodeHandler configured on FlowEngine",
3007 )
3008 .map_err(pre_effect)?;
3009 let session_id = ctx.session_id.unwrap_or("");
3010 let result = handler
3011 .execute(
3012 ctx.tenant,
3013 &self.default_env,
3014 graph_id,
3015 session_id,
3016 &payload,
3017 )
3018 .await?;
3019 Ok(NodeOutput::new(result))
3020 }
3021
3022 #[cfg(not(feature = "agentic-worker"))]
3023 async fn execute_dw_agent_graph(
3024 &self,
3025 _ctx: &FlowContext<'_>,
3026 graph_id: &str,
3027 _payload: Value,
3028 ) -> Result<NodeOutput> {
3029 anyhow::bail!(
3030 "DwAgentGraph node '{graph_id}' cannot run: this build was compiled without the \
3031 `agentic-worker` feature. Rebuild with --features agentic-worker."
3032 )
3033 }
3034
3035 async fn execute_state_get(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
3036 let key = Self::extract_state_key_helper(&payload)?;
3037 let pack = self.pack_for_flow(ctx)?;
3038 let store = pack
3039 .state_store_handle()
3040 .context("state store is not configured for this runtime")?;
3041 let tenant_ctx = self.state_tenant_ctx(ctx)?;
3042 let state_key = greentic_state::StateKey::new(&key);
3043 let value = store
3044 .get_json(
3045 &tenant_ctx,
3046 crate::storage::state::STATE_PREFIX,
3047 &state_key,
3048 None,
3049 )
3050 .with_context(|| format!("state.get failed for key `{key}`"))?;
3051 let payload = serde_json::json!({
3052 "key": key,
3053 "value": value,
3054 "found": value.is_some(),
3055 });
3056 Ok(NodeOutput::new(payload))
3057 }
3058
3059 async fn execute_state_set(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
3060 let key = Self::extract_state_key_helper(&payload)?;
3061 let value = payload.get("value").cloned().unwrap_or(Value::Null);
3062 let pack = self.pack_for_flow(ctx)?;
3063 let store = pack
3064 .state_store_handle()
3065 .context("state store is not configured for this runtime")?;
3066 let tenant_ctx = self.state_tenant_ctx(ctx)?;
3067 let state_key = greentic_state::StateKey::new(&key);
3068 store
3069 .set_json(
3070 &tenant_ctx,
3071 crate::storage::state::STATE_PREFIX,
3072 &state_key,
3073 None,
3074 &value,
3075 None,
3076 )
3077 .with_context(|| format!("state.set failed for key `{key}`"))?;
3078 let payload = serde_json::json!({ "key": key, "value": value });
3079 Ok(NodeOutput::new(payload))
3080 }
3081
3082 fn pack_for_flow(&self, ctx: &FlowContext<'_>) -> Result<&Arc<PackRuntime>> {
3083 let key = FlowKey {
3084 pack_id: ctx.pack_id.to_string(),
3085 flow_id: ctx.flow_id.to_string(),
3086 };
3087 let idx = self.flow_sources.get(&key).with_context(|| {
3088 format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
3089 })?;
3090 Ok(&self.packs[*idx])
3091 }
3092
3093 fn extract_state_key_helper(payload: &Value) -> Result<String> {
3094 payload
3095 .get("key")
3096 .and_then(Value::as_str)
3097 .map(String::from)
3098 .filter(|k| !k.is_empty())
3099 .context("state node payload missing required `key` (non-empty string)")
3100 }
3101
3102 fn state_tenant_ctx(&self, ctx: &FlowContext<'_>) -> Result<greentic_types::TenantCtx> {
3103 let env = greentic_types::EnvId::from_str(&self.default_env)
3104 .with_context(|| format!("invalid env id `{}`", self.default_env))?;
3105 let tenant = greentic_types::TenantId::from_str(ctx.tenant)
3106 .with_context(|| format!("invalid tenant id `{}`", ctx.tenant))?;
3107 Ok(greentic_types::TenantCtx::new(env, tenant))
3108 }
3109
3110 async fn apply_jump(
3111 &self,
3112 ctx: &FlowContext<'_>,
3113 state: &mut ExecutionState,
3114 jump: JumpControl,
3115 ) -> Result<JumpTarget> {
3116 let target_flow = jump.flow.trim();
3117 if target_flow.is_empty() {
3118 return Err(terminal_flow_error("missing_flow"));
3119 }
3120
3121 let flow = self
3122 .get_or_load_flow(ctx.pack_id, target_flow)
3123 .await
3124 .with_context(|| format!("unknown_flow:{target_flow}"))?;
3125
3126 let target_node = if let Some(node) = jump.node.as_deref() {
3127 let parsed = NodeId::from_str(node)
3128 .map_err(|err| terminal_flow_error(format!("unknown_node:{node}: {err}")))?;
3129 if !flow.nodes.contains_key(&parsed) {
3130 return Err(terminal_flow_error(format!("unknown_node:{node}")));
3131 }
3132 parsed
3133 } else {
3134 flow.start
3135 .clone()
3136 .or_else(|| flow.nodes.keys().next().cloned())
3137 .ok_or_else(|| {
3138 terminal_flow_error(format!(
3139 "jump_failed: flow {target_flow} has no start node"
3140 ))
3141 })?
3142 };
3143
3144 let max_redirects = jump.max_redirects.unwrap_or(3);
3145 if state.redirect_count() >= max_redirects {
3146 return Err(terminal_flow_error("redirect_limit"));
3147 }
3148 state.increment_redirect_count();
3149 state.replace_input(jump.payload.clone());
3150 state.last_output = Some(jump.payload);
3151 tracing::info!(
3152 flow_id = %ctx.flow_id,
3153 target_flow = %target_flow,
3154 target_node = %target_node.as_str(),
3155 reason = ?jump.reason,
3156 redirects = state.redirect_count(),
3157 "flow.jump.applied"
3158 );
3159
3160 Ok(JumpTarget {
3161 flow_id: target_flow.to_string(),
3162 flow,
3163 node_id: target_node,
3164 })
3165 }
3166
3167 async fn execute_flow_call(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
3168 #[derive(Deserialize)]
3169 struct FlowCallPayload {
3170 #[serde(alias = "flow")]
3171 flow_id: String,
3172 #[serde(default)]
3173 input: Value,
3174 }
3175
3176 let call: FlowCallPayload =
3177 serde_json::from_value(payload).context("invalid payload for flow.call node")?;
3178 if call.flow_id.trim().is_empty() {
3179 return Err(terminal_flow_error(
3180 "flow.call requires a non-empty flow_id",
3181 ));
3182 }
3183
3184 let sub_input = if call.input.is_null() {
3185 Value::Null
3186 } else {
3187 call.input
3188 };
3189
3190 let flow_id_owned = call.flow_id;
3191 let action = "flow.call";
3192 let sub_ctx = FlowContext {
3193 tenant: ctx.tenant,
3194 pack_id: ctx.pack_id,
3195 flow_id: flow_id_owned.as_str(),
3196 node_id: None,
3197 tool: ctx.tool,
3198 action: Some(action),
3199 session_id: ctx.session_id,
3200 provider_id: ctx.provider_id,
3201 reply_scope: ctx.reply_scope,
3202 retry_config: ctx.retry_config,
3203 attempt: ctx.attempt,
3204 observer: ctx.observer,
3205 mocks: ctx.mocks,
3206 caller: ctx.caller,
3209 };
3210
3211 let depth = FLOW_CALL_DEPTH.try_with(|depth| *depth).unwrap_or(0);
3212 if depth >= MAX_FLOW_CALL_DEPTH {
3213 return Err(terminal_flow_error(format!(
3214 "flow.call nesting exceeds {MAX_FLOW_CALL_DEPTH} levels (calling {})",
3215 flow_id_owned
3216 )));
3217 }
3218 let sub_ctx = FlowContext {
3221 retry_config: RetryConfig {
3222 max_attempts: 1,
3223 ..sub_ctx.retry_config
3224 },
3225 ..sub_ctx
3226 };
3227 let execution = FLOW_CALL_DEPTH
3228 .scope(
3229 depth + 1,
3230 Box::pin(self.execute_propagating_failure(sub_ctx, sub_input)),
3231 )
3232 .await
3233 .with_context(|| format!("flow.call failed for {}", flow_id_owned))?;
3234 match execution.status {
3235 FlowStatus::Completed => Ok(NodeOutput::new(execution.output)),
3236 FlowStatus::Waiting(wait) => Err(terminal_flow_error(format!(
3238 "flow.call cannot pause (flow {} waiting {:?})",
3239 flow_id_owned, wait.reason
3240 ))),
3241 }
3242 }
3243}
3244
3245fn branch_target(
3251 on_status: &std::collections::BTreeMap<String, NodeId>,
3252 default: Option<&NodeId>,
3253 output: &NodeOutput,
3254) -> Option<NodeId> {
3255 let status_of = |value: &Value| match value {
3256 Value::String(text) => Some(text.clone()),
3257 Value::Number(number) => Some(number.to_string()),
3258 Value::Bool(flag) => Some(flag.to_string()),
3259 _ => None,
3260 };
3261 let status = output
3262 .payload
3263 .get("status")
3264 .and_then(status_of)
3265 .or_else(|| output.meta.get("status").and_then(status_of));
3266 status
3267 .and_then(|status| on_status.get(&status).cloned())
3268 .or_else(|| default.cloned())
3269}
3270
3271#[cfg(feature = "agentic-worker")]
3272use crate::runner::media_node::MAX_CREATED_PER_TURN;
3273
3274#[cfg(not(feature = "agentic-worker"))]
3277const MAX_CREATED_PER_TURN: usize = 20;
3278
3279#[cfg(feature = "agentic-worker")]
3280fn attach_created_files(reply: Value, created: Vec<Value>) -> Value {
3281 crate::runner::media_node::attach_created(reply, created)
3282}
3283
3284#[cfg(not(feature = "agentic-worker"))]
3286fn attach_created_files(reply: Value, _created: Vec<Value>) -> Value {
3287 reply
3288}
3289
3290const MAX_FLOW_CALL_DEPTH: u32 = 16;
3292
3293tokio::task_local! {
3294 static FLOW_CALL_DEPTH: u32;
3296}
3297
3298fn execute_flow_goto(payload: Value) -> Result<DispatchOutcome> {
3317 #[derive(Deserialize)]
3318 struct FlowGotoPayload {
3319 #[serde(alias = "flow")]
3320 flow_id: String,
3321 #[serde(default)]
3322 node: Option<String>,
3323 #[serde(default)]
3324 input: Value,
3325 #[serde(default)]
3326 max_redirects: Option<u32>,
3327 #[serde(default)]
3328 reason: Option<String>,
3329 }
3330
3331 let goto: FlowGotoPayload =
3332 serde_json::from_value(payload).context("invalid payload for flow.goto node")?;
3333 let flow = goto.flow_id.trim().to_string();
3334 if flow.is_empty() {
3335 return Err(terminal_flow_error(
3336 "flow.goto requires a non-empty flow_id",
3337 ));
3338 }
3339 let node = goto
3340 .node
3341 .map(|n| n.trim().to_string())
3342 .filter(|n| !n.is_empty());
3343
3344 let jump = JumpControl {
3345 flow,
3346 node,
3347 payload: goto.input,
3348 hints: Value::Null,
3352 max_redirects: goto.max_redirects,
3353 reason: goto.reason.or_else(|| Some("flow.goto node".to_string())),
3354 };
3355 let output = NodeOutput::with_meta(jump.payload.clone(), jump.hints.clone());
3356 Ok(DispatchOutcome::with_control(
3357 output,
3358 NodeControl::Jump(jump),
3359 ))
3360}
3361
3362impl FlowEngine {
3363 async fn execute_component_exec(
3364 &self,
3365 ctx: &FlowContext<'_>,
3366 node_id: &str,
3367 node: &HostNode,
3368 payload: Value,
3369 event: &NodeEvent<'_>,
3370 overrides: ComponentOverrides<'_>,
3371 ) -> Result<NodeOutput> {
3372 #[derive(Deserialize)]
3373 struct ComponentPayload {
3374 #[serde(default, alias = "component_ref", alias = "component")]
3375 component: Option<String>,
3376 #[serde(alias = "op")]
3377 operation: Option<String>,
3378 #[serde(default)]
3379 input: Value,
3380 #[serde(default)]
3381 config: Value,
3382 }
3383
3384 let payload: ComponentPayload =
3385 serde_json::from_value(payload).context("invalid payload for component.exec")?;
3386 let component_ref = overrides
3387 .component
3388 .map(str::to_string)
3389 .or_else(|| payload.component.filter(|v| !v.trim().is_empty()))
3390 .with_context(|| "component.exec requires a component_ref")?;
3391 let operation = resolve_component_operation(
3392 node_id,
3393 node.component_id.as_str(),
3394 payload.operation,
3395 overrides.operation,
3396 node.operation_in_mapping.as_deref(),
3397 )?;
3398
3399 let call = ComponentCall {
3400 component_ref,
3401 operation,
3402 input: payload.input,
3403 config: payload.config,
3404 has_error_route: node_has_error_route(&node.routing),
3405 };
3406
3407 self.invoke_component_call(ctx, node_id, call, event).await
3408 }
3409
3410 async fn execute_component_call(
3411 &self,
3412 ctx: &FlowContext<'_>,
3413 node_id: &str,
3414 node: &HostNode,
3415 payload: Value,
3416 component_ref: &str,
3417 event: &NodeEvent<'_>,
3418 ) -> Result<NodeOutput> {
3419 let payload_operation = extract_operation_from_mapping(&payload);
3420 let (input, config) = split_operation_payload(payload);
3421 let operation = resolve_component_operation(
3422 node_id,
3423 node.component_id.as_str(),
3424 payload_operation,
3425 node.operation_name.as_deref(),
3426 node.operation_in_mapping.as_deref(),
3427 )?;
3428 let call = ComponentCall {
3429 component_ref: component_ref.to_string(),
3430 operation,
3431 input,
3432 config,
3433 has_error_route: node_has_error_route(&node.routing),
3434 };
3435 self.invoke_component_call(ctx, node_id, call, event).await
3436 }
3437
3438 async fn invoke_component_call(
3439 &self,
3440 ctx: &FlowContext<'_>,
3441 node_id: &str,
3442 mut call: ComponentCall,
3443 event: &NodeEvent<'_>,
3444 ) -> Result<NodeOutput> {
3445 self.validate_component(ctx, event, &call)?;
3446 let key = FlowKey {
3447 pack_id: ctx.pack_id.to_string(),
3448 flow_id: ctx.flow_id.to_string(),
3449 };
3450 let pack_idx = *self.flow_sources.get(&key).with_context(|| {
3451 format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
3452 })?;
3453 let pack = Arc::clone(&self.packs[pack_idx]);
3454
3455 promote_card_config_to_invocation(&mut call.input, &call.config);
3462
3463 resolve_card_assets(&mut call.input, &pack);
3467
3468 let is_card = is_card_invocation(&call.input);
3476
3477 let exec_ctx = component_exec_ctx(ctx, node_id);
3478 let caller = component_caller(ctx);
3479 let input_json = if is_card {
3480 serde_json::to_string(&call.input)?
3481 } else {
3482 let meta = InvocationMeta {
3484 env: &self.default_env,
3485 tenant: ctx.tenant,
3486 flow_id: ctx.flow_id,
3487 node_id: Some(node_id),
3488 provider_id: ctx.provider_id,
3489 session_id: ctx.session_id,
3490 attempt: ctx.attempt,
3491 };
3492 let invocation_envelope = build_invocation_envelope_as(
3493 meta,
3494 caller.as_ref(),
3495 call.operation.as_str(),
3496 call.input,
3497 )
3498 .context("build invocation envelope for component call")?;
3499 serde_json::to_string(&invocation_envelope)?
3500 };
3501 let config_json = if call.config.is_null() {
3502 None
3503 } else {
3504 Some(serde_json::to_string(&call.config)?)
3505 };
3506
3507 #[cfg(feature = "fault-injection")]
3508 {
3509 let fault_ctx = FaultContext {
3510 pack_id: ctx.pack_id,
3511 flow_id: ctx.flow_id,
3512 node_id: Some(node_id),
3513 attempt: ctx.attempt,
3514 };
3515 maybe_fail(FaultPoint::BeforeComponentCall, fault_ctx).map_err(injected_error)?;
3516 }
3517 let value = pack
3518 .invoke_component_for(
3519 call.component_ref.as_str(),
3520 exec_ctx,
3521 caller,
3522 ctx.provider_id,
3523 call.operation.as_str(),
3524 config_json,
3525 input_json,
3526 )
3527 .await?;
3528 #[cfg(feature = "fault-injection")]
3529 {
3530 let fault_ctx = FaultContext {
3531 pack_id: ctx.pack_id,
3532 flow_id: ctx.flow_id,
3533 node_id: Some(node_id),
3534 attempt: ctx.attempt,
3535 };
3536 maybe_fail(FaultPoint::AfterComponentCall, fault_ctx).map_err(injected_error)?;
3537 }
3538
3539 if let Some((code, message)) = component_error(&value) {
3540 if call.has_error_route {
3545 return Ok(NodeOutput::errored(value));
3546 }
3547 bail!(
3548 "component {} failed: {}: {}",
3549 call.component_ref,
3550 code,
3551 message
3552 );
3553 }
3554 if let Some((code, message)) = mcp_tool_error(&value) {
3567 if call.has_error_route {
3568 return Ok(NodeOutput::errored(normalize_mcp_tool_error(
3577 &value, &code, &message,
3578 )));
3579 }
3580 bail!(
3581 "component {} returned tool error: {}: {}",
3582 call.component_ref,
3583 code,
3584 message
3585 );
3586 }
3587 let meta = outcome_meta(&value);
3588 Ok(NodeOutput::with_meta(value, meta))
3589 }
3590
3591 async fn execute_provider_invoke(
3592 &self,
3593 ctx: &FlowContext<'_>,
3594 node_id: &str,
3595 state: &ExecutionState,
3596 payload: Value,
3597 event: &NodeEvent<'_>,
3598 ) -> Result<NodeOutput> {
3599 #[derive(Deserialize)]
3600 struct ProviderPayload {
3601 #[serde(default)]
3602 provider_id: Option<String>,
3603 #[serde(default)]
3604 provider_type: Option<String>,
3605 #[serde(default, alias = "operation")]
3606 op: Option<String>,
3607 #[serde(default)]
3608 input: Value,
3609 #[serde(default)]
3610 in_map: Value,
3611 #[serde(default)]
3612 out_map: Value,
3613 }
3614
3615 let payload: ProviderPayload = serde_json::from_value(payload)
3618 .context("invalid payload for provider.invoke")
3619 .map_err(pre_effect)?;
3620 let op = payload
3621 .op
3622 .as_deref()
3623 .filter(|v| !v.trim().is_empty())
3624 .with_context(|| "provider.invoke requires an op")
3625 .map_err(pre_effect)?
3626 .to_string();
3627
3628 let prev = state
3629 .last_output
3630 .as_ref()
3631 .cloned()
3632 .unwrap_or_else(|| Value::Object(JsonMap::new()));
3633 let base_ctx = template_context(state, prev);
3634
3635 let input_value = if !payload.in_map.is_null() {
3636 let mut ctx_value = base_ctx.clone();
3637 if let Value::Object(ref mut map) = ctx_value {
3638 map.insert("input".into(), payload.input.clone());
3639 map.insert("result".into(), payload.input.clone());
3640 }
3641 render_template_value(
3642 &payload.in_map,
3643 &ctx_value,
3644 TemplateOptions {
3645 allow_pointer: true,
3646 },
3647 )
3648 .context("failed to render provider.invoke in_map")
3649 .map_err(pre_effect)?
3650 } else if !payload.input.is_null() {
3651 payload.input
3652 } else {
3653 Value::Null
3654 };
3655 let input_json = serde_json::to_vec(&input_value).map_err(pre_effect)?;
3656
3657 self.validate_tool(
3658 ctx,
3659 event,
3660 payload.provider_id.as_deref(),
3661 payload.provider_type.as_deref(),
3662 &op,
3663 &input_value,
3664 )
3665 .map_err(pre_effect)?;
3666
3667 let key = FlowKey {
3668 pack_id: ctx.pack_id.to_string(),
3669 flow_id: ctx.flow_id.to_string(),
3670 };
3671 let pack_idx = *self
3672 .flow_sources
3673 .get(&key)
3674 .with_context(|| format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id))
3675 .map_err(pre_effect)?;
3676 let pack = Arc::clone(&self.packs[pack_idx]);
3677 let binding = pack.resolve_provider(
3678 payload.provider_id.as_deref(),
3679 payload.provider_type.as_deref(),
3680 );
3681
3682 if binding.is_err()
3684 && let Some(output) = self.try_invoke_cross_pack_resolver(
3685 payload.provider_id.as_deref(),
3686 payload.provider_type.as_deref(),
3687 &op,
3688 &input_json,
3689 ctx.tenant,
3690 )?
3691 {
3692 return Ok(output);
3693 }
3694
3695 let binding = binding.map_err(pre_effect)?;
3696 let exec_ctx = component_exec_ctx(ctx, node_id);
3697 #[cfg(feature = "fault-injection")]
3698 {
3699 let fault_ctx = FaultContext {
3700 pack_id: ctx.pack_id,
3701 flow_id: ctx.flow_id,
3702 node_id: Some(node_id),
3703 attempt: ctx.attempt,
3704 };
3705 maybe_fail(FaultPoint::BeforeToolCall, fault_ctx)
3706 .map_err(injected_error)
3707 .map_err(pre_effect)?;
3708 }
3709 let provider_metric_id = payload
3710 .provider_id
3711 .as_deref()
3712 .or(payload.provider_type.as_deref())
3713 .unwrap_or("unknown");
3714 let invoke_started = std::time::Instant::now();
3715 let invoke_result = pack
3716 .invoke_provider(&binding, exec_ctx, &op, input_json)
3717 .await;
3718 let invoke_duration_ms = invoke_started.elapsed().as_secs_f64() * 1000.0;
3719 crate::metrics::record_provider_invocation(
3720 ctx.tenant,
3721 provider_metric_id,
3722 &op,
3723 if invoke_result.is_ok() { "ok" } else { "err" },
3724 invoke_duration_ms,
3725 );
3726 let result = invoke_result?;
3727 #[cfg(feature = "fault-injection")]
3728 {
3729 let fault_ctx = FaultContext {
3730 pack_id: ctx.pack_id,
3731 flow_id: ctx.flow_id,
3732 node_id: Some(node_id),
3733 attempt: ctx.attempt,
3734 };
3735 maybe_fail(FaultPoint::AfterToolCall, fault_ctx).map_err(injected_error)?;
3736 }
3737
3738 let output = if payload.out_map.is_null() {
3739 result
3740 } else {
3741 let mut ctx_value = base_ctx;
3742 if let Value::Object(ref mut map) = ctx_value {
3743 map.insert("input".into(), result.clone());
3744 map.insert("result".into(), result.clone());
3745 }
3746 render_template_value(
3747 &payload.out_map,
3748 &ctx_value,
3749 TemplateOptions {
3750 allow_pointer: true,
3751 },
3752 )
3753 .context("failed to render provider.invoke out_map")?
3754 };
3755 Ok(NodeOutput::new(output))
3756 }
3757
3758 fn try_invoke_cross_pack_resolver(
3759 &self,
3760 provider_id: Option<&str>,
3761 provider_type: Option<&str>,
3762 op: &str,
3763 input_json: &[u8],
3764 tenant: &str,
3765 ) -> Result<Option<NodeOutput>> {
3766 tracing::debug!(
3767 has_resolver = self.cross_pack_resolver.is_some(),
3768 "provider.invoke: pack-local failed"
3769 );
3770 let Some(resolver) = self.cross_pack_resolver.as_ref() else {
3771 return Ok(None);
3772 };
3773 let provider_id = provider_id.unwrap_or("unknown");
3774 tracing::info!(
3775 provider_id,
3776 op = %op,
3777 "provider.invoke: pack-local resolution failed, trying cross-pack resolver"
3778 );
3779 let result_value =
3780 resolver.invoke(provider_id, provider_type, op, input_json, tenant, None)?;
3781 Ok(Some(NodeOutput::new(result_value)))
3782 }
3783
3784 fn validate_component(
3785 &self,
3786 ctx: &FlowContext<'_>,
3787 event: &NodeEvent<'_>,
3788 call: &ComponentCall,
3789 ) -> Result<()> {
3790 if self.validation.mode == ValidationMode::Off {
3791 return Ok(());
3792 }
3793 let mut metadata = JsonMap::new();
3794 metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
3795 if let Some(id) = ctx.session_id {
3796 metadata.insert("session".to_string(), json!({ "id": id }));
3797 }
3798 let envelope = json!({
3799 "component_id": call.component_ref,
3800 "operation": call.operation,
3801 "input": call.input,
3802 "config": call.config,
3803 "metadata": Value::Object(metadata),
3804 });
3805 let issues = validate_component_envelope(&envelope);
3806 self.report_validation(ctx, event, "component", issues)
3807 }
3808
3809 fn validate_tool(
3810 &self,
3811 ctx: &FlowContext<'_>,
3812 event: &NodeEvent<'_>,
3813 provider_id: Option<&str>,
3814 provider_type: Option<&str>,
3815 operation: &str,
3816 input: &Value,
3817 ) -> Result<()> {
3818 if self.validation.mode == ValidationMode::Off {
3819 return Ok(());
3820 }
3821 let tool_id = provider_id.or(provider_type).unwrap_or("provider.invoke");
3822 let mut metadata = JsonMap::new();
3823 metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
3824 if let Some(id) = ctx.session_id {
3825 metadata.insert("session".to_string(), json!({ "id": id }));
3826 }
3827 let envelope = json!({
3828 "tool_id": tool_id,
3829 "operation": operation,
3830 "input": input,
3831 "metadata": Value::Object(metadata),
3832 });
3833 let issues = validate_tool_envelope(&envelope);
3834 self.report_validation(ctx, event, "tool", issues)
3835 }
3836
3837 fn report_validation(
3838 &self,
3839 ctx: &FlowContext<'_>,
3840 event: &NodeEvent<'_>,
3841 kind: &str,
3842 issues: Vec<ValidationIssue>,
3843 ) -> Result<()> {
3844 if issues.is_empty() {
3845 return Ok(());
3846 }
3847 if let Some(observer) = ctx.observer {
3848 observer.on_validation(event, &issues);
3849 }
3850 match self.validation.mode {
3851 ValidationMode::Warn => {
3852 tracing::warn!(
3853 tenant = ctx.tenant,
3854 flow_id = ctx.flow_id,
3855 node_id = event.node_id,
3856 kind,
3857 issues = ?issues,
3858 "invocation envelope validation issues"
3859 );
3860 Ok(())
3861 }
3862 ValidationMode::Error => {
3863 tracing::error!(
3864 tenant = ctx.tenant,
3865 flow_id = ctx.flow_id,
3866 node_id = event.node_id,
3867 kind,
3868 issues = ?issues,
3869 "invocation envelope validation failed"
3870 );
3871 bail!("invocation_validation_failed");
3872 }
3873 ValidationMode::Off => Ok(()),
3874 }
3875 }
3876
3877 pub fn flows(&self) -> &[FlowDescriptor] {
3878 &self.flows
3879 }
3880
3881 pub async fn flow_node_ids(&self, pack_id: &str, flow_id: &str) -> Vec<String> {
3889 match self.get_or_load_flow(pack_id, flow_id).await {
3890 Ok(flow) => flow
3891 .nodes
3892 .keys()
3893 .map(|id| id.as_str().to_string())
3894 .collect(),
3895 Err(error) => {
3896 tracing::debug!(
3897 pack_id,
3898 flow_id,
3899 error = %error,
3900 "flow not loadable while listing node ids; treating as no nodes"
3901 );
3902 Vec::new()
3903 }
3904 }
3905 }
3906
3907 pub fn flow_by_key(&self, pack_id: &str, flow_id: &str) -> Option<&FlowDescriptor> {
3908 self.flows
3909 .iter()
3910 .find(|descriptor| descriptor.pack_id == pack_id && descriptor.id == flow_id)
3911 }
3912
3913 pub fn flow_by_type(&self, flow_type: &str) -> Option<&FlowDescriptor> {
3914 let mut matches = self
3915 .flows
3916 .iter()
3917 .filter(|descriptor| descriptor.flow_type == flow_type);
3918 let first = matches.next()?;
3919 if matches.next().is_some() {
3920 return None;
3921 }
3922 Some(first)
3923 }
3924
3925 pub fn entry_flow_by_type(&self, flow_type: &str) -> Option<&FlowDescriptor> {
3943 let mut matches = self.flows.iter().filter(|descriptor| {
3944 descriptor.flow_type == flow_type
3945 && descriptor.entry
3946 && !self
3947 .messaging_provider_pack_ids
3948 .contains(&descriptor.pack_id)
3949 });
3950 let first = matches.next()?;
3951 if matches.next().is_some() {
3952 return None;
3953 }
3954 Some(first)
3955 }
3956
3957 pub(crate) fn pack_identity(&self, pack_id: &str) -> Option<(String, Option<String>, String)> {
3960 self.packs
3961 .iter()
3962 .find(|pack| pack.metadata().pack_id == pack_id)
3963 .map(|pack| {
3964 let meta = pack.metadata();
3965 (
3966 meta.pack_id.clone(),
3967 pack.manifest_name().map(str::to_string),
3968 meta.version.clone(),
3969 )
3970 })
3971 }
3972
3973 pub fn flow_by_id(&self, flow_id: &str) -> Option<&FlowDescriptor> {
3974 let mut matches = self
3975 .flows
3976 .iter()
3977 .filter(|descriptor| descriptor.id == flow_id);
3978 let first = matches.next()?;
3979 if matches.next().is_some() {
3980 return None;
3981 }
3982 Some(first)
3983 }
3984}
3985
3986pub trait ExecutionObserver: Send + Sync {
3987 fn on_node_start(&self, event: &NodeEvent<'_>);
3988 fn on_node_end(&self, event: &NodeEvent<'_>, output: &Value);
3989 fn on_node_error(&self, event: &NodeEvent<'_>, error: &dyn StdError);
3990 fn on_validation(&self, _event: &NodeEvent<'_>, _issues: &[ValidationIssue]) {}
3991 fn on_flow_attempt(&self, _flow_id: &str, _attempt: u32) {}
3997 fn on_flow_exit(&self, _flow_id: &str) {}
4001}
4002
4003pub struct NodeEvent<'a> {
4004 pub context: &'a FlowContext<'a>,
4005 pub node_id: &'a str,
4006 pub node: &'a HostNode,
4007 pub payload: &'a Value,
4008}
4009
4010#[cfg(feature = "agentic-worker")]
4028const MAX_PARK_TURNS: u32 = 100;
4029
4030#[derive(Clone, Debug, Serialize, Deserialize)]
4037struct PendingCardAnswers {
4038 node_id: String,
4039 answers: JsonMap<String, Value>,
4040}
4041
4042#[derive(Clone, Debug, Serialize, Deserialize)]
4043pub struct ExecutionState {
4044 #[serde(default)]
4045 entry: Value,
4046 #[serde(default)]
4047 input: Value,
4048 #[serde(default)]
4049 nodes: HashMap<String, NodeOutput>,
4050 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4054 node_order: Vec<String>,
4055 #[serde(default)]
4056 egress: Vec<Value>,
4057 #[serde(default, skip_serializing_if = "Option::is_none")]
4058 last_output: Option<Value>,
4059 #[serde(default)]
4060 redirect_count: u32,
4061 #[serde(default)]
4062 vars: JsonMap<String, Value>,
4063 #[serde(default)]
4068 park_turns: HashMap<String, u32>,
4069 #[serde(default)]
4073 pending_agent_await: HashMap<String, ()>,
4074 #[serde(skip)]
4080 created_artifacts: Vec<Value>,
4081 #[serde(default)]
4095 pending_approval_await: HashMap<String, Option<String>>,
4096 #[serde(default)]
4103 pending_approval_token: HashMap<String, String>,
4104 #[serde(default)]
4110 pending_tool_await: HashMap<String, ()>,
4111 #[serde(default, skip_serializing_if = "Option::is_none")]
4115 pending_card_answers: Option<PendingCardAnswers>,
4116 #[serde(default, skip_serializing_if = "Option::is_none")]
4122 resumed_at: Option<String>,
4123}
4124
4125impl ExecutionState {
4126 fn new(input: Value) -> Self {
4127 Self {
4128 entry: input.clone(),
4129 input,
4130 nodes: HashMap::new(),
4131 node_order: Vec::new(),
4132 egress: Vec::new(),
4133 last_output: None,
4134 redirect_count: 0,
4135 vars: JsonMap::new(),
4136 park_turns: HashMap::new(),
4137 pending_agent_await: HashMap::new(),
4138 created_artifacts: Vec::new(),
4139 pending_approval_await: HashMap::new(),
4140 pending_approval_token: HashMap::new(),
4141 pending_tool_await: HashMap::new(),
4142 pending_card_answers: None,
4143 resumed_at: None,
4144 }
4145 }
4146
4147 #[allow(dead_code)]
4151 fn ensure_entry(&mut self) {
4152 if self.entry.is_null() {
4153 self.entry = self.input.clone();
4154 }
4155 }
4156
4157 fn context(&self) -> Value {
4158 let mut nodes = JsonMap::new();
4159 for (id, output) in &self.nodes {
4160 nodes.insert(
4161 id.clone(),
4162 json!({
4163 "ok": output.ok,
4164 "payload": output.payload.clone(),
4165 "meta": output.meta.clone(),
4166 }),
4167 );
4168 }
4169 json!({
4170 "entry": self.entry.clone(),
4171 "input": self.input.clone(),
4172 "nodes": nodes,
4173 "redirect_count": self.redirect_count,
4174 "park_turns": self.park_turns.clone(),
4175 "pending_agent_await": self.pending_agent_await.keys().cloned().collect::<Vec<_>>(),
4176 })
4177 }
4178
4179 fn record_node_output(&mut self, node_id: String, output: NodeOutput) {
4181 self.node_order.retain(|id| id != &node_id);
4182 self.node_order.push(node_id.clone());
4183 self.nodes.insert(node_id, output);
4184 }
4185
4186 fn first_unhandled_failure(&self, flow: &HostFlow) -> Option<(String, NodeOutput)> {
4190 let handled = |id: &str| {
4191 NodeId::from_str(id)
4192 .ok()
4193 .and_then(|node_id| flow.nodes.get(&node_id))
4194 .is_some_and(|node| node_has_error_route(&node.routing))
4195 };
4196 let ordered = self
4197 .node_order
4198 .iter()
4199 .filter_map(|id| self.nodes.get(id).map(|out| (id, out)));
4200 let mut unordered: Vec<(&String, &NodeOutput)> = self
4204 .nodes
4205 .iter()
4206 .filter(|(id, _)| !self.node_order.contains(id))
4207 .collect();
4208 unordered.sort_by(|a, b| a.0.cmp(b.0));
4209 unordered
4210 .into_iter()
4211 .chain(ordered)
4212 .find(|(id, out)| !out.ok && !handled(id))
4213 .map(|(id, out)| (id.clone(), out.clone()))
4214 }
4215
4216 fn outputs_map(&self) -> JsonMap<String, Value> {
4217 let mut outputs = JsonMap::new();
4218 for (id, output) in &self.nodes {
4219 outputs.insert(id.clone(), node_output_view(&output.payload));
4220 }
4221 outputs
4222 }
4223 fn push_egress(&mut self, payload: Value) {
4224 self.egress.push(payload);
4225 }
4226
4227 fn replace_input(&mut self, input: Value) {
4228 self.input = input;
4229 }
4230
4231 fn clear_egress(&mut self) {
4235 self.egress.clear();
4236 self.created_artifacts.clear();
4237 }
4238
4239 fn note_created_artifacts(&mut self, created: Vec<Value>) {
4242 let mut dropped = 0usize;
4243 for file in created {
4244 if self.created_artifacts.len() >= MAX_CREATED_PER_TURN {
4245 dropped += 1;
4248 continue;
4249 }
4250 let id = file.get("id").and_then(Value::as_str);
4251 let known = self
4252 .created_artifacts
4253 .iter()
4254 .any(|seen| seen.get("id").and_then(Value::as_str) == id);
4255 if id.is_some() && !known {
4256 self.created_artifacts.push(file);
4257 }
4258 }
4259 if dropped > 0 {
4260 tracing::warn!(
4261 dropped,
4262 cap = MAX_CREATED_PER_TURN,
4263 "a turn created more files than the per-turn delivery cap; the extra files are stored but not listed in the reply"
4264 );
4265 }
4266 }
4267
4268 fn redirect_count(&self) -> u32 {
4269 self.redirect_count
4270 }
4271
4272 fn reset_redirect_count(&mut self) {
4273 self.redirect_count = 0;
4274 }
4275
4276 fn increment_redirect_count(&mut self) {
4277 self.redirect_count = self.redirect_count.saturating_add(1);
4278 }
4279
4280 #[cfg(any(feature = "agentic-worker", test))]
4286 fn bump_park_turns(&mut self, node_id: &str) -> u32 {
4287 let entry = self.park_turns.entry(node_id.to_string()).or_insert(0);
4288 *entry = entry.saturating_add(1);
4289 *entry
4290 }
4291
4292 #[cfg(any(feature = "agentic-worker", test))]
4295 fn reset_park_turns(&mut self, node_id: &str) {
4296 self.park_turns.remove(node_id);
4297 }
4298
4299 #[cfg(any(feature = "agentic-worker", test))]
4303 fn mark_agent_await(&mut self, node_id: &str) {
4304 self.pending_agent_await.insert(node_id.to_string(), ());
4305 }
4306
4307 #[cfg(any(feature = "agentic-worker", test))]
4312 fn take_agent_await(&mut self, node_id: &str) -> bool {
4313 self.pending_agent_await.remove(node_id).is_some()
4314 }
4315
4316 #[cfg(any(feature = "agentic-worker", test))]
4318 fn mark_tool_await(&mut self, node_id: &str) {
4319 self.pending_tool_await.insert(node_id.to_string(), ());
4320 }
4321
4322 #[cfg(any(feature = "agentic-worker", test))]
4324 fn take_tool_await(&mut self, node_id: &str) -> bool {
4325 self.pending_tool_await.remove(node_id).is_some()
4326 }
4327
4328 fn mark_approval_await(&mut self, node_id: &str, parked: ParkedApproval) {
4331 self.pending_approval_await
4332 .insert(node_id.to_string(), parked.correlation_id);
4333 match parked.token_fingerprint {
4334 Some(fingerprint) => {
4335 self.pending_approval_token
4336 .insert(node_id.to_string(), fingerprint);
4337 }
4338 None => {
4339 self.pending_approval_token.remove(node_id);
4340 }
4341 }
4342 }
4343
4344 fn take_approval_await(&mut self, node_id: &str) -> Option<ParkedApproval> {
4348 let correlation_id = self.pending_approval_await.remove(node_id)?;
4349 Some(ParkedApproval {
4350 correlation_id,
4351 token_fingerprint: self.pending_approval_token.remove(node_id),
4352 })
4353 }
4354
4355 pub(crate) fn pending_approvals(&self) -> Vec<ParkedApproval> {
4358 self.pending_approval_await
4359 .iter()
4360 .map(|(node_id, correlation_id)| ParkedApproval {
4361 correlation_id: correlation_id.clone(),
4362 token_fingerprint: self.pending_approval_token.get(node_id).cloned(),
4363 })
4364 .collect()
4365 }
4366
4367 fn finalize_with(mut self, final_payload: Option<Value>) -> Value {
4368 let created = std::mem::take(&mut self.created_artifacts);
4369 let reply = self.finalize_reply(final_payload);
4370 attach_created_files(reply, created)
4371 }
4372
4373 fn finalize_reply(mut self, final_payload: Option<Value>) -> Value {
4374 if self.egress.is_empty() {
4375 return final_payload.unwrap_or(Value::Null);
4376 }
4377 let mut emitted = std::mem::take(&mut self.egress);
4378 if let Some(value) = final_payload {
4379 match value {
4380 Value::Null => {}
4381 Value::Array(items) => emitted.extend(items),
4382 other if emitted.last() == Some(&other) => {}
4390 other => emitted.push(other),
4391 }
4392 }
4393 Value::Array(emitted)
4394 }
4395}
4396
4397#[derive(Clone, Debug, Serialize, Deserialize)]
4398struct NodeOutput {
4399 ok: bool,
4400 payload: Value,
4401 meta: Value,
4402 #[serde(skip)]
4407 created: Vec<Value>,
4408}
4409
4410impl NodeOutput {
4411 fn new(payload: Value) -> Self {
4412 Self {
4413 ok: true,
4414 payload,
4415 meta: Value::Null,
4416 created: Vec::new(),
4417 }
4418 }
4419
4420 #[allow(dead_code)]
4424 fn with_error(node_id: &str, err: &(dyn std::error::Error + 'static)) -> Self {
4425 Self {
4426 ok: false,
4427 payload: Value::Null,
4428 meta: json!({
4429 "error": {
4430 "kind": "flow_node_failed",
4431 "message": err.to_string(),
4432 "node_id": node_id,
4433 }
4434 }),
4435 created: Vec::new(),
4436 }
4437 }
4438}
4439
4440struct DispatchOutcome {
4441 output: NodeOutput,
4442 control: NodeControl,
4443}
4444
4445impl DispatchOutcome {
4446 fn complete(output: NodeOutput) -> Self {
4447 Self {
4448 output,
4449 control: NodeControl::Continue,
4450 }
4451 }
4452
4453 fn wait(output: NodeOutput, reason: Option<String>) -> Self {
4454 Self {
4455 output,
4456 control: NodeControl::Wait { reason },
4457 }
4458 }
4459
4460 fn await_here(output: NodeOutput, reason: Option<String>, correlation_id: String) -> Self {
4461 Self {
4462 output,
4463 control: NodeControl::AwaitHere {
4464 reason,
4465 correlation_id,
4466 },
4467 }
4468 }
4469
4470 fn with_control(output: NodeOutput, control: NodeControl) -> Self {
4471 Self { output, control }
4472 }
4473}
4474
4475#[derive(Clone, Debug)]
4476enum NodeControl {
4477 Continue,
4478 Wait {
4479 reason: Option<String>,
4480 },
4481 #[allow(dead_code)]
4493 LoopHere {
4494 reason: Option<String>,
4495 },
4496 AwaitHere {
4503 reason: Option<String>,
4504 #[allow(dead_code)]
4510 correlation_id: String,
4511 },
4512 Jump(JumpControl),
4513 Respond {
4514 text: Option<String>,
4515 card_cbor: Option<Vec<u8>>,
4516 needs_user: Option<bool>,
4517 },
4518}
4519
4520#[derive(Clone, Debug)]
4521struct JumpControl {
4522 flow: String,
4523 node: Option<String>,
4524 payload: Value,
4525 hints: Value,
4526 max_redirects: Option<u32>,
4527 reason: Option<String>,
4528}
4529
4530#[derive(Clone, Debug)]
4531struct JumpTarget {
4532 flow_id: String,
4533 flow: HostFlow,
4534 node_id: NodeId,
4535}
4536
4537impl NodeOutput {
4538 fn with_meta(payload: Value, meta: Value) -> Self {
4539 Self {
4540 ok: true,
4541 payload,
4542 meta,
4543 created: Vec::new(),
4544 }
4545 }
4546
4547 fn errored(payload: Value) -> Self {
4561 let mut meta = JsonMap::new();
4562 if let Some(outcome) = payload.get("outcome").and_then(Value::as_str) {
4563 meta.insert("outcome".to_string(), Value::String(outcome.to_string()));
4564 }
4565 if let Some(error) = payload.get("error") {
4566 meta.insert("error".to_string(), error.clone());
4567 }
4568 let meta = if meta.is_empty() {
4569 Value::Null
4570 } else {
4571 Value::Object(meta)
4572 };
4573 Self {
4574 ok: false,
4575 payload,
4576 meta,
4577 created: Vec::new(),
4578 }
4579 }
4580}
4581
4582fn component_exec_ctx(ctx: &FlowContext<'_>, node_id: &str) -> ComponentExecCtx {
4596 ComponentExecCtx {
4597 tenant: ComponentTenantCtx {
4598 tenant: ctx.tenant.to_string(),
4599 team: None,
4600 user: ctx.provider_id.map(str::to_string),
4601 trace_id: None,
4602 i18n_id: None,
4603 correlation_id: ctx.session_id.map(str::to_string),
4604 deadline_unix_ms: None,
4605 attempt: ctx.attempt,
4606 idempotency_key: ctx.session_id.map(str::to_string),
4607 },
4608 i18n_id: None,
4609 flow_id: ctx.flow_id.to_string(),
4610 node_id: Some(node_id.to_string()),
4611 }
4612}
4613
4614fn component_caller(ctx: &FlowContext<'_>) -> Option<crate::caller_identity::ComponentCaller> {
4618 ctx.caller
4619 .and_then(crate::caller_identity::ComponentCaller::from_block)
4620}
4621
4622fn to_node_output(value: &Value) -> greentic_types::node_io::NodeOutput {
4634 use greentic_types::node_io::{ErrorKind, NodeError, NodeOutput as NioOutput};
4635
4636 if let Value::Object(map) = value {
4637 let native_errors = map.contains_key("errors") && !map.contains_key("ok");
4640 let native_data = map.contains_key("data") && !map.contains_key("ok") && map.len() == 1;
4641 if (native_errors || native_data)
4642 && let Ok(parsed) = serde_json::from_value::<NioOutput>(value.clone())
4643 {
4644 return parsed;
4645 }
4646 if let Some((code, message)) = component_error(value) {
4648 return NioOutput::failed(vec![NodeError {
4649 code,
4650 message,
4651 kind: ErrorKind::Internal,
4652 retryable: false,
4653 source: None,
4654 details: Value::Null,
4655 }]);
4656 }
4657 }
4658 NioOutput::ok(value.clone())
4660}
4661
4662fn node_output_view(payload: &Value) -> Value {
4667 let nio = to_node_output(payload);
4668 let data = nio.data().cloned().unwrap_or(Value::Null);
4669 let errors = serde_json::to_value(nio.errors()).unwrap_or_else(|_| Value::Array(Vec::new()));
4670 match payload {
4671 Value::Object(map) => {
4672 let mut view = map.clone();
4673 view.insert("data".to_string(), data);
4674 view.insert("errors".to_string(), errors);
4675 Value::Object(view)
4676 }
4677 other => other.clone(),
4678 }
4679}
4680
4681enum DeclaredAnswerFields {
4693 Absent,
4696 Malformed,
4700 Declared(Vec<String>),
4702}
4703
4704fn declared_answer_fields(payload_expr: &Value) -> DeclaredAnswerFields {
4732 let Some(raw) = payload_expr.get("answer_fields") else {
4733 return DeclaredAnswerFields::Absent;
4734 };
4735 let Some(arr) = raw.as_array() else {
4736 return DeclaredAnswerFields::Malformed;
4737 };
4738 match arr
4739 .iter()
4740 .map(|entry| entry.as_str().map(str::to_string))
4741 .collect::<Option<Vec<String>>>()
4742 {
4743 Some(list) => DeclaredAnswerFields::Declared(list),
4744 None => DeclaredAnswerFields::Malformed,
4745 }
4746}
4747
4748fn consume_routing_action(entry: &mut Value) {
4754 for pointer in ["/input/metadata", "/metadata"] {
4755 if let Some(Value::Object(meta)) = entry.pointer_mut(pointer) {
4756 meta.remove("action");
4757 }
4758 }
4759}
4760
4761fn attach_pending_card_answers(
4781 state: &mut ExecutionState,
4782 node_id: &str,
4783 node: &HostNode,
4784 output: &mut NodeOutput,
4785) -> bool {
4786 let is_target = state
4787 .pending_card_answers
4788 .as_ref()
4789 .is_some_and(|pending| pending.node_id == node_id);
4790 if !is_target {
4791 return false;
4792 }
4793 let Some(pending) = state.pending_card_answers.take() else {
4794 return false;
4795 };
4796 let Some(map) = output.payload.as_object_mut() else {
4800 tracing::warn!(
4801 node_id = %node_id,
4802 "node output payload is not an object; submitted answers not attached"
4803 );
4804 return true;
4805 };
4806 if map.contains_key("answers") {
4807 tracing::warn!(
4808 node_id = %node_id,
4809 "node output already carries `answers`; overwriting with the submitted fields"
4810 );
4811 }
4812 let answers = match declared_answer_fields(&node.payload_expr) {
4813 DeclaredAnswerFields::Declared(allow_list) => {
4814 let allowed: std::collections::HashSet<&str> =
4815 allow_list.iter().map(String::as_str).collect();
4816 pending
4817 .answers
4818 .into_iter()
4819 .filter(|(key, _)| allowed.contains(key.as_str()))
4820 .collect()
4821 }
4822 DeclaredAnswerFields::Malformed => {
4823 tracing::warn!(
4829 node_id = %node_id,
4830 "answer_fields present but malformed; falling back to unfiltered answers"
4831 );
4832 pending.answers
4833 }
4834 DeclaredAnswerFields::Absent => pending.answers,
4835 };
4836 map.insert("answers".to_string(), Value::Object(answers));
4837 true
4838}
4839
4840fn resumed_card_node(snapshot: &FlowSnapshot) -> Option<String> {
4844 snapshot.awaiting_submit.then(|| snapshot.next_node.clone())
4845}
4846
4847fn awaiting_tool_input(payload: &Value) -> bool {
4856 payload.get("terminated_by").and_then(Value::as_str) == Some("awaiting_tool_input")
4857}
4858
4859pub(crate) fn tool_presentation(payload: &Value) -> Option<&Value> {
4862 if !awaiting_tool_input(payload) {
4863 return None;
4864 }
4865 payload
4866 .get("pending_presentation")
4867 .filter(|value| !value.is_null())
4868}
4869
4870const SUBMIT_MARKER_KEY: &str = "greentic_submit";
4875
4876pub(crate) fn rendered_park(payload: &Value) -> Value {
4882 let Some(card) = tool_presentation(payload) else {
4883 return payload.clone();
4884 };
4885 let side_reply = payload
4886 .get("side_turn")
4887 .and_then(Value::as_bool)
4888 .unwrap_or(false)
4889 && payload
4890 .get("reply")
4891 .and_then(Value::as_str)
4892 .is_some_and(|reply| !reply.trim().is_empty());
4893 if !side_reply {
4894 return card.clone();
4895 }
4896 let mut reply = payload.clone();
4897 if let Some(map) = reply.as_object_mut() {
4898 map.remove("pending_presentation");
4899 map.remove("side_turn");
4900 }
4901 let mut items = vec![reply];
4904 match card {
4905 Value::Array(cards) => items.extend(cards.iter().cloned()),
4906 single => items.push(single.clone()),
4907 }
4908 Value::Array(items)
4909}
4910
4911#[cfg(any(feature = "agentic-worker", test))]
4917const ENVELOPE_TRANSPORT_KEYS: &[&str] = &[
4918 "id",
4919 "tenant",
4920 "channel",
4921 "session_id",
4922 "reply_scope",
4923 "from",
4924 "to",
4925 "correlation_id",
4926 "attachments",
4927 "extensions",
4928];
4929
4930#[cfg(any(feature = "agentic-worker", test))]
4951const CHANNEL_CONTEXT_METADATA_KEYS: &[&str] = &[
4952 "locale",
4953 "team",
4954 "env",
4955 "autoStart",
4956 "universal",
4957 "user_id",
4958 "user_verified",
4959 "flow_hint",
4960 "extensions",
4961];
4962
4963#[cfg(any(feature = "agentic-worker", test))]
4965const CHANNEL_CONTEXT_METADATA_PREFIX: &str = "channel.";
4966
4967#[cfg(any(feature = "agentic-worker", test))]
4968fn is_channel_context_key(key: &str) -> bool {
4969 CHANNEL_CONTEXT_METADATA_KEYS.contains(&key) || key.starts_with(CHANNEL_CONTEXT_METADATA_PREFIX)
4970}
4971
4972#[cfg(any(feature = "agentic-worker", test))]
4977fn stamped_identity_matches(key: &str, value: &Value, envelope: &Value) -> bool {
4978 let Some(value) = value.as_str() else {
4979 return false;
4980 };
4981 match key {
4982 "route" => envelope.get("session_id").and_then(Value::as_str) == Some(value),
4983 "tenant" => envelope.pointer("/tenant/tenant").and_then(Value::as_str) == Some(value),
4984 _ => false,
4985 }
4986}
4987
4988#[cfg(any(feature = "agentic-worker", test))]
4995fn is_channel_envelope(map: &JsonMap<String, Value>) -> bool {
4996 map.contains_key("session_id") && map.contains_key("channel") && map.contains_key("tenant")
4997}
4998
4999#[cfg(any(feature = "agentic-worker", test))]
5011fn is_card_submit(entry: &Value) -> bool {
5012 let metadata = resolve_entry_metadata(entry).and_then(Value::as_object);
5013 let has_action = metadata
5014 .and_then(|meta| meta.get("action"))
5015 .and_then(Value::as_str)
5016 .is_some_and(|action| !action.trim().is_empty());
5017 if has_action {
5018 return true;
5019 }
5020 let marked = metadata
5023 .and_then(|meta| meta.get(SUBMIT_MARKER_KEY))
5024 .is_some_and(|value| value.as_str() == Some("true") || value.as_bool() == Some(true));
5025 if marked {
5026 return true;
5027 }
5028 let envelope = entry
5029 .get("input")
5030 .filter(|v| v.is_object())
5031 .unwrap_or(entry);
5032 let root_input = envelope.as_object().is_some_and(|map| {
5033 let channel_envelope = is_channel_envelope(map);
5034 map.keys().any(|key| {
5035 key != "metadata"
5036 && key != "text"
5037 && !(channel_envelope && ENVELOPE_TRANSPORT_KEYS.contains(&key.as_str()))
5038 })
5039 });
5040 let metadata_input = metadata.is_some_and(|meta| {
5041 meta.iter().any(|(key, value)| {
5042 key != "action"
5043 && key != SUBMIT_MARKER_KEY
5044 && !is_channel_context_key(key)
5045 && !stamped_identity_matches(key, value, envelope)
5046 })
5047 });
5048 root_input || metadata_input
5049}
5050
5051fn pending_from_snapshot(snapshot: &FlowSnapshot, input: &Value) -> Option<PendingCardAnswers> {
5052 if !snapshot.awaiting_submit {
5053 return None;
5054 }
5055 Some(PendingCardAnswers {
5056 node_id: snapshot.next_node.clone(),
5057 answers: submitted_fields(input),
5058 })
5059}
5060
5061fn outcome_meta(output: &Value) -> Value {
5062 match output.get("outcome").and_then(Value::as_str) {
5063 Some(outcome) => json!({ "outcome": outcome }),
5064 None => Value::Null,
5065 }
5066}
5067
5068fn component_error(value: &Value) -> Option<(String, String)> {
5069 let obj = value.as_object()?;
5070 let ok = obj.get("ok").and_then(Value::as_bool)?;
5071 if ok {
5072 return None;
5073 }
5074 let err = obj.get("error")?.as_object()?;
5075 let code = err
5076 .get("code")
5077 .and_then(Value::as_str)
5078 .unwrap_or("component_error");
5079 let message = err
5080 .get("message")
5081 .and_then(Value::as_str)
5082 .unwrap_or("component reported error");
5083 Some((code.to_string(), message.to_string()))
5084}
5085
5086#[cfg(feature = "agentic-worker")]
5087fn agent_error_log_fields(entry: &Value) -> (String, String) {
5091 match entry.get("error") {
5092 Some(Value::Object(obj)) => (
5093 obj.get("code")
5094 .and_then(Value::as_str)
5095 .unwrap_or("unknown")
5096 .to_string(),
5097 obj.get("message")
5098 .and_then(Value::as_str)
5099 .unwrap_or_default()
5100 .to_string(),
5101 ),
5102 Some(Value::String(message)) => ("unknown".to_string(), message.clone()),
5103 _ => ("unknown".to_string(), String::new()),
5104 }
5105}
5106
5107#[cfg(feature = "agentic-worker")]
5118fn agent_error_envelope_reply(entry: &Value) -> (String, Value) {
5119 let error = entry.get("error").filter(|e| !e.is_null());
5120 let output = entry.get("output");
5121 let partial = output
5122 .and_then(|o| o.get("reply"))
5123 .and_then(Value::as_str)
5124 .filter(|reply| !reply.trim().is_empty());
5125 let message = partial
5126 .map(str::to_string)
5127 .unwrap_or_else(|| user_facing_flow_failure_text(entry));
5128 let mut payload = serde_json::Map::new();
5129 payload.insert("reply".to_string(), Value::String(message.clone()));
5130 if let Some(error) = error {
5131 payload.insert("error".to_string(), error.clone());
5132 }
5133 if partial.is_some()
5134 && let Some(trail) = output.and_then(|o| o.get("trail"))
5135 {
5136 payload.insert("trail".to_string(), trail.clone());
5137 }
5138 (message, Value::Object(payload))
5139}
5140
5141fn mcp_tool_error(value: &Value) -> Option<(String, String)> {
5146 let obj = value.as_object()?;
5147 if obj.contains_key("result") {
5149 return None;
5150 }
5151 let err = obj.get("error")?.as_object()?;
5152 let code = err
5153 .get("code")
5154 .and_then(Value::as_str)
5155 .unwrap_or("tool_error");
5156 let raw_message = err
5157 .get("message")
5158 .and_then(Value::as_str)
5159 .unwrap_or("tool returned an error");
5160 let status = err.get("status").and_then(Value::as_u64);
5161 let message = match status {
5162 Some(s) => format!("{raw_message} (status {s})"),
5163 None => raw_message.to_string(),
5164 };
5165 Some((code.to_string(), message))
5166}
5167
5168fn normalize_mcp_tool_error(value: &Value, code: &str, message: &str) -> Value {
5184 let mut obj = value.as_object().cloned().unwrap_or_default();
5185 obj.insert("ok".to_string(), Value::Bool(false));
5186 let mut error = obj
5187 .get("error")
5188 .and_then(Value::as_object)
5189 .cloned()
5190 .unwrap_or_default();
5191 error.insert("code".to_string(), Value::String(code.to_string()));
5192 error.insert("message".to_string(), Value::String(message.to_string()));
5193 obj.insert("error".to_string(), Value::Object(error));
5194 Value::Object(obj)
5195}
5196
5197#[cfg(feature = "agentic-worker")]
5234fn mcp_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
5235 if !has_error_route {
5236 return NodeOutput::new(bound);
5237 }
5238 let Some(error) = result.get("error") else {
5239 return NodeOutput::new(bound);
5240 };
5241 if let Some((code, message)) = mcp_tool_error(result) {
5251 return NodeOutput::errored(normalize_mcp_tool_error(&bound, &code, &message));
5252 }
5253 let message = error
5254 .as_str()
5255 .map(str::to_string)
5256 .unwrap_or_else(|| error.to_string());
5257 NodeOutput::errored(normalize_mcp_tool_error(
5258 &bound,
5259 "mcp_call_failed",
5260 &message,
5261 ))
5262}
5263
5264#[cfg(feature = "agentic-worker")]
5270fn bind_node_result(payload: &Value, result: Value) -> Value {
5271 match payload.get("output").and_then(Value::as_str) {
5272 Some(key) if !key.is_empty() => json!({ key: result }),
5273 _ => result,
5274 }
5275}
5276
5277#[cfg(feature = "agentic-worker")]
5282fn is_blank(value: &Value) -> bool {
5283 match value {
5284 Value::Null => true,
5285 Value::String(text) => text.trim().is_empty(),
5286 _ => false,
5287 }
5288}
5289
5290#[cfg(feature = "agentic-worker")]
5313fn a2a_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
5314 if !has_error_route {
5315 return NodeOutput::new(bound);
5316 }
5317 let Some(error) = result.get("error").and_then(Value::as_str) else {
5318 return NodeOutput::new(bound);
5319 };
5320 let code = match result.get("status").and_then(Value::as_str) {
5321 Some("failed") => "a2a_agent_failed",
5322 _ => "a2a_call_failed",
5323 };
5324 NodeOutput::errored(normalize_mcp_tool_error(&bound, code, error))
5325}
5326
5327#[cfg(feature = "agentic-worker")]
5331fn media_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
5332 if !crate::runner::media_node::is_failure(result) {
5333 let mut output = NodeOutput::new(bound);
5334 output.created = crate::runner::media_node::created_files(result);
5335 return output;
5336 }
5337 if !has_error_route {
5338 return NodeOutput::new(bound);
5339 }
5340 NodeOutput::errored(normalize_mcp_tool_error(
5341 &bound,
5342 &crate::runner::media_node::failure_code(result),
5343 &crate::runner::media_node::failure_message(result),
5344 ))
5345}
5346
5347#[cfg(feature = "agentic-worker")]
5357fn sorla_failure(msg: impl Into<String>, has_error_route: bool) -> Result<DispatchOutcome> {
5358 let msg = msg.into();
5359 if has_error_route {
5360 Ok(DispatchOutcome::complete(NodeOutput::errored(json!({
5361 "error": msg
5362 }))))
5363 } else {
5364 Err(anyhow!(msg))
5365 }
5366}
5367
5368fn extract_wait_reason(payload: &Value) -> Option<String> {
5369 match payload {
5370 Value::String(s) => Some(s.clone()),
5371 Value::Object(map) => map
5372 .get("reason")
5373 .and_then(Value::as_str)
5374 .map(|value| value.to_string()),
5375 _ => None,
5376 }
5377}
5378
5379fn component_dispatch_outcome(output: NodeOutput) -> Result<DispatchOutcome> {
5380 if let Some(control) = parse_component_control(&output.payload)? {
5381 return Ok(match control {
5382 NodeControl::Jump(jump) => {
5383 let adjusted = NodeOutput::with_meta(jump.payload.clone(), jump.hints.clone());
5384 DispatchOutcome::with_control(adjusted, NodeControl::Jump(jump))
5385 }
5386 NodeControl::Respond {
5387 text,
5388 card_cbor,
5389 needs_user,
5390 } => DispatchOutcome::with_control(
5391 output,
5392 NodeControl::Respond {
5393 text,
5394 card_cbor,
5395 needs_user,
5396 },
5397 ),
5398 other => DispatchOutcome::with_control(output, other),
5399 });
5400 }
5401 Ok(DispatchOutcome::complete(output))
5402}
5403
5404fn parse_component_control(payload: &Value) -> Result<Option<NodeControl>> {
5408 parse_component_control_inner(payload).map_err(|err| terminal_flow_error(format!("{err:#}")))
5409}
5410
5411fn parse_component_control_inner(payload: &Value) -> Result<Option<NodeControl>> {
5412 let Value::Object(map) = payload else {
5413 return Ok(None);
5414 };
5415 let Some(control_value) = map.get("greentic_control") else {
5416 return Ok(None);
5417 };
5418 let control = control_value
5419 .as_object()
5420 .ok_or_else(|| anyhow!("jump_failed: greentic_control must be an object"))?;
5421 let action = control
5422 .get("action")
5423 .and_then(Value::as_str)
5424 .ok_or_else(|| anyhow!("jump_failed: greentic_control.action is required"))?;
5425 let version = control
5426 .get("v")
5427 .and_then(Value::as_u64)
5428 .ok_or_else(|| anyhow!("jump_failed: greentic_control.v is required"))?;
5429 if version != 1 {
5430 bail!("jump_failed: unsupported greentic_control.v={version}");
5431 }
5432
5433 match action {
5434 "jump" => {
5435 let flow = control
5436 .get("flow")
5437 .and_then(Value::as_str)
5438 .map(str::trim)
5439 .filter(|value| !value.is_empty())
5440 .ok_or_else(|| anyhow!("jump_failed: jump flow is required"))?
5441 .to_string();
5442 let node = control
5443 .get("node")
5444 .and_then(Value::as_str)
5445 .map(str::trim)
5446 .filter(|value| !value.is_empty())
5447 .map(str::to_string);
5448 let payload = control.get("payload").cloned().unwrap_or(Value::Null);
5449 let hints = control.get("hints").cloned().unwrap_or(Value::Null);
5450 let max_redirects = control
5451 .get("max_redirects")
5452 .and_then(Value::as_u64)
5453 .and_then(|value| u32::try_from(value).ok());
5454 let reason = control
5455 .get("reason")
5456 .and_then(Value::as_str)
5457 .map(str::to_string);
5458 Ok(Some(NodeControl::Jump(JumpControl {
5459 flow,
5460 node,
5461 payload,
5462 hints,
5463 max_redirects,
5464 reason,
5465 })))
5466 }
5467 "respond" => {
5468 let text = control
5469 .get("text")
5470 .and_then(Value::as_str)
5471 .map(str::to_string);
5472 let card_cbor = control
5473 .get("card_cbor")
5474 .and_then(Value::as_array)
5475 .map(|bytes| {
5476 bytes
5477 .iter()
5478 .filter_map(Value::as_u64)
5479 .filter_map(|value| u8::try_from(value).ok())
5480 .collect::<Vec<_>>()
5481 });
5482 let needs_user = control.get("needs_user").and_then(Value::as_bool);
5483 Ok(Some(NodeControl::Respond {
5484 text,
5485 card_cbor,
5486 needs_user,
5487 }))
5488 }
5489 _ => Ok(None),
5490 }
5491}
5492
5493fn alias_input_to_entry(mut entry: Value) -> Value {
5504 if let Value::Object(map) = &mut entry
5505 && !map.contains_key("input")
5506 {
5507 let base = Value::Object(map.clone());
5508 map.insert("input".into(), base);
5509 }
5510 entry
5511}
5512
5513fn merge_submitted_fields_into_entry(mut entry: Value, fields: JsonMap<String, Value>) -> Value {
5545 if let Value::Object(map) = &mut entry {
5546 for (key, value) in fields {
5547 map.entry(key).or_insert(value);
5548 }
5549 }
5550 entry
5551}
5552
5553fn now_namespace(at: DateTime<Utc>) -> Value {
5582 json!({
5583 "iso": at.to_rfc3339_opts(SecondsFormat::Millis, true),
5584 "epoch_ms": at.timestamp_millis(),
5585 "date": at.format("%Y-%m-%d").to_string(),
5586 })
5587}
5588
5589fn template_context(state: &ExecutionState, prev: Value) -> Value {
5603 let entry = if state.entry.is_null() {
5604 Value::Object(JsonMap::new())
5605 } else {
5606 let fields = submitted_fields(&state.entry);
5610 merge_submitted_fields_into_entry(alias_input_to_entry(state.entry.clone()), fields)
5611 };
5612 let mut ctx = JsonMap::new();
5613 ctx.insert("entry".into(), entry.clone());
5614 ctx.insert("in".into(), entry); ctx.insert("prev".into(), prev);
5616 ctx.insert("node".into(), Value::Object(state.outputs_map()));
5617 ctx.insert("state".into(), state.context());
5618 ctx.insert("vars".into(), Value::Object(state.vars.clone()));
5619 ctx.insert("now".into(), now_namespace(Utc::now()));
5620 Value::Object(ctx)
5621}
5622
5623fn seed_vars_and_collect_missing_required(
5629 vars_init: &JsonMap<String, Value>,
5630 required: &[String],
5631 target: &mut JsonMap<String, Value>,
5632) -> Vec<String> {
5633 for (name, default) in vars_init.iter() {
5634 target
5635 .entry(name.clone())
5636 .or_insert_with(|| default.clone());
5637 }
5638 required
5639 .iter()
5640 .filter(|name| !target.contains_key(name.as_str()))
5641 .cloned()
5642 .collect()
5643}
5644
5645impl From<Flow> for HostFlow {
5646 fn from(value: Flow) -> Self {
5647 let mut nodes = IndexMap::new();
5648 for (id, node) in value.nodes {
5649 nodes.insert(id.clone(), HostNode::from(node));
5650 }
5651 let start = value
5652 .entrypoints
5653 .get("default")
5654 .and_then(Value::as_str)
5655 .and_then(|id| NodeId::from_str(id).ok())
5656 .or_else(|| nodes.keys().next().cloned());
5657 let vars_init = value
5658 .metadata
5659 .extra
5660 .get("vars_init")
5661 .and_then(|v| v.as_object())
5662 .map(|decls| {
5663 decls
5664 .iter()
5665 .filter_map(|(name, decl)| {
5666 decl.get("default").map(|d| (name.clone(), d.clone()))
5667 })
5668 .collect::<JsonMap<String, Value>>()
5669 })
5670 .unwrap_or_default();
5671 let required_vars = value
5672 .metadata
5673 .extra
5674 .get("vars_init")
5675 .and_then(|v| v.as_object())
5676 .map(|decls| {
5677 decls
5678 .iter()
5679 .filter(|(_, decl)| decl.get("required") == Some(&Value::Bool(true)))
5680 .map(|(name, _)| name.clone())
5681 .collect::<Vec<String>>()
5682 })
5683 .unwrap_or_default();
5684 let slot_schema = value
5688 .metadata
5689 .extra
5690 .get(SLOT_SCHEMA_METADATA_KEY)
5691 .filter(|v| !v.is_null())
5692 .cloned();
5693 Self {
5694 id: value.id.as_str().to_string(),
5695 start,
5696 nodes,
5697 vars_init,
5698 required_vars,
5699 slot_schema,
5700 }
5701 }
5702}
5703
5704impl From<Node> for HostNode {
5705 fn from(node: Node) -> Self {
5706 let full_ref = node.component.id.as_str().to_string();
5707 let operation_in_mapping = extract_operation_from_mapping(&node.input.mapping);
5708 let is_builtin = full_ref.starts_with("component.exec")
5717 || full_ref.starts_with("flow.")
5718 || full_ref.starts_with("emit.")
5719 || full_ref.starts_with("session.")
5720 || full_ref.starts_with("provider.")
5721 || full_ref.starts_with("dw.")
5722 || full_ref.starts_with("sorla.")
5723 || full_ref.starts_with("operala.")
5724 || full_ref.starts_with("agentic.")
5725 || full_ref.starts_with("approval.")
5733 || full_ref.starts_with("var.")
5734 || full_ref.starts_with("media.")
5735 || full_ref.starts_with("mcp:")
5738 || full_ref.starts_with("a2a:");
5742 let (component_ref, raw_operation) =
5748 if node.component.operation.is_some() || is_builtin || operation_in_mapping.is_some() {
5749 (full_ref, node.component.operation.clone())
5750 } else if let Some(dot) = full_ref.rfind('.') {
5751 let comp = full_ref[..dot].to_string();
5752 let op = full_ref[dot + 1..].to_string();
5753 (comp, Some(op))
5754 } else {
5755 (full_ref, None)
5756 };
5757 let operation_is_component_exec = raw_operation.as_deref() == Some("component.exec");
5758 let operation_is_emit = raw_operation
5759 .as_deref()
5760 .map(|op| op.starts_with("emit."))
5761 .unwrap_or(false);
5762 let is_component_exec = component_ref == "component.exec" || operation_is_component_exec;
5763
5764 let kind = if is_component_exec {
5765 let target = if component_ref == "component.exec" {
5766 if let Some(op) = raw_operation
5767 .as_deref()
5768 .filter(|op| op.starts_with("emit."))
5769 {
5770 op.to_string()
5771 } else {
5772 extract_target_component(&node.input.mapping)
5773 .unwrap_or_else(|| "component.exec".to_string())
5774 }
5775 } else {
5776 extract_target_component(&node.input.mapping)
5777 .unwrap_or_else(|| component_ref.clone())
5778 };
5779 if target.starts_with("emit.") {
5780 NodeKind::BuiltinEmit {
5781 kind: emit_kind_from_ref(&target),
5782 }
5783 } else {
5784 NodeKind::Exec {
5785 target_component: target,
5786 }
5787 }
5788 } else if operation_is_emit {
5789 NodeKind::BuiltinEmit {
5790 kind: emit_kind_from_ref(raw_operation.as_deref().unwrap_or("emit.log")),
5791 }
5792 } else {
5793 match component_ref.as_str() {
5794 "flow.call" => NodeKind::FlowCall,
5795 "flow.goto" => NodeKind::FlowGoto,
5796 "provider.invoke" => NodeKind::ProviderInvoke,
5797 "session.wait" => NodeKind::Wait,
5798 "state.get" => NodeKind::BuiltinStateGet,
5799 "state.set" => NodeKind::BuiltinStateSet,
5800 "var.set" => {
5801 let name = node
5802 .input
5803 .mapping
5804 .get("name")
5805 .and_then(Value::as_str)
5806 .unwrap_or("")
5807 .to_string();
5808 let value = node
5809 .input
5810 .mapping
5811 .get("value")
5812 .cloned()
5813 .unwrap_or(Value::Null);
5814 NodeKind::VarSet { name, value }
5815 }
5816 "dw.agent" => NodeKind::DwAgent {
5817 agent_id: raw_operation.clone().unwrap_or_default(),
5818 conversational: node.conversational,
5821 },
5822 "dw.agent_graph" => NodeKind::DwAgentGraph {
5823 graph_id: raw_operation.clone().unwrap_or_default(),
5824 },
5825 "sorla.call" => NodeKind::SorlaCall {
5826 target: raw_operation.clone().unwrap_or_default(),
5827 },
5828 "operala.call" => NodeKind::OperalaCall {
5829 target: raw_operation.clone().unwrap_or_default(),
5830 },
5831 "agentic.call" => NodeKind::AgenticCall {
5832 target: raw_operation.clone().unwrap_or_default(),
5833 },
5834 "telco-x.call" => NodeKind::TelcoXCall {
5835 target: raw_operation.clone().unwrap_or_default(),
5836 },
5837 "approval.call" => NodeKind::ApprovalCall {
5838 target: raw_operation.clone().unwrap_or_default(),
5839 },
5840 comp if comp.starts_with("emit.") => NodeKind::BuiltinEmit {
5841 kind: emit_kind_from_ref(comp),
5842 },
5843 "mcp" => mcp_node_kind(&node.input.mapping, raw_operation.as_deref()),
5852 comp if comp.starts_with("mcp:") => mcp_node_kind(&node.input.mapping, Some(comp)),
5858 "a2a" => a2a_node_kind(&node.input.mapping, raw_operation.as_deref()),
5866 comp if comp.starts_with("a2a:") => a2a_node_kind(&node.input.mapping, Some(comp)),
5867 "media.create" => NodeKind::MediaCreate,
5870 other => NodeKind::PackComponent {
5871 component_ref: other.to_string(),
5872 },
5873 }
5874 };
5875 let component_label = match &kind {
5876 NodeKind::Exec { .. } => "component.exec".to_string(),
5877 NodeKind::PackComponent { component_ref } => component_ref.clone(),
5878 NodeKind::ProviderInvoke => "provider.invoke".to_string(),
5879 NodeKind::FlowCall => "flow.call".to_string(),
5880 NodeKind::FlowGoto => "flow.goto".to_string(),
5881 NodeKind::BuiltinEmit { kind } => emit_ref_from_kind(kind),
5882 NodeKind::BuiltinStateGet => "state.get".to_string(),
5883 NodeKind::BuiltinStateSet => "state.set".to_string(),
5884 NodeKind::VarSet { .. } => "var.set".to_string(),
5885 NodeKind::Wait => "session.wait".to_string(),
5886 NodeKind::DwAgent { .. } => "dw.agent".to_string(),
5887 NodeKind::DwAgentGraph { .. } => "dw.agent_graph".to_string(),
5888 NodeKind::SorlaCall { .. } => "sorla.call".to_string(),
5889 NodeKind::OperalaCall { .. } => "operala.call".to_string(),
5890 NodeKind::AgenticCall { .. } => "agentic.call".to_string(),
5891 NodeKind::TelcoXCall { .. } => "telco-x.call".to_string(),
5892 NodeKind::ApprovalCall { .. } => "approval.call".to_string(),
5893 NodeKind::Mcp { server_id, tool } => format!("mcp:{server_id}/{tool}"),
5894 NodeKind::A2a { agent_id } => format!("a2a:{agent_id}"),
5895 NodeKind::MediaCreate => "media.create".to_string(),
5896 };
5897 let operation_name = if is_component_exec && operation_is_component_exec {
5898 None
5899 } else {
5900 raw_operation.clone()
5901 };
5902 let vars_out = node
5906 .input
5907 .mapping
5908 .get("vars_out")
5909 .and_then(Value::as_object)
5910 .cloned();
5911 let response_timeout_secs = response_timeout_from_mapping(&node.input.mapping);
5912 let payload_expr = match kind {
5913 NodeKind::BuiltinEmit { .. } => extract_emit_payload(&node.input.mapping),
5914 NodeKind::VarSet { .. } => Value::Null,
5917 _ => {
5918 let mut mapping = node.input.mapping.clone();
5922 if let Some(obj) = mapping.as_object_mut() {
5923 obj.remove("vars_out");
5924 obj.remove(RESPONSE_TIMEOUT_KEY);
5926 }
5927 mapping
5928 }
5929 };
5930 Self {
5931 kind,
5932 component: component_label,
5933 component_id: if is_component_exec {
5934 "component.exec".to_string()
5935 } else {
5936 component_ref
5937 },
5938 operation_name,
5939 operation_in_mapping,
5940 payload_expr,
5941 routing: node.routing,
5942 vars_out,
5943 response_timeout_secs,
5944 }
5945 }
5946}
5947
5948pub(crate) const RESPONSE_TIMEOUT_KEY: &str = "response_timeout_secs";
5953
5954fn response_timeout_from_mapping(mapping: &Value) -> Option<u64> {
5957 mapping
5958 .get(RESPONSE_TIMEOUT_KEY)
5959 .and_then(Value::as_u64)
5960 .filter(|secs| *secs > 0)
5961}
5962
5963fn mcp_node_kind(payload: &Value, legacy_ref: Option<&str>) -> NodeKind {
5976 if let Some((server_id, tool)) = crate::runner::mcp_node::server_tool_from_payload(payload) {
5977 return NodeKind::Mcp { server_id, tool };
5978 }
5979 if let Some((server_id, tool)) = legacy_ref.and_then(parse_legacy_mcp_ref) {
5980 return NodeKind::Mcp { server_id, tool };
5981 }
5982 NodeKind::PackComponent {
5983 component_ref: "mcp".to_string(),
5984 }
5985}
5986
5987fn a2a_node_kind(payload: &Value, legacy_ref: Option<&str>) -> NodeKind {
5999 if let Some(agent_id) = crate::runner::a2a_node::agent_from_payload(payload) {
6000 return NodeKind::A2a { agent_id };
6001 }
6002 if let Some(agent_id) = legacy_ref.and_then(crate::runner::a2a_node::agent_from_ref) {
6003 return NodeKind::A2a { agent_id };
6004 }
6005 NodeKind::PackComponent {
6006 component_ref: "a2a".to_string(),
6007 }
6008}
6009
6010fn parse_legacy_mcp_ref(reference: &str) -> Option<(String, String)> {
6014 let rest = reference.strip_prefix("mcp:").unwrap_or(reference);
6015 let (server, tool) = rest.split_once('/')?;
6016 if server.is_empty() || tool.is_empty() {
6017 return None;
6018 }
6019 Some((server.to_string(), tool.to_string()))
6020}
6021
6022fn extract_target_component(payload: &Value) -> Option<String> {
6023 match payload {
6024 Value::Object(map) => map
6025 .get("component")
6026 .or_else(|| map.get("component_ref"))
6027 .and_then(Value::as_str)
6028 .map(|s| s.to_string()),
6029 _ => None,
6030 }
6031}
6032
6033fn extract_operation_from_mapping(payload: &Value) -> Option<String> {
6034 match payload {
6035 Value::Object(map) => map
6036 .get("operation")
6037 .or_else(|| map.get("op"))
6038 .and_then(Value::as_str)
6039 .map(str::trim)
6040 .filter(|value| !value.is_empty())
6041 .map(|value| value.to_string()),
6042 _ => None,
6043 }
6044}
6045
6046fn extract_emit_payload(payload: &Value) -> Value {
6047 if let Value::Object(map) = payload {
6048 if let Some(input) = map.get("input") {
6049 return input.clone();
6050 }
6051 if let Some(inner) = map.get("payload") {
6052 return inner.clone();
6053 }
6054 }
6055 payload.clone()
6056}
6057
6058fn split_operation_payload(payload: Value) -> (Value, Value) {
6059 if let Value::Object(mut map) = payload.clone()
6060 && map.contains_key("input")
6061 {
6062 let input = map.remove("input").unwrap_or(Value::Null);
6063 let config = map.remove("config").unwrap_or(Value::Null);
6064 let legacy_only = map.keys().all(|key| {
6065 matches!(
6066 key.as_str(),
6067 "operation" | "op" | "component" | "component_ref"
6068 )
6069 });
6070 if legacy_only {
6071 return (input, config);
6072 }
6073 }
6074 (payload, Value::Null)
6075}
6076
6077fn resolve_component_operation(
6078 node_id: &str,
6079 component_label: &str,
6080 payload_operation: Option<String>,
6081 operation_override: Option<&str>,
6082 operation_in_mapping: Option<&str>,
6083) -> Result<String> {
6084 if let Some(op) = operation_override
6085 .map(str::trim)
6086 .filter(|value| !value.is_empty())
6087 {
6088 return Ok(op.to_string());
6089 }
6090
6091 if let Some(op) = payload_operation
6092 .as_deref()
6093 .map(str::trim)
6094 .filter(|value| !value.is_empty())
6095 {
6096 return Ok(op.to_string());
6097 }
6098
6099 let mut message = format!(
6100 "missing operation for node `{}` (component `{}`); expected node.component.operation to be set",
6101 node_id, component_label,
6102 );
6103 if let Some(found) = operation_in_mapping {
6104 message.push_str(&format!(
6105 ". Found operation in input.mapping (`{}`) but this is not used; pack compiler must preserve node.component.operation.",
6106 found
6107 ));
6108 }
6109 bail!(message);
6110}
6111
6112fn emit_kind_from_ref(component_ref: &str) -> EmitKind {
6113 match component_ref {
6114 "emit.log" => EmitKind::Log,
6115 "emit.response" => EmitKind::Response,
6116 other => EmitKind::Other(other.to_string()),
6117 }
6118}
6119
6120fn emit_ref_from_kind(kind: &EmitKind) -> String {
6121 match kind {
6122 EmitKind::Log => "emit.log".to_string(),
6123 EmitKind::Response => "emit.response".to_string(),
6124 EmitKind::Other(other) => other.clone(),
6125 }
6126}
6127
6128fn is_card_invocation(input: &Value) -> bool {
6131 if let Value::Object(map) = input {
6132 return map.contains_key("card_source") || map.contains_key("card_spec");
6133 }
6134 false
6135}
6136
6137fn promote_card_config_to_invocation(input: &mut Value, config: &Value) {
6149 if is_card_invocation(input) {
6150 return;
6151 }
6152
6153 let cfg_map = card_defaults_source(input, config);
6154 let Some(cfg) = cfg_map else { return };
6155
6156 let default_asset = cfg
6157 .get("default_card_asset")
6158 .and_then(Value::as_str)
6159 .map(str::trim)
6160 .filter(|value| !value.is_empty())
6161 .map(str::to_string);
6162 let default_inline = cfg
6163 .get("default_card_inline")
6164 .filter(|value| value.is_object() || value.is_array())
6165 .cloned();
6166 let default_source = cfg
6167 .get("default_source")
6168 .and_then(Value::as_str)
6169 .map(str::trim)
6170 .filter(|value| !value.is_empty())
6171 .map(str::to_lowercase);
6172
6173 if default_asset.is_none() && default_inline.is_none() && default_source.is_none() {
6174 return;
6175 }
6176
6177 let card_source = default_source.unwrap_or_else(|| {
6178 if default_inline.is_some() {
6179 "inline".to_string()
6180 } else {
6181 "asset".to_string()
6182 }
6183 });
6184
6185 let mut card_spec = serde_json::Map::new();
6186 match card_source.as_str() {
6187 "asset" => {
6188 if let Some(path) = default_asset {
6189 card_spec.insert("asset_path".into(), Value::String(path));
6190 }
6191 }
6192 "inline" => {
6193 if let Some(inline) = default_inline {
6194 card_spec.insert("inline_json".into(), inline);
6195 }
6196 }
6197 _ => {}
6198 }
6199
6200 if !matches!(input, Value::Object(_)) {
6201 *input = Value::Object(serde_json::Map::new());
6202 }
6203 if let Value::Object(map) = input {
6204 map.insert("card_source".into(), Value::String(card_source));
6205 map.insert("card_spec".into(), Value::Object(card_spec));
6206 }
6207}
6208
6209fn card_defaults_source<'a>(
6214 input: &'a Value,
6215 config: &'a Value,
6216) -> Option<&'a serde_json::Map<String, Value>> {
6217 if let Value::Object(map) = config {
6218 return Some(map);
6219 }
6220 if let Value::Object(map) = input
6221 && let Some(Value::Object(nested)) = map.get("config")
6222 {
6223 return Some(nested);
6224 }
6225 None
6226}
6227
6228fn activity_locale(entry: &Value) -> Option<&str> {
6239 entry
6240 .pointer("/input/metadata/locale")
6241 .or_else(|| entry.pointer("/metadata/locale"))
6242 .and_then(Value::as_str)
6243 .filter(|locale| !locale.trim().is_empty())
6244}
6245
6246fn inject_card_locale(payload: &mut Value, entry: &Value) {
6247 if !is_card_invocation(payload) {
6248 return;
6249 }
6250 let Value::Object(map) = payload else { return };
6251 if map.contains_key("locale") {
6252 return;
6253 }
6254 if let Some(locale) = activity_locale(entry) {
6255 map.insert("locale".into(), Value::String(locale.to_string()));
6256 }
6257}
6258
6259fn inject_card_route(payload: &mut Value, entry: &Value, node: &HostNode) {
6274 let is_adaptive_card =
6275 node.component_id().contains("adaptive-card") || node.component.contains("adaptive-card");
6276 if !is_adaptive_card || is_card_invocation(payload) {
6277 return;
6278 }
6279 let route = entry
6280 .pointer("/input/metadata/routeToCardId")
6281 .or_else(|| entry.pointer("/metadata/routeToCardId"))
6282 .or_else(|| entry.pointer("/input/metadata/toCardId"))
6283 .or_else(|| entry.pointer("/metadata/toCardId"))
6284 .or_else(|| entry.pointer("/input/metadata/nextCardId"))
6285 .or_else(|| entry.pointer("/metadata/nextCardId"))
6286 .and_then(Value::as_str)
6287 .map(str::trim)
6288 .filter(|value| !value.is_empty());
6289 let Some(route) = route else {
6290 return;
6291 };
6292
6293 if !matches!(payload, Value::Object(_)) {
6294 *payload = Value::Object(serde_json::Map::new());
6295 }
6296 if let Value::Object(map) = payload {
6297 let mut card_spec = serde_json::Map::new();
6298 card_spec.insert(
6299 "asset_path".into(),
6300 Value::String(format!("assets/cards/{route}.json")),
6301 );
6302 map.insert("card_source".into(), Value::String("asset".into()));
6303 map.insert("card_spec".into(), Value::Object(card_spec));
6304 tracing::debug!(route_to_card = %route, "inject_card_route: routed card asset selected");
6305 }
6306}
6307
6308fn inject_slot_definitions(input: &mut Value, slot_schema: &Value, flow_id: &str, node_id: &str) {
6314 if input.is_null() {
6315 *input = Value::Object(serde_json::Map::new());
6316 }
6317 let Some(map) = input.as_object_mut() else {
6318 tracing::warn!(
6319 flow_id,
6320 node_id,
6321 "slot-extractor input is not an object; cannot inject slot_definitions"
6322 );
6323 return;
6324 };
6325 if map.contains_key("slot_definitions") {
6326 return;
6327 }
6328 let slot_count = slot_schema.as_array().map_or(0, Vec::len);
6329 tracing::debug!(
6330 flow_id,
6331 slot_count,
6332 "injecting flow-level slot_schema as slot_definitions into slot-extractor input"
6333 );
6334 map.insert("slot_definitions".to_string(), slot_schema.clone());
6335}
6336
6337fn resolve_card_assets(input: &mut Value, pack: &crate::pack::PackRuntime) {
6344 resolve_card_spec_asset(input, pack);
6345
6346 if let Value::Object(map) = input
6349 && let Some(Value::Object(call)) = map.get_mut("call")
6350 && let Some(payload) = call.get_mut("payload")
6351 {
6352 resolve_card_spec_asset(payload, pack);
6353 }
6354}
6355
6356fn resolve_card_spec_asset(value: &mut Value, pack: &crate::pack::PackRuntime) {
6358 let Value::Object(map) = value else { return };
6359
6360 let is_asset = map
6361 .get("card_source")
6362 .and_then(Value::as_str)
6363 .map(|s| s.eq_ignore_ascii_case("asset"))
6364 .unwrap_or(false);
6365 if !is_asset {
6366 return;
6367 }
6368
6369 let asset_path = map
6370 .get("card_spec")
6371 .and_then(|spec| spec.get("asset_path"))
6372 .and_then(Value::as_str)
6373 .map(str::to_string);
6374
6375 let Some(asset_path) = asset_path else { return };
6376
6377 match pack.read_asset(&asset_path) {
6378 Ok(bytes) => {
6379 let card_json: Value = match serde_json::from_slice(&bytes) {
6380 Ok(v) => v,
6381 Err(err) => {
6382 tracing::warn!(
6383 asset_path,
6384 %err,
6385 "failed to parse card asset as JSON; leaving as asset reference"
6386 );
6387 return;
6388 }
6389 };
6390 tracing::debug!(asset_path, "pre-resolved card asset to inline_json");
6391 map.insert("card_source".into(), Value::String("inline".into()));
6392 if let Some(Value::Object(spec)) = map.get_mut("card_spec") {
6393 spec.insert("inline_json".into(), card_json);
6394 spec.remove("asset_path");
6395 }
6396 }
6397 Err(err) => {
6398 tracing::warn!(
6399 asset_path,
6400 %err,
6401 "card asset not found in pack; leaving as asset reference"
6402 );
6403 }
6404 }
6405
6406 let configured_bundle_path = map
6413 .get("card_spec")
6414 .and_then(|spec| spec.get("i18n_bundle_path"))
6415 .and_then(Value::as_str)
6416 .map(|s| s.trim().trim_end_matches('/').to_string())
6417 .filter(|s| !s.is_empty());
6418
6419 let bundle_path = configured_bundle_path
6420 .clone()
6421 .unwrap_or_else(|| "assets/i18n".to_string());
6422
6423 let i18n_entries = load_i18n_bundle_entries(&bundle_path, |path| pack.read_asset(path));
6424
6425 if !i18n_entries.is_empty() {
6426 let locale_keys: Vec<_> = i18n_entries.keys().cloned().collect();
6427 if let Some(Value::Object(spec)) = map.get_mut("card_spec") {
6428 spec.insert("i18n_inline".into(), Value::Object(i18n_entries));
6429 if configured_bundle_path.is_some() {
6430 tracing::info!(%bundle_path, ?locale_keys, "pre-resolved i18n bundle into card_spec.i18n_inline");
6431 } else {
6432 tracing::info!(%bundle_path, ?locale_keys, "auto-discovered i18n bundle and inlined into card_spec.i18n_inline");
6433 }
6434 }
6435 }
6436}
6437
6438fn load_i18n_bundle_entries<F>(bundle_path: &str, mut read_asset: F) -> JsonMap<String, Value>
6439where
6440 F: FnMut(&str) -> Result<Vec<u8>>,
6441{
6442 let mut i18n_entries = JsonMap::new();
6443
6444 if bundle_path.ends_with(".json") {
6445 if let Ok(bytes) = read_asset(bundle_path)
6446 && let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
6447 {
6448 i18n_entries.insert("en".to_string(), Value::Object(entries));
6449 }
6450 return i18n_entries;
6451 }
6452
6453 let manifest_path = format!("{bundle_path}/_manifest.json");
6454 let locale_codes: Vec<String> = read_asset(&manifest_path)
6455 .ok()
6456 .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
6457 .and_then(|value| {
6458 let locales = value
6459 .get("locales")
6460 .and_then(Value::as_array)
6461 .cloned()
6462 .or_else(|| value.as_array().cloned());
6463 locales.map(|items| {
6464 items
6465 .iter()
6466 .filter_map(Value::as_str)
6467 .map(String::from)
6468 .collect()
6469 })
6470 })
6471 .unwrap_or_default();
6472
6473 tracing::info!(%bundle_path, ?locale_codes, "i18n manifest discovered locales");
6474
6475 for locale in &locale_codes {
6476 let candidate = format!("{bundle_path}/{locale}.json");
6477 if let Ok(bytes) = read_asset(&candidate)
6478 && let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
6479 {
6480 i18n_entries.insert(locale.clone(), Value::Object(entries));
6481 }
6482 }
6483 if !i18n_entries.contains_key("en") {
6484 let en_path = format!("{bundle_path}/en.json");
6485 if let Ok(bytes) = read_asset(&en_path)
6486 && let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
6487 {
6488 i18n_entries.insert("en".to_string(), Value::Object(entries));
6489 }
6490 }
6491
6492 i18n_entries
6493}
6494
6495#[derive(Debug)]
6504pub(crate) enum CustomRoutingDecision {
6505 Next(NodeId),
6506 End,
6507 Wait,
6508}
6509
6510fn evaluate_custom_routing(
6523 raw: &Value,
6524 output: &NodeOutput,
6525 state: &ExecutionState,
6526 flow_ir: &HostFlow,
6527 node_id: &NodeId,
6528) -> CustomRoutingDecision {
6529 let routes = match raw.as_array() {
6530 Some(arr) => arr,
6531 None => {
6532 tracing::warn!(
6533 flow_id = %flow_ir.id,
6534 node_id = %node_id,
6535 "custom routing is not an array; terminating"
6536 );
6537 return CustomRoutingDecision::End;
6538 }
6539 };
6540
6541 let ctx = build_routing_context(
6548 output,
6549 state,
6550 default_success_event(routes),
6551 default_error_event(routes),
6552 );
6553
6554 let mut has_condition = false;
6555 let mut unmatched_conditions: Vec<&str> = Vec::new();
6556 for route in routes {
6557 let condition = route.get("condition").and_then(|v| v.as_str());
6558 let to = route.get("to").and_then(|v| v.as_str());
6559
6560 if route.get("on_message").and_then(Value::as_bool) == Some(true) {
6561 has_condition = true;
6566 unmatched_conditions.push("on_message");
6567 let resumed_here = state.resumed_at.as_deref() == Some(node_id.as_str());
6568 let no_action = resolve_dotted_path(&ctx, "response.action")
6569 .is_none_or(|action| action.trim().is_empty());
6570 if resumed_here
6571 && no_action
6572 && let Some(target) = to
6573 && let Ok(nid) = NodeId::new(target)
6574 {
6575 tracing::debug!(
6576 flow_id = %flow_ir.id,
6577 node_id = %node_id,
6578 target = target,
6579 "on_message route taken"
6580 );
6581 return CustomRoutingDecision::Next(nid);
6582 }
6583 continue;
6584 }
6585 if let Some(cond) = condition {
6586 has_condition = true;
6587 unmatched_conditions.push(cond);
6588 if evaluate_simple_condition(cond, &ctx)
6589 && let Some(target) = to
6590 && let Ok(nid) = NodeId::new(target)
6591 {
6592 tracing::debug!(
6593 flow_id = %flow_ir.id,
6594 node_id = %node_id,
6595 condition = cond,
6596 target = target,
6597 "conditional route matched"
6598 );
6599 return CustomRoutingDecision::Next(nid);
6600 }
6601 } else if let Some(target) = to
6602 && let Ok(nid) = NodeId::new(target)
6603 {
6604 tracing::debug!(
6605 flow_id = %flow_ir.id,
6606 node_id = %node_id,
6607 target = target,
6608 "default route taken"
6609 );
6610 return CustomRoutingDecision::Next(nid);
6611 }
6612 }
6613
6614 if has_condition {
6621 tracing::warn!(
6622 flow_id = %flow_ir.id,
6623 node_id = %node_id,
6624 conditions = ?unmatched_conditions,
6625 "no conditional route matched; pausing run at current node for resume"
6626 );
6627 CustomRoutingDecision::Wait
6628 } else {
6629 tracing::warn!(
6630 flow_id = %flow_ir.id,
6631 node_id = %node_id,
6632 "no route matched and no conditions present; terminating"
6633 );
6634 CustomRoutingDecision::End
6635 }
6636}
6637
6638fn evaluate_simple_condition(condition: &str, ctx: &Value) -> bool {
6649 let Some((op, path, expected)) = split_at_first_operator(condition) else {
6650 return false;
6651 };
6652 match op {
6653 "==" => string_eq(ctx, path, expected, false),
6654 "!=" => string_eq(ctx, path, expected, true),
6655 ">=" => numeric_cmp(ctx, path, expected, |a, b| a >= b),
6656 "<=" => numeric_cmp(ctx, path, expected, |a, b| a <= b),
6657 ">" => numeric_cmp(ctx, path, expected, |a, b| a > b),
6658 "<" => numeric_cmp(ctx, path, expected, |a, b| a < b),
6659 " contains " => {
6660 let needle = expected.to_lowercase();
6661 resolve_dotted_path(ctx, path)
6662 .is_some_and(|actual| actual.to_lowercase().contains(&needle))
6663 }
6664 _ => false,
6665 }
6666}
6667
6668const CONDITION_OPERATORS: [&str; 7] = ["==", "!=", ">=", "<=", ">", "<", " contains "];
6671
6672fn split_at_first_operator(condition: &str) -> Option<(&'static str, &str, &str)> {
6680 let mut in_quotes = false;
6681 for (idx, ch) in condition.char_indices() {
6682 if ch == '"' {
6683 in_quotes = !in_quotes;
6684 continue;
6685 }
6686 if in_quotes {
6687 continue;
6688 }
6689 let rest = &condition[idx..];
6690 if let Some(op) = CONDITION_OPERATORS.iter().find(|op| rest.starts_with(**op)) {
6691 let path = condition[..idx].trim();
6692 let value = condition[idx + op.len()..].trim().trim_matches('"');
6693 return Some((op, path, value));
6694 }
6695 }
6696 None
6697}
6698
6699fn string_eq(ctx: &Value, path: &str, expected: &str, negate: bool) -> bool {
6702 let matches = resolve_dotted_path(ctx, path)
6703 .as_deref()
6704 .is_some_and(|a| a.eq_ignore_ascii_case(expected));
6705 if negate { !matches } else { matches }
6706}
6707
6708fn numeric_cmp(ctx: &Value, path: &str, expected: &str, cmp: impl Fn(f64, f64) -> bool) -> bool {
6711 let Some(actual) = resolve_dotted_path(ctx, path).and_then(|a| a.trim().parse::<f64>().ok())
6712 else {
6713 return false;
6714 };
6715 let Ok(rhs) = expected.parse::<f64>() else {
6716 return false;
6717 };
6718 cmp(actual, rhs)
6719}
6720
6721fn resolve_dotted_path(value: &Value, path: &str) -> Option<String> {
6723 let parts: Vec<&str> = path.split('.').collect();
6724 let mut current = value;
6725 for part in &parts {
6726 current = current.get(part)?;
6727 }
6728 match current {
6729 Value::String(s) => Some(s.clone()),
6730 Value::Bool(b) => Some(b.to_string()),
6731 Value::Number(n) => Some(n.to_string()),
6732 _ => Some(current.to_string()),
6733 }
6734}
6735
6736const MAX_STEPS_PER_TURN: usize = 10_000;
6741
6742fn check_step_budget(steps_run: usize, flow_id: &str) -> Result<()> {
6746 if steps_run > MAX_STEPS_PER_TURN {
6747 return Err(terminal_flow_error(format!(
6751 "flow_step_limit_exceeded: flow `{flow_id}` ran more than {MAX_STEPS_PER_TURN} nodes in one turn (routing cycle?)"
6752 )));
6753 }
6754 Ok(())
6755}
6756
6757const SUCCESS_EVENT_PORTS: [&str; 3] = ["on_success", "on_complete", "on_submit"];
6762
6763const ERROR_EVENT_PORTS: [&str; 3] = ["on_error", "on_cancel", "on_timeout"];
6768
6769fn node_has_error_route(routing: &Routing) -> bool {
6776 let Routing::Custom(raw) = routing else {
6777 return false;
6778 };
6779 let Some(routes) = raw.as_array() else {
6780 return false;
6781 };
6782 routes.iter().any(|route| {
6783 let by_event = route
6784 .get("event")
6785 .and_then(Value::as_str)
6786 .is_some_and(|e| ERROR_EVENT_PORTS.contains(&e));
6787 let by_condition = route
6788 .get("condition")
6789 .and_then(Value::as_str)
6790 .is_some_and(|c| ERROR_EVENT_PORTS.iter().any(|port| c.contains(port)));
6791 by_event || by_condition
6792 })
6793}
6794
6795fn default_success_event(routes: &[Value]) -> &'static str {
6805 default_event(routes, &SUCCESS_EVENT_PORTS, "on_success")
6806}
6807
6808fn default_error_event(routes: &[Value]) -> &'static str {
6813 default_event(routes, &ERROR_EVENT_PORTS, "on_error")
6814}
6815
6816fn default_event(routes: &[Value], ports: &[&'static str], fallback: &'static str) -> &'static str {
6819 let referenced: Vec<&str> = routes
6820 .iter()
6821 .filter_map(|route| route.get("condition").and_then(Value::as_str))
6822 .filter_map(condition_event_eq)
6823 .collect();
6824 ports
6825 .iter()
6826 .copied()
6827 .find(|port| referenced.contains(port))
6828 .unwrap_or(fallback)
6829}
6830
6831fn condition_event_eq(condition: &str) -> Option<&str> {
6834 let idx = condition.find("==")?;
6835 if condition[..idx].trim() != "event" {
6836 return None;
6837 }
6838 Some(condition[idx + 2..].trim().trim_matches('"'))
6839}
6840
6841fn resolve_entry_metadata(entry: &Value) -> Option<&Value> {
6848 entry
6849 .pointer("/input/metadata")
6850 .or_else(|| entry.pointer("/metadata"))
6851}
6852
6853fn submitted_fields(entry: &Value) -> JsonMap<String, Value> {
6879 let mut fields = JsonMap::new();
6880 if let Some(Value::Object(meta)) = resolve_entry_metadata(entry) {
6881 for (key, value) in meta {
6882 if key == "action" || key == SUBMIT_MARKER_KEY {
6883 continue;
6884 }
6885 fields.insert(key.clone(), value.clone());
6886 }
6887 }
6888 let envelope = entry
6889 .get("input")
6890 .filter(|v| v.is_object())
6891 .unwrap_or(entry);
6892 if let Some(map) = envelope.as_object() {
6893 for (key, value) in map {
6894 if key == "metadata" || key == "text" {
6895 continue;
6896 }
6897 fields.insert(key.clone(), value.clone());
6898 }
6899 }
6900 fields
6901}
6902
6903fn build_routing_context(
6930 output: &NodeOutput,
6931 state: &ExecutionState,
6932 success_event: &str,
6933 error_event: &str,
6934) -> Value {
6935 let mut ctx = match &output.payload {
6936 Value::Object(map) => map.clone(),
6937 _ => JsonMap::new(),
6938 };
6939
6940 let entry = alias_input_to_entry(state.entry.clone());
6945 ctx.insert("entry".into(), entry.clone());
6946 ctx.insert("in".into(), entry.clone());
6947
6948 ctx.insert("node".into(), Value::Object(state.outputs_map()));
6955
6956 let metadata = resolve_entry_metadata(&entry);
6960
6961 let mut response = JsonMap::new();
6962 if let Some(Value::Object(meta)) = metadata {
6963 for (k, v) in meta {
6964 match v {
6966 Value::String(s) => {
6967 response.insert(k.clone(), Value::String(s.clone()));
6968 }
6969 other => {
6970 response.insert(k.clone(), other.clone());
6971 }
6972 }
6973 }
6974 }
6975 if let Some(text) = entry
6977 .pointer("/input/text")
6978 .or_else(|| entry.pointer("/text"))
6979 .filter(|t| !t.is_null())
6980 {
6981 response.insert("text".into(), text.clone());
6982 }
6983 ctx.insert("response".into(), Value::Object(response));
6984
6985 let event = output
6994 .meta
6995 .get("outcome")
6996 .and_then(Value::as_str)
6997 .map(str::to_string)
6998 .unwrap_or_else(|| {
6999 if output.ok {
7000 success_event
7001 } else {
7002 error_event
7003 }
7004 .to_string()
7005 });
7006 ctx.insert("event".into(), Value::String(event));
7007
7008 Value::Object(ctx)
7009}
7010
7011fn approval_requires_human(input: &Value) -> bool {
7019 let mode = input
7020 .get("mode")
7021 .and_then(Value::as_str)
7022 .unwrap_or("always");
7023 match mode {
7024 "above_risk" => match (
7027 finite_number(input, "risk"),
7028 finite_number(input, "risk_threshold"),
7029 ) {
7030 (Some(risk), Some(threshold)) => risk >= threshold,
7031 _ => true,
7032 },
7033 "above_confidence" => match (
7034 finite_number(input, "confidence"),
7035 finite_number(input, "confidence_threshold"),
7036 ) {
7037 (Some(confidence), Some(threshold)) => confidence < threshold,
7038 _ => true,
7039 },
7040 _ => true,
7042 }
7043}
7044
7045fn finite_number(input: &Value, key: &str) -> Option<f64> {
7047 input
7048 .get(key)
7049 .and_then(Value::as_f64)
7050 .filter(|n| n.is_finite())
7051}
7052
7053fn entry_is_approval_response(entry: &Value) -> bool {
7058 entry.get("ok").is_some()
7059}
7060
7061#[derive(Clone, Debug, Default, PartialEq, Eq)]
7063pub(crate) struct ParkedApproval {
7064 pub(crate) correlation_id: Option<String>,
7067 pub(crate) token_fingerprint: Option<String>,
7070}
7071
7072pub(crate) fn response_authenticates(response: &Value, parked: &ParkedApproval) -> bool {
7078 match parked.token_fingerprint.as_deref() {
7079 None => true,
7080 Some(fingerprint) => {
7081 approval_token::verify(approval_token::from_response(response), fingerprint)
7082 }
7083 }
7084}
7085
7086fn approval_outcome_from_entry(entry: &Value) -> &'static str {
7097 let timed_out = entry
7098 .pointer("/error/code")
7099 .and_then(Value::as_str)
7100 .is_some_and(|code| code.eq_ignore_ascii_case("timeout"));
7101 if timed_out {
7102 return "timeout";
7103 }
7104 if entry.get("ok").and_then(Value::as_bool) == Some(false) {
7106 return "denied";
7107 }
7108 match entry.pointer("/output/decision").and_then(Value::as_str) {
7109 Some(decision) if decision.eq_ignore_ascii_case("approved") => "approved",
7110 _ => "denied",
7111 }
7112}
7113
7114#[cfg(test)]
7115mod approval_gate_tests {
7116 use super::{approval_outcome_from_entry, approval_requires_human, entry_is_approval_response};
7117 use serde_json::json;
7118
7119 #[test]
7120 fn above_risk_auto_approves_below_threshold() {
7121 let input = json!({ "risk": 0.5, "mode": "above_risk", "risk_threshold": 0.7 });
7122 assert!(!approval_requires_human(&input));
7123 }
7124
7125 #[test]
7126 fn above_risk_requires_human_at_or_above_threshold() {
7127 let input = json!({ "risk": 0.9, "mode": "above_risk", "risk_threshold": 0.7 });
7128 assert!(approval_requires_human(&input));
7129 }
7130
7131 #[test]
7132 fn above_confidence_requires_human_when_low_confidence() {
7133 let input =
7134 json!({ "confidence": 0.4, "mode": "above_confidence", "confidence_threshold": 0.8 });
7135 assert!(approval_requires_human(&input));
7136 }
7137
7138 #[test]
7139 fn above_risk_fails_closed_on_missing_or_non_numeric_values() {
7140 for input in [
7141 json!({ "mode": "above_risk", "risk_threshold": 0.7 }),
7142 json!({ "mode": "above_risk", "risk": null, "risk_threshold": 0.7 }),
7143 json!({ "mode": "above_risk", "risk": "0.1", "risk_threshold": 0.7 }),
7144 json!({ "mode": "above_risk", "risk": 0.1 }),
7145 json!({ "mode": "above_risk", "risk": 0.1, "risk_threshold": "high" }),
7146 json!({ "mode": "above_risk" }),
7147 ] {
7148 assert!(approval_requires_human(&input), "{input}");
7149 }
7150 }
7151
7152 #[test]
7153 fn above_confidence_fails_closed_on_missing_or_non_numeric_values() {
7154 for input in [
7155 json!({ "mode": "above_confidence", "confidence_threshold": 0.5 }),
7156 json!({ "mode": "above_confidence", "confidence": "0.99", "confidence_threshold": 0.5 }),
7157 json!({ "mode": "above_confidence", "confidence": 0.99 }),
7158 json!({ "mode": "above_confidence", "confidence": null, "confidence_threshold": null }),
7159 ] {
7160 assert!(approval_requires_human(&input), "{input}");
7161 }
7162 let ok =
7163 json!({ "mode": "above_confidence", "confidence": 0.9, "confidence_threshold": 0.5 });
7164 assert!(!approval_requires_human(&ok));
7165 }
7166
7167 #[test]
7168 fn always_and_missing_gate_require_human() {
7169 assert!(approval_requires_human(&json!({ "mode": "always" })));
7170 assert!(approval_requires_human(&json!({})));
7171 }
7172
7173 #[test]
7174 fn entry_is_a_response_only_when_the_envelope_has_ok() {
7175 assert!(entry_is_approval_response(
7177 &json!({ "ok": true, "output": { "decision": "approved" } })
7178 ));
7179 assert!(entry_is_approval_response(
7180 &json!({ "ok": false, "error": { "code": "timeout" } })
7181 ));
7182 assert!(!entry_is_approval_response(
7184 &json!({ "text": "hi", "metadata": { "action": "go" } })
7185 ));
7186 assert!(!entry_is_approval_response(&json!({})));
7187 }
7188
7189 #[test]
7190 fn outcome_reads_the_decision() {
7191 assert_eq!(
7192 approval_outcome_from_entry(
7193 &json!({ "ok": true, "output": { "decision": "approved" } })
7194 ),
7195 "approved"
7196 );
7197 assert_eq!(
7198 approval_outcome_from_entry(&json!({ "ok": true, "output": { "decision": "denied" } })),
7199 "denied"
7200 );
7201 }
7202
7203 #[test]
7204 fn timeout_wins_over_the_decision() {
7205 assert_eq!(
7207 approval_outcome_from_entry(
7208 &json!({ "ok": false, "output": null, "error": { "code": "timeout" } })
7209 ),
7210 "timeout"
7211 );
7212 }
7213
7214 #[test]
7215 fn unknown_or_missing_decision_fails_closed_to_denied() {
7216 assert_eq!(
7218 approval_outcome_from_entry(&json!({ "ok": true, "output": { "decision": "maybe" } })),
7219 "denied"
7220 );
7221 assert_eq!(
7222 approval_outcome_from_entry(&json!({ "ok": true, "output": {} })),
7223 "denied"
7224 );
7225 assert_eq!(
7226 approval_outcome_from_entry(&json!({ "ok": true })),
7227 "denied"
7228 );
7229 assert_eq!(
7230 approval_outcome_from_entry(&json!({ "ok": false, "error": { "code": "nats_down" } })),
7231 "denied"
7232 );
7233 }
7234
7235 #[test]
7236 fn a_failed_envelope_is_denied_even_if_it_carries_an_approval() {
7237 assert_eq!(
7240 approval_outcome_from_entry(&json!({
7241 "ok": false,
7242 "error": { "code": "nats_down" },
7243 "output": { "decision": "approved" }
7244 })),
7245 "denied"
7246 );
7247 }
7248
7249 #[test]
7250 fn decision_match_is_case_insensitive() {
7251 assert_eq!(
7252 approval_outcome_from_entry(
7253 &json!({ "ok": true, "output": { "decision": "Approved" } })
7254 ),
7255 "approved"
7256 );
7257 }
7258}
7259
7260#[cfg(test)]
7261mod tests {
7262 use super::*;
7263 #[test]
7264 fn should_retry_typed_and_message_transient_errors() {
7265 assert!(should_retry(&anyhow!("internal server error")));
7266 assert!(should_retry(&anyhow!("service unavailable: timeout")));
7267 assert!(!should_retry(&anyhow!("bad request")));
7268 assert!(should_retry(&anyhow::Error::new(TransientFlowError(
7269 "upstream hiccup".into()
7270 ))));
7271 let wrapped = anyhow::Error::new(TransientFlowError("x".into())).context("node failed");
7272 assert!(should_retry(&wrapped));
7273 let io = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::TimedOut));
7274 assert!(should_retry(&io));
7275 let denied = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
7276 assert!(!should_retry(&denied));
7277 }
7278
7279 #[test]
7280 fn branch_target_routes_on_status_then_default() {
7281 let a = NodeId::from_str("a").unwrap();
7282 let b = NodeId::from_str("b").unwrap();
7283 let d = NodeId::from_str("d").unwrap();
7284 let mut on_status = std::collections::BTreeMap::new();
7285 on_status.insert("approved".to_string(), a.clone());
7286 on_status.insert("true".to_string(), b.clone());
7287 let out = NodeOutput::new(json!({ "status": "approved" }));
7288 assert_eq!(branch_target(&on_status, Some(&d), &out), Some(a));
7289 let flag = NodeOutput::new(json!({ "status": true }));
7290 assert_eq!(branch_target(&on_status, Some(&d), &flag), Some(b));
7291 let unknown = NodeOutput::new(json!({ "status": "other" }));
7292 assert_eq!(
7293 branch_target(&on_status, Some(&d), &unknown),
7294 Some(d.clone())
7295 );
7296 let none = NodeOutput::new(json!({}));
7297 assert_eq!(branch_target(&on_status, None, &none), None);
7298 }
7299
7300 #[test]
7301 fn first_unhandled_failure_uses_execution_order_and_skips_handled_nodes() {
7302 let failed = |msg: &str| {
7303 let mut out = NodeOutput::new(json!({}));
7304 out.ok = false;
7305 out.meta = json!({ "error": { "message": msg } });
7306 out
7307 };
7308 let mut state = ExecutionState::new(json!({}));
7309 state.record_node_output("z_first".to_string(), failed("first"));
7311 state.record_node_output("a_second".to_string(), failed("second"));
7312
7313 let mut flow = HostFlow {
7314 id: "f".to_string(),
7315 start: None,
7316 nodes: IndexMap::new(),
7317 vars_init: JsonMap::new(),
7318 required_vars: Vec::new(),
7319 slot_schema: None,
7320 };
7321 let (id, _) = state.first_unhandled_failure(&flow).expect("a failure");
7322 assert_eq!(id, "z_first");
7323
7324 let mut handled = HostNode::for_test("comp", Some("op"));
7327 handled.routing = Routing::Custom(json!([
7328 { "condition": "event == \"on_error\"", "to": "recover" }
7329 ]));
7330 flow.nodes
7331 .insert(NodeId::from_str("z_first").unwrap(), handled);
7332 let (id, _) = state.first_unhandled_failure(&flow).expect("a failure");
7333 assert_eq!(id, "a_second");
7334 }
7335
7336 fn native_op_key_for(kind: &NodeKind) -> Option<&'static str> {
7352 match kind {
7353 NodeKind::Exec { .. } | NodeKind::PackComponent { .. } => None,
7355 NodeKind::BuiltinEmit { .. } | NodeKind::Mcp { .. } | NodeKind::A2a { .. } => None,
7361
7362 NodeKind::ProviderInvoke => Some("provider.invoke"),
7363 NodeKind::FlowCall => Some("flow.call"),
7364 NodeKind::FlowGoto => Some("flow.goto"),
7365 NodeKind::BuiltinStateGet => Some("state.get"),
7366 NodeKind::BuiltinStateSet => Some("state.set"),
7367 NodeKind::VarSet { .. } => Some("var.set"),
7368 NodeKind::MediaCreate => Some("media.create"),
7369 NodeKind::Wait => Some("session.wait"),
7370 NodeKind::DwAgent { .. } => Some("dw.agent"),
7371 NodeKind::DwAgentGraph { .. } => Some("dw.agent_graph"),
7372 NodeKind::SorlaCall { .. } => Some("sorla.call"),
7373 NodeKind::OperalaCall { .. } => Some("operala.call"),
7374 NodeKind::AgenticCall { .. } => Some("agentic.call"),
7375 NodeKind::TelcoXCall { .. } => Some("telco-x.call"),
7376 NodeKind::ApprovalCall { .. } => Some("approval.call"),
7377 }
7378 }
7379
7380 #[test]
7381 fn every_engine_dispatched_op_key_is_native_to_the_loader() {
7382 for key in [
7386 "provider.invoke",
7387 "flow.call",
7388 "flow.goto",
7389 "state.get",
7390 "state.set",
7391 "var.set",
7392 "session.wait",
7393 "dw.agent",
7394 "dw.agent_graph",
7395 "sorla.call",
7396 "operala.call",
7397 "agentic.call",
7398 "telco-x.call",
7399 "approval.call",
7400 "media.create",
7401 ] {
7402 assert!(
7403 crate::runner::flow_adapter::is_native_op_key(key),
7404 "the engine dispatches `{key}`, but the loader does not treat it \
7405 as native — it will be wrapped as a generic component and the \
7406 engine arm becomes unreachable"
7407 );
7408 }
7409 assert!(crate::runner::flow_adapter::is_native_op_key(
7411 "emit.response"
7412 ));
7413 assert!(crate::runner::flow_adapter::is_native_op_key(
7414 "mcp:srv/tool"
7415 ));
7416 for key in ["mcp", "mcp:srv/tool", "a2a", "a2a:8d2f0c1e-recipe"] {
7419 assert!(
7420 crate::runner::flow_adapter::is_native_op_key(key),
7421 "the engine dispatches `{key}`, but the loader does not treat it as native"
7422 );
7423 }
7424 assert!(!crate::runner::flow_adapter::is_native_op_key("mcp.exec"));
7426 assert!(!crate::runner::flow_adapter::is_native_op_key("a2a.exec"));
7427
7428 assert_eq!(native_op_key_for(&NodeKind::FlowGoto), Some("flow.goto"));
7430 }
7431
7432 #[test]
7439 fn the_a2a_component_ref_is_a_valid_component_id() {
7440 assert!(greentic_types::ComponentId::from_str("a2a").is_ok());
7441 }
7442
7443 #[test]
7447 fn the_media_create_component_ref_is_a_valid_component_id() {
7448 assert!(greentic_types::ComponentId::from_str("media.create").is_ok());
7449 assert!(crate::runner::flow_adapter::is_native_op_key(
7450 "media.create"
7451 ));
7452 assert_eq!(
7453 native_op_key_for(&NodeKind::MediaCreate),
7454 Some("media.create")
7455 );
7456 }
7457
7458 #[cfg(feature = "agentic-worker")]
7459 #[test]
7460 fn a_media_failure_is_an_errored_node_only_with_an_error_route() {
7461 let result = json!({"ok": false, "error": {"code": "invalid_input", "message": "no text"}});
7462 let payload = json!({ "format": "pdf", "output": "file" });
7463 let quiet = media_node_output(bind_node_result(&payload, result.clone()), &result, false);
7464 assert!(quiet.ok);
7465 assert_eq!(quiet.payload["file"]["error"]["code"], "invalid_input");
7466 let routed = media_node_output(bind_node_result(&payload, result.clone()), &result, true);
7467 assert!(!routed.ok);
7468 assert_eq!(routed.payload["error"]["code"], "invalid_input");
7469 assert_eq!(routed.payload["error"]["message"], "no text");
7470 assert!(
7471 routed.payload["file"].is_object(),
7472 "the output key survives"
7473 );
7474 let good = json!({"ok": true, "artifact": {"id": "artifact://x"}});
7475 let out = media_node_output(good.clone(), &good, true);
7476 assert!(out.ok);
7477 }
7478
7479 #[test]
7480 fn a2a_node_kind_prefers_the_payload_over_the_ref() {
7481 let payload = json!({ "agent": "from-payload", "message": "hi" });
7482 assert!(matches!(
7483 a2a_node_kind(&payload, Some("a2a:from-ref")),
7484 NodeKind::A2a { agent_id } if agent_id == "from-payload"
7485 ));
7486 }
7487
7488 #[test]
7489 fn a2a_node_kind_falls_back_to_both_ref_spellings() {
7490 for reference in ["a2a:8d2f0c1e-recipe", "8d2f0c1e-recipe"] {
7491 assert!(
7492 matches!(
7493 a2a_node_kind(&json!({ "message": "hi" }), Some(reference)),
7494 NodeKind::A2a { agent_id } if agent_id == "8d2f0c1e-recipe"
7495 ),
7496 "{reference} must resolve the agent id"
7497 );
7498 }
7499 }
7500
7501 #[test]
7505 fn an_a2a_node_naming_no_agent_loads_as_a_generic_component() {
7506 for legacy in [None, Some("a2a:"), Some("")] {
7507 assert!(
7508 matches!(
7509 a2a_node_kind(&json!({ "message": "hi" }), legacy),
7510 NodeKind::PackComponent { .. }
7511 ),
7512 "legacy={legacy:?} must not classify as an a2a node"
7513 );
7514 }
7515 }
7516
7517 #[cfg(feature = "agentic-worker")]
7518 fn a2a_result(status: &str, extra: (&str, &str)) -> Value {
7519 json!({ "status": status, "agent": "recipe", extra.0: extra.1 })
7520 }
7521
7522 #[cfg(feature = "agentic-worker")]
7526 #[test]
7527 fn without_an_error_route_an_a2a_node_reports_ok_and_keeps_the_value() {
7528 let result = a2a_result("error", ("error", "card unreachable"));
7529 let output = a2a_node_output(bind_node_result(&json!({}), result.clone()), &result, false);
7530 assert!(output.ok);
7531 assert_eq!(output.payload["error"], "card unreachable");
7532 }
7533
7534 #[cfg(feature = "agentic-worker")]
7540 #[test]
7541 fn only_a_failure_marks_an_a2a_node_errored_and_the_two_failures_keep_their_codes() {
7542 let cases = [
7544 ("completed", "reply", true, None),
7545 ("input_required", "question", true, None),
7546 ("working", "detail", true, None),
7547 ("failed", "error", false, Some("a2a_agent_failed")),
7548 ("error", "error", false, Some("a2a_call_failed")),
7549 ];
7550 for (status, key, ok, code) in cases {
7551 let result = a2a_result(status, (key, "some text"));
7552 let output =
7553 a2a_node_output(bind_node_result(&json!({}), result.clone()), &result, true);
7554 assert_eq!(
7555 output.ok, ok,
7556 "status {status} produced {:?}",
7557 output.payload
7558 );
7559 assert_eq!(
7560 output.payload["status"], status,
7561 "the status must survive so a flow can still route on it"
7562 );
7563 match code {
7564 Some(code) => {
7565 assert_eq!(output.payload["error"]["code"], code, "status {status}");
7566 assert_eq!(output.payload["error"]["message"], "some text");
7567 }
7568 None => assert!(
7569 output.payload["error"].is_null() || output.payload["error"].is_string(),
7570 "status {status} must not be reshaped into an error envelope: {:?}",
7571 output.payload
7572 ),
7573 }
7574 }
7575 }
7576
7577 #[cfg(feature = "agentic-worker")]
7581 #[test]
7582 fn a_failed_a2a_node_keeps_its_output_binding_key() {
7583 let result = a2a_result("failed", ("error", "the agent rejected the request"));
7584 let payload = json!({ "agent": "recipe", "message": "hi", "output": "answer" });
7585 let output = a2a_node_output(bind_node_result(&payload, result.clone()), &result, true);
7586 assert!(!output.ok);
7587 assert_eq!(output.payload["answer"]["status"], "failed");
7588 assert_eq!(output.payload["error"]["code"], "a2a_agent_failed");
7589 }
7590
7591 #[cfg(feature = "agentic-worker")]
7594 #[test]
7595 fn the_output_binding_rule_is_one_rule_for_both_remote_tool_nodes() {
7596 let result = json!({ "status": "completed", "reply": "an omelette" });
7597 assert_eq!(
7598 bind_node_result(&json!({ "output": "answer" }), result.clone()),
7599 json!({ "answer": result })
7600 );
7601 for payload in [json!({}), json!({ "output": "" }), json!("not an object")] {
7602 assert_eq!(bind_node_result(&payload, result.clone()), result);
7603 }
7604 }
7605
7606 #[cfg(feature = "agentic-worker")]
7609 #[test]
7610 fn a_blank_message_is_recognised_as_nothing_to_send() {
7611 for blank in [json!(null), json!(""), json!(" ")] {
7612 assert!(is_blank(&blank), "{blank} must read as blank");
7613 }
7614 for present in [json!("hi"), json!(0), json!(false), json!({ "a": 1 })] {
7615 assert!(!is_blank(&present), "{present} must read as content");
7616 }
7617 }
7618
7619 #[cfg(feature = "agentic-worker")]
7627 struct PanicIfDispatchedHandler;
7628
7629 #[cfg(feature = "agentic-worker")]
7630 #[async_trait::async_trait]
7631 impl crate::runner::remote_dispatch::RemoteDispatchHandler for PanicIfDispatchedHandler {
7632 async fn dispatch(
7633 &self,
7634 _request: crate::runner::remote_dispatch::RemoteDispatch,
7635 ) -> anyhow::Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
7636 panic!(
7637 "a route document resolved for this SoR; NATS must never be reached \
7638 (amendment A1: a route document always wins over NATS)"
7639 );
7640 }
7641 }
7642
7643 #[cfg(feature = "agentic-worker")]
7644 fn sorla_call_node(routing: Routing) -> HostNode {
7645 HostNode {
7646 kind: NodeKind::SorlaCall {
7647 target: "landlord".to_string(),
7648 },
7649 component: "sorla.call".into(),
7650 component_id: "sorla.call".into(),
7651 operation_name: None,
7652 operation_in_mapping: None,
7653 payload_expr: Value::Null,
7654 routing,
7655 vars_out: None,
7656 response_timeout_secs: None,
7657 }
7658 }
7659
7660 #[cfg(feature = "agentic-worker")]
7661 fn sorla_call_ctx() -> FlowContext<'static> {
7662 FlowContext {
7663 tenant: "acme",
7664 pack_id: "test-pack",
7665 flow_id: "f",
7666 node_id: None,
7667 tool: None,
7668 action: None,
7669 session_id: None,
7670 provider_id: None,
7671 reply_scope: None,
7672 retry_config: RetryConfig {
7673 max_attempts: 1,
7674 base_delay_ms: 1,
7675 },
7676 attempt: 1,
7677 observer: None,
7678 mocks: None,
7679 caller: None,
7680 }
7681 }
7682
7683 #[cfg(feature = "agentic-worker")]
7684 #[tokio::test]
7685 async fn a_route_document_wins_over_nats() {
7686 let server = wiremock::MockServer::start().await;
7687 wiremock::Mock::given(wiremock::matchers::method("GET"))
7688 .and(wiremock::matchers::path("/admin/v1/capabilities"))
7689 .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
7690 crate::runner::sorx_invoker::fixtures::caps_response_one_business_action(),
7691 ))
7692 .mount(&server)
7693 .await;
7694 wiremock::Mock::given(wiremock::matchers::method("POST"))
7695 .and(wiremock::matchers::path("/admin/v1/capabilities/invoke"))
7696 .respond_with(
7697 wiremock::ResponseTemplate::new(200)
7698 .set_body_json(json!({"ok": true, "result": {"id": "pay-1"}})),
7699 )
7700 .mount(&server)
7701 .await;
7702
7703 let secrets = crate::runner::sorla_route::test_secrets::Handle::with(&[(
7704 "secrets://default/acme/_/sorla/landlord",
7705 &format!(r#"{{"url":"{}","tenant":"acme"}}"#, server.uri()),
7706 )])
7707 .manager();
7708
7709 let mut engine = minimal_engine();
7710 engine.mcp_secrets = Some(secrets);
7711 engine.remote_dispatch_handler = Some(Arc::new(PanicIfDispatchedHandler));
7712
7713 let ctx = sorla_call_ctx();
7714 let node = sorla_call_node(Routing::End);
7715 let mut state = ExecutionState::new(Value::Null);
7716 let payload = json!({
7717 "await": true,
7718 "operation": "record_rent_payment",
7719 "input": {"amount": 5},
7720 });
7721 let event = NodeEvent {
7722 context: &ctx,
7723 node_id: "call",
7724 node: &node,
7725 payload: &payload,
7726 };
7727
7728 let outcome = engine
7729 .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7730 .await
7731 .expect("a resolved route document must dispatch over HTTP, never NATS");
7732
7733 assert!(outcome.output.ok);
7734 assert_eq!(
7735 outcome.output.payload,
7736 json!({"id": "pay-1"}),
7737 "the node output must be the HTTP result"
7738 );
7739 }
7740
7741 #[cfg(feature = "agentic-worker")]
7746 #[tokio::test]
7747 async fn a_backend_failure_never_falls_back_to_nats() {
7748 let secrets = crate::runner::sorla_route::test_secrets::Handle::with(&[]);
7749 secrets.fail(
7750 "secrets://default/acme/_/sorla/landlord",
7751 "connection refused",
7752 );
7753
7754 let mut engine = minimal_engine();
7755 engine.mcp_secrets = Some(secrets.manager());
7756 engine.remote_dispatch_handler = Some(Arc::new(PanicIfDispatchedHandler));
7757
7758 let ctx = sorla_call_ctx();
7759 let node = sorla_call_node(Routing::End);
7760 let mut state = ExecutionState::new(Value::Null);
7761 let payload = json!({
7762 "await": true,
7763 "operation": "record_rent_payment",
7764 "input": {},
7765 });
7766 let event = NodeEvent {
7767 context: &ctx,
7768 node_id: "call",
7769 node: &node,
7770 payload: &payload,
7771 };
7772
7773 let result = engine
7774 .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7775 .await;
7776 let err = match result {
7777 Err(err) => err,
7778 Ok(_) => panic!("a backend failure must fail the node, not silently succeed"),
7779 };
7780 assert!(err.to_string().contains("could not be read"), "got: {err}");
7781 }
7782
7783 #[cfg(feature = "agentic-worker")]
7784 #[tokio::test]
7785 async fn no_route_and_no_nats_fails_with_sorla_route_missing() {
7786 let engine = minimal_engine();
7790 let ctx = sorla_call_ctx();
7791 let payload = json!({
7792 "await": true,
7793 "operation": "record_rent_payment",
7794 "input": {},
7795 });
7796
7797 let node = sorla_call_node(Routing::End);
7799 let mut state = ExecutionState::new(Value::Null);
7800 let event = NodeEvent {
7801 context: &ctx,
7802 node_id: "call",
7803 node: &node,
7804 payload: &payload,
7805 };
7806 let result = engine
7807 .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7808 .await;
7809 let err = match result {
7810 Err(err) => err,
7811 Ok(_) => panic!("no route document and no NATS handler must fail the node"),
7812 };
7813 assert!(
7814 err.to_string().contains("sorla_route_missing"),
7815 "got: {err}"
7816 );
7817
7818 let node = sorla_call_node(Routing::Custom(json!([
7821 { "condition": "event == \"on_success\"", "to": "n" },
7822 { "condition": "event == \"on_error\"", "to": "e" },
7823 ])));
7824 let mut state = ExecutionState::new(Value::Null);
7825 let event = NodeEvent {
7826 context: &ctx,
7827 node_id: "call",
7828 node: &node,
7829 payload: &payload,
7830 };
7831 let outcome = engine
7832 .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7833 .await
7834 .expect("an error-routed node must complete, not hard-fail");
7835 assert!(!outcome.output.ok);
7836 let message = outcome
7837 .output
7838 .payload
7839 .get("error")
7840 .and_then(Value::as_str)
7841 .unwrap_or_default();
7842 assert!(message.contains("sorla_route_missing"), "got: {message}");
7843 }
7844
7845 #[cfg(feature = "agentic-worker")]
7848 #[tokio::test]
7849 async fn an_approval_inbox_leaves_sorla_route_missing_intact() {
7850 let mut engine = minimal_engine();
7851 engine.set_approval_dispatch_handler(Arc::new(PanicIfDispatchedHandler));
7852 let ctx = sorla_call_ctx();
7853 let payload = json!({
7854 "await": true,
7855 "operation": "record_rent_payment",
7856 "input": {},
7857 });
7858 let node = sorla_call_node(Routing::End);
7859 let mut state = ExecutionState::new(Value::Null);
7860 let event = NodeEvent {
7861 context: &ctx,
7862 node_id: "call",
7863 node: &node,
7864 payload: &payload,
7865 };
7866 let err = match engine
7867 .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7868 .await
7869 {
7870 Err(err) => err,
7871 Ok(_) => panic!("a missing route with only the approval inbox must fail the node"),
7872 };
7873 assert!(
7874 err.to_string().contains("sorla_route_missing"),
7875 "got: {err}"
7876 );
7877 }
7878
7879 #[cfg(feature = "agentic-worker")]
7882 #[tokio::test]
7883 async fn only_approval_dispatches_use_the_approval_slot() {
7884 let inbox = Arc::new(ScriptedNatsDispatcher {
7885 calls: Mutex::new(vec![]),
7886 });
7887 let mut engine = minimal_engine();
7888 engine.set_approval_dispatch_handler(inbox.clone());
7889
7890 let ctx = sorla_call_ctx();
7891 let node = HostNode::for_test_approval("hitl");
7892 let mut state = ExecutionState::new(Value::Null);
7893 let payload = json!({ "await": true, "input": { "mode": "always" } });
7894 let event = NodeEvent {
7895 context: &ctx,
7896 node_id: "gate",
7897 node: &node,
7898 payload: &payload,
7899 };
7900 let outcome = engine
7901 .dispatch_node(&ctx, "gate", &node, &mut state, payload.clone(), &event)
7902 .await
7903 .expect("approval.call must dispatch through the approval slot");
7904 assert!(matches!(outcome.control, NodeControl::AwaitHere { .. }));
7905 {
7906 let calls = inbox.calls.lock().unwrap();
7907 assert_eq!(calls.len(), 1);
7908 assert_eq!(calls[0].runtime, APPROVAL_RUNTIME);
7909 assert!(calls[0].decision_token.is_some());
7910 assert!(
7911 crate::runner::runtime_session_resumer::split_dispatch_nonce(
7912 &calls[0].correlation_id
7913 )
7914 .1
7915 .is_some(),
7916 "the id carries its per-dispatch nonce"
7917 );
7918 }
7919 let parked = state.pending_approvals();
7920 assert_eq!(parked.len(), 1);
7921 assert!(parked[0].token_fingerprint.is_some());
7922
7923 let err = engine
7924 .execute_remote_dispatch(&ctx, "telco-x", "t", json!({"await": true}), true)
7925 .await
7926 .err()
7927 .expect("a non-approval runtime must not use the approval slot");
7928 assert!(
7929 err.to_string()
7930 .contains("no RemoteDispatchHandler configured"),
7931 "got: {err}"
7932 );
7933 assert_eq!(inbox.calls.lock().unwrap().len(), 1);
7934 }
7935
7936 #[cfg(feature = "agentic-worker")]
7939 #[tokio::test]
7940 async fn approval_falls_back_to_the_shared_slot() {
7941 let shared = Arc::new(ScriptedNatsDispatcher {
7942 calls: Mutex::new(vec![]),
7943 });
7944 let mut engine = minimal_engine();
7945 engine.set_remote_dispatch_handler(shared.clone());
7946 let ctx = sorla_call_ctx();
7947 let node = HostNode::for_test_approval("hitl");
7948 let mut state = ExecutionState::new(Value::Null);
7949 let payload = json!({ "await": true, "input": { "mode": "always" } });
7950 let event = NodeEvent {
7951 context: &ctx,
7952 node_id: "gate",
7953 node: &node,
7954 payload: &payload,
7955 };
7956 engine
7957 .dispatch_node(&ctx, "gate", &node, &mut state, payload.clone(), &event)
7958 .await
7959 .expect("approval.call must fall back to the shared slot");
7960 assert_eq!(shared.calls.lock().unwrap().len(), 1);
7961 }
7962
7963 use crate::validate::{ValidationConfig, ValidationMode};
7964 use greentic_types::{
7965 Flow, FlowComponentRef, FlowId, FlowKind, FlowMetadata, InputMapping, Node, NodeId,
7966 OutputMapping, Routing, TelemetryHints,
7967 };
7968 use serde_json::json;
7969 use std::collections::{BTreeMap, HashMap as StdHashMap};
7970 use std::str::FromStr;
7971 use std::sync::Mutex;
7972 use tokio::runtime::Runtime;
7973
7974 fn minimal_engine() -> FlowEngine {
7975 FlowEngine {
7976 packs: Vec::new(),
7977 flows: Vec::new(),
7978 flow_sources: HashMap::new(),
7979 messaging_provider_pack_ids: std::collections::HashSet::new(),
7980 flow_cache: RwLock::new(HashMap::new()),
7981 default_env: "local".to_string(),
7982 validation: ValidationConfig {
7983 mode: ValidationMode::Off,
7984 },
7985 cross_pack_resolver: None,
7986 rollout_ids: RolloutIds::default(),
7987 approval_dispatch_handler: None,
7988 remote_dispatch_handler: None,
7989 #[cfg(feature = "agentic-worker")]
7990 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
7991 #[cfg(feature = "agentic-worker")]
7992 agent_node_handler: None,
7993 #[cfg(feature = "agentic-worker")]
7994 graph_node_handler: None,
7995 #[cfg(feature = "agentic-worker")]
7996 mcp_tool_source: None,
7997 #[cfg(feature = "agentic-worker")]
7998 mcp_secrets: None,
7999 #[cfg(feature = "agentic-worker")]
8000 a2a_sources: RwLock::new(HashMap::new()),
8001 #[cfg(feature = "agentic-worker")]
8002 ext_artifact_port: None,
8003 operala_node_handler: None,
8004 }
8005 }
8006
8007 #[cfg(feature = "agentic-worker")]
8010 struct StubSecrets;
8011
8012 #[cfg(feature = "agentic-worker")]
8013 #[async_trait::async_trait]
8014 impl greentic_secrets_lib::SecretsManager for StubSecrets {
8015 async fn read(&self, _path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
8016 Ok(Vec::new())
8017 }
8018 async fn write(&self, _path: &str, _bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
8019 Ok(())
8020 }
8021 async fn delete(&self, _path: &str) -> greentic_secrets_lib::Result<()> {
8022 Ok(())
8023 }
8024 }
8025
8026 #[cfg(feature = "agentic-worker")]
8034 #[test]
8035 #[serial_test::serial]
8036 fn an_injected_manager_is_what_an_mcp_node_dispatches_with() {
8037 let injected: crate::secrets::DynSecretsManager = std::sync::Arc::new(StubSecrets);
8038 let engine = minimal_engine().with_mcp_secrets(Some(injected.clone()));
8039 let chosen = engine
8040 .mcp_secrets_for_dispatch()
8041 .expect("an injected manager is always a choice");
8042 assert!(std::sync::Arc::ptr_eq(&chosen, &injected));
8043 }
8044
8045 #[cfg(feature = "agentic-worker")]
8048 #[test]
8049 fn no_injection_leaves_the_env_derived_behaviour_alone() {
8050 let engine = minimal_engine();
8051 assert!(engine.mcp_secrets.is_none());
8052 }
8053
8054 #[cfg(feature = "agentic-worker")]
8058 #[test]
8059 #[serial_test::serial]
8060 fn binding_no_manager_does_not_clear_one_already_bound() {
8061 let injected: crate::secrets::DynSecretsManager = std::sync::Arc::new(StubSecrets);
8062 let engine = minimal_engine()
8063 .with_mcp_secrets(Some(injected.clone()))
8064 .with_mcp_secrets(None);
8065 let chosen = engine
8066 .mcp_secrets_for_dispatch()
8067 .expect("the bound manager must survive");
8068 assert!(std::sync::Arc::ptr_eq(&chosen, &injected));
8069 }
8070
8071 fn flow_desc(id: &str, pack_id: &str, flow_type: &str, entry: bool) -> FlowDescriptor {
8072 FlowDescriptor {
8073 id: id.into(),
8074 flow_type: flow_type.into(),
8075 pack_id: pack_id.into(),
8076 profile: pack_id.into(),
8077 version: "0.0.0".into(),
8078 description: None,
8079 entry,
8080 }
8081 }
8082
8083 #[test]
8084 fn entry_flow_by_type_disambiguates_entrypoint_from_internal_helpers() {
8085 let mut engine = minimal_engine();
8090 engine.flows = vec![
8091 flow_desc("default", "weatherapi-pack", "messaging", true),
8092 flow_desc("flow_", "weatherapi-pack", "messaging", false),
8093 flow_desc("flow_error", "weatherapi-pack", "messaging", false),
8094 flow_desc("flow_get_weather", "weatherapi-pack", "messaging", false),
8095 ];
8096
8097 assert!(
8099 engine.flow_by_type("messaging").is_none(),
8100 "multiple messaging flows must be ambiguous for the plain lookup"
8101 );
8102 let resolved = engine
8104 .entry_flow_by_type("messaging")
8105 .expect("single entry flow must resolve");
8106 assert_eq!(resolved.id, "default");
8107 assert_eq!(resolved.pack_id, "weatherapi-pack");
8108 }
8109
8110 #[test]
8111 fn entry_flow_by_type_still_ambiguous_across_two_entrypoints() {
8112 let mut engine = minimal_engine();
8115 engine.flows = vec![
8116 flow_desc("default", "pack.a", "messaging", true),
8117 flow_desc("default", "pack.b", "messaging", true),
8118 flow_desc("helper", "pack.a", "messaging", false),
8119 ];
8120 assert!(engine.entry_flow_by_type("messaging").is_none());
8121 }
8122
8123 #[test]
8124 fn entry_flow_by_type_excludes_messaging_provider_pack_flows() {
8125 let mut engine = minimal_engine();
8131 engine.flows = vec![
8132 flow_desc("main", "hr-onboarding-pack", "messaging", true),
8133 flow_desc("main", "messaging-teams", "messaging", true),
8134 ];
8135 engine
8138 .messaging_provider_pack_ids
8139 .insert("messaging-teams".to_string());
8140
8141 assert!(engine.flow_by_type("messaging").is_none());
8143 let resolved = engine
8145 .entry_flow_by_type("messaging")
8146 .expect("app entry flow must resolve past the provider flow");
8147 assert_eq!(resolved.id, "main");
8148 assert_eq!(resolved.pack_id, "hr-onboarding-pack");
8149 }
8150
8151 #[test]
8152 fn entry_flow_by_type_matches_plain_lookup_for_single_flow() {
8153 let mut engine = minimal_engine();
8156 engine.flows = vec![flow_desc("only", "pack.a", "messaging", true)];
8157 assert_eq!(
8158 engine.flow_by_type("messaging").map(|f| f.id.as_str()),
8159 Some("only")
8160 );
8161 assert_eq!(
8162 engine
8163 .entry_flow_by_type("messaging")
8164 .map(|f| f.id.as_str()),
8165 Some("only")
8166 );
8167 }
8168
8169 #[test]
8170 fn to_node_output_legacy_success_becomes_data() {
8171 let out = to_node_output(&json!({ "ok": true, "temp": "20C" }));
8173 assert!(out.is_ok(), "legacy ok:true must classify as Data");
8174 let data = out.data().expect("data present");
8175 assert_eq!(data.get("temp").and_then(Value::as_str), Some("20C"));
8176 }
8177
8178 #[test]
8179 fn to_node_output_legacy_error_becomes_errors() {
8180 let out = to_node_output(
8182 &json!({ "ok": false, "error": { "code": "E_BAD", "message": "boom" } }),
8183 );
8184 assert!(!out.is_ok(), "legacy ok:false must classify as Errors");
8185 let errs = out.errors();
8186 assert_eq!(errs.len(), 1);
8187 assert_eq!(errs[0].code, "E_BAD");
8188 assert_eq!(errs[0].message, "boom");
8189 }
8190
8191 #[test]
8192 fn to_node_output_native_data_envelope_roundtrips() {
8193 let out = to_node_output(&json!({ "data": { "x": 1 } }));
8195 assert!(out.is_ok());
8196 assert_eq!(
8197 out.data().and_then(|d| d.get("x")).and_then(Value::as_i64),
8198 Some(1)
8199 );
8200 }
8201
8202 #[test]
8203 fn to_node_output_native_errors_envelope_roundtrips() {
8204 let out = to_node_output(&json!({
8206 "errors": [ { "code": "C", "message": "m", "kind": "validation",
8207 "retryable": false, "details": {} } ]
8208 }));
8209 assert!(!out.is_ok());
8210 assert_eq!(out.errors()[0].code, "C");
8211 assert_eq!(
8212 out.errors()[0].kind,
8213 greentic_types::node_io::ErrorKind::Validation
8214 );
8215 }
8216
8217 #[test]
8218 fn to_node_output_bare_object_becomes_data() {
8219 let out = to_node_output(&json!({ "foo": 1 }));
8221 assert!(out.is_ok());
8222 assert_eq!(
8223 out.data()
8224 .and_then(|d| d.get("foo"))
8225 .and_then(Value::as_i64),
8226 Some(1)
8227 );
8228 }
8229
8230 #[test]
8231 fn templating_renders_with_partials_and_data() {
8232 let mut state = ExecutionState::new(json!({ "city": "London" }));
8233 state.nodes.insert(
8234 "forecast".to_string(),
8235 NodeOutput::new(json!({ "temp": "20C" })),
8236 );
8237
8238 let ctx = state.context();
8240 assert_eq!(ctx["nodes"]["forecast"]["payload"]["temp"], json!("20C"));
8241 }
8242
8243 #[test]
8244 fn outputs_map_exposes_node_io_data_and_errors_alongside_flat() {
8245 let mut state = ExecutionState::new(json!({}));
8246 state.nodes.insert(
8247 "forecast".to_string(),
8248 NodeOutput::new(json!({ "temp": "20C" })),
8249 );
8250 let outs = state.outputs_map();
8251 assert_eq!(outs["forecast"]["temp"], json!("20C"));
8253 assert_eq!(outs["forecast"]["data"]["temp"], json!("20C"));
8255 assert_eq!(outs["forecast"]["errors"], json!([]));
8257 }
8258
8259 #[test]
8260 fn finalize_wraps_emitted_payloads() {
8261 let mut state = ExecutionState::new(json!({}));
8262 state.push_egress(json!({ "text": "first" }));
8263 state.push_egress(json!({ "text": "second" }));
8264 let result = state.finalize_with(Some(json!({ "text": "final" })));
8265 assert_eq!(
8266 result,
8267 json!([
8268 { "text": "first" },
8269 { "text": "second" },
8270 { "text": "final" }
8271 ])
8272 );
8273 }
8274
8275 #[test]
8276 fn finalize_does_not_double_terminal_emit_response() {
8277 let card = json!({ "renderedCard": { "type": "AdaptiveCard" } });
8282 let mut state = ExecutionState::new(json!({}));
8283 state.push_egress(card.clone());
8284 let result = state.finalize_with(Some(card.clone()));
8285 assert_eq!(result, json!([card]));
8286 }
8287
8288 #[test]
8289 fn finalize_still_appends_distinct_terminal_output() {
8290 let mut state = ExecutionState::new(json!({}));
8293 state.push_egress(json!({ "text": "emitted" }));
8294 let result = state.finalize_with(Some(json!({ "text": "final" })));
8295 assert_eq!(result, json!([{ "text": "emitted" }, { "text": "final" }]));
8296 }
8297
8298 #[test]
8299 fn alias_input_to_entry_exposes_input_for_bare_message() {
8300 let msg = json!({ "text": "hi", "metadata": { "operation": "get_weather" } });
8304 let aliased = alias_input_to_entry(msg);
8305 assert_eq!(
8306 aliased.pointer("/metadata/operation"),
8307 Some(&json!("get_weather"))
8308 );
8309 assert_eq!(
8310 aliased.pointer("/input/metadata/operation"),
8311 Some(&json!("get_weather"))
8312 );
8313 }
8314
8315 #[test]
8316 fn alias_input_to_entry_preserves_explicit_input_wrapper() {
8317 let wrapped = json!({ "input": { "metadata": { "operation": "x" } } });
8319 assert_eq!(alias_input_to_entry(wrapped.clone()), wrapped);
8320 }
8321
8322 #[test]
8323 fn alias_input_to_entry_ignores_non_objects() {
8324 assert_eq!(alias_input_to_entry(json!("hi")), json!("hi"));
8325 assert_eq!(alias_input_to_entry(json!(null)), json!(null));
8326 }
8327
8328 fn render_entry(entry: Value, expr: &str) -> Value {
8330 let st = ExecutionState::new(entry);
8331 let ctx = template_context(&st, Value::Null);
8332 render_template_value(&json!(expr), &ctx, TemplateOptions::default())
8333 .expect("template renders")
8334 }
8335
8336 #[test]
8337 fn entry_root_exposes_submitted_fields_on_the_wrapped_path() {
8338 let entry = json!({
8342 "input": {
8343 "metadata": { "action": "submit", "company_size": "11-50" },
8344 "text": "hi"
8345 },
8346 "tenant": "acme",
8347 "correlation_id": "c-1"
8348 });
8349
8350 assert_eq!(
8351 render_entry(entry.clone(), "{{entry.company_size}}"),
8352 json!("11-50")
8353 );
8354 assert_eq!(
8356 render_entry(entry.clone(), "{{in.company_size}}"),
8357 json!("11-50")
8358 );
8359 assert_eq!(
8361 render_entry(entry.clone(), "{{entry.input.metadata.company_size}}"),
8362 json!("11-50")
8363 );
8364 assert_eq!(
8365 render_entry(entry.clone(), "{{in.input.metadata.company_size}}"),
8366 json!("11-50")
8367 );
8368 assert_eq!(
8370 render_entry(entry.clone(), "{{entry.tenant}}"),
8371 json!("acme")
8372 );
8373 assert_eq!(
8374 render_entry(entry.clone(), "{{entry.correlation_id}}"),
8375 json!("c-1")
8376 );
8377 assert_eq!(
8379 render_entry(entry.clone(), "{{entry.input.text}}"),
8380 json!("hi")
8381 );
8382 assert_eq!(
8383 render_entry(entry, "{{entry.input.metadata.action}}"),
8384 json!("submit")
8385 );
8386 }
8387
8388 #[test]
8389 fn entry_root_exposes_submitted_fields_on_the_demo_path() {
8390 let entry = json!({
8394 "company_size": "11-50",
8395 "metadata": { "action": "submit", "email": "a@b.c" },
8396 "text": "hi"
8397 });
8398
8399 assert_eq!(
8400 render_entry(entry.clone(), "{{entry.company_size}}"),
8401 json!("11-50")
8402 );
8403 assert_eq!(
8404 render_entry(entry.clone(), "{{entry.email}}"),
8405 json!("a@b.c")
8406 );
8407 assert_eq!(
8409 render_entry(entry.clone(), "{{entry.metadata.email}}"),
8410 json!("a@b.c")
8411 );
8412 assert_eq!(render_entry(entry, "{{entry.text}}"), json!("hi"));
8414 }
8415
8416 #[test]
8417 fn entry_merge_never_clobbers_an_existing_root_key() {
8418 let entry = json!({
8421 "input": {
8422 "metadata": { "tenant": "evil", "company_size": "11-50" }
8423 },
8424 "tenant": "acme"
8425 });
8426
8427 assert_eq!(
8428 render_entry(entry.clone(), "{{entry.tenant}}"),
8429 json!("acme")
8430 );
8431 assert_eq!(
8432 render_entry(entry.clone(), "{{entry.company_size}}"),
8433 json!("11-50")
8434 );
8435 assert_eq!(
8437 render_entry(entry, "{{entry.input.metadata.company_size}}"),
8438 json!("11-50")
8439 );
8440 }
8441
8442 #[test]
8443 fn entry_and_in_stay_identical_after_the_merge() {
8444 let entry = json!({
8445 "input": { "metadata": { "action": "submit", "email": "a@b.c" } },
8446 "tenant": "acme"
8447 });
8448 let st = ExecutionState::new(entry);
8449 let ctx = template_context(&st, Value::Null);
8450 assert_eq!(
8451 ctx.pointer("/entry"),
8452 ctx.pointer("/in"),
8453 "`in` is an alias of `entry` and must not drift from it"
8454 );
8455 }
8456
8457 #[test]
8458 fn entry_merge_leaves_a_non_object_entry_untouched() {
8459 assert_eq!(
8462 merge_submitted_fields_into_entry(json!("hi"), JsonMap::new()),
8463 json!("hi")
8464 );
8465 let mut fields = JsonMap::new();
8466 fields.insert("x".into(), json!(1));
8467 assert_eq!(
8468 merge_submitted_fields_into_entry(json!(null), fields),
8469 json!(null)
8470 );
8471 }
8472
8473 #[test]
8474 fn finalize_flattens_final_array() {
8475 let mut state = ExecutionState::new(json!({}));
8476 state.push_egress(json!({ "text": "only" }));
8477 let result = state.finalize_with(Some(json!([
8478 { "text": "extra-1" },
8479 { "text": "extra-2" }
8480 ])));
8481 assert_eq!(
8482 result,
8483 json!([
8484 { "text": "only" },
8485 { "text": "extra-1" },
8486 { "text": "extra-2" }
8487 ])
8488 );
8489 }
8490
8491 #[test]
8492 fn inject_card_locale_uses_entry_metadata_without_overwriting_payload() {
8493 let mut payload = json!({
8494 "card_source": "inline",
8495 "card_spec": { "title": "Hello" }
8496 });
8497 inject_card_locale(
8498 &mut payload,
8499 &json!({"input": {"metadata": {"locale": "nl-NL"}}}),
8500 );
8501 assert_eq!(payload["locale"], json!("nl-NL"));
8502
8503 let mut existing = json!({
8504 "card_source": "inline",
8505 "card_spec": { "title": "Hello" },
8506 "locale": "en-GB"
8507 });
8508 inject_card_locale(&mut existing, &json!({"metadata": {"locale": "nl-NL"}}));
8509 assert_eq!(existing["locale"], json!("en-GB"));
8510 }
8511
8512 #[test]
8513 fn load_i18n_bundle_entries_reads_manifest_and_falls_back_to_en() {
8514 let assets = StdHashMap::from([
8515 (
8516 "cards/i18n/_manifest.json".to_string(),
8517 br#"{"locales":["de"]}"#.to_vec(),
8518 ),
8519 (
8520 "cards/i18n/de.json".to_string(),
8521 br#"{"title":"Hallo"}"#.to_vec(),
8522 ),
8523 (
8524 "cards/i18n/en.json".to_string(),
8525 br#"{"title":"Hello"}"#.to_vec(),
8526 ),
8527 ]);
8528
8529 let entries = load_i18n_bundle_entries("cards/i18n", |path| {
8530 assets
8531 .get(path)
8532 .cloned()
8533 .with_context(|| format!("missing asset {path}"))
8534 });
8535
8536 assert_eq!(entries["de"]["title"], json!("Hallo"));
8537 assert_eq!(entries["en"]["title"], json!("Hello"));
8538 }
8539
8540 #[test]
8541 fn load_i18n_bundle_entries_reads_single_file_bundle() {
8542 let entries = load_i18n_bundle_entries("cards/i18n.json", |path| {
8543 if path == "cards/i18n.json" {
8544 Ok(br#"{"title":"Hello"}"#.to_vec())
8545 } else {
8546 bail!("unexpected asset {path}");
8547 }
8548 });
8549
8550 assert_eq!(entries["en"]["title"], json!("Hello"));
8551 }
8552
8553 struct TestCrossPackResolver;
8554
8555 impl CrossPackResolver for TestCrossPackResolver {
8556 fn invoke(
8557 &self,
8558 provider_id: &str,
8559 provider_type: Option<&str>,
8560 op: &str,
8561 input: &[u8],
8562 tenant: &str,
8563 team: Option<&str>,
8564 ) -> Result<Value> {
8565 Ok(json!({
8566 "provider_id": provider_id,
8567 "provider_type": provider_type,
8568 "op": op,
8569 "tenant": tenant,
8570 "team": team,
8571 "input": serde_json::from_slice::<Value>(input)?,
8572 }))
8573 }
8574 }
8575
8576 #[test]
8577 fn cross_pack_resolver_returns_node_output_when_present() {
8578 let mut engine = minimal_engine();
8579 engine.set_cross_pack_resolver(Arc::new(TestCrossPackResolver));
8580
8581 let output = engine
8582 .try_invoke_cross_pack_resolver(
8583 Some("mail"),
8584 Some("messaging"),
8585 "send",
8586 br#"{"subject":"hello"}"#,
8587 "demo",
8588 )
8589 .expect("resolver invocation")
8590 .expect("resolver output");
8591
8592 assert_eq!(
8593 output.payload,
8594 json!({
8595 "provider_id": "mail",
8596 "provider_type": "messaging",
8597 "op": "send",
8598 "tenant": "demo",
8599 "team": null,
8600 "input": { "subject": "hello" },
8601 })
8602 );
8603 }
8604
8605 #[test]
8606 fn flow_goto_builds_a_jump_to_the_named_flow() {
8607 let outcome = execute_flow_goto(json!({
8608 "flow_id": "support",
8609 "node": "ask_order",
8610 "input": { "order": "A-1" },
8611 }))
8612 .expect("goto builds");
8613
8614 let NodeControl::Jump(jump) = outcome.control else {
8615 panic!("flow.goto must produce a Jump, got {:?}", outcome.control);
8616 };
8617 assert_eq!(jump.flow, "support");
8618 assert_eq!(jump.node.as_deref(), Some("ask_order"));
8619 assert_eq!(jump.payload, json!({ "order": "A-1" }));
8620 assert_eq!(outcome.output.payload, json!({ "order": "A-1" }));
8623 }
8624
8625 #[test]
8628 fn flow_goto_accepts_the_flow_alias_and_defaults_the_entry_node() {
8629 let outcome = execute_flow_goto(json!({ "flow": "support" })).expect("goto builds");
8630 let NodeControl::Jump(jump) = outcome.control else {
8631 panic!("expected a Jump");
8632 };
8633 assert_eq!(jump.flow, "support");
8634 assert!(
8635 jump.node.is_none(),
8636 "no node means `apply_jump` uses the target flow's start"
8637 );
8638 assert_eq!(jump.payload, Value::Null);
8639 }
8640
8641 #[test]
8644 fn flow_goto_refuses_an_empty_flow_id() {
8645 for payload in [json!({ "flow_id": "" }), json!({ "flow_id": " " })] {
8646 let err = execute_flow_goto(payload)
8647 .err()
8648 .expect("empty target must not build");
8649 assert!(
8650 err.to_string().contains("flow_id"),
8651 "error must name the field: {err}"
8652 );
8653 }
8654 let err = execute_flow_goto(json!({ "input": {} }))
8655 .err()
8656 .expect("missing target");
8657 assert!(err.to_string().contains("flow.goto"), "got: {err}");
8658 }
8659
8660 #[test]
8664 fn flow_goto_treats_a_blank_entry_node_as_absent() {
8665 let outcome =
8666 execute_flow_goto(json!({ "flow_id": "support", "node": " " })).expect("goto builds");
8667 let NodeControl::Jump(jump) = outcome.control else {
8668 panic!("expected a Jump");
8669 };
8670 assert!(jump.node.is_none());
8671 }
8672
8673 #[test]
8676 fn flow_goto_forwards_the_redirect_ceiling_and_reason() {
8677 let outcome = execute_flow_goto(json!({
8678 "flow_id": "support",
8679 "max_redirects": 1,
8680 "reason": "menu choice",
8681 }))
8682 .expect("goto builds");
8683 let NodeControl::Jump(jump) = outcome.control else {
8684 panic!("expected a Jump");
8685 };
8686 assert_eq!(jump.max_redirects, Some(1));
8687 assert_eq!(jump.reason.as_deref(), Some("menu choice"));
8688 }
8689
8690 #[test]
8693 fn flow_goto_names_itself_as_the_reason_by_default() {
8694 let outcome = execute_flow_goto(json!({ "flow_id": "support" })).expect("goto builds");
8695 let NodeControl::Jump(jump) = outcome.control else {
8696 panic!("expected a Jump");
8697 };
8698 assert_eq!(jump.reason.as_deref(), Some("flow.goto node"));
8699 }
8700
8701 #[test]
8702 fn parse_component_control_ignores_plain_payload() {
8703 let payload = json!({
8704 "flow": "not-a-control-field",
8705 "node": "n1"
8706 });
8707 let control = parse_component_control(&payload).expect("parse control");
8708 assert!(control.is_none());
8709 }
8710
8711 #[test]
8712 fn parse_component_control_parses_jump_marker() {
8713 let payload = json!({
8714 "greentic_control": {
8715 "action": "jump",
8716 "v": 1,
8717 "flow": "flow.b",
8718 "node": "node-2",
8719 "payload": { "message": "hi" },
8720 "hints": { "k": "v" },
8721 "max_redirects": 2,
8722 "reason": "handoff"
8723 }
8724 });
8725 let control = parse_component_control(&payload)
8726 .expect("parse control")
8727 .expect("missing control");
8728 match control {
8729 NodeControl::Jump(jump) => {
8730 assert_eq!(jump.flow, "flow.b");
8731 assert_eq!(jump.node.as_deref(), Some("node-2"));
8732 assert_eq!(jump.payload, json!({ "message": "hi" }));
8733 assert_eq!(jump.hints, json!({ "k": "v" }));
8734 assert_eq!(jump.max_redirects, Some(2));
8735 assert_eq!(jump.reason.as_deref(), Some("handoff"));
8736 }
8737 other => panic!("expected jump control, got {other:?}"),
8738 }
8739 }
8740
8741 #[test]
8742 fn parse_component_control_rejects_invalid_marker() {
8743 let payload = json!({
8744 "greentic_control": "bad-shape"
8745 });
8746 let err = parse_component_control(&payload).expect_err("expected invalid marker error");
8747 assert!(err.to_string().contains("greentic_control"));
8748 }
8749
8750 #[test]
8751 fn missing_operation_reports_node_and_component() {
8752 let engine = minimal_engine();
8753 let rt = Runtime::new().unwrap();
8754 let retry_config = RetryConfig {
8755 max_attempts: 1,
8756 base_delay_ms: 1,
8757 };
8758 let ctx = FlowContext {
8759 tenant: "tenant",
8760 pack_id: "test-pack",
8761 flow_id: "flow",
8762 node_id: Some("missing-op"),
8763 tool: None,
8764 action: None,
8765 session_id: None,
8766 provider_id: None,
8767 reply_scope: None,
8768 retry_config,
8769 attempt: 1,
8770 observer: None,
8771 mocks: None,
8772 caller: None,
8773 };
8774 let node = HostNode {
8775 kind: NodeKind::Exec {
8776 target_component: "qa.process".into(),
8777 },
8778 component: "component.exec".into(),
8779 component_id: "component.exec".into(),
8780 operation_name: None,
8781 operation_in_mapping: None,
8782 payload_expr: Value::Null,
8783 routing: Routing::End,
8784 vars_out: None,
8785 response_timeout_secs: None,
8786 };
8787 let _state = ExecutionState::new(Value::Null);
8788 let payload = json!({ "component": "qa.process" });
8789 let event = NodeEvent {
8790 context: &ctx,
8791 node_id: "missing-op",
8792 node: &node,
8793 payload: &payload,
8794 };
8795 let err = rt
8796 .block_on(engine.execute_component_exec(
8797 &ctx,
8798 "missing-op",
8799 &node,
8800 payload.clone(),
8801 &event,
8802 ComponentOverrides {
8803 component: None,
8804 operation: None,
8805 },
8806 ))
8807 .unwrap_err();
8808 let message = err.to_string();
8809 assert!(
8810 message.contains("missing operation for node `missing-op`"),
8811 "unexpected message: {message}"
8812 );
8813 assert!(
8814 message.contains("(component `component.exec`)"),
8815 "unexpected message: {message}"
8816 );
8817 }
8818
8819 #[test]
8820 fn missing_operation_mentions_mapping_hint() {
8821 let engine = minimal_engine();
8822 let rt = Runtime::new().unwrap();
8823 let retry_config = RetryConfig {
8824 max_attempts: 1,
8825 base_delay_ms: 1,
8826 };
8827 let ctx = FlowContext {
8828 tenant: "tenant",
8829 pack_id: "test-pack",
8830 flow_id: "flow",
8831 node_id: Some("missing-op-hint"),
8832 tool: None,
8833 action: None,
8834 session_id: None,
8835 provider_id: None,
8836 reply_scope: None,
8837 retry_config,
8838 attempt: 1,
8839 observer: None,
8840 mocks: None,
8841 caller: None,
8842 };
8843 let node = HostNode {
8844 kind: NodeKind::Exec {
8845 target_component: "qa.process".into(),
8846 },
8847 component: "component.exec".into(),
8848 component_id: "component.exec".into(),
8849 operation_name: None,
8850 operation_in_mapping: Some("render".into()),
8851 payload_expr: Value::Null,
8852 routing: Routing::End,
8853 vars_out: None,
8854 response_timeout_secs: None,
8855 };
8856 let _state = ExecutionState::new(Value::Null);
8857 let payload = json!({ "component": "qa.process" });
8858 let event = NodeEvent {
8859 context: &ctx,
8860 node_id: "missing-op-hint",
8861 node: &node,
8862 payload: &payload,
8863 };
8864 let err = rt
8865 .block_on(engine.execute_component_exec(
8866 &ctx,
8867 "missing-op-hint",
8868 &node,
8869 payload.clone(),
8870 &event,
8871 ComponentOverrides {
8872 component: None,
8873 operation: None,
8874 },
8875 ))
8876 .unwrap_err();
8877 let message = err.to_string();
8878 assert!(
8879 message.contains("missing operation for node `missing-op-hint`"),
8880 "unexpected message: {message}"
8881 );
8882 assert!(
8883 message.contains("Found operation in input.mapping (`render`)"),
8884 "unexpected message: {message}"
8885 );
8886 }
8887
8888 struct CountingObserver {
8889 starts: Mutex<Vec<String>>,
8890 ends: Mutex<Vec<Value>>,
8891 }
8892
8893 impl CountingObserver {
8894 fn new() -> Self {
8895 Self {
8896 starts: Mutex::new(Vec::new()),
8897 ends: Mutex::new(Vec::new()),
8898 }
8899 }
8900 }
8901
8902 impl ExecutionObserver for CountingObserver {
8903 fn on_node_start(&self, event: &NodeEvent<'_>) {
8904 self.starts.lock().unwrap().push(event.node_id.to_string());
8905 }
8906
8907 fn on_node_end(&self, _event: &NodeEvent<'_>, output: &Value) {
8908 self.ends.lock().unwrap().push(output.clone());
8909 }
8910
8911 fn on_node_error(&self, _event: &NodeEvent<'_>, _error: &dyn StdError) {}
8912 }
8913
8914 #[test]
8924 fn approval_call_component_id_is_not_dot_split() {
8925 let node = Node {
8926 id: NodeId::from_str("gate").unwrap(),
8927 component: FlowComponentRef {
8928 id: "approval.call".parse().unwrap(),
8929 pack_alias: None,
8930 operation: None,
8931 },
8932 input: InputMapping {
8933 mapping: json!({ "await": true, "input": { "mode": "always" } }),
8934 },
8935 output: OutputMapping {
8936 mapping: Value::Null,
8937 },
8938 err_map: None,
8939 routing: Routing::End,
8940 telemetry: TelemetryHints::default(),
8941 conversational: false,
8942 };
8943 let host_node = HostNode::from(node);
8944 assert_eq!(
8945 host_node.component_id(),
8946 "approval.call",
8947 "approval.call must stay intact; splitting it yields 'approval', which \
8948 is never a key in the pack's component map"
8949 );
8950 assert_eq!(
8951 host_node.operation_name(),
8952 None,
8953 "the id is already complete — lowering must not invent an operation"
8954 );
8955 }
8956
8957 #[test]
8967 fn approval_call_with_no_operation_dispatches_as_approval_call() {
8968 let node = Node {
8969 id: NodeId::from_str("gate").unwrap(),
8970 component: FlowComponentRef {
8971 id: "approval.call".parse().unwrap(),
8972 pack_alias: None,
8973 operation: None,
8974 },
8975 input: InputMapping {
8976 mapping: json!({ "await": true, "input": { "mode": "always" } }),
8977 },
8978 output: OutputMapping {
8979 mapping: Value::Null,
8980 },
8981 err_map: None,
8982 routing: Routing::End,
8983 telemetry: TelemetryHints::default(),
8984 conversational: false,
8985 };
8986 let host_node = HostNode::from(node);
8987 assert!(
8988 matches!(&host_node.kind, NodeKind::ApprovalCall { target } if target.is_empty()),
8989 "expected NodeKind::ApprovalCall with an empty target, got {:?}",
8990 host_node.kind
8991 );
8992 }
8993
8994 #[test]
8995 fn emits_end_event_for_successful_node() {
8996 let node_id = NodeId::from_str("emit").unwrap();
8997 let node = Node {
8998 id: node_id.clone(),
8999 component: FlowComponentRef {
9000 id: "emit.log".parse().unwrap(),
9001 pack_alias: None,
9002 operation: None,
9003 },
9004 input: InputMapping {
9005 mapping: json!({ "message": "logged" }),
9006 },
9007 output: OutputMapping {
9008 mapping: Value::Null,
9009 },
9010 err_map: None,
9011 routing: Routing::End,
9012 telemetry: TelemetryHints::default(),
9013 conversational: false,
9014 };
9015 let mut nodes = indexmap::IndexMap::default();
9016 nodes.insert(node_id.clone(), node);
9017 let flow = Flow {
9018 schema_version: "1.0".into(),
9019 id: FlowId::from_str("emit.flow").unwrap(),
9020 kind: FlowKind::Messaging,
9021 entrypoints: BTreeMap::from([(
9022 "default".to_string(),
9023 Value::String(node_id.to_string()),
9024 )]),
9025 nodes,
9026 metadata: Default::default(),
9027 };
9028 let host_flow = HostFlow::from(flow);
9029
9030 let engine = FlowEngine {
9031 packs: Vec::new(),
9032 flows: Vec::new(),
9033 flow_sources: HashMap::new(),
9034 messaging_provider_pack_ids: std::collections::HashSet::new(),
9035 flow_cache: RwLock::new(HashMap::from([(
9036 FlowKey {
9037 pack_id: "test-pack".to_string(),
9038 flow_id: "emit.flow".to_string(),
9039 },
9040 host_flow,
9041 )])),
9042 default_env: "local".to_string(),
9043 validation: ValidationConfig {
9044 mode: ValidationMode::Off,
9045 },
9046 cross_pack_resolver: None,
9047 rollout_ids: RolloutIds::default(),
9048 approval_dispatch_handler: None,
9049 remote_dispatch_handler: None,
9050 #[cfg(feature = "agentic-worker")]
9051 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9052 #[cfg(feature = "agentic-worker")]
9053 agent_node_handler: None,
9054 #[cfg(feature = "agentic-worker")]
9055 graph_node_handler: None,
9056 #[cfg(feature = "agentic-worker")]
9057 mcp_tool_source: None,
9058 #[cfg(feature = "agentic-worker")]
9059 mcp_secrets: None,
9060 #[cfg(feature = "agentic-worker")]
9061 a2a_sources: RwLock::new(HashMap::new()),
9062 #[cfg(feature = "agentic-worker")]
9063 ext_artifact_port: None,
9064 operala_node_handler: None,
9065 };
9066 let observer = CountingObserver::new();
9067 let ctx = FlowContext {
9068 tenant: "demo",
9069 pack_id: "test-pack",
9070 flow_id: "emit.flow",
9071 node_id: None,
9072 tool: None,
9073 action: None,
9074 session_id: None,
9075 provider_id: None,
9076 reply_scope: None,
9077 retry_config: RetryConfig {
9078 max_attempts: 1,
9079 base_delay_ms: 1,
9080 },
9081 attempt: 1,
9082 observer: Some(&observer),
9083 mocks: None,
9084 caller: None,
9085 };
9086
9087 let rt = Runtime::new().unwrap();
9088 let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
9089 assert!(matches!(result.status, FlowStatus::Completed));
9090
9091 assert!(
9095 !result.node_outputs.is_empty(),
9096 "completed flow must expose its per-node outputs"
9097 );
9098 assert!(
9099 result
9100 .node_outputs
9101 .values()
9102 .any(|v| v.to_string().contains("logged")),
9103 "node_outputs must carry the executed node's payload: {:?}",
9104 result.node_outputs
9105 );
9106
9107 let starts = observer.starts.lock().unwrap();
9108 let ends = observer.ends.lock().unwrap();
9109 assert_eq!(starts.len(), 1);
9110 assert_eq!(ends.len(), 1);
9111 assert_eq!(ends[0], json!({ "message": "logged" }));
9112 }
9113
9114 #[test]
9115 fn dotted_component_id_with_mapping_operation_is_not_split() {
9116 let node = Node {
9122 conversational: false,
9123 id: NodeId::from_str("render").unwrap(),
9124 component: FlowComponentRef {
9125 id: "ai.greentic.component-templates".parse().unwrap(),
9126 pack_alias: None,
9127 operation: None,
9128 },
9129 input: InputMapping {
9130 mapping: json!({ "operation": "handle_message", "input": "hi" }),
9131 },
9132 output: OutputMapping {
9133 mapping: Value::Null,
9134 },
9135 err_map: None,
9136 routing: Routing::End,
9137 telemetry: TelemetryHints::default(),
9138 };
9139 let host = HostNode::from(node);
9140 assert!(
9141 matches!(&host.kind, NodeKind::PackComponent { component_ref } if component_ref == "ai.greentic.component-templates"),
9142 "dotted component id must stay intact, got kind {:?}",
9143 host.kind
9144 );
9145 assert_eq!(host.component, "ai.greentic.component-templates");
9146 assert_eq!(host.operation_in_mapping(), Some("handle_message"));
9147 }
9148
9149 #[test]
9150 fn packed_component_operation_id_still_splits_without_mapping_operation() {
9151 let node = Node {
9155 conversational: false,
9156 id: NodeId::from_str("render").unwrap(),
9157 component: FlowComponentRef {
9158 id: "templating.handlebars".parse().unwrap(),
9159 pack_alias: None,
9160 operation: None,
9161 },
9162 input: InputMapping {
9163 mapping: json!({ "text": "hello" }),
9164 },
9165 output: OutputMapping {
9166 mapping: Value::Null,
9167 },
9168 err_map: None,
9169 routing: Routing::End,
9170 telemetry: TelemetryHints::default(),
9171 };
9172 let host = HostNode::from(node);
9173 assert!(
9174 matches!(&host.kind, NodeKind::PackComponent { component_ref } if component_ref == "templating"),
9175 "packed <component>.<operation> id must split, got kind {:?}",
9176 host.kind
9177 );
9178 assert_eq!(host.operation_name(), Some("handlebars"));
9179 }
9180
9181 #[cfg(feature = "agentic-worker")]
9182 #[test]
9191 fn the_agent_node_receives_the_context_caller_not_a_payload_one() {
9192 use crate::runner::agent_node::AgentNodeHandler;
9193 use std::sync::Mutex;
9194
9195 struct Recorder(Arc<Mutex<Option<Value>>>);
9197
9198 #[async_trait::async_trait]
9199 impl AgentNodeHandler for Recorder {
9200 async fn execute(
9201 &self,
9202 _tenant_id: &str,
9203 _env_id: &str,
9204 _agent_id: &str,
9205 _session_id: &str,
9206 _flow_input: &Value,
9207 _conversational: bool,
9208 caller: Option<&Value>,
9209 ) -> anyhow::Result<Value> {
9210 *self.0.lock().unwrap() = caller.cloned();
9211 Ok(json!({ "reply": "ok", "trail": [], "terminated_by": "done" }))
9212 }
9213 }
9214
9215 let seen = Arc::new(Mutex::new(None));
9216 let handler: Arc<dyn AgentNodeHandler> = Arc::new(Recorder(Arc::clone(&seen)));
9217
9218 let node_id = NodeId::from_str("agent").unwrap();
9219 let node = Node {
9220 id: node_id.clone(),
9221 component: FlowComponentRef {
9222 id: "dw.agent".parse().unwrap(),
9223 pack_alias: None,
9224 operation: Some("greeter".to_string()),
9225 },
9226 input: InputMapping {
9228 mapping: json!({
9229 "user_text": "ping",
9230 "caller": { "user_verified": true, "sub": "forged@evil" }
9231 }),
9232 },
9233 output: OutputMapping {
9234 mapping: Value::Null,
9235 },
9236 err_map: None,
9237 routing: Routing::End,
9238 telemetry: TelemetryHints::default(),
9239 conversational: false,
9240 };
9241 let mut nodes = indexmap::IndexMap::default();
9242 nodes.insert(node_id.clone(), node);
9243 let flow = Flow {
9244 schema_version: "1.0".into(),
9245 id: FlowId::from_str("dw.flow").unwrap(),
9246 kind: FlowKind::Messaging,
9247 entrypoints: BTreeMap::from([(
9248 "default".to_string(),
9249 Value::String(node_id.to_string()),
9250 )]),
9251 nodes,
9252 metadata: Default::default(),
9253 };
9254
9255 let engine = FlowEngine {
9256 packs: Vec::new(),
9257 flows: Vec::new(),
9258 flow_sources: HashMap::new(),
9259 messaging_provider_pack_ids: std::collections::HashSet::new(),
9260 flow_cache: RwLock::new(HashMap::from([(
9261 FlowKey {
9262 pack_id: "test-pack".to_string(),
9263 flow_id: "dw.flow".to_string(),
9264 },
9265 HostFlow::from(flow),
9266 )])),
9267 default_env: "local".to_string(),
9268 validation: ValidationConfig {
9269 mode: ValidationMode::Off,
9270 },
9271 cross_pack_resolver: None,
9272 rollout_ids: RolloutIds::default(),
9273 approval_dispatch_handler: None,
9274 remote_dispatch_handler: None,
9275 #[cfg(feature = "agentic-worker")]
9276 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9277 #[cfg(feature = "agentic-worker")]
9278 agent_node_handler: Some(handler),
9279 #[cfg(feature = "agentic-worker")]
9280 graph_node_handler: None,
9281 #[cfg(feature = "agentic-worker")]
9282 mcp_tool_source: None,
9283 #[cfg(feature = "agentic-worker")]
9284 mcp_secrets: None,
9285 #[cfg(feature = "agentic-worker")]
9286 a2a_sources: RwLock::new(HashMap::new()),
9287 #[cfg(feature = "agentic-worker")]
9288 ext_artifact_port: None,
9289 operala_node_handler: None,
9290 };
9291
9292 let trusted = json!({ "user_verified": true, "sub": "u-1@acme" });
9293 let ctx = FlowContext {
9294 tenant: "demo",
9295 pack_id: "test-pack",
9296 flow_id: "dw.flow",
9297 node_id: None,
9298 tool: None,
9299 action: None,
9300 session_id: Some("sess-1"),
9301 provider_id: None,
9302 reply_scope: None,
9303 retry_config: RetryConfig {
9304 max_attempts: 1,
9305 base_delay_ms: 1,
9306 },
9307 attempt: 1,
9308 observer: None,
9309 mocks: None,
9310 caller: Some(&trusted),
9311 };
9312
9313 let rt = Runtime::new().unwrap();
9314 rt.block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
9315 .unwrap();
9316
9317 let got = seen.lock().unwrap().clone().expect("handler saw a caller");
9318 assert_eq!(
9319 got["sub"], "u-1@acme",
9320 "the context caller must win over the payload one"
9321 );
9322 assert_ne!(got["sub"], "forged@evil");
9323 }
9324
9325 #[cfg(feature = "agentic-worker")]
9326 #[test]
9327 fn dw_agent_node_routes_to_handler_and_returns_reply() {
9328 use crate::runner::agent_node::{AgentNodeHandler, RuntimeAgentNodeHandler};
9329 use greentic_aw_runtime::cost::MockTokenMeter;
9330 use greentic_aw_runtime::llm::LlmResponse;
9331 use greentic_aw_runtime::mock::{
9332 MockAgentStateStore, MockConfigProvider, MockLlmBackend, MockTelemetry, NoopToolLedger,
9333 };
9334 use greentic_aw_runtime::{
9335 AgentConfig, AgentLimits, AgentRuntime, LlmProviderRef, TenantContext,
9336 };
9337
9338 let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
9340 content: Some("pong".into()),
9341 tool_calls: vec![],
9342 tokens_in: 1,
9343 tokens_out: 1,
9344 })]));
9345 let store = Arc::new(MockAgentStateStore::new());
9346 let telemetry = Arc::new(MockTelemetry::new());
9347
9348 let config_provider = MockConfigProvider::new();
9353 let tenant = TenantContext::new("demo", "local");
9354 config_provider.insert(
9355 &tenant,
9356 "greeter",
9357 AgentConfig {
9358 agent_id: "greeter".into(),
9359 system_prompt: "sys".into(),
9360 tools: vec![],
9361 guardrails: vec![],
9362 llm: LlmProviderRef {
9363 provider: "mock".into(),
9364 model: "m".into(),
9365 credential_ref: None,
9366 },
9367 limits: AgentLimits::default(),
9368 memory: None,
9369 knowledge: None,
9370 conversational: false,
9371 opening_message: None,
9372 on_text_while_parked: Default::default(),
9373 },
9374 );
9375 let config_provider = Arc::new(config_provider);
9376 let token_meter = Arc::new(MockTokenMeter::new(0));
9377 let ledger = Arc::new(NoopToolLedger);
9378 let ext_runtime = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
9379 let runtime = Arc::new(AgentRuntime::new(
9380 config_provider,
9381 store,
9382 ext_runtime,
9383 llm,
9384 telemetry,
9385 token_meter,
9386 ledger,
9387 None,
9388 ));
9389 let handler: Arc<dyn AgentNodeHandler> =
9390 Arc::new(RuntimeAgentNodeHandler::new(runtime, None, None, None));
9391
9392 let node_id = NodeId::from_str("agent").unwrap();
9394 let node = Node {
9395 id: node_id.clone(),
9396 component: FlowComponentRef {
9397 id: "dw.agent".parse().unwrap(),
9398 pack_alias: None,
9399 operation: Some("greeter".to_string()),
9400 },
9401 input: InputMapping {
9402 mapping: json!({ "user_text": "ping" }),
9403 },
9404 output: OutputMapping {
9405 mapping: Value::Null,
9406 },
9407 err_map: None,
9408 routing: Routing::End,
9409 telemetry: TelemetryHints::default(),
9410 conversational: false,
9411 };
9412 let mut nodes = indexmap::IndexMap::default();
9413 nodes.insert(node_id.clone(), node);
9414 let flow = Flow {
9415 schema_version: "1.0".into(),
9416 id: FlowId::from_str("dw.flow").unwrap(),
9417 kind: FlowKind::Messaging,
9418 entrypoints: BTreeMap::from([(
9419 "default".to_string(),
9420 Value::String(node_id.to_string()),
9421 )]),
9422 nodes,
9423 metadata: Default::default(),
9424 };
9425 let host_flow = HostFlow::from(flow);
9426
9427 let engine = FlowEngine {
9428 packs: Vec::new(),
9429 flows: Vec::new(),
9430 flow_sources: HashMap::new(),
9431 messaging_provider_pack_ids: std::collections::HashSet::new(),
9432 flow_cache: RwLock::new(HashMap::from([(
9433 FlowKey {
9434 pack_id: "test-pack".to_string(),
9435 flow_id: "dw.flow".to_string(),
9436 },
9437 host_flow,
9438 )])),
9439 default_env: "local".to_string(),
9440 validation: ValidationConfig {
9441 mode: ValidationMode::Off,
9442 },
9443 cross_pack_resolver: None,
9444 rollout_ids: RolloutIds::default(),
9445 approval_dispatch_handler: None,
9446 remote_dispatch_handler: None,
9447 #[cfg(feature = "agentic-worker")]
9448 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9449 #[cfg(feature = "agentic-worker")]
9450 agent_node_handler: Some(handler),
9451 #[cfg(feature = "agentic-worker")]
9452 graph_node_handler: None,
9453 #[cfg(feature = "agentic-worker")]
9454 mcp_tool_source: None,
9455 #[cfg(feature = "agentic-worker")]
9456 mcp_secrets: None,
9457 #[cfg(feature = "agentic-worker")]
9458 a2a_sources: RwLock::new(HashMap::new()),
9459 #[cfg(feature = "agentic-worker")]
9460 ext_artifact_port: None,
9461 operala_node_handler: None,
9462 };
9463 let ctx = FlowContext {
9464 tenant: "demo",
9465 pack_id: "test-pack",
9466 flow_id: "dw.flow",
9467 node_id: None,
9468 tool: None,
9469 action: None,
9470 session_id: Some("sess-1"),
9471 provider_id: None,
9472 reply_scope: None,
9473 retry_config: RetryConfig {
9474 max_attempts: 1,
9475 base_delay_ms: 1,
9476 },
9477 attempt: 1,
9478 observer: None,
9479 mocks: None,
9480 caller: None,
9481 };
9482
9483 let rt = Runtime::new().unwrap();
9484 let result = rt
9485 .block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
9486 .unwrap();
9487 assert!(matches!(result.status, FlowStatus::Completed));
9488
9489 let output_str = serde_json::to_string(&result.output).unwrap();
9492 assert!(
9493 output_str.contains("pong"),
9494 "expected agent reply in flow output, got: {output_str}"
9495 );
9496 }
9497
9498 #[cfg(feature = "agentic-worker")]
9504 #[test]
9505 fn dw_agent_graph_node_routes_to_handler_and_returns_reply() {
9506 use std::sync::Mutex;
9507
9508 use crate::runner::graph_node::GraphNodeHandler;
9509
9510 struct RecordingGraphHandler {
9512 seen: Mutex<Option<(String, String, String, String)>>,
9513 }
9514
9515 #[async_trait::async_trait]
9516 impl GraphNodeHandler for RecordingGraphHandler {
9517 async fn execute(
9518 &self,
9519 tenant_id: &str,
9520 env_id: &str,
9521 graph_id: &str,
9522 session_id: &str,
9523 _flow_input: &Value,
9524 ) -> Result<Value> {
9525 *self.seen.lock().unwrap() = Some((
9526 tenant_id.to_string(),
9527 env_id.to_string(),
9528 graph_id.to_string(),
9529 session_id.to_string(),
9530 ));
9531 Ok(json!({
9532 "reply": "graph-pong",
9533 "trail": [],
9534 "terminated_by": "respond",
9535 }))
9536 }
9537 }
9538
9539 let handler = Arc::new(RecordingGraphHandler {
9540 seen: Mutex::new(None),
9541 });
9542 let handler_dyn: Arc<dyn GraphNodeHandler> = handler.clone();
9543
9544 let node_id = NodeId::from_str("graph").unwrap();
9546 let node = Node {
9547 id: node_id.clone(),
9548 component: FlowComponentRef {
9549 id: "dw.agent_graph".parse().unwrap(),
9550 pack_alias: None,
9551 operation: Some("triage".to_string()),
9552 },
9553 input: InputMapping {
9554 mapping: json!({ "user_text": "ping" }),
9555 },
9556 output: OutputMapping {
9557 mapping: Value::Null,
9558 },
9559 err_map: None,
9560 routing: Routing::End,
9561 telemetry: TelemetryHints::default(),
9562 conversational: false,
9563 };
9564 let mut nodes = indexmap::IndexMap::default();
9565 nodes.insert(node_id.clone(), node);
9566 let flow = Flow {
9567 schema_version: "1.0".into(),
9568 id: FlowId::from_str("dwg.flow").unwrap(),
9569 kind: FlowKind::Messaging,
9570 entrypoints: BTreeMap::from([(
9571 "default".to_string(),
9572 Value::String(node_id.to_string()),
9573 )]),
9574 nodes,
9575 metadata: Default::default(),
9576 };
9577 let host_flow = HostFlow::from(flow);
9578
9579 let engine = FlowEngine {
9580 packs: Vec::new(),
9581 flows: Vec::new(),
9582 flow_sources: HashMap::new(),
9583 messaging_provider_pack_ids: std::collections::HashSet::new(),
9584 flow_cache: RwLock::new(HashMap::from([(
9585 FlowKey {
9586 pack_id: "test-pack".to_string(),
9587 flow_id: "dwg.flow".to_string(),
9588 },
9589 host_flow,
9590 )])),
9591 default_env: "local".to_string(),
9592 validation: ValidationConfig {
9593 mode: ValidationMode::Off,
9594 },
9595 cross_pack_resolver: None,
9596 rollout_ids: RolloutIds::default(),
9597 approval_dispatch_handler: None,
9598 remote_dispatch_handler: None,
9599 #[cfg(feature = "agentic-worker")]
9600 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9601 #[cfg(feature = "agentic-worker")]
9602 agent_node_handler: None,
9603 #[cfg(feature = "agentic-worker")]
9604 graph_node_handler: Some(handler_dyn),
9605 #[cfg(feature = "agentic-worker")]
9606 mcp_tool_source: None,
9607 #[cfg(feature = "agentic-worker")]
9608 mcp_secrets: None,
9609 #[cfg(feature = "agentic-worker")]
9610 a2a_sources: RwLock::new(HashMap::new()),
9611 #[cfg(feature = "agentic-worker")]
9612 ext_artifact_port: None,
9613 operala_node_handler: None,
9614 };
9615 let ctx = FlowContext {
9616 tenant: "demo",
9617 pack_id: "test-pack",
9618 flow_id: "dwg.flow",
9619 node_id: None,
9620 tool: None,
9621 action: None,
9622 session_id: Some("sess-1"),
9623 provider_id: None,
9624 reply_scope: None,
9625 retry_config: RetryConfig {
9626 max_attempts: 1,
9627 base_delay_ms: 1,
9628 },
9629 attempt: 1,
9630 observer: None,
9631 mocks: None,
9632 caller: None,
9633 };
9634
9635 let rt = Runtime::new().unwrap();
9636 let result = rt
9637 .block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
9638 .unwrap();
9639 assert!(matches!(result.status, FlowStatus::Completed));
9640
9641 let seen = handler.seen.lock().unwrap().clone();
9644 assert_eq!(
9645 seen,
9646 Some((
9647 "demo".to_string(),
9648 "local".to_string(),
9649 "triage".to_string(),
9650 "sess-1".to_string(),
9651 )),
9652 "dw.agent_graph dispatch must mirror dw.agent's tenant/env/graph_id/session derivation"
9653 );
9654
9655 let output_str = serde_json::to_string(&result.output).unwrap();
9656 assert!(
9657 output_str.contains("graph-pong"),
9658 "expected graph reply in flow output, got: {output_str}"
9659 );
9660 }
9661
9662 #[cfg(feature = "agentic-worker")]
9668 #[test]
9669 fn dw_agent_nats_mode_dispatches_remote() {
9670 use std::sync::Mutex;
9671
9672 use crate::runner::agent_node::DwAgentDispatch;
9673 use crate::runner::remote_dispatch::{
9674 RemoteDispatch, RemoteDispatchAction, RemoteDispatchHandler,
9675 };
9676
9677 struct RecordingDispatcher {
9680 seen: Mutex<Option<RemoteDispatch>>,
9681 }
9682
9683 #[async_trait::async_trait]
9684 impl RemoteDispatchHandler for RecordingDispatcher {
9685 async fn dispatch(
9686 &self,
9687 request: RemoteDispatch,
9688 ) -> anyhow::Result<RemoteDispatchAction> {
9689 let corr = request.correlation_id.clone();
9690 *self.seen.lock().unwrap() = Some(request);
9691 Ok(RemoteDispatchAction::AwaitingResponse {
9692 correlation_id: corr,
9693 })
9694 }
9695 }
9696
9697 let dispatcher = Arc::new(RecordingDispatcher {
9698 seen: Mutex::new(None),
9699 });
9700
9701 let resume_id = NodeId::from_str("after-agent").unwrap();
9706 let node_id = NodeId::from_str("agent-nats").unwrap();
9707 let agent_node = Node {
9708 id: node_id.clone(),
9709 component: FlowComponentRef {
9710 id: "dw.agent".parse().unwrap(),
9711 pack_alias: None,
9712 operation: Some("greeter".to_string()),
9713 },
9714 input: InputMapping {
9715 mapping: json!({ "user_text": "hi" }),
9716 },
9717 output: OutputMapping {
9718 mapping: Value::Null,
9719 },
9720 err_map: None,
9721 routing: Routing::Next {
9722 node_id: resume_id.clone(),
9723 },
9724 telemetry: TelemetryHints::default(),
9725 conversational: false,
9726 };
9727 let resume_node = Node {
9728 id: resume_id.clone(),
9729 component: FlowComponentRef {
9730 id: "emit.log".parse().unwrap(),
9731 pack_alias: None,
9732 operation: None,
9733 },
9734 input: InputMapping {
9735 mapping: json!({ "message": "done" }),
9736 },
9737 output: OutputMapping {
9738 mapping: Value::Null,
9739 },
9740 err_map: None,
9741 routing: Routing::End,
9742 telemetry: TelemetryHints::default(),
9743 conversational: false,
9744 };
9745 let mut nodes = indexmap::IndexMap::default();
9746 nodes.insert(node_id.clone(), agent_node);
9747 nodes.insert(resume_id.clone(), resume_node);
9748 let flow = Flow {
9749 schema_version: "1.0".into(),
9750 id: FlowId::from_str("nats-agent.flow").unwrap(),
9751 kind: FlowKind::Messaging,
9752 entrypoints: BTreeMap::from([(
9753 "default".to_string(),
9754 Value::String(node_id.to_string()),
9755 )]),
9756 nodes,
9757 metadata: Default::default(),
9758 };
9759 let host_flow = HostFlow::from(flow);
9760
9761 let engine = FlowEngine {
9762 packs: Vec::new(),
9763 flows: Vec::new(),
9764 flow_sources: HashMap::new(),
9765 messaging_provider_pack_ids: std::collections::HashSet::new(),
9766 flow_cache: RwLock::new(HashMap::from([(
9767 FlowKey {
9768 pack_id: "test-pack".to_string(),
9769 flow_id: "nats-agent.flow".to_string(),
9770 },
9771 host_flow,
9772 )])),
9773 default_env: "local".to_string(),
9774 validation: ValidationConfig {
9775 mode: ValidationMode::Off,
9776 },
9777 cross_pack_resolver: None,
9778 rollout_ids: RolloutIds::default(),
9779 approval_dispatch_handler: None,
9780 remote_dispatch_handler: Some(dispatcher.clone() as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>),
9781 #[cfg(feature = "agentic-worker")]
9782 dw_agent_dispatch: DwAgentDispatch::Nats,
9783 #[cfg(feature = "agentic-worker")]
9784 agent_node_handler: None,
9786 #[cfg(feature = "agentic-worker")]
9787 graph_node_handler: None,
9788 #[cfg(feature = "agentic-worker")]
9789 mcp_tool_source: None,
9790 #[cfg(feature = "agentic-worker")]
9791 mcp_secrets: None,
9792 #[cfg(feature = "agentic-worker")]
9793 a2a_sources: RwLock::new(HashMap::new()),
9794 #[cfg(feature = "agentic-worker")]
9795 ext_artifact_port: None,
9796 operala_node_handler: None,
9797 };
9798
9799 let ctx = FlowContext {
9800 tenant: "demo",
9801 pack_id: "test-pack",
9802 flow_id: "nats-agent.flow",
9803 node_id: None,
9804 tool: None,
9805 action: None,
9806 session_id: Some("sess-nats"),
9807 provider_id: None,
9808 reply_scope: None,
9809 retry_config: RetryConfig {
9810 max_attempts: 1,
9811 base_delay_ms: 1,
9812 },
9813 attempt: 1,
9814 observer: None,
9815 mocks: None,
9816 caller: None,
9817 };
9818
9819 let rt = Runtime::new().unwrap();
9820 let result = rt
9821 .block_on(engine.execute(ctx, json!({ "user_text": "hi" })))
9822 .unwrap();
9823
9824 assert!(
9826 matches!(result.status, FlowStatus::Waiting(_)),
9827 "expected Waiting outcome from dw.agent Nats mode, got: {:?}",
9828 result.status
9829 );
9830
9831 let seen = dispatcher.seen.lock().unwrap();
9834 let dispatch = seen.as_ref().expect("dispatcher was not called");
9835 assert_eq!(
9836 dispatch.runtime, "agentic",
9837 "runtime name must be 'agentic'"
9838 );
9839 assert_eq!(dispatch.target, "greeter", "target must be the agent_id");
9840 assert_eq!(
9841 dispatch.input,
9842 json!({ "user_text": "hi" }),
9843 "node payload must be forwarded as dispatch input"
9844 );
9845 }
9846
9847 fn host_flow_for_test(
9848 flow_id: &str,
9849 node_ids: &[&str],
9850 default_start: Option<&str>,
9851 ) -> HostFlow {
9852 let mut nodes = indexmap::IndexMap::default();
9853 for node_id in node_ids {
9854 let id = NodeId::from_str(node_id).unwrap();
9855 let node = Node {
9856 id: id.clone(),
9857 component: FlowComponentRef {
9858 id: "emit.log".parse().unwrap(),
9859 pack_alias: None,
9860 operation: None,
9861 },
9862 input: InputMapping {
9863 mapping: json!({ "message": node_id }),
9864 },
9865 output: OutputMapping {
9866 mapping: Value::Null,
9867 },
9868 err_map: None,
9869 routing: Routing::End,
9870 telemetry: TelemetryHints::default(),
9871 conversational: false,
9872 };
9873 nodes.insert(id, node);
9874 }
9875 let mut entrypoints = BTreeMap::new();
9876 if let Some(start) = default_start {
9877 entrypoints.insert("default".to_string(), Value::String(start.to_string()));
9878 }
9879 HostFlow::from(Flow {
9880 schema_version: "1.0".into(),
9881 id: FlowId::from_str(flow_id).unwrap(),
9882 kind: FlowKind::Messaging,
9883 entrypoints,
9884 nodes,
9885 metadata: Default::default(),
9886 })
9887 }
9888
9889 fn jump_test_engine() -> FlowEngine {
9890 let target_flow = host_flow_for_test("flow.target", &["node-a", "node-b"], None);
9891 FlowEngine {
9892 packs: Vec::new(),
9893 flows: Vec::new(),
9894 flow_sources: HashMap::new(),
9895 messaging_provider_pack_ids: std::collections::HashSet::new(),
9896 flow_cache: RwLock::new(HashMap::from([(
9897 FlowKey {
9898 pack_id: "test-pack".to_string(),
9899 flow_id: "flow.target".to_string(),
9900 },
9901 target_flow,
9902 )])),
9903 default_env: "local".to_string(),
9904 validation: ValidationConfig {
9905 mode: ValidationMode::Off,
9906 },
9907 cross_pack_resolver: None,
9908 rollout_ids: RolloutIds::default(),
9909 approval_dispatch_handler: None,
9910 remote_dispatch_handler: None,
9911 #[cfg(feature = "agentic-worker")]
9912 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9913 #[cfg(feature = "agentic-worker")]
9914 agent_node_handler: None,
9915 #[cfg(feature = "agentic-worker")]
9916 graph_node_handler: None,
9917 #[cfg(feature = "agentic-worker")]
9918 mcp_tool_source: None,
9919 #[cfg(feature = "agentic-worker")]
9920 mcp_secrets: None,
9921 #[cfg(feature = "agentic-worker")]
9922 a2a_sources: RwLock::new(HashMap::new()),
9923 #[cfg(feature = "agentic-worker")]
9924 ext_artifact_port: None,
9925 operala_node_handler: None,
9926 }
9927 }
9928
9929 fn jump_ctx<'a>(flow_id: &'a str) -> FlowContext<'a> {
9930 FlowContext {
9931 tenant: "demo",
9932 pack_id: "test-pack",
9933 flow_id,
9934 node_id: None,
9935 tool: None,
9936 action: None,
9937 session_id: None,
9938 provider_id: None,
9939 reply_scope: None,
9940 retry_config: RetryConfig {
9941 max_attempts: 1,
9942 base_delay_ms: 1,
9943 },
9944 attempt: 1,
9945 observer: None,
9946 mocks: None,
9947 caller: None,
9948 }
9949 }
9950
9951 #[test]
9954 fn component_exec_ctx_presents_the_verified_caller() {
9955 let block = json!({
9956 "user_verified": true,
9957 "sub": "u-1@acme",
9958 "team": "sales",
9959 "groups": ["employee"]
9960 });
9961 let mut ctx = jump_ctx("caller.flow");
9962 ctx.provider_id = Some("messaging-webchat");
9963 ctx.caller = Some(&block);
9964
9965 let exec = component_exec_ctx(&ctx, "lookup");
9966 let caller = component_caller(&ctx);
9967 let v05 = crate::component_api::exec_ctx_v0_5_as(&exec, caller.as_ref());
9968 assert_eq!(v05.tenant.user_id.as_deref(), Some("u-1@acme"));
9969 assert_eq!(v05.tenant.team_id.as_deref(), Some("sales"));
9970 let v06 =
9971 crate::component_api::envelope_v0_6_as(&exec, caller.as_ref(), "c", "{}").unwrap();
9972 assert_eq!(v06.ctx.user_id.as_deref(), Some("u-1@acme"));
9973 assert_eq!(v06.ctx.team_id.as_deref(), Some("sales"));
9974 assert_eq!(exec.tenant.user.as_deref(), Some("messaging-webchat"));
9977 assert_eq!(exec.tenant.team, None);
9978 }
9979
9980 #[test]
9987 fn component_exec_ctx_without_a_verified_caller_presents_no_user() {
9988 let unverified = json!({ "user_verified": false, "sub": "u-1", "team": "sales" });
9989 for provider in ["messaging-webchat", "greentic-run-demo"] {
9990 for caller in [None, Some(&unverified)] {
9991 let mut ctx = jump_ctx("caller.flow");
9992 ctx.provider_id = Some(provider);
9993 ctx.caller = caller;
9994 let exec = component_exec_ctx(&ctx, "lookup");
9995 let caller = component_caller(&ctx);
9996 assert!(caller.is_none());
9997
9998 let v05 = crate::component_api::exec_ctx_v0_5_for(
9999 &exec,
10000 caller.as_ref(),
10001 ctx.provider_id,
10002 );
10003 assert_eq!(v05.tenant.user_id, None);
10004 assert_eq!(v05.tenant.user, None);
10005 assert_eq!(v05.tenant.provider_id.as_deref(), Some(provider));
10006 assert_eq!(v05.tenant.team_id, None);
10007 assert!(v05.tenant.attributes.is_empty());
10008
10009 let v04 = crate::component_api::exec_ctx_v0_4_for(
10010 &exec,
10011 caller.as_ref(),
10012 ctx.provider_id,
10013 );
10014 assert_eq!(v04.tenant.user, None);
10015
10016 let v06 = crate::component_api::envelope_v0_6_for(
10017 &exec,
10018 caller.as_ref(),
10019 ctx.provider_id,
10020 "c",
10021 "{}",
10022 )
10023 .unwrap();
10024 assert_eq!(v06.ctx.user_id, None);
10025
10026 assert_eq!(exec.tenant.user.as_deref(), Some(provider));
10030 assert_eq!(exec.tenant.team, None);
10031 }
10032 }
10033 }
10034
10035 #[test]
10038 fn component_exec_ctx_with_a_verified_caller_also_names_the_provider() {
10039 let block = json!({ "user_verified": true, "sub": "u-1@acme" });
10040 let mut ctx = jump_ctx("caller.flow");
10041 ctx.provider_id = Some("messaging-webchat");
10042 ctx.caller = Some(&block);
10043 let exec = component_exec_ctx(&ctx, "lookup");
10044 let caller = component_caller(&ctx);
10045 let v05 = crate::component_api::exec_ctx_v0_5_for(&exec, caller.as_ref(), ctx.provider_id);
10046 assert_eq!(v05.tenant.user_id.as_deref(), Some("u-1@acme"));
10047 assert_eq!(v05.tenant.provider_id.as_deref(), Some("messaging-webchat"));
10048 assert_eq!(exec.tenant.user.as_deref(), Some("messaging-webchat"));
10049 }
10050
10051 #[test]
10052 fn with_rollout_ids_binds_revision_identity() {
10053 let engine = minimal_engine().with_rollout_ids(RolloutIds {
10054 customer_id: Some("cust-acme".into()),
10055 deployment_id: Some("01JTKS".into()),
10056 bundle_id: Some("customer.support".into()),
10057 revision_id: Some("01JTKR".into()),
10058 });
10059 assert_eq!(engine.rollout_ids.revision_id.as_deref(), Some("01JTKR"));
10060 assert_eq!(engine.rollout_ids.deployment_id.as_deref(), Some("01JTKS"));
10061 assert!(minimal_engine().rollout_ids.is_empty());
10063 }
10064
10065 #[cfg(feature = "agentic-worker")]
10069 #[test]
10070 fn mcp_credential_unit_is_the_revisions_bundle_id() {
10071 let engine = minimal_engine().with_rollout_ids(RolloutIds {
10072 customer_id: None,
10073 deployment_id: Some("01JTKS".into()),
10074 bundle_id: Some("customer.support".into()),
10075 revision_id: Some("01JTKR".into()),
10076 });
10077 assert_eq!(engine.mcp_credential_unit(), Some("customer.support"));
10078 assert_eq!(minimal_engine().mcp_credential_unit(), None);
10079 }
10080
10081 #[test]
10090 fn a_flow_goto_node_produces_a_jump_the_engine_applies() {
10091 let outcome = execute_flow_goto(json!({
10092 "flow_id": "flow.target",
10093 "input": { "order": "A-1" },
10094 }))
10095 .expect("goto builds");
10096 let NodeControl::Jump(jump) = outcome.control else {
10097 panic!("expected a Jump");
10098 };
10099
10100 let engine = jump_test_engine();
10101 let mut state = ExecutionState::new(Value::Null);
10102 let rt = Runtime::new().unwrap();
10103 let target = rt
10104 .block_on(engine.apply_jump(&jump_ctx("flow.source"), &mut state, jump))
10105 .expect("the engine must accept the jump a flow.goto node builds");
10106
10107 assert_eq!(target.flow_id, "flow.target");
10108 assert_eq!(
10109 target.node_id.as_str(),
10110 "node-a",
10111 "no explicit node means the target flow's first node"
10112 );
10113 assert_eq!(
10114 state.redirect_count(),
10115 1,
10116 "the loop guard must have counted"
10117 );
10118 }
10119
10120 #[test]
10123 fn a_flow_goto_node_can_name_the_entry_node() {
10124 let outcome = execute_flow_goto(json!({ "flow_id": "flow.target", "node": "node-b" }))
10125 .expect("goto builds");
10126 let NodeControl::Jump(jump) = outcome.control else {
10127 panic!("expected a Jump");
10128 };
10129
10130 let engine = jump_test_engine();
10131 let mut state = ExecutionState::new(Value::Null);
10132 let rt = Runtime::new().unwrap();
10133 let target = rt
10134 .block_on(engine.apply_jump(&jump_ctx("flow.source"), &mut state, jump))
10135 .expect("jump applies");
10136 assert_eq!(target.node_id.as_str(), "node-b");
10137 }
10138
10139 #[test]
10140 fn apply_jump_unknown_flow_errors() {
10141 let engine = minimal_engine();
10142 let mut state = ExecutionState::new(Value::Null);
10143 let rt = Runtime::new().unwrap();
10144 let err = rt
10145 .block_on(engine.apply_jump(
10146 &jump_ctx("flow.source"),
10147 &mut state,
10148 JumpControl {
10149 flow: "flow.missing".into(),
10150 node: None,
10151 payload: json!({ "ok": true }),
10152 hints: Value::Null,
10153 max_redirects: None,
10154 reason: None,
10155 },
10156 ))
10157 .unwrap_err();
10158 assert!(
10159 err.to_string().contains("unknown_flow"),
10160 "unexpected error: {err}"
10161 );
10162 }
10163
10164 #[test]
10165 fn deterministic_jump_failures_are_terminal_not_retried() {
10166 let rt = Runtime::new().unwrap();
10167 let jump = |flow: &str, node: Option<&str>| JumpControl {
10168 flow: flow.into(),
10169 node: node.map(str::to_string),
10170 payload: json!({ "ok": true }),
10171 hints: Value::Null,
10172 max_redirects: None,
10173 reason: None,
10174 };
10175
10176 let engine = minimal_engine();
10178 let mut state = ExecutionState::new(Value::Null);
10179 let err = rt
10180 .block_on(engine.apply_jump(
10181 &jump_ctx("flow.source"),
10182 &mut state,
10183 jump("flow.missing", None),
10184 ))
10185 .unwrap_err();
10186 assert!(err.to_string().contains("unknown_flow"), "{err}");
10187 assert!(
10188 is_terminal_flow_error(&err),
10189 "unknown_flow must be terminal"
10190 );
10191 assert!(!should_retry(&err));
10192
10193 let engine = jump_test_engine();
10196 for node in ["node-missing", "not a valid id!"] {
10197 let mut state = ExecutionState::new(Value::Null);
10198 let err = rt
10199 .block_on(engine.apply_jump(
10200 &jump_ctx("flow.source"),
10201 &mut state,
10202 jump("flow.target", Some(node)),
10203 ))
10204 .unwrap_err();
10205 assert!(err.to_string().contains("unknown_node"), "{err}");
10206 assert!(is_terminal_flow_error(&err), "unknown_node {node:?}");
10207 }
10208
10209 let empty = host_flow_for_test("flow.empty", &[], None);
10211 engine.flow_cache.write().insert(
10212 FlowKey {
10213 pack_id: "test-pack".to_string(),
10214 flow_id: "flow.empty".to_string(),
10215 },
10216 empty,
10217 );
10218 let mut state = ExecutionState::new(Value::Null);
10219 let err = rt
10220 .block_on(engine.apply_jump(
10221 &jump_ctx("flow.source"),
10222 &mut state,
10223 jump("flow.empty", None),
10224 ))
10225 .unwrap_err();
10226 assert!(err.to_string().contains("no start node"), "{err}");
10227 assert!(is_terminal_flow_error(&err));
10228 }
10229
10230 #[test]
10231 fn external_effect_classification_is_narrow_and_explicit() {
10232 assert!(NodeKind::SorlaCall { target: "t".into() }.performs_external_effect());
10233 assert!(NodeKind::AgenticCall { target: "t".into() }.performs_external_effect());
10234 assert!(NodeKind::ApprovalCall { target: "t".into() }.performs_external_effect());
10235 assert!(NodeKind::MediaCreate.performs_external_effect());
10236 assert!(NodeKind::FlowCall.performs_external_effect());
10237 assert!(
10238 !NodeKind::BuiltinEmit {
10239 kind: EmitKind::Response
10240 }
10241 .performs_external_effect()
10242 );
10243 assert!(!NodeKind::BuiltinStateGet.performs_external_effect());
10244 assert!(!NodeKind::Wait.performs_external_effect());
10245 }
10246
10247 #[test]
10248 fn terminal_after_effects_only_changes_failures_that_follow_an_effect() {
10249 let transient = || anyhow!("internal timeout: unavailable");
10250 let before = terminal_after_effects(transient(), false);
10252 assert!(!is_terminal_flow_error(&before));
10253 assert!(should_retry(&before));
10254 let after = terminal_after_effects(transient(), true);
10256 assert!(is_terminal_flow_error(&after));
10257 assert!(!should_retry(&after));
10258 assert_eq!(after.to_string(), "internal timeout: unavailable");
10259 let chained = anyhow::Error::new(TransientFlowError(
10263 "connect to https://internal.example:8443/x refused".into(),
10264 ))
10265 .context("sorla.call failed");
10266 let rebuilt = terminal_after_effects(chained, true);
10267 assert!(is_terminal_flow_error(&rebuilt));
10268 assert_eq!(rebuilt.to_string(), "sorla.call failed");
10270 assert_eq!(
10272 format!("{rebuilt:#}"),
10273 "sorla.call failed: connect to https://internal.example:8443/x refused"
10274 );
10275 assert_eq!(
10276 crate::run_outcome::error::anyhow_chain_text(&rebuilt),
10277 "sorla.call failed\ncaused by: connect to https://internal.example:8443/x refused"
10278 );
10279 assert!(!should_retry(&rebuilt));
10282 fn assert_send_sync<T: Send + Sync + 'static>(_: &T) {}
10283 assert_send_sync(&TerminalFlowError {
10284 message: String::new(),
10285 original: None,
10286 after_effects: false,
10287 });
10288 }
10289
10290 #[test]
10291 fn only_a_failure_that_followed_an_effect_carries_the_after_effects_marker() {
10292 let deterministic = terminal_flow_error("flow x has no node `y`");
10294 assert!(is_terminal_flow_error(&deterministic));
10295 assert!(!is_after_effects_failure(&deterministic));
10296 let untouched = terminal_after_effects(deterministic, false);
10298 assert!(!is_after_effects_failure(&untouched));
10299 let marked = terminal_after_effects(anyhow!("internal timeout"), true);
10301 assert!(is_after_effects_failure(&marked));
10302 assert_eq!(marked.to_string(), "internal timeout");
10303 let upgraded = terminal_after_effects(terminal_flow_error("step limit"), true);
10305 assert!(is_after_effects_failure(&upgraded));
10306 assert_eq!(upgraded.to_string(), "step limit");
10307 assert!(is_after_effects_failure(&upgraded.context("outer")));
10309 assert!(is_after_effects_failure(&pre_effect(marked)));
10310 assert!(!is_after_effects_failure(&anyhow!("plain")));
10311 }
10312
10313 #[test]
10314 fn pre_effect_marker_keeps_message_and_inner_classification() {
10315 let marked = pre_effect(
10316 anyhow::Error::new(TransientFlowError("429 slow down".into())).context("llm call"),
10317 );
10318 assert!(is_pre_effect_error(&marked));
10319 assert_eq!(marked.to_string(), "llm call");
10320 assert!(should_retry(&marked));
10322 let with_ctx = marked.context("outer");
10323 assert!(is_pre_effect_error(&with_ctx));
10324 assert!(should_retry(&with_ctx));
10325 assert!(is_terminal_flow_error(&pre_effect(terminal_flow_error(
10327 "x"
10328 ))));
10329 assert!(!is_pre_effect_error(&anyhow!("plain")));
10331 }
10332
10333 type DispatchStep = fn() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction>;
10334
10335 struct ScriptedDispatch {
10337 calls: std::sync::atomic::AtomicUsize,
10338 script: Vec<DispatchStep>,
10339 }
10340
10341 #[async_trait::async_trait]
10342 impl crate::runner::remote_dispatch::RemoteDispatchHandler for ScriptedDispatch {
10343 async fn dispatch(
10344 &self,
10345 _request: crate::runner::remote_dispatch::RemoteDispatch,
10346 ) -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10347 let n = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
10348 (self.script[n.min(self.script.len() - 1)])()
10349 }
10350 }
10351
10352 fn dispatched() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10353 Ok(crate::runner::remote_dispatch::RemoteDispatchAction::Dispatched)
10354 }
10355 fn transient_pre_effect() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10356 Err(pre_effect(
10357 anyhow::Error::new(TransientFlowError("broker 503".into())).context("publish"),
10358 ))
10359 }
10360 fn transient_unproven() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10361 Err(anyhow::Error::new(TransientFlowError("broker 503".into())).context("publish"))
10362 }
10363
10364 fn drive_dispatch_chain(
10367 handler: Option<Vec<DispatchStep>>,
10368 nodes: usize,
10369 ) -> (anyhow::Error, usize) {
10370 let mut engine = jump_test_engine();
10371 let scripted = handler.map(|script| {
10372 Arc::new(ScriptedDispatch {
10373 calls: std::sync::atomic::AtomicUsize::new(0),
10374 script,
10375 })
10376 });
10377 engine.remote_dispatch_handler = scripted
10378 .clone()
10379 .map(|h| h as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>);
10380 let ids: Vec<String> = (0..nodes).map(|i| format!("n{i}")).collect();
10381 let specs: Vec<(&str, &str, Value)> = ids
10382 .iter()
10383 .map(|id| (id.as_str(), "agentic.call", json!({ "await": false })))
10384 .collect();
10385 let flow = chain_flow("chain.flow", &specs);
10386 let rt = Runtime::new().unwrap();
10387 let ctx = jump_ctx("chain.flow");
10388 let failure = match rt.block_on(engine.drive_flow(
10389 &ctx,
10390 flow,
10391 ExecutionState::new(Value::Null),
10392 None,
10393 "chain.flow".to_string(),
10394 )) {
10395 Ok(_) => panic!("the chain must fail"),
10396 Err(failure) => failure,
10397 };
10398 let count = scripted
10399 .map(|h| h.calls.load(std::sync::atomic::Ordering::SeqCst))
10400 .unwrap_or(0);
10401 (failure.error, count)
10402 }
10403
10404 #[test]
10405 fn effect_node_failing_before_any_effect_is_retried() {
10406 let (err, calls) = drive_dispatch_chain(Some(vec![transient_pre_effect]), 1);
10407 assert_eq!(calls, 1);
10408 assert!(!is_terminal_flow_error(&err), "{err:#}");
10409 assert!(should_retry(&err), "{err:#}");
10410 }
10411
10412 #[test]
10413 fn effect_node_with_no_handler_is_a_pre_effect_config_error_that_is_not_retried() {
10414 let (err, _) = drive_dispatch_chain(None, 1);
10420 assert!(
10421 err.to_string().contains("no RemoteDispatchHandler"),
10422 "{err}"
10423 );
10424 assert!(is_pre_effect_error(&err), "{err:#}");
10425 assert!(!is_terminal_flow_error(&err), "{err:#}");
10426 assert!(!should_retry(&err), "{err:#}");
10427 }
10428
10429 fn drive_single_failing_node(component: &str, input: Value) -> anyhow::Error {
10432 let engine = jump_test_engine();
10433 let flow = chain_flow("chain.flow", &[("n0", component, input)]);
10434 let rt = Runtime::new().unwrap();
10435 let ctx = jump_ctx("chain.flow");
10436 match rt.block_on(engine.drive_flow(
10437 &ctx,
10438 flow,
10439 ExecutionState::new(Value::Null),
10440 None,
10441 "chain.flow".to_string(),
10442 )) {
10443 Ok(_) => panic!("the node must fail"),
10444 Err(failure) => failure.error,
10445 }
10446 }
10447
10448 #[test]
10449 fn provider_invoke_failures_before_the_call_are_pre_effect() {
10450 for input in [
10453 json!({"op": 5}),
10454 json!({}),
10455 json!({"op": "send", "input": {"a": 1}}),
10456 ] {
10457 let err = drive_single_failing_node("provider.invoke", input.clone());
10458 assert!(is_pre_effect_error(&err), "{input}: {err:#}");
10459 }
10460 }
10461
10462 #[cfg(feature = "agentic-worker")]
10463 #[test]
10464 fn a2a_without_a_registered_pack_fails_pre_effect() {
10465 let err = drive_single_failing_node("a2a", json!({"agent": "x", "message": "hi"}));
10466 assert!(is_pre_effect_error(&err), "{err:#}");
10467 }
10468
10469 #[test]
10470 fn effect_node_failure_that_is_not_proven_pre_effect_is_terminal() {
10471 let (err, calls) = drive_dispatch_chain(Some(vec![transient_unproven]), 1);
10472 assert_eq!(calls, 1);
10473 assert!(is_terminal_flow_error(&err), "{err:#}");
10474 assert!(!should_retry(&err));
10475 }
10476
10477 #[test]
10478 fn failure_after_a_completed_effect_is_terminal_even_if_pre_effect_for_its_node() {
10479 let (err, calls) = drive_dispatch_chain(Some(vec![dispatched, transient_pre_effect]), 2);
10483 assert_eq!(calls, 2);
10484 assert!(is_terminal_flow_error(&err), "{err:#}");
10485 assert!(!should_retry(&err));
10486 }
10487
10488 #[test]
10489 fn failed_effect_nodes_may_have_partial_effects_except_flow_call() {
10490 assert!(NodeKind::MediaCreate.may_have_partial_effect_on_failure());
10491 assert!(NodeKind::SorlaCall { target: "t".into() }.may_have_partial_effect_on_failure());
10492 assert!(!NodeKind::FlowCall.may_have_partial_effect_on_failure());
10493 assert!(!NodeKind::BuiltinStateGet.may_have_partial_effect_on_failure());
10494 assert!(!NodeKind::Wait.may_have_partial_effect_on_failure());
10495 }
10496
10497 fn chain_flow(flow_id: &str, nodes: &[(&str, &str, Value)]) -> HostFlow {
10498 let mut map = indexmap::IndexMap::default();
10499 for (index, (node_id, component, input)) in nodes.iter().enumerate() {
10500 let id = NodeId::from_str(node_id).unwrap();
10501 let routing = match nodes.get(index + 1) {
10502 Some((next, _, _)) => Routing::Next {
10503 node_id: NodeId::from_str(next).unwrap(),
10504 },
10505 None => Routing::End,
10506 };
10507 map.insert(
10508 id.clone(),
10509 Node {
10510 id,
10511 component: FlowComponentRef {
10512 id: component.parse().unwrap(),
10513 pack_alias: None,
10514 operation: None,
10515 },
10516 input: InputMapping {
10517 mapping: input.clone(),
10518 },
10519 output: OutputMapping {
10520 mapping: Value::Null,
10521 },
10522 err_map: None,
10523 routing,
10524 telemetry: TelemetryHints::default(),
10525 conversational: false,
10526 },
10527 );
10528 }
10529 HostFlow::from(Flow {
10530 schema_version: "1.0".into(),
10531 id: FlowId::from_str(flow_id).unwrap(),
10532 kind: FlowKind::Messaging,
10533 entrypoints: BTreeMap::from([(
10534 "default".to_string(),
10535 Value::String(nodes[0].0.to_string()),
10536 )]),
10537 nodes: map,
10538 metadata: Default::default(),
10539 })
10540 }
10541
10542 fn drive_chain_failure(first_component: &str, first_input: Value) -> anyhow::Error {
10545 let engine = jump_test_engine();
10546 let flow = chain_flow(
10547 "chain.flow",
10548 &[
10549 ("first", first_component, first_input),
10550 ("boom", "flow.call", json!({})),
10551 ],
10552 );
10553 let rt = Runtime::new().unwrap();
10554 let ctx = jump_ctx("chain.flow");
10555 let failure = match rt.block_on(engine.drive_flow(
10556 &ctx,
10557 flow,
10558 ExecutionState::new(Value::Null),
10559 None,
10560 "chain.flow".to_string(),
10561 )) {
10562 Ok(_) => panic!("the flow.call node must fail"),
10563 Err(failure) => failure,
10564 };
10565 failure.error
10566 }
10567
10568 #[test]
10569 fn a_failure_after_an_effectful_node_is_terminal() {
10570 let err = drive_chain_failure("flow.call", json!({ "flow": "flow.target" }));
10572 assert!(
10573 err.to_string().contains("flow.call"),
10574 "original message kept: {err}"
10575 );
10576 assert!(is_terminal_flow_error(&err), "must not be re-run: {err:#}");
10577 }
10578
10579 #[test]
10580 fn a_failure_after_a_pure_node_stays_retryable() {
10581 let err = drive_chain_failure("emit.log", json!({ "message": "hi" }));
10582 assert!(
10583 !is_terminal_flow_error(&err),
10584 "no effect happened, the turn may be re-run: {err:#}"
10585 );
10586 }
10587
10588 #[test]
10589 fn invalid_greentic_control_is_terminal() {
10590 for payload in [
10591 json!({ "greentic_control": "bad-shape" }),
10592 json!({ "greentic_control": { "v": 1 } }),
10593 json!({ "greentic_control": { "action": "jump", "v": 2 } }),
10594 json!({ "greentic_control": { "action": "jump", "v": 1 } }),
10595 ] {
10596 let err = parse_component_control(&payload).expect_err("invalid control");
10597 assert!(
10598 err.to_string().contains("jump_failed")
10599 || err.to_string().contains("greentic_control")
10600 );
10601 assert!(is_terminal_flow_error(&err), "{payload}");
10602 assert!(!should_retry(&err));
10603 }
10604 }
10605
10606 #[test]
10607 fn apply_jump_unknown_node_errors() {
10608 let engine = jump_test_engine();
10609 let mut state = ExecutionState::new(Value::Null);
10610 let rt = Runtime::new().unwrap();
10611 let err = rt
10612 .block_on(engine.apply_jump(
10613 &jump_ctx("flow.source"),
10614 &mut state,
10615 JumpControl {
10616 flow: "flow.target".into(),
10617 node: Some("node-missing".into()),
10618 payload: json!({ "ok": true }),
10619 hints: Value::Null,
10620 max_redirects: None,
10621 reason: None,
10622 },
10623 ))
10624 .unwrap_err();
10625 assert!(
10626 err.to_string().contains("unknown_node"),
10627 "unexpected error: {err}"
10628 );
10629 }
10630
10631 #[test]
10632 fn apply_jump_uses_default_start_fallback() {
10633 let engine = jump_test_engine();
10634 let mut state = ExecutionState::new(Value::Null);
10635 let rt = Runtime::new().unwrap();
10636 let target = rt
10637 .block_on(engine.apply_jump(
10638 &jump_ctx("flow.source"),
10639 &mut state,
10640 JumpControl {
10641 flow: "flow.target".into(),
10642 node: None,
10643 payload: json!({ "k": "v" }),
10644 hints: Value::Null,
10645 max_redirects: None,
10646 reason: None,
10647 },
10648 ))
10649 .expect("jump target");
10650 assert_eq!(target.flow_id, "flow.target");
10651 assert_eq!(target.node_id.as_str(), "node-a");
10652 }
10653
10654 #[test]
10655 fn condition_values_containing_another_operator_split_at_the_real_one() {
10656 let ctx = json!({ "x": "5", "msg": { "text": "a>=b" }, "n": 7 });
10657 assert!(evaluate_simple_condition(r#"msg.text == "a>=b""#, &ctx));
10658 assert!(!evaluate_simple_condition(r#"msg.text != "a>=b""#, &ctx));
10659 assert!(evaluate_simple_condition(r#"n > "3""#, &ctx));
10661 assert!(!evaluate_simple_condition(r#"n > "a==b""#, &ctx));
10662 assert!(evaluate_simple_condition(r#"x >= 5"#, &ctx));
10663 assert!(evaluate_simple_condition(r#"msg.text contains "=b""#, &ctx));
10664 assert!(!evaluate_simple_condition("no operator here", &ctx));
10665 }
10666
10667 #[test]
10668 fn step_budget_trips_only_past_the_cap() {
10669 assert!(check_step_budget(MAX_STEPS_PER_TURN, "f").is_ok());
10670 let err = check_step_budget(MAX_STEPS_PER_TURN + 1, "f").unwrap_err();
10671 assert!(err.to_string().contains("flow_step_limit_exceeded"));
10672 assert!(!should_retry(&err));
10673 assert!(is_terminal_flow_error(&err));
10674 }
10675
10676 #[test]
10677 fn terminal_marker_overrides_transient_sounding_text() {
10678 let err = terminal_flow_error("internal timeout: unavailable");
10679 assert!(!should_retry(&err));
10680 assert!(!should_retry(&err.context("node failed")));
10681 assert!(should_retry(&anyhow!("internal server error")));
10682 }
10683
10684 #[test]
10685 fn redirect_count_resets_for_a_resumed_turn() {
10686 let mut state = ExecutionState::new(Value::Null);
10687 state.increment_redirect_count();
10688 state.increment_redirect_count();
10689 assert_eq!(state.redirect_count(), 2);
10690 state.reset_redirect_count();
10691 assert_eq!(state.redirect_count(), 0);
10692 }
10693
10694 #[test]
10695 fn apply_jump_redirect_limit_enforced() {
10696 let engine = jump_test_engine();
10697 let mut state = ExecutionState::new(Value::Null);
10698 state.redirect_count = 3;
10699 let rt = Runtime::new().unwrap();
10700 let err = rt
10701 .block_on(engine.apply_jump(
10702 &jump_ctx("flow.source"),
10703 &mut state,
10704 JumpControl {
10705 flow: "flow.target".into(),
10706 node: None,
10707 payload: json!({ "k": "v" }),
10708 hints: Value::Null,
10709 max_redirects: Some(3),
10710 reason: None,
10711 },
10712 ))
10713 .unwrap_err();
10714 assert_eq!(err.to_string(), "redirect_limit");
10715 }
10716
10717 #[test]
10718 fn park_turns_bump_and_reset() {
10719 let mut state = ExecutionState::new(Value::Null);
10720 assert_eq!(state.bump_park_turns("a"), 1);
10721 assert_eq!(state.bump_park_turns("a"), 2);
10722 assert_eq!(state.bump_park_turns("b"), 1);
10724 assert_eq!(state.bump_park_turns("a"), 3);
10725
10726 state.reset_park_turns("a");
10727 assert_eq!(
10728 state.bump_park_turns("a"),
10729 1,
10730 "reset must restart from zero"
10731 );
10732 assert_eq!(
10733 state.bump_park_turns("b"),
10734 2,
10735 "resetting `a` must not disturb `b`'s counter"
10736 );
10737 }
10738
10739 #[test]
10740 fn park_turns_survives_snapshot_roundtrip() {
10741 let mut state = ExecutionState::new(json!({}));
10745 state.bump_park_turns("agent-1");
10746 state.bump_park_turns("agent-1");
10747
10748 let encoded = serde_json::to_string(&state).expect("serialize");
10749 let decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
10750 assert_eq!(decoded.park_turns.get("agent-1"), Some(&2));
10751
10752 let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
10755 let decoded_legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
10756 assert!(decoded_legacy.park_turns.is_empty());
10757 }
10758
10759 #[test]
10760 fn pending_agent_await_mark_and_take() {
10761 let mut st = ExecutionState::new(serde_json::json!({}));
10762 assert!(!st.take_agent_await("agent"), "unmarked node takes false");
10763 st.mark_agent_await("agent");
10764 assert!(st.take_agent_await("agent"), "marked node takes true");
10765 assert!(!st.take_agent_await("agent"), "take clears the marker");
10766 st.mark_agent_await("a");
10768 st.mark_agent_await("b");
10769 assert!(st.take_agent_await("a"));
10770 assert!(st.take_agent_await("b"));
10771 }
10772
10773 #[test]
10774 fn pending_agent_await_survives_snapshot_roundtrip() {
10775 let mut st = ExecutionState::new(serde_json::json!({}));
10776 st.mark_agent_await("agent");
10777 let json = serde_json::to_string(&st).expect("serialize");
10778 let back: ExecutionState = serde_json::from_str(&json).expect("deserialize");
10779 let mut back = back;
10780 assert!(
10781 back.take_agent_await("agent"),
10782 "marker survives serde round-trip"
10783 );
10784 let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0,"vars":{},"park_turns":{}}"#;
10786 let mut legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy decode");
10787 assert!(!legacy.take_agent_await("agent"), "absent key → empty");
10788 }
10789
10790 #[test]
10791 fn approval_await_mark_and_take() {
10792 let mut st = ExecutionState::new(json!({}));
10793 assert!(
10794 st.take_approval_await("gate").is_none(),
10795 "unmarked node takes None"
10796 );
10797 st.mark_approval_await("gate", parked("corr::n=abc", Some("fp")));
10798 assert_eq!(
10799 st.take_approval_await("gate"),
10800 Some(parked("corr::n=abc", Some("fp"))),
10801 "marked node takes its recorded correlation and fingerprint"
10802 );
10803 assert!(
10804 st.take_approval_await("gate").is_none(),
10805 "take clears the mark"
10806 );
10807 }
10808
10809 #[test]
10810 fn approval_await_survives_snapshot_roundtrip() {
10811 let mut st = ExecutionState::new(json!({}));
10812 st.mark_approval_await("gate", parked("corr::n=abc", Some("fp")));
10813 let encoded = serde_json::to_string(&st).expect("serialize");
10814 assert!(
10815 !encoded.contains("decision_token"),
10816 "only the fingerprint is persisted"
10817 );
10818 let mut decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
10819 assert_eq!(
10820 decoded.pending_approvals(),
10821 vec![parked("corr::n=abc", Some("fp"))]
10822 );
10823 assert_eq!(
10824 decoded.take_approval_await("gate"),
10825 Some(parked("corr::n=abc", Some("fp"))),
10826 "the marker, correlation and fingerprint must survive a park/resume snapshot"
10827 );
10828 }
10829
10830 #[test]
10831 fn approval_await_defaults_empty_for_old_snapshots() {
10832 let mut decoded: ExecutionState =
10834 serde_json::from_str(r#"{"entry":{},"input":{}}"#).expect("old snapshot decodes");
10835 assert!(decoded.take_approval_await("gate").is_none());
10836 }
10837
10838 #[test]
10839 fn approval_await_decodes_the_pre_correlation_unit_marker() {
10840 let mut decoded: ExecutionState = serde_json::from_str(
10844 r#"{"entry":{},"input":{},"pending_approval_await":{"gate":null}}"#,
10845 )
10846 .expect("pre-correlation snapshot decodes");
10847 assert_eq!(decoded.pending_approvals(), vec![ParkedApproval::default()]);
10848 assert_eq!(
10849 decoded.take_approval_await("gate"),
10850 Some(ParkedApproval::default())
10851 );
10852 }
10853
10854 fn parked(correlation: &str, fingerprint: Option<&str>) -> ParkedApproval {
10855 ParkedApproval {
10856 correlation_id: Some(correlation.to_string()),
10857 token_fingerprint: fingerprint.map(str::to_string),
10858 }
10859 }
10860
10861 #[test]
10862 fn a_snapshot_parked_before_tokens_has_no_fingerprint_and_is_not_verified() {
10863 let decoded: ExecutionState = serde_json::from_str(
10865 r#"{"entry":{},"input":{},"pending_approval_await":{"gate":"corr::n=abc"}}"#,
10866 )
10867 .expect("pre-token snapshot decodes");
10868 let parks = decoded.pending_approvals();
10869 assert_eq!(parks, vec![parked("corr::n=abc", None)]);
10870 assert!(response_authenticates(
10871 &json!({"ok": true, "output": {"decision": "approved"}}),
10872 &parks[0]
10873 ));
10874 }
10875
10876 #[test]
10877 fn a_tokened_gate_resumes_only_on_its_own_token_and_only_once() {
10878 let issued = approval_token::issue();
10879 let mut st = ExecutionState::new(json!({}));
10880 st.mark_approval_await("gate", parked("corr", Some(&issued.fingerprint)));
10881 let right =
10882 json!({"ok": true, "output": {"decision": "approved", "decision_token": issued.token}});
10883 let wrong = json!({"ok": true, "output": {"decision": "approved", "decision_token": approval_token::issue().token}});
10884 let missing = json!({"ok": true, "output": {"decision": "approved"}});
10885
10886 let park = st.take_approval_await("gate").expect("parked");
10887 assert!(!response_authenticates(&missing, &park));
10888 assert!(!response_authenticates(&wrong, &park));
10889 assert!(response_authenticates(&right, &park));
10890 assert!(st.take_approval_await("gate").is_none());
10892 assert!(st.pending_approvals().is_empty());
10893 }
10894
10895 #[test]
10896 fn dispatch_outcome_await_here_stores_variant() {
10897 let output = NodeOutput::new(json!({"ok": true}));
10902 let outcome = DispatchOutcome::await_here(
10903 output,
10904 Some("awaiting agent response".to_string()),
10905 "corr-123".to_string(),
10906 );
10907 match outcome.control {
10908 NodeControl::AwaitHere {
10909 reason,
10910 correlation_id,
10911 } => {
10912 assert_eq!(reason.as_deref(), Some("awaiting agent response"));
10913 assert_eq!(correlation_id, "corr-123");
10914 }
10915 other => panic!("expected NodeControl::AwaitHere, got {other:?}"),
10916 }
10917 }
10918
10919 fn on_message_routing() -> Value {
10922 json!([
10923 { "condition": "response.action == \"go_a\"", "to": "page_a" },
10924 { "to": "fallback", "on_message": true },
10925 { "out": true }
10926 ])
10927 }
10928
10929 fn empty_flow() -> HostFlow {
10930 HostFlow {
10931 id: "flow.test".to_string(),
10932 start: None,
10933 nodes: IndexMap::new(),
10934 vars_init: JsonMap::new(),
10935 required_vars: Vec::new(),
10936 slot_schema: None,
10937 }
10938 }
10939
10940 fn route_with(resumed_at: Option<&str>, entry: Value) -> CustomRoutingDecision {
10941 let mut state = ExecutionState::new(entry.clone());
10942 state.entry = entry;
10943 state.resumed_at = resumed_at.map(str::to_string);
10944 evaluate_custom_routing(
10945 &on_message_routing(),
10946 &NodeOutput::new(Value::Null),
10947 &state,
10948 &empty_flow(),
10949 &NodeId::from_str("menu").unwrap(),
10950 )
10951 }
10952
10953 #[test]
10954 fn an_on_message_route_does_not_fire_when_the_card_was_just_rendered() {
10955 let decision = route_with(None, json!({ "text": "hello" }));
10957 assert!(
10958 matches!(decision, CustomRoutingDecision::Wait),
10959 "a freshly rendered card must park, got {decision:?}"
10960 );
10961 }
10962
10963 #[test]
10964 fn an_on_message_route_is_taken_when_the_person_types_at_the_parked_card() {
10965 let decision = route_with(Some("menu"), json!({ "text": "2+2 berapa?" }));
10966 match decision {
10967 CustomRoutingDecision::Next(n) => assert_eq!(n.as_str(), "fallback"),
10968 other => panic!("expected fallback, got {other:?}"),
10969 }
10970 }
10971
10972 #[test]
10973 fn a_button_still_wins_over_the_on_message_route() {
10974 let entry = json!({ "text": "", "metadata": { "action": "go_a" } });
10975 match route_with(Some("menu"), entry) {
10976 CustomRoutingDecision::Next(n) => assert_eq!(n.as_str(), "page_a"),
10977 other => panic!("expected page_a, got {other:?}"),
10978 }
10979 }
10980
10981 #[test]
10982 fn an_unknown_action_reparks_instead_of_taking_the_on_message_route() {
10983 let entry = json!({ "text": "", "metadata": { "action": "stale_button" } });
10984 let decision = route_with(Some("menu"), entry);
10985 assert!(
10986 matches!(decision, CustomRoutingDecision::Wait),
10987 "a click that matches nothing is not a typed message, got {decision:?}"
10988 );
10989 }
10990
10991 #[test]
10992 fn a_resume_at_another_node_does_not_take_the_route() {
10993 let decision = route_with(Some("some_other_card"), json!({ "text": "hi" }));
10994 assert!(matches!(decision, CustomRoutingDecision::Wait));
10995 }
10996
10997 #[test]
10998 fn only_a_card_awaiting_its_submit_counts_as_a_resumed_card() {
10999 let mut snapshot = FlowSnapshot {
11000 pack_id: "p".into(),
11001 flow_id: "f".into(),
11002 next_flow: None,
11003 next_node: "menu".into(),
11004 awaiting_submit: true,
11005 state: ExecutionState::new(Value::Null),
11006 };
11007 assert_eq!(resumed_card_node(&snapshot).as_deref(), Some("menu"));
11008 snapshot.awaiting_submit = false;
11010 assert_eq!(resumed_card_node(&snapshot), None);
11011 }
11012
11013 #[test]
11020 fn evaluate_custom_routing_waits_when_conditional_falls_through() {
11021 let raw_routing = json!([
11022 { "condition": "response.action == \"go\"", "to": "next" },
11023 { "out": true }
11024 ]);
11025 let flow_ir = HostFlow {
11026 id: "flow.test".to_string(),
11027 start: None,
11028 nodes: IndexMap::new(),
11029 vars_init: JsonMap::new(),
11030 required_vars: Vec::new(),
11031 slot_schema: None,
11032 };
11033 let current_node = NodeId::from_str("current").unwrap();
11034 let output = NodeOutput::new(Value::Null);
11035
11036 let mut state_empty = ExecutionState::new(json!({ "metadata": { "action": "" } }));
11038 state_empty.entry = json!({ "metadata": { "action": "" } });
11039 let decision_empty =
11040 evaluate_custom_routing(&raw_routing, &output, &state_empty, &flow_ir, ¤t_node);
11041 assert!(
11042 matches!(decision_empty, CustomRoutingDecision::Wait),
11043 "expected Wait on conditional fall-through, got {decision_empty:?}"
11044 );
11045
11046 let mut state_go = ExecutionState::new(json!({ "metadata": { "action": "go" } }));
11048 state_go.entry = json!({ "metadata": { "action": "go" } });
11049 let decision_go =
11050 evaluate_custom_routing(&raw_routing, &output, &state_go, &flow_ir, ¤t_node);
11051 match decision_go {
11052 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
11053 other => panic!("expected Next(\"next\"), got {other:?}"),
11054 }
11055 }
11056
11057 #[test]
11058 fn node_output_with_error_marks_ok_false_and_stashes_in_meta() {
11059 let err: Box<dyn std::error::Error + 'static> =
11060 Box::<dyn std::error::Error + 'static>::from("weatherapi returned 401 Unauthorized");
11061 let out = NodeOutput::with_error("call_weather", err.as_ref());
11062 assert!(!out.ok);
11063 assert_eq!(out.payload, Value::Null);
11064 assert_eq!(out.meta["error"]["kind"], "flow_node_failed");
11065 assert_eq!(out.meta["error"]["node_id"], "call_weather");
11066 assert_eq!(
11067 out.meta["error"]["message"],
11068 "weatherapi returned 401 Unauthorized"
11069 );
11070 }
11071
11072 #[test]
11073 fn lift_first_node_error_promotes_node_meta_to_output_metadata() {
11074 let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
11079 let err: Box<dyn std::error::Error + 'static> =
11080 Box::<dyn std::error::Error + 'static>::from("weatherapi returned 401 Unauthorized");
11081 nodes.insert(
11082 "call_weather".to_string(),
11083 NodeOutput::with_error("call_weather", err.as_ref()),
11084 );
11085 nodes.insert(
11086 "render_current_card".to_string(),
11087 NodeOutput::new(json!({ "text": "message" })),
11088 );
11089
11090 let final_output = json!({ "text": "message" });
11091 let enriched = lift_first_node_error_from_nodes(final_output, &nodes);
11092 assert_eq!(
11093 enriched["metadata"]["error_kind"], "flow_node_failed",
11094 "first failing node's kind must be lifted"
11095 );
11096 assert_eq!(
11097 enriched["metadata"]["error_message"],
11098 "weatherapi returned 401 Unauthorized"
11099 );
11100 assert_eq!(enriched["metadata"]["node_id"], "call_weather");
11101 assert_eq!(enriched["text"], "message");
11104 }
11105
11106 #[test]
11107 fn lift_first_node_error_is_noop_when_all_nodes_ok() {
11108 let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
11109 nodes.insert(
11110 "ok_node".to_string(),
11111 NodeOutput::new(json!({ "text": "all good" })),
11112 );
11113 let output = json!({ "text": "all good" });
11114 let lifted = lift_first_node_error_from_nodes(output.clone(), &nodes);
11115 assert_eq!(lifted, output);
11116 }
11117
11118 fn broken_flow_engine(pack_id_str: &str, flow_id_str: &str) -> FlowEngine {
11121 let host_flow = host_flow_for_test(flow_id_str, &["only-node"], Some("does-not-exist"));
11122 FlowEngine {
11123 operala_node_handler: None,
11124 packs: Vec::new(),
11125 flows: Vec::new(),
11126 flow_sources: HashMap::new(),
11127 messaging_provider_pack_ids: std::collections::HashSet::new(),
11128 flow_cache: RwLock::new(HashMap::from([(
11129 FlowKey {
11130 pack_id: pack_id_str.to_string(),
11131 flow_id: flow_id_str.to_string(),
11132 },
11133 host_flow,
11134 )])),
11135 default_env: "local".to_string(),
11136 validation: ValidationConfig {
11137 mode: ValidationMode::Off,
11138 },
11139 cross_pack_resolver: None,
11140 rollout_ids: RolloutIds::default(),
11141 approval_dispatch_handler: None,
11142 remote_dispatch_handler: None,
11143 #[cfg(feature = "agentic-worker")]
11144 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
11145 #[cfg(feature = "agentic-worker")]
11146 agent_node_handler: None,
11147 #[cfg(feature = "agentic-worker")]
11148 graph_node_handler: None,
11149 #[cfg(feature = "agentic-worker")]
11150 mcp_tool_source: None,
11151 #[cfg(feature = "agentic-worker")]
11152 mcp_secrets: None,
11153 #[cfg(feature = "agentic-worker")]
11154 a2a_sources: RwLock::new(HashMap::new()),
11155 #[cfg(feature = "agentic-worker")]
11156 ext_artifact_port: None,
11157 }
11158 }
11159
11160 fn terminal_failure_ctx<'a>(pack_id_str: &'a str, flow_id_str: &'a str) -> FlowContext<'a> {
11162 FlowContext {
11163 tenant: "demo",
11164 pack_id: pack_id_str,
11165 flow_id: flow_id_str,
11166 node_id: None,
11167 tool: None,
11168 action: None,
11169 session_id: Some("conv-1"),
11170 provider_id: None,
11171 reply_scope: None,
11172 retry_config: RetryConfig {
11173 max_attempts: 1,
11174 base_delay_ms: 1,
11175 },
11176 attempt: 1,
11177 observer: None,
11178 mocks: None,
11179 caller: None,
11180 }
11181 }
11182
11183 #[tokio::test]
11187 async fn a_terminal_failure_keeps_the_outputs_of_the_nodes_that_ran() {
11188 let (pack_id_str, flow_id_str) = ("test-pack", "partial.flow");
11189 let node = |id: &str, component: &str, routing: Routing| {
11190 let id = NodeId::from_str(id).unwrap();
11191 (
11192 id.clone(),
11193 Node {
11194 id,
11195 component: FlowComponentRef {
11196 id: component.parse().unwrap(),
11197 pack_alias: None,
11198 operation: None,
11199 },
11200 input: InputMapping {
11201 mapping: json!({ "message": "hello" }),
11202 },
11203 output: OutputMapping {
11204 mapping: Value::Null,
11205 },
11206 err_map: None,
11207 routing,
11208 telemetry: TelemetryHints::default(),
11209 conversational: false,
11210 },
11211 )
11212 };
11213 let mut nodes = indexmap::IndexMap::default();
11214 let (first_id, first) = node(
11215 "first",
11216 "emit.log",
11217 Routing::Next {
11218 node_id: NodeId::from_str("second").unwrap(),
11219 },
11220 );
11221 nodes.insert(first_id, first);
11222 let (second_id, second) = node("second", "no.such.component", Routing::End);
11223 nodes.insert(second_id, second);
11224 let flow = HostFlow::from(Flow {
11225 schema_version: "1.0".into(),
11226 id: FlowId::from_str(flow_id_str).unwrap(),
11227 kind: FlowKind::Messaging,
11228 entrypoints: BTreeMap::from([("default".to_string(), Value::String("first".into()))]),
11229 nodes,
11230 metadata: Default::default(),
11231 });
11232 let engine = broken_flow_engine(pack_id_str, flow_id_str);
11233 engine.flow_cache.write().insert(
11234 FlowKey {
11235 pack_id: pack_id_str.to_string(),
11236 flow_id: flow_id_str.to_string(),
11237 },
11238 flow,
11239 );
11240 let ctx = terminal_failure_ctx(pack_id_str, flow_id_str);
11241 let result = engine
11242 .execute(ctx, Value::Null)
11243 .await
11244 .expect("a session flow surfaces the failure as an envelope");
11245 assert_eq!(
11246 result.output["metadata"]["error_kind"],
11247 "flow_execution_failed"
11248 );
11249 assert!(
11250 result.node_outputs.contains_key("first"),
11251 "the node that ran before the failure must keep its output, got {:?}",
11252 result.node_outputs
11253 );
11254 }
11255
11256 #[tokio::test]
11257 async fn execute_user_facing_flow_failure_returns_completed_with_error_envelope() {
11258 let flow_id_str = "broken.flow";
11262 let pack_id_str = "test-pack";
11263 let engine = broken_flow_engine(pack_id_str, flow_id_str);
11264 let ctx = terminal_failure_ctx(pack_id_str, flow_id_str);
11265 let result = engine
11266 .execute(ctx, Value::Null)
11267 .await
11268 .expect("must not propagate Err");
11269 assert!(matches!(result.status, FlowStatus::Completed));
11270 assert_eq!(
11271 result.output["metadata"]["error_kind"],
11272 "flow_execution_failed"
11273 );
11274 let msg = result.output["metadata"]["error_message"]
11275 .as_str()
11276 .unwrap_or("");
11277 assert!(!msg.is_empty(), "error_message must be populated");
11278 assert_eq!(result.output["metadata"]["flow_id"], "broken.flow");
11279 assert_eq!(
11286 result.output["text"],
11287 user_facing_flow_failure_text(&Value::Null),
11288 "a terminal session-flow failure must carry the resolved user-facing message"
11289 );
11290 let shown = result.output["text"].as_str().unwrap_or_default();
11293 assert!(
11294 !shown.trim().is_empty(),
11295 "an empty `text` is silent on every channel"
11296 );
11297 assert!(
11299 !shown.contains("does-not-exist"),
11300 "raw engine text must stay in metadata.error_message"
11301 );
11302 }
11303
11304 #[tokio::test]
11310 async fn execute_user_facing_flow_failure_answers_in_the_conversation_locale() {
11311 let flow_id_str = "broken.flow";
11312 let pack_id_str = "test-pack";
11313 let engine = broken_flow_engine(pack_id_str, flow_id_str);
11314
11315 let result = engine
11317 .execute(
11318 terminal_failure_ctx(pack_id_str, flow_id_str),
11319 json!({ "metadata": { "locale": "id-ID" } }),
11320 )
11321 .await
11322 .expect("must not propagate Err");
11323 let shown = result.output["text"].as_str().unwrap_or_default();
11324 assert_eq!(
11325 shown,
11326 user_facing_flow_failure_text_for("id"),
11327 "an Indonesian conversation must be answered in Indonesian"
11328 );
11329 assert_ne!(
11330 shown,
11331 crate::runner::i18n::FLOW_EXECUTION_FAILED_EN,
11332 "the conversation locale was ignored"
11333 );
11334
11335 let nested = engine
11338 .execute(
11339 terminal_failure_ctx(pack_id_str, flow_id_str),
11340 json!({ "input": { "metadata": { "locale": "ja" } } }),
11341 )
11342 .await
11343 .expect("must not propagate Err");
11344 let nested_text = nested.output["text"].as_str().unwrap_or_default();
11345 assert_eq!(nested_text, user_facing_flow_failure_text_for("ja"));
11346 assert!(!nested_text.trim().is_empty());
11347 assert!(
11348 !nested_text.contains("does-not-exist"),
11349 "raw engine text must stay in metadata.error_message in every locale"
11350 );
11351
11352 let unknown = engine
11354 .execute(
11355 terminal_failure_ctx(pack_id_str, flow_id_str),
11356 json!({ "metadata": { "locale": "kl-GL" } }),
11357 )
11358 .await
11359 .expect("must not propagate Err");
11360 assert_eq!(
11361 unknown.output["text"],
11362 crate::runner::i18n::FLOW_EXECUTION_FAILED_EN
11363 );
11364 }
11365
11366 #[test]
11367 fn activity_locale_reads_both_shapes_and_treats_blank_as_absent() {
11368 assert_eq!(
11369 activity_locale(&json!({ "metadata": { "locale": "nl-NL" } })),
11370 Some("nl-NL")
11371 );
11372 assert_eq!(
11373 activity_locale(&json!({ "input": { "metadata": { "locale": "en-GB" } } })),
11374 Some("en-GB")
11375 );
11376 assert_eq!(
11378 activity_locale(&json!({
11379 "input": { "metadata": { "locale": "ja" } },
11380 "metadata": { "locale": "id" },
11381 })),
11382 Some("ja")
11383 );
11384 assert_eq!(
11386 activity_locale(&json!({ "metadata": { "locale": " " } })),
11387 None
11388 );
11389 assert_eq!(
11390 activity_locale(&json!({ "metadata": { "locale": "" } })),
11391 None
11392 );
11393 assert_eq!(
11394 activity_locale(&json!({ "metadata": { "locale": 7 } })),
11395 None
11396 );
11397 assert_eq!(activity_locale(&Value::Null), None);
11398 assert_eq!(activity_locale(&json!({})), None);
11399 }
11400
11401 #[test]
11407 fn user_facing_flow_failure_text_is_localized_and_never_empty() {
11408 let english = user_facing_flow_failure_text_for("en");
11409 assert_eq!(english, crate::runner::i18n::FLOW_EXECUTION_FAILED_EN);
11410
11411 for locale in ["id", "es", "ja", "zh"] {
11414 let translated = user_facing_flow_failure_text_for(locale);
11415 assert_ne!(
11416 translated, english,
11417 "`{locale}` must resolve to its own wording, not English"
11418 );
11419 }
11420
11421 assert_eq!(user_facing_flow_failure_text_for("id-ID"), {
11423 user_facing_flow_failure_text_for("id")
11424 });
11425 assert_eq!(user_facing_flow_failure_text_for("zh_TW"), {
11426 user_facing_flow_failure_text_for("zh")
11427 });
11428
11429 for locale in ["", "xx", "klingon", "C", "C.UTF-8", "POSIX"] {
11432 assert_eq!(
11433 user_facing_flow_failure_text_for(locale),
11434 english,
11435 "`{locale}` must fall back to English"
11436 );
11437 }
11438
11439 for locale in ["en", "id", "es", "ja", "zh", "", "xx", "C.UTF-8"] {
11441 let text = user_facing_flow_failure_text_for(locale);
11442 assert!(
11443 !text.trim().is_empty(),
11444 "`{locale}` resolved to empty text, which is silent on every channel"
11445 );
11446 }
11447 }
11448
11449 #[test]
11450 fn mcp_tool_error_recognises_generator_error_shape() {
11451 let value = json!({
11454 "error": {
11455 "code": "tool_error",
11456 "message": "API request returned status 401",
11457 "status": 401
11458 }
11459 });
11460 let (code, message) = mcp_tool_error(&value).expect("must detect MCP error shape");
11461 assert_eq!(code, "tool_error");
11462 assert!(message.contains("API request returned status 401"));
11463 assert!(message.contains("(status 401)"));
11464 }
11465
11466 #[test]
11467 fn mcp_tool_error_skips_success_responses() {
11468 let value = json!({ "result": { "current": { "temp_c": 19.0 } } });
11470 assert!(mcp_tool_error(&value).is_none());
11471 }
11472
11473 #[test]
11474 fn mcp_tool_error_skips_non_object_and_unrelated_shapes() {
11475 assert!(mcp_tool_error(&Value::Null).is_none());
11476 assert!(mcp_tool_error(&json!({"unrelated": true})).is_none());
11477 assert!(mcp_tool_error(&json!({"error": "oops"})).is_none());
11479 }
11480
11481 #[test]
11486 fn normalize_mcp_tool_error_matches_component_error_shape() {
11487 let value = json!({
11488 "error": { "code": "tool_error", "message": "boom", "status": 502 }
11489 });
11490 let normalized = normalize_mcp_tool_error(&value, "tool_error", "boom (status 502)");
11491 assert_eq!(
11492 component_error(&normalized),
11493 Some(("tool_error".to_string(), "boom (status 502)".to_string())),
11494 "the normalized payload must be recognised by component_error verbatim"
11495 );
11496 assert_eq!(normalized["error"]["status"], json!(502));
11498 }
11499
11500 #[cfg(feature = "agentic-worker")]
11517 #[test]
11518 fn mcp_node_output_reports_failure_when_the_node_has_an_error_route() {
11519 let result = json!({ "error": "MCP is not configured on this runner" });
11520 let bound = result.clone();
11521
11522 let out = mcp_node_output(bound, &result, true);
11523
11524 assert!(
11525 !out.ok,
11526 "a failed MCP call with an error route must not report ok"
11527 );
11528 assert_eq!(
11529 component_error(&out.payload),
11530 Some((
11531 "mcp_call_failed".to_string(),
11532 "MCP is not configured on this runner".to_string()
11533 )),
11534 "the payload must be recognised by component_error verbatim, got {:?}",
11535 out.payload
11536 );
11537 assert_eq!(
11538 out.meta.pointer("/error/message").and_then(Value::as_str),
11539 Some("MCP is not configured on this runner"),
11540 "the message must reach meta.error where lift_first_node_error_from_nodes reads it"
11541 );
11542
11543 let view = node_output_view(&out.payload);
11544 let errors = view["errors"].as_array().expect("errors must be an array");
11545 assert_eq!(errors.len(), 1, "errors must be populated, got {view:?}");
11546 assert_eq!(
11547 errors[0]["message"], "MCP is not configured on this runner",
11548 "{{{{node.<id>.errors[0].message}}}} must surface the real message"
11549 );
11550 }
11551
11552 #[cfg(feature = "agentic-worker")]
11564 #[test]
11565 fn mcp_node_output_uses_mcp_tool_error_for_the_object_shaped_error() {
11566 let result = json!({
11567 "error": {
11568 "code": "tool_error",
11569 "message": "API request returned status 401",
11570 "status": 401
11571 }
11572 });
11573 let bound = result.clone();
11574
11575 let (expected_code, expected_message) =
11576 mcp_tool_error(&result).expect("the detector must recognise this shape");
11577
11578 let out = mcp_node_output(bound, &result, true);
11579
11580 assert!(
11581 !out.ok,
11582 "an object-shaped MCP tool error with an error route must not report ok"
11583 );
11584 assert_eq!(
11585 component_error(&out.payload),
11586 Some((expected_code.clone(), expected_message.clone())),
11587 "the code/message must be exactly what mcp_tool_error derives, got {:?}",
11588 out.payload
11589 );
11590 assert_eq!(expected_code, "tool_error");
11593 assert!(expected_message.contains("API request returned status 401"));
11594 assert!(expected_message.contains("(status 401)"));
11595
11596 let view = node_output_view(&out.payload);
11597 let errors = view["errors"].as_array().expect("errors must be an array");
11598 assert_eq!(errors.len(), 1, "errors must be populated, got {view:?}");
11599 assert_eq!(errors[0]["message"], expected_message);
11600 }
11601
11602 #[cfg(feature = "agentic-worker")]
11610 #[test]
11611 fn mcp_node_output_preserves_the_output_binding_key_alongside_the_error_envelope() {
11612 let result = json!({ "error": "connection refused" });
11613 let bound = json!({ "quote_result_data": result.clone() });
11614
11615 let out = mcp_node_output(bound.clone(), &result, true);
11616
11617 assert!(!out.ok);
11618 assert_eq!(
11619 out.payload["quote_result_data"], result,
11620 "the output-key binding must survive untouched, got {:?}",
11621 out.payload
11622 );
11623 assert_eq!(out.payload["ok"], json!(false));
11624 assert_eq!(out.payload["error"]["code"], "mcp_call_failed");
11625 assert_eq!(out.payload["error"]["message"], "connection refused");
11626
11627 let view = node_output_view(&out.payload);
11628 assert_eq!(
11629 view["quote_result_data"], result,
11630 "{{{{node.<id>.quote_result_data}}}} must still resolve, got {view:?}"
11631 );
11632 let errors = view["errors"].as_array().expect("errors must be an array");
11633 assert_eq!(errors[0]["message"], "connection refused");
11634 }
11635
11636 #[cfg(feature = "agentic-worker")]
11648 #[test]
11649 fn mcp_node_output_ignores_failure_when_the_node_has_no_error_route() {
11650 let result = json!({ "error": "MCP is not configured on this runner" });
11651 let bound = json!({ "quote_result_data": result.clone() });
11652
11653 let out = mcp_node_output(bound.clone(), &result, false);
11654
11655 assert!(
11656 out.ok,
11657 "a node with no error route must keep reporting ok, unchanged from pre-R3"
11658 );
11659 assert_eq!(
11660 out.payload, bound,
11661 "the payload must be exactly the bound value, no envelope reshaping"
11662 );
11663 assert_eq!(out.meta, Value::Null);
11664 }
11665
11666 #[cfg(feature = "agentic-worker")]
11670 #[test]
11671 fn mcp_node_output_stays_ok_on_success_regardless_of_error_route() {
11672 let result = json!({ "annual_premium": 1234 });
11673 let bound = json!({ "quote_result_data": result.clone() });
11674
11675 for has_error_route in [true, false] {
11676 let out = mcp_node_output(bound.clone(), &result, has_error_route);
11677 assert!(out.ok, "a successful MCP call must report ok");
11678 assert_eq!(out.payload, bound);
11679 assert_eq!(out.meta, Value::Null);
11680 }
11681 }
11682
11683 #[cfg(feature = "agentic-worker")]
11686 #[test]
11687 fn mcp_failure_with_on_error_route_routes_to_the_error_branch() {
11688 let raw_routing = json!([
11689 { "condition": "event == \"on_success\"", "to": "ok_node" },
11690 { "condition": "event == \"on_error\"", "to": "err_node" }
11691 ]);
11692 let routing = Routing::Custom(raw_routing.clone());
11693 let flow_ir = HostFlow {
11694 id: "flow.test".to_string(),
11695 start: None,
11696 nodes: IndexMap::new(),
11697 vars_init: JsonMap::new(),
11698 required_vars: Vec::new(),
11699 slot_schema: None,
11700 };
11701 let current = NodeId::from_str("current").unwrap();
11702 let state = ExecutionState::new(json!({}));
11703
11704 let result = json!({ "error": "MCP is not configured on this runner" });
11705 let has_error_route = node_has_error_route(&routing);
11706 assert!(has_error_route);
11707 let out = mcp_node_output(result.clone(), &result, has_error_route);
11708
11709 match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, ¤t) {
11710 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err_node"),
11711 other => panic!("expected the on_error route, got {other:?}"),
11712 }
11713 }
11714
11715 #[cfg(feature = "agentic-worker")]
11720 #[test]
11721 fn mcp_failure_with_success_only_routing_never_parks() {
11722 let raw_routing = json!([
11723 { "condition": "event == \"on_success\"", "to": "ok_node" }
11724 ]);
11725 let routing = Routing::Custom(raw_routing.clone());
11726 let flow_ir = HostFlow {
11727 id: "flow.test".to_string(),
11728 start: None,
11729 nodes: IndexMap::new(),
11730 vars_init: JsonMap::new(),
11731 required_vars: Vec::new(),
11732 slot_schema: None,
11733 };
11734 let current = NodeId::from_str("current").unwrap();
11735 let state = ExecutionState::new(json!({}));
11736
11737 let result = json!({ "error": "MCP is not configured on this runner" });
11738 let has_error_route = node_has_error_route(&routing);
11739 assert!(
11740 !has_error_route,
11741 "a success-only Custom routing has no error branch"
11742 );
11743 let out = mcp_node_output(result.clone(), &result, has_error_route);
11744 assert!(out.ok, "no error route means the failure is not surfaced");
11745
11746 match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, ¤t) {
11747 CustomRoutingDecision::Next(nid) => assert_eq!(
11748 nid.as_str(),
11749 "ok_node",
11750 "the flow must continue on the success path, not park"
11751 ),
11752 other => panic!(
11753 "a node with no error route must never park on an MCP failure, got {other:?}"
11754 ),
11755 }
11756 }
11757
11758 #[tokio::test]
11759 async fn execute_non_user_facing_flow_failure_still_propagates() {
11760 let flow_id_str = "broken.flow";
11763 let pack_id_str = "test-pack";
11764 let host_flow = host_flow_for_test(flow_id_str, &["only-node"], Some("does-not-exist"));
11765 let engine = FlowEngine {
11766 operala_node_handler: None,
11767 packs: Vec::new(),
11768 flows: Vec::new(),
11769 flow_sources: HashMap::new(),
11770 messaging_provider_pack_ids: std::collections::HashSet::new(),
11771 flow_cache: RwLock::new(HashMap::from([(
11772 FlowKey {
11773 pack_id: pack_id_str.to_string(),
11774 flow_id: flow_id_str.to_string(),
11775 },
11776 host_flow,
11777 )])),
11778 default_env: "local".to_string(),
11779 validation: ValidationConfig {
11780 mode: ValidationMode::Off,
11781 },
11782 cross_pack_resolver: None,
11783 rollout_ids: RolloutIds::default(),
11784 approval_dispatch_handler: None,
11785 remote_dispatch_handler: None,
11786 #[cfg(feature = "agentic-worker")]
11787 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
11788 #[cfg(feature = "agentic-worker")]
11789 agent_node_handler: None,
11790 #[cfg(feature = "agentic-worker")]
11791 graph_node_handler: None,
11792 #[cfg(feature = "agentic-worker")]
11793 mcp_tool_source: None,
11794 #[cfg(feature = "agentic-worker")]
11795 mcp_secrets: None,
11796 #[cfg(feature = "agentic-worker")]
11797 a2a_sources: RwLock::new(HashMap::new()),
11798 #[cfg(feature = "agentic-worker")]
11799 ext_artifact_port: None,
11800 };
11801 let ctx = FlowContext {
11802 tenant: "demo",
11803 pack_id: pack_id_str,
11804 flow_id: flow_id_str,
11805 node_id: None,
11806 tool: None,
11807 action: None,
11808 session_id: None,
11809 provider_id: None,
11810 reply_scope: None,
11811 retry_config: RetryConfig {
11812 max_attempts: 1,
11813 base_delay_ms: 1,
11814 },
11815 attempt: 1,
11816 observer: None,
11817 mocks: None,
11818 caller: None,
11819 };
11820 let result = engine.execute(ctx, Value::Null).await;
11821 assert!(result.is_err(), "non-user-facing flow must propagate Err");
11822 }
11823
11824 #[test]
11827 fn host_flow_extracts_slot_schema_from_metadata_extra() {
11828 use greentic_types::FlowMetadata;
11829 use std::collections::BTreeSet;
11830
11831 let schema = json!([
11832 {"name": "counterparty", "slot_type": "string", "required": true},
11833 {"name": "due_date", "slot_type": "date", "required": true}
11834 ]);
11835 let flow = Flow {
11836 schema_version: "flow-v1".into(),
11837 id: FlowId::from_str("test.flow").unwrap(),
11838 kind: FlowKind::Messaging,
11839 entrypoints: BTreeMap::new(),
11840 nodes: IndexMap::default(),
11841 metadata: FlowMetadata {
11842 title: None,
11843 description: None,
11844 tags: BTreeSet::new(),
11845 extra: json!({(SLOT_SCHEMA_METADATA_KEY): schema}),
11846 },
11847 };
11848 let host = HostFlow::from(flow);
11849 assert_eq!(
11850 host.slot_schema.as_ref(),
11851 Some(&schema),
11852 "HostFlow must extract slot_schema from metadata.extra"
11853 );
11854 }
11855
11856 #[test]
11857 fn host_flow_slot_schema_is_none_when_absent() {
11858 let flow = Flow {
11859 schema_version: "flow-v1".into(),
11860 id: FlowId::from_str("test.flow").unwrap(),
11861 kind: FlowKind::Messaging,
11862 entrypoints: BTreeMap::new(),
11863 nodes: IndexMap::default(),
11864 metadata: Default::default(),
11865 };
11866 let host = HostFlow::from(flow);
11867 assert!(
11868 host.slot_schema.is_none(),
11869 "HostFlow.slot_schema must be None when metadata.extra has no greentic.slot_schema"
11870 );
11871 }
11872
11873 #[test]
11874 fn inject_slot_definitions_adds_to_object_input() {
11875 let schema = json!([
11876 {"name": "city", "slot_type": "string"}
11877 ]);
11878 let mut input = json!({"utterance": "hello"});
11879 inject_slot_definitions(&mut input, &schema, "f", "n");
11880 assert_eq!(
11881 input,
11882 json!({"utterance": "hello", "slot_definitions": schema}),
11883 "slot_definitions must be injected into existing object"
11884 );
11885 }
11886
11887 #[test]
11888 fn inject_slot_definitions_wraps_null_input() {
11889 let schema = json!([{"name": "x", "slot_type": "string"}]);
11890 let mut input = Value::Null;
11891 inject_slot_definitions(&mut input, &schema, "f", "n");
11892 assert_eq!(
11893 input,
11894 json!({"slot_definitions": schema}),
11895 "null input must become an object with slot_definitions"
11896 );
11897 }
11898
11899 #[test]
11900 fn inject_slot_definitions_preserves_explicit_inline() {
11901 let flow_schema = json!([{"name": "city", "slot_type": "string"}]);
11902 let inline_defs = json!([{"name": "country", "slot_type": "string"}]);
11903 let mut input = json!({
11904 "utterance": "hello",
11905 "slot_definitions": inline_defs
11906 });
11907 inject_slot_definitions(&mut input, &flow_schema, "f", "n");
11908 assert_eq!(
11909 input["slot_definitions"], inline_defs,
11910 "explicit inline slot_definitions must not be overwritten"
11911 );
11912 }
11913
11914 #[test]
11915 fn inject_slot_definitions_skips_non_object_input() {
11916 let schema = json!([{"name": "x", "slot_type": "string"}]);
11917 let mut input = json!("a string");
11918 inject_slot_definitions(&mut input, &schema, "f", "n");
11919 assert_eq!(
11920 input,
11921 json!("a string"),
11922 "non-object input must be left unchanged"
11923 );
11924 }
11925
11926 fn make_flow_doc_for_test(
11927 id: &str,
11928 node_name: &str,
11929 component: &str,
11930 slot_schema: Option<Value>,
11931 ) -> greentic_flow::model::FlowDoc {
11932 use greentic_flow::model::{FlowDoc, NodeDoc};
11933
11934 let mut nodes = IndexMap::new();
11935 nodes.insert(
11936 node_name.to_string(),
11937 NodeDoc {
11938 raw: {
11939 let mut m = IndexMap::new();
11940 m.insert(
11941 "component.exec".to_string(),
11942 json!({ "component": component }),
11943 );
11944 m
11945 },
11946 routing: json!([{ "out": true }]),
11947 ..Default::default()
11948 },
11949 );
11950
11951 FlowDoc {
11952 id: id.into(),
11953 title: None,
11954 description: None,
11955 flow_type: "messaging".into(),
11956 start: Some(node_name.into()),
11957 parameters: json!({}),
11958 tags: Vec::new(),
11959 schema_version: None,
11960 entrypoints: IndexMap::new(),
11961 meta: None,
11962 slot_schema,
11963 nodes,
11964 }
11965 }
11966
11967 #[test]
11973 fn compile_flow_round_trips_slot_schema_into_host_flow() {
11974 let slot_defs = json!([
11975 { "name": "counterparty", "slot_type": "string", "required": true,
11976 "pattern": ".+" },
11977 { "name": "due_date", "slot_type": "date", "required": true,
11978 "pattern": "\\d{4}-\\d{2}-\\d{2}" }
11979 ]);
11980 let doc = make_flow_doc_for_test(
11981 "slot-test",
11982 "extractor",
11983 "slot-extractor",
11984 Some(slot_defs.clone()),
11985 );
11986
11987 let flow = greentic_flow::compile_flow(doc).expect("compile_flow must succeed");
11988 assert_eq!(
11989 flow.metadata.extra.get(SLOT_SCHEMA_METADATA_KEY),
11990 Some(&slot_defs),
11991 "compile_flow must forward slot_schema into metadata.extra"
11992 );
11993
11994 let host = HostFlow::from(flow);
11995 assert_eq!(
11996 host.slot_schema.as_ref(),
11997 Some(&slot_defs),
11998 "HostFlow.slot_schema must survive the compile_flow -> HostFlow round-trip"
11999 );
12000 }
12001
12002 #[test]
12006 fn compile_flow_without_slot_schema_leaves_host_flow_none() {
12007 let doc = make_flow_doc_for_test("no-slots", "echo", "echo", None);
12008
12009 let flow = greentic_flow::compile_flow(doc).expect("compile_flow must succeed");
12010 assert!(
12011 flow.metadata.extra.get(SLOT_SCHEMA_METADATA_KEY).is_none(),
12012 "metadata.extra must not contain greentic.slot_schema when FlowDoc.slot_schema is None"
12013 );
12014
12015 let host = HostFlow::from(flow);
12016 assert!(
12017 host.slot_schema.is_none(),
12018 "HostFlow.slot_schema must be None when FlowDoc has no slot_schema"
12019 );
12020 }
12021
12022 #[test]
12029 fn multi_edge_node_routes_on_injected_event() {
12030 let raw_routing = json!([
12031 { "condition": "event == \"on_success\"", "to": "next" },
12032 { "condition": "event == \"on_error\"", "to": "err" }
12033 ]);
12034 let flow_ir = HostFlow {
12035 id: "flow.test".to_string(),
12036 start: None,
12037 nodes: IndexMap::new(),
12038 vars_init: JsonMap::new(),
12039 required_vars: Vec::new(),
12040 slot_schema: None,
12041 };
12042 let current = NodeId::from_str("current").unwrap();
12043 let state = ExecutionState::new(json!({}));
12044
12045 let ok_out = NodeOutput::new(json!({ "x": 1 }));
12047 match evaluate_custom_routing(&raw_routing, &ok_out, &state, &flow_ir, ¤t) {
12048 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
12049 other => panic!("expected Next(\"next\"), got {other:?}"),
12050 }
12051
12052 let routed = NodeOutput::with_meta(json!({}), json!({ "outcome": "on_error" }));
12054 match evaluate_custom_routing(&raw_routing, &routed, &state, &flow_ir, ¤t) {
12055 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err"),
12056 other => panic!("expected Next(\"err\"), got {other:?}"),
12057 }
12058 }
12059
12060 #[test]
12061 fn approval_outcomes_route_three_ways() {
12062 let raw_routing = json!([
12066 { "condition": "event == \"approved\"", "to": "do_it" },
12067 { "condition": "event == \"denied\"", "to": "reject" },
12068 { "condition": "event == \"timeout\"", "to": "escalate" }
12069 ]);
12070 let flow_ir = HostFlow {
12071 slot_schema: None,
12072 id: "flow.test".to_string(),
12073 start: None,
12074 nodes: IndexMap::new(),
12075 vars_init: JsonMap::new(),
12076 required_vars: Vec::new(),
12077 };
12078 let current = NodeId::from_str("gate").unwrap();
12079 let state = ExecutionState::new(json!({}));
12080
12081 for (outcome, expected) in [
12082 ("approved", "do_it"),
12083 ("denied", "reject"),
12084 ("timeout", "escalate"),
12085 ] {
12086 let out = NodeOutput::with_meta(json!({}), json!({ "outcome": outcome }));
12087 match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, ¤t) {
12088 CustomRoutingDecision::Next(nid) => assert_eq!(
12089 nid.as_str(),
12090 expected,
12091 "outcome {outcome} must route to {expected}"
12092 ),
12093 other => panic!("outcome {outcome}: expected Next({expected}), got {other:?}"),
12094 }
12095 }
12096 }
12097
12098 #[test]
12102 fn errored_output_routes_to_on_error_branch() {
12103 let raw_routing = json!([
12104 { "condition": "event == \"on_success\"", "to": "ok_node" },
12105 { "condition": "event == \"on_error\"", "to": "err_node" }
12106 ]);
12107 let flow_ir = HostFlow {
12108 id: "flow.test".to_string(),
12109 start: None,
12110 nodes: IndexMap::new(),
12111 vars_init: JsonMap::new(),
12112 required_vars: Vec::new(),
12113 slot_schema: None,
12114 };
12115 let current = NodeId::from_str("current").unwrap();
12116 let state = ExecutionState::new(json!({}));
12117
12118 let errored =
12119 NodeOutput::errored(json!({ "ok": false, "error": { "code": "E", "message": "m" } }));
12120 match evaluate_custom_routing(&raw_routing, &errored, &state, &flow_ir, ¤t) {
12121 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err_node"),
12122 other => panic!("expected on_error route, got {other:?}"),
12123 }
12124 }
12125
12126 #[test]
12132 fn errored_output_with_outcome_routes_to_that_branch() {
12133 let raw_routing = json!([
12134 { "condition": "event == \"on_success\"", "to": "ok_node" },
12135 { "condition": "event == \"on_timeout\"", "to": "timeout_node" },
12136 { "condition": "event == \"on_error\"", "to": "err_node" }
12137 ]);
12138 let flow_ir = HostFlow {
12139 id: "flow.test".to_string(),
12140 start: None,
12141 nodes: IndexMap::new(),
12142 vars_init: JsonMap::new(),
12143 required_vars: Vec::new(),
12144 slot_schema: None,
12145 };
12146 let current = NodeId::from_str("current").unwrap();
12147 let state = ExecutionState::new(json!({}));
12148
12149 let errored = NodeOutput::errored(json!({
12150 "ok": false,
12151 "outcome": "on_timeout",
12152 "error": { "code": "E", "message": "m" }
12153 }));
12154 match evaluate_custom_routing(&raw_routing, &errored, &state, &flow_ir, ¤t) {
12155 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "timeout_node"),
12156 other => panic!("expected on_timeout route, got {other:?}"),
12157 }
12158 }
12159
12160 #[test]
12168 fn errored_output_preserves_meta_error_alongside_outcome() {
12169 let errored = NodeOutput::errored(json!({
12170 "ok": false,
12171 "outcome": "on_timeout",
12172 "error": { "code": "E1", "message": "boom" }
12173 }));
12174 assert_eq!(
12175 errored.meta.get("outcome").and_then(Value::as_str),
12176 Some("on_timeout"),
12177 "outcome must survive so routing can pick the on_timeout branch"
12178 );
12179 assert_eq!(
12180 errored.meta["error"]["message"], "boom",
12181 "error must survive alongside outcome, not be clobbered by it"
12182 );
12183
12184 let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
12185 nodes.insert("run".to_string(), errored);
12186 let lifted = lift_first_node_error_from_nodes(json!({}), &nodes);
12187 assert_eq!(
12188 lifted["metadata"]["error_message"], "boom",
12189 "lift_first_node_error_from_nodes must read the real message, not the generic fallback"
12190 );
12191 assert_eq!(lifted["metadata"]["node_id"], "run");
12192 }
12193
12194 #[test]
12202 fn component_error_routed_failure_surfaces_real_message_via_lift() {
12203 let errored = NodeOutput::errored(json!({
12204 "ok": false,
12205 "error": { "code": "E1", "message": "disk full" }
12206 }));
12207 let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
12208 nodes.insert("run".to_string(), errored);
12209 let lifted = lift_first_node_error_from_nodes(json!({}), &nodes);
12210 assert_eq!(
12211 lifted["metadata"]["error_message"], "disk full",
12212 "a component_error-routed failure must surface its real message, \
12213 not the generic \"flow node failed\" default"
12214 );
12215 assert_eq!(lifted["metadata"]["node_id"], "run");
12216 }
12217
12218 #[test]
12219 fn node_has_error_route_detects_error_family_ports() {
12220 let with_err = Routing::Custom(json!([
12221 { "condition": "event == \"on_success\"", "to": "n" },
12222 { "condition": "event == \"on_error\"", "to": "e" }
12223 ]));
12224 assert!(
12225 node_has_error_route(&with_err),
12226 "on_error route must be detected"
12227 );
12228
12229 let only_success = Routing::Custom(json!([
12230 { "condition": "event == \"on_success\"", "to": "n" }
12231 ]));
12232 assert!(
12233 !node_has_error_route(&only_success),
12234 "a success-only Custom routing has no error branch"
12235 );
12236
12237 let plain = Routing::Next {
12238 node_id: NodeId::from_str("n").unwrap(),
12239 };
12240 assert!(
12241 !node_has_error_route(&plain),
12242 "Routing::Next has no error branch"
12243 );
12244 }
12245
12246 #[test]
12255 fn success_default_matches_available_outcome_port() {
12256 let flow_ir = HostFlow {
12257 id: "flow.test".to_string(),
12258 start: None,
12259 nodes: IndexMap::new(),
12260 vars_init: JsonMap::new(),
12261 required_vars: Vec::new(),
12262 slot_schema: None,
12263 };
12264 let current = NodeId::from_str("current").unwrap();
12265 let state = ExecutionState::new(json!({}));
12266 let ok_out = NodeOutput::new(json!({ "answer": "hi" }));
12268
12269 let on_complete_routing = json!([
12271 { "condition": "event == \"on_complete\"", "to": "next" },
12272 { "condition": "event == \"on_cancel\"", "to": "cancelled" }
12273 ]);
12274 match evaluate_custom_routing(&on_complete_routing, &ok_out, &state, &flow_ir, ¤t) {
12275 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
12276 other => panic!("expected Next(\"next\") via on_complete default, got {other:?}"),
12277 }
12278
12279 let on_submit_routing = json!([
12281 { "condition": "event == \"on_submit\"", "to": "saved" },
12282 { "condition": "event == \"on_cancel\"", "to": "cancelled" }
12283 ]);
12284 match evaluate_custom_routing(&on_submit_routing, &ok_out, &state, &flow_ir, ¤t) {
12285 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "saved"),
12286 other => panic!("expected Next(\"saved\") via on_submit default, got {other:?}"),
12287 }
12288
12289 let on_success_routing = json!([
12292 { "condition": "event == \"on_success\"", "to": "ok" },
12293 { "condition": "event == \"on_error\"", "to": "err" }
12294 ]);
12295 match evaluate_custom_routing(&on_success_routing, &ok_out, &state, &flow_ir, ¤t) {
12296 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "ok"),
12297 other => panic!("expected Next(\"ok\") via on_success default, got {other:?}"),
12298 }
12299 }
12300
12301 #[test]
12315 fn condition_evaluator_supports_comparisons_and_contains() {
12316 let ctx = json!({
12317 "a": { "age": 18 },
12318 "b": { "status": "ok" },
12319 "c": { "text": "Hello World" }
12320 });
12321
12322 assert!(evaluate_simple_condition("a.age >= 18", &ctx));
12324 assert!(!evaluate_simple_condition("a.age > 18", &ctx));
12325 assert!(evaluate_simple_condition("a.age <= 18", &ctx));
12326 assert!(!evaluate_simple_condition("a.age < 18", &ctx));
12327
12328 assert!(evaluate_simple_condition("c.text contains \"world\"", &ctx));
12330 assert!(!evaluate_simple_condition("c.text contains \"bye\"", &ctx));
12331
12332 assert!(evaluate_simple_condition("b.status == \"ok\"", &ctx));
12334 assert!(!evaluate_simple_condition("b.status != \"ok\"", &ctx));
12335 assert!(!evaluate_simple_condition("b.status >= 1", &ctx));
12337 }
12338
12339 #[test]
12349 fn routing_context_exposes_prior_node_outputs_under_node() {
12350 let mut state = ExecutionState::new(json!({}));
12351 state
12352 .nodes
12353 .insert("register".into(), NodeOutput::new(json!({ "q_age": 21 })));
12354
12355 let current = NodeOutput::new(json!({ "status": "ok" }));
12356 let ctx = build_routing_context(¤t, &state, "on_success", "on_error");
12357
12358 assert!(
12360 evaluate_simple_condition("node.register.q_age >= 18", &ctx),
12361 "a prior node's output must be readable via node.<id>.<field>: {ctx:?}"
12362 );
12363 assert!(
12365 evaluate_simple_condition("node.register.data.q_age >= 18", &ctx),
12366 "the data envelope must resolve like it does in params: {ctx:?}"
12367 );
12368 }
12369
12370 #[test]
12371 fn routing_context_keeps_the_predecessor_shorthand() {
12372 let mut state = ExecutionState::new(json!({}));
12376 state
12377 .nodes
12378 .insert("register".into(), NodeOutput::new(json!({ "q_age": 21 })));
12379
12380 let current = NodeOutput::new(json!({ "q_age": 30 }));
12381 let ctx = build_routing_context(¤t, &state, "on_success", "on_error");
12382
12383 assert!(
12384 evaluate_simple_condition("q_age >= 30", &ctx),
12385 "the bare form must still resolve against the current payload: {ctx:?}"
12386 );
12387 }
12388
12389 #[test]
12390 fn routing_context_does_not_resolve_a_missing_node() {
12391 let state = ExecutionState::new(json!({}));
12394 let current = NodeOutput::new(json!({ "status": "ok" }));
12395 let ctx = build_routing_context(¤t, &state, "on_success", "on_error");
12396
12397 assert!(
12398 !evaluate_simple_condition("node.ghost.x == \"y\"", &ctx),
12399 "a missing node must not resolve: {ctx:?}"
12400 );
12401 }
12402
12403 #[test]
12409 fn failure_default_matches_available_outcome_port() {
12410 let flow_ir = HostFlow {
12411 id: "flow.test".to_string(),
12412 start: None,
12413 nodes: IndexMap::new(),
12414 vars_init: JsonMap::new(),
12415 required_vars: Vec::new(),
12416 slot_schema: None,
12417 };
12418 let current = NodeId::from_str("current").unwrap();
12419 let state = ExecutionState::new(json!({}));
12420 let err_out = NodeOutput {
12422 ok: false,
12423 payload: json!({}),
12424 meta: Value::Null,
12425 created: Vec::new(),
12426 };
12427
12428 let on_cancel_routing = json!([
12430 { "condition": "event == \"on_complete\"", "to": "next" },
12431 { "condition": "event == \"on_cancel\"", "to": "cancelled" }
12432 ]);
12433 match evaluate_custom_routing(&on_cancel_routing, &err_out, &state, &flow_ir, ¤t) {
12434 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "cancelled"),
12435 other => panic!("expected Next(\"cancelled\") via on_cancel default, got {other:?}"),
12436 }
12437
12438 let on_error_routing = json!([
12440 { "condition": "event == \"on_success\"", "to": "ok" },
12441 { "condition": "event == \"on_error\"", "to": "err" }
12442 ]);
12443 match evaluate_custom_routing(&on_error_routing, &err_out, &state, &flow_ir, ¤t) {
12444 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err"),
12445 other => panic!("expected Next(\"err\") via on_error default, got {other:?}"),
12446 }
12447
12448 let on_timeout_routing = json!([
12450 { "condition": "event == \"on_success\"", "to": "ok" },
12451 { "condition": "event == \"on_timeout\"", "to": "timed_out" }
12452 ]);
12453 match evaluate_custom_routing(&on_timeout_routing, &err_out, &state, &flow_ir, ¤t) {
12454 CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "timed_out"),
12455 other => panic!("expected Next(\"timed_out\") via on_timeout default, got {other:?}"),
12456 }
12457 }
12458
12459 #[test]
12460 fn outcome_meta_surfaces_component_emitted_outcome() {
12461 assert_eq!(
12464 outcome_meta(&json!({ "ok": true, "outcome": "on_complete" })),
12465 json!({ "outcome": "on_complete" })
12466 );
12467 assert_eq!(
12469 outcome_meta(&json!({ "ok": true, "body": {} })),
12470 Value::Null
12471 );
12472 }
12473
12474 #[cfg(feature = "agentic-worker")]
12504 #[tokio::test]
12505 #[ignore = "requires live NATS; run with --ignored after `nats-server -js`"]
12506 async fn dw_agent_scale_to_zero_nats_e2e() {
12507 use crate::runner::agent_node::DwAgentDispatch;
12508 use crate::runner::dispatch_listener::{SessionResumer, run_response_listener};
12509 use crate::runner::remote_dispatch::NatsDispatcher;
12510 use futures::StreamExt as _;
12511 use greentic_types::{
12512 RuntimeDispatchResponse, TenantCtx as DispatchTenantCtx, request_topic, response_topic,
12513 };
12514 use tokio::sync::Notify;
12515
12516 let nats_url = match std::env::var("GREENTIC_EVENTS_NATS_URL") {
12517 Ok(url) => url,
12518 Err(_) => {
12519 eprintln!(
12520 "skipping dw_agent_scale_to_zero_nats_e2e: GREENTIC_EVENTS_NATS_URL not set"
12521 );
12522 return;
12523 }
12524 };
12525
12526 let resume_id = NodeId::from_str("after-agent").unwrap();
12530 let agent_node_id = NodeId::from_str("agent-e2e").unwrap();
12531 let agent_node = Node {
12532 id: agent_node_id.clone(),
12533 component: FlowComponentRef {
12534 id: "dw.agent".parse().unwrap(),
12535 pack_alias: None,
12536 operation: Some("greeter".to_string()),
12537 },
12538 input: InputMapping {
12539 mapping: json!({ "user_text": "ping" }),
12540 },
12541 output: OutputMapping {
12542 mapping: Value::Null,
12543 },
12544 err_map: None,
12545 routing: Routing::Next {
12546 node_id: resume_id.clone(),
12547 },
12548 telemetry: TelemetryHints::default(),
12549 conversational: false,
12550 };
12551 let resume_node = Node {
12552 id: resume_id.clone(),
12553 component: FlowComponentRef {
12554 id: "emit.log".parse().unwrap(),
12555 pack_alias: None,
12556 operation: None,
12557 },
12558 input: InputMapping {
12559 mapping: json!({ "message": "resumed" }),
12560 },
12561 output: OutputMapping {
12562 mapping: Value::Null,
12563 },
12564 err_map: None,
12565 routing: Routing::End,
12566 telemetry: TelemetryHints::default(),
12567 conversational: false,
12568 };
12569 let mut nodes = indexmap::IndexMap::default();
12570 nodes.insert(agent_node_id.clone(), agent_node);
12571 nodes.insert(resume_id.clone(), resume_node);
12572 let flow = greentic_types::Flow {
12573 schema_version: "1.0".into(),
12574 id: greentic_types::FlowId::from_str("e2e-agent.flow").unwrap(),
12575 kind: greentic_types::FlowKind::Messaging,
12576 entrypoints: BTreeMap::from([(
12577 "default".to_string(),
12578 Value::String(agent_node_id.to_string()),
12579 )]),
12580 nodes,
12581 metadata: Default::default(),
12582 };
12583 let host_flow = HostFlow::from(flow);
12584
12585 let dispatcher_client = async_nats::connect(&nats_url)
12587 .await
12588 .expect("NATS: dispatcher client");
12589 let bridge_client = async_nats::connect(&nats_url)
12590 .await
12591 .expect("NATS: fake bridge client");
12592 let listener_client = async_nats::connect(&nats_url)
12593 .await
12594 .expect("NATS: response listener client");
12595
12596 let agentic_request_subject = request_topic("agentic");
12598 let agentic_response_subject = response_topic("agentic");
12599 let mut req_sub = bridge_client
12600 .subscribe(agentic_request_subject.clone())
12601 .await
12602 .expect("fake bridge: subscribe to agentic request subject");
12603 let bridge_reply_client = bridge_client.clone();
12604 let reply_subject = agentic_response_subject.clone();
12605 tokio::spawn(async move {
12606 while let Some(msg) = req_sub.next().await {
12607 let headers = msg.headers.as_ref();
12608 let get_hdr = |name: &str| {
12609 headers
12610 .and_then(|h| h.get(name))
12611 .map(|v| v.as_str().to_owned())
12612 .unwrap_or_default()
12613 };
12614 let correlation_id = get_hdr("Greentic-Correlation-Id");
12615 let tenant = get_hdr("Greentic-Tenant");
12616 let env = get_hdr("Greentic-Env");
12617
12618 let response_payload = RuntimeDispatchResponse {
12619 ok: true,
12620 output: json!({
12621 "reply": "pong",
12622 "trail": [],
12623 "terminated_by": "final_reply"
12624 }),
12625 events: vec![],
12626 error: None,
12627 };
12628 let body =
12629 serde_json::to_vec(&response_payload).expect("serialize fake bridge response");
12630
12631 let mut resp_headers = async_nats::HeaderMap::new();
12632 resp_headers.insert("Greentic-Correlation-Id", correlation_id.as_str());
12633 resp_headers.insert("Greentic-Tenant", tenant.as_str());
12634 resp_headers.insert("Greentic-Env", env.as_str());
12635
12636 bridge_reply_client
12637 .publish_with_headers(reply_subject.clone(), resp_headers, body.into())
12638 .await
12639 .expect("fake bridge: publish response");
12640 }
12641 });
12642
12643 struct RecordingResumer {
12645 calls: std::sync::Mutex<Vec<(String, Value)>>,
12646 notify: Notify,
12647 }
12648
12649 impl RecordingResumer {
12650 fn new() -> Self {
12651 Self {
12652 calls: std::sync::Mutex::new(vec![]),
12653 notify: Notify::new(),
12654 }
12655 }
12656 }
12657
12658 #[async_trait::async_trait]
12659 impl SessionResumer for RecordingResumer {
12660 async fn resume(
12661 &self,
12662 _tenant: DispatchTenantCtx,
12663 correlation_id: &str,
12664 output: Value,
12665 ) -> anyhow::Result<()> {
12666 self.calls
12667 .lock()
12668 .unwrap()
12669 .push((correlation_id.to_string(), output));
12670 self.notify.notify_one();
12671 Ok(())
12672 }
12673 }
12674
12675 let resumer = Arc::new(RecordingResumer::new());
12676 let resumer_for_listener = resumer.clone();
12677 tokio::spawn(async move {
12678 run_response_listener(listener_client, "agentic".to_owned(), resumer_for_listener)
12679 .await
12680 .expect("response listener exited unexpectedly");
12681 });
12682
12683 tokio::time::sleep(tokio::time::Duration::from_millis(150)).await;
12685
12686 let nats_engine_dispatcher = Arc::new(NatsDispatcher::new(dispatcher_client));
12688 let engine = FlowEngine {
12689 packs: Vec::new(),
12690 flows: Vec::new(),
12691 flow_sources: StdHashMap::new(),
12692 messaging_provider_pack_ids: std::collections::HashSet::new(),
12693 flow_cache: RwLock::new(StdHashMap::from([(
12694 FlowKey {
12695 pack_id: "e2e-pack".to_string(),
12696 flow_id: "e2e-agent.flow".to_string(),
12697 },
12698 host_flow,
12699 )])),
12700 default_env: "local".to_string(),
12701 validation: crate::validate::ValidationConfig {
12702 mode: crate::validate::ValidationMode::Off,
12703 },
12704 cross_pack_resolver: None,
12705 rollout_ids: RolloutIds::default(),
12706 approval_dispatch_handler: None,
12707 remote_dispatch_handler: Some(
12708 nats_engine_dispatcher
12709 as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
12710 ),
12711 dw_agent_dispatch: DwAgentDispatch::Nats,
12712 agent_node_handler: None,
12713 graph_node_handler: None,
12714 mcp_tool_source: None,
12715 mcp_secrets: None,
12716 #[cfg(feature = "agentic-worker")]
12717 a2a_sources: RwLock::new(HashMap::new()),
12718 #[cfg(feature = "agentic-worker")]
12719 ext_artifact_port: None,
12720 operala_node_handler: None,
12721 };
12722
12723 let ctx = FlowContext {
12724 tenant: "demo",
12725 pack_id: "e2e-pack",
12726 flow_id: "e2e-agent.flow",
12727 node_id: None,
12728 tool: None,
12729 action: None,
12730 session_id: Some("e2e-sess-1"),
12731 provider_id: None,
12732 reply_scope: None,
12733 retry_config: RetryConfig {
12734 max_attempts: 1,
12735 base_delay_ms: 1,
12736 },
12737 attempt: 1,
12738 observer: None,
12739 mocks: None,
12740 caller: None,
12741 };
12742
12743 let result = engine
12745 .execute(ctx, json!({ "user_text": "ping" }))
12746 .await
12747 .expect("engine.execute succeeded");
12748
12749 assert!(
12750 matches!(result.status, FlowStatus::Waiting(_)),
12751 "expected FlowStatus::Waiting from dw.agent Nats path, got: {:?}",
12752 result.status
12753 );
12754 eprintln!("dw.agent: flow paused (Waiting) — dispatch published to NATS");
12755
12756 let wait = tokio::time::timeout(
12758 tokio::time::Duration::from_secs(5),
12759 resumer.notify.notified(),
12760 )
12761 .await;
12762
12763 assert!(
12764 wait.is_ok(),
12765 "timed out waiting for fake bridge reply — is NATS running? ({nats_url})"
12766 );
12767
12768 let calls = resumer.calls.lock().unwrap();
12770 assert_eq!(
12771 calls.len(),
12772 1,
12773 "resumer should have been called exactly once"
12774 );
12775 let (ref _corr, ref output) = calls[0];
12776 assert_eq!(
12777 output["output"]["reply"],
12778 json!("pong"),
12779 "resumed reply must match the aw-serve canned reply"
12780 );
12781 eprintln!(
12782 "PASSED: dw.agent scale-to-zero NATS e2e — reply={:?}",
12783 output["output"]["reply"]
12784 );
12785 }
12786
12787 #[test]
12788 fn execution_state_vars_survive_serde_round_trip() {
12789 let mut st = ExecutionState::new(json!({}));
12791 st.vars.insert("counter".into(), json!(3));
12792 st.vars.insert("region".into(), json!("us-east-1"));
12793
12794 let encoded = serde_json::to_string(&st).expect("serialize");
12795 let decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
12796
12797 assert_eq!(decoded.vars.get("counter"), Some(&json!(3)));
12798 assert_eq!(decoded.vars.get("region"), Some(&json!("us-east-1")));
12799 }
12800
12801 #[test]
12802 fn execution_state_vars_default_empty_for_old_snapshots() {
12803 let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
12805 let decoded: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
12806 assert!(decoded.vars.is_empty());
12807 }
12808
12809 #[test]
12810 fn template_context_exposes_vars_namespace_typed() {
12811 let mut st = ExecutionState::new(serde_json::json!({}));
12812 st.vars.insert("count".into(), serde_json::json!(5));
12813 st.vars.insert("name".into(), serde_json::json!("aws"));
12814
12815 let ctx = template_context(&st, serde_json::Value::Null);
12816 let rendered_num = render_template_value(
12818 &serde_json::json!("{{vars.count}}"),
12819 &ctx,
12820 TemplateOptions::default(),
12821 )
12822 .expect("render num");
12823 assert_eq!(rendered_num, serde_json::json!(5));
12824
12825 let rendered_str = render_template_value(
12826 &serde_json::json!("prefix-{{vars.name}}"),
12827 &ctx,
12828 TemplateOptions::default(),
12829 )
12830 .expect("render str");
12831 assert_eq!(rendered_str, serde_json::json!("prefix-aws"));
12832 }
12833
12834 #[test]
12835 fn vars_namespace_does_not_shadow_existing_namespaces() {
12836 let st = ExecutionState::new(serde_json::json!({"user": {"id": 7}}));
12837 let ctx = template_context(&st, serde_json::Value::Null);
12838 let obj = ctx.as_object().expect("ctx object");
12839 for key in ["entry", "in", "prev", "node", "state", "vars", "now"] {
12840 assert!(obj.contains_key(key), "context must expose `{key}`");
12841 }
12842 }
12843
12844 fn fixed_instant() -> DateTime<Utc> {
12848 DateTime::parse_from_rfc3339("2026-09-09T10:53:04.250Z")
12849 .expect("a literal RFC3339 instant")
12850 .with_timezone(&Utc)
12851 }
12852
12853 #[test]
12854 fn now_namespace_carries_iso_epoch_ms_and_date() {
12855 let now = now_namespace(fixed_instant());
12856 assert_eq!(now["iso"], serde_json::json!("2026-09-09T10:53:04.250Z"));
12857 assert_eq!(now["epoch_ms"], serde_json::json!(1_788_951_184_250i64));
12858 assert_eq!(now["date"], serde_json::json!("2026-09-09"));
12859 }
12860
12861 #[test]
12865 fn a_node_config_can_render_a_timestamp_it_was_never_given() {
12866 let st = ExecutionState::new(serde_json::json!({}));
12867 let ctx = template_context(&st, serde_json::Value::Null);
12868
12869 let rendered = render_template_value(
12870 &serde_json::json!({ "hs_timestamp": "{{now.iso}}" }),
12871 &ctx,
12872 TemplateOptions::default(),
12873 )
12874 .expect("render");
12875
12876 let stamp = rendered["hs_timestamp"]
12877 .as_str()
12878 .expect("an ISO string, not an object");
12879 assert!(
12880 DateTime::parse_from_rfc3339(stamp).is_ok(),
12881 "`{stamp}` must parse as RFC3339 — an API rejecting it is the \
12882 failure this field exists to prevent"
12883 );
12884 }
12885
12886 #[test]
12890 fn epoch_ms_resolves_as_a_number_not_a_string() {
12891 let st = ExecutionState::new(serde_json::json!({}));
12892 let ctx = template_context(&st, serde_json::Value::Null);
12893
12894 let rendered = render_template_value(
12895 &serde_json::json!("{{now.epoch_ms}}"),
12896 &ctx,
12897 TemplateOptions::default(),
12898 )
12899 .expect("render");
12900
12901 assert!(
12902 rendered.is_i64(),
12903 "expected a JSON number, got {rendered:?}"
12904 );
12905 }
12906
12907 #[test]
12912 fn a_now_reference_no_longer_renders_as_the_empty_string() {
12913 let st = ExecutionState::new(serde_json::json!({}));
12914 let ctx = template_context(&st, serde_json::Value::Null);
12915
12916 for expression in ["{{now.iso}}", "{{now.date}}"] {
12917 let rendered = render_template_value(
12918 &serde_json::json!(expression),
12919 &ctx,
12920 TemplateOptions::default(),
12921 )
12922 .expect("render");
12923 assert_ne!(
12924 rendered,
12925 serde_json::json!(""),
12926 "`{expression}` must resolve to something"
12927 );
12928 }
12929 }
12930
12931 #[test]
12934 fn one_context_sees_a_single_instant() {
12935 let st = ExecutionState::new(serde_json::json!({}));
12936 let ctx = template_context(&st, serde_json::Value::Null);
12937
12938 let rendered = render_template_value(
12939 &serde_json::json!({ "a": "{{now.iso}}", "b": "{{now.iso}}" }),
12940 &ctx,
12941 TemplateOptions::default(),
12942 )
12943 .expect("render");
12944
12945 assert_eq!(rendered["a"], rendered["b"]);
12946 }
12947
12948 fn flow_with_extra(extra: serde_json::Value) -> Flow {
12954 Flow {
12955 schema_version: "1.0".into(),
12956 id: FlowId::from_str("test.flow").unwrap(),
12957 kind: FlowKind::Messaging,
12958 entrypoints: BTreeMap::new(),
12959 nodes: indexmap::IndexMap::default(),
12960 metadata: FlowMetadata {
12961 title: None,
12962 description: None,
12963 tags: Default::default(),
12964 extra,
12965 },
12966 }
12967 }
12968
12969 #[test]
12970 fn seed_vars_seeds_defaults_and_reports_missing_required() {
12971 use serde_json::json;
12972 let mut vars_init = JsonMap::new();
12973 vars_init.insert("region".into(), json!("us-east-1"));
12974
12975 let required = vec!["name".to_string(), "region".to_string()];
12977 let mut target = JsonMap::new();
12978
12979 let missing = seed_vars_and_collect_missing_required(&vars_init, &required, &mut target);
12980
12981 assert_eq!(
12982 target.get("region"),
12983 Some(&json!("us-east-1")),
12984 "default seeded"
12985 );
12986 assert_eq!(
12987 missing,
12988 vec!["name".to_string()],
12989 "only the defaultless required var is missing"
12990 );
12991 }
12992
12993 #[test]
12994 fn seed_vars_respects_preexisting_value_for_required() {
12995 use serde_json::json;
12996 let vars_init = JsonMap::new(); let required = vec!["name".to_string()];
12998 let mut target = JsonMap::new();
12999 target.insert("name".into(), json!("Budi")); let missing = seed_vars_and_collect_missing_required(&vars_init, &required, &mut target);
13002
13003 assert!(
13004 missing.is_empty(),
13005 "a required var with a provided value is not missing"
13006 );
13007 assert_eq!(
13008 target.get("name"),
13009 Some(&json!("Budi")),
13010 "provided value not overwritten"
13011 );
13012 }
13013
13014 #[test]
13015 fn from_flow_extracts_vars_init() {
13016 let flow = flow_with_extra(serde_json::json!({
13017 "vars_init": {
13018 "region": { "type": "string", "default": "us-east-1" },
13019 "counter": { "type": "number", "default": 0 }
13020 }
13021 }));
13022 let host: HostFlow = HostFlow::from(flow);
13023 assert_eq!(
13024 host.vars_init.get("region"),
13025 Some(&serde_json::json!("us-east-1"))
13026 );
13027 assert_eq!(host.vars_init.get("counter"), Some(&serde_json::json!(0)));
13028 }
13029
13030 #[test]
13031 fn from_flow_vars_init_absent() {
13032 let flow = flow_with_extra(serde_json::json!({}));
13033 let host: HostFlow = HostFlow::from(flow);
13034 assert!(host.vars_init.is_empty());
13035 }
13036
13037 #[test]
13038 fn from_flow_collects_required_vars() {
13039 let flow = flow_with_extra(serde_json::json!({
13040 "vars_init": {
13041 "name": { "type": "string", "required": true },
13042 "region": { "type": "string", "default": "us-east-1" },
13043 "note": { "type": "string", "required": false }
13044 }
13045 }));
13046 let host: HostFlow = HostFlow::from(flow);
13047 assert_eq!(host.required_vars, vec!["name".to_string()]);
13048 }
13049
13050 #[test]
13051 fn execute_once_fails_on_missing_required_var() {
13052 let node_id = NodeId::from_str("n1").unwrap();
13053 let node = Node {
13054 id: node_id.clone(),
13055 component: FlowComponentRef {
13056 id: "emit.log".parse().unwrap(),
13057 pack_alias: None,
13058 operation: None,
13059 },
13060 input: InputMapping {
13061 mapping: json!({ "message": "{{vars.region}}" }),
13062 },
13063 output: OutputMapping {
13064 mapping: Value::Null,
13065 },
13066 err_map: None,
13067 routing: Routing::End,
13068 telemetry: TelemetryHints::default(),
13069 conversational: false,
13070 };
13071 let mut nodes = indexmap::IndexMap::default();
13072 nodes.insert(node_id.clone(), node);
13073 let flow = Flow {
13074 schema_version: "1.0".into(),
13075 id: FlowId::from_str("vars.flow").unwrap(),
13076 kind: FlowKind::Messaging,
13077 entrypoints: BTreeMap::from([(
13078 "default".to_string(),
13079 Value::String(node_id.to_string()),
13080 )]),
13081 nodes,
13082 metadata: FlowMetadata {
13083 title: None,
13084 description: None,
13085 tags: Default::default(),
13086 extra: json!({
13087 "vars_init": {
13088 "region": { "type": "string", "required": true }
13089 }
13090 }),
13091 },
13092 };
13093 let host_flow = HostFlow::from(flow);
13094
13095 let engine = FlowEngine {
13096 messaging_provider_pack_ids: Default::default(),
13097 rollout_ids: RolloutIds::default(),
13098 packs: Vec::new(),
13099 flows: Vec::new(),
13100 flow_sources: HashMap::new(),
13101 flow_cache: RwLock::new(HashMap::from([(
13102 FlowKey {
13103 pack_id: "test-pack".to_string(),
13104 flow_id: "vars.flow".to_string(),
13105 },
13106 host_flow,
13107 )])),
13108 default_env: "local".to_string(),
13109 validation: ValidationConfig {
13110 mode: ValidationMode::Off,
13111 },
13112 cross_pack_resolver: None,
13113 approval_dispatch_handler: None,
13114 remote_dispatch_handler: None,
13115 #[cfg(feature = "agentic-worker")]
13116 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13117 #[cfg(feature = "agentic-worker")]
13118 agent_node_handler: None,
13119 #[cfg(feature = "agentic-worker")]
13120 graph_node_handler: None,
13121 #[cfg(feature = "agentic-worker")]
13122 mcp_tool_source: None,
13123 #[cfg(feature = "agentic-worker")]
13124 mcp_secrets: None,
13125 #[cfg(feature = "agentic-worker")]
13126 a2a_sources: RwLock::new(HashMap::new()),
13127 #[cfg(feature = "agentic-worker")]
13128 ext_artifact_port: None,
13129 operala_node_handler: None,
13130 };
13131
13132 let observer = CountingObserver::new();
13133 let ctx = FlowContext {
13134 tenant: "demo",
13135 pack_id: "test-pack",
13136 flow_id: "vars.flow",
13137 node_id: None,
13138 tool: None,
13139 action: None,
13140 session_id: None,
13141 provider_id: None,
13142 reply_scope: None,
13143 retry_config: RetryConfig {
13144 max_attempts: 1,
13145 base_delay_ms: 1,
13146 },
13147 attempt: 1,
13148 observer: Some(&observer),
13149 mocks: None,
13150 caller: None,
13151 };
13152
13153 let rt = Runtime::new().unwrap();
13154 let err = rt
13155 .block_on(engine.execute(ctx, Value::Null))
13156 .expect_err("a required var with no default and no value must fail the run");
13157 let msg = err.to_string();
13158 assert!(msg.contains("region"), "error names the missing var: {msg}");
13159 assert!(
13160 !should_retry(&err),
13161 "missing-required-var is deterministic and must not be retried"
13162 );
13163 assert!(
13164 observer.ends.lock().unwrap().is_empty(),
13165 "flow aborted before the node ran"
13166 );
13167 }
13168
13169 #[test]
13170 fn execute_once_seeds_declared_vars() {
13171 let node_id = NodeId::from_str("n1").unwrap();
13176 let node = Node {
13177 id: node_id.clone(),
13178 component: FlowComponentRef {
13179 id: "emit.log".parse().unwrap(),
13180 pack_alias: None,
13181 operation: None,
13182 },
13183 input: InputMapping {
13184 mapping: json!({ "message": "{{vars.region}}" }),
13185 },
13186 output: OutputMapping {
13187 mapping: Value::Null,
13188 },
13189 err_map: None,
13190 routing: Routing::End,
13191 telemetry: TelemetryHints::default(),
13192 conversational: false,
13193 };
13194 let mut nodes = indexmap::IndexMap::default();
13195 nodes.insert(node_id.clone(), node);
13196 let flow = Flow {
13197 schema_version: "1.0".into(),
13198 id: FlowId::from_str("vars.flow").unwrap(),
13199 kind: FlowKind::Messaging,
13200 entrypoints: BTreeMap::from([(
13201 "default".to_string(),
13202 Value::String(node_id.to_string()),
13203 )]),
13204 nodes,
13205 metadata: FlowMetadata {
13206 title: None,
13207 description: None,
13208 tags: Default::default(),
13209 extra: json!({
13210 "vars_init": {
13211 "region": { "type": "string", "default": "us-east-1" }
13212 }
13213 }),
13214 },
13215 };
13216 let host_flow = HostFlow::from(flow);
13217
13218 let engine = FlowEngine {
13219 messaging_provider_pack_ids: Default::default(),
13220 rollout_ids: RolloutIds::default(),
13221 packs: Vec::new(),
13222 flows: Vec::new(),
13223 flow_sources: HashMap::new(),
13224 flow_cache: RwLock::new(HashMap::from([(
13225 FlowKey {
13226 pack_id: "test-pack".to_string(),
13227 flow_id: "vars.flow".to_string(),
13228 },
13229 host_flow,
13230 )])),
13231 default_env: "local".to_string(),
13232 validation: ValidationConfig {
13233 mode: ValidationMode::Off,
13234 },
13235 cross_pack_resolver: None,
13236 approval_dispatch_handler: None,
13237 remote_dispatch_handler: None,
13238 #[cfg(feature = "agentic-worker")]
13239 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13240 #[cfg(feature = "agentic-worker")]
13241 agent_node_handler: None,
13242 #[cfg(feature = "agentic-worker")]
13243 graph_node_handler: None,
13244 #[cfg(feature = "agentic-worker")]
13245 mcp_tool_source: None,
13246 #[cfg(feature = "agentic-worker")]
13247 mcp_secrets: None,
13248 #[cfg(feature = "agentic-worker")]
13249 a2a_sources: RwLock::new(HashMap::new()),
13250 #[cfg(feature = "agentic-worker")]
13251 ext_artifact_port: None,
13252 operala_node_handler: None,
13253 };
13254
13255 let observer = CountingObserver::new();
13256 let ctx = FlowContext {
13257 tenant: "demo",
13258 pack_id: "test-pack",
13259 flow_id: "vars.flow",
13260 node_id: None,
13261 tool: None,
13262 action: None,
13263 session_id: None,
13264 provider_id: None,
13265 reply_scope: None,
13266 retry_config: RetryConfig {
13267 max_attempts: 1,
13268 base_delay_ms: 1,
13269 },
13270 attempt: 1,
13271 observer: Some(&observer),
13272 mocks: None,
13273 caller: None,
13274 };
13275
13276 let rt = Runtime::new().unwrap();
13277 let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
13278 assert!(matches!(result.status, FlowStatus::Completed));
13279
13280 let ends = observer.ends.lock().unwrap();
13281 assert_eq!(ends.len(), 1);
13282 assert_eq!(
13283 ends[0].get("message").and_then(Value::as_str),
13284 Some("us-east-1"),
13285 "vars.region must be seeded to its default and rendered in the node payload"
13286 );
13287 }
13288
13289 fn var_set_flow(
13298 var_set_input: Value,
13299 emit_input: Value,
13300 vars_init_extra: Option<Value>,
13301 ) -> Flow {
13302 let set_id = NodeId::from_str("set1").unwrap();
13303 let emit_id = NodeId::from_str("emit1").unwrap();
13304
13305 let set_node = Node {
13306 id: set_id.clone(),
13307 component: FlowComponentRef {
13308 id: "var.set".parse().unwrap(),
13309 pack_alias: None,
13310 operation: None,
13311 },
13312 input: InputMapping {
13313 mapping: var_set_input,
13314 },
13315 output: OutputMapping {
13316 mapping: Value::Null,
13317 },
13318 err_map: None,
13319 routing: Routing::Next {
13320 node_id: emit_id.clone(),
13321 },
13322 telemetry: TelemetryHints::default(),
13323 conversational: false,
13324 };
13325
13326 let emit_node = Node {
13327 id: emit_id.clone(),
13328 component: FlowComponentRef {
13329 id: "emit.log".parse().unwrap(),
13330 pack_alias: None,
13331 operation: None,
13332 },
13333 input: InputMapping {
13334 mapping: emit_input,
13335 },
13336 output: OutputMapping {
13337 mapping: Value::Null,
13338 },
13339 err_map: None,
13340 routing: Routing::End,
13341 telemetry: TelemetryHints::default(),
13342 conversational: false,
13343 };
13344
13345 let mut nodes = indexmap::IndexMap::default();
13346 nodes.insert(set_id.clone(), set_node);
13347 nodes.insert(emit_id.clone(), emit_node);
13348
13349 let extra = vars_init_extra.unwrap_or(serde_json::json!({}));
13350
13351 Flow {
13352 schema_version: "1.0".into(),
13353 id: FlowId::from_str("var.set.flow").unwrap(),
13354 kind: FlowKind::Messaging,
13355 entrypoints: BTreeMap::from([(
13356 "default".to_string(),
13357 Value::String(set_id.to_string()),
13358 )]),
13359 nodes,
13360 metadata: FlowMetadata {
13361 title: None,
13362 description: None,
13363 tags: Default::default(),
13364 extra,
13365 },
13366 }
13367 }
13368
13369 fn run_var_set_flow(flow: Flow) -> (FlowStatus, Vec<Value>) {
13370 let host_flow = HostFlow::from(flow);
13371 let engine = FlowEngine {
13372 messaging_provider_pack_ids: Default::default(),
13373 rollout_ids: RolloutIds::default(),
13374 packs: Vec::new(),
13375 flows: Vec::new(),
13376 flow_sources: StdHashMap::new(),
13377 flow_cache: RwLock::new(StdHashMap::from([(
13378 FlowKey {
13379 pack_id: "test-pack".to_string(),
13380 flow_id: "var.set.flow".to_string(),
13381 },
13382 host_flow,
13383 )])),
13384 default_env: "local".to_string(),
13385 validation: ValidationConfig {
13386 mode: ValidationMode::Off,
13387 },
13388 cross_pack_resolver: None,
13389 approval_dispatch_handler: None,
13390 remote_dispatch_handler: None,
13391 #[cfg(feature = "agentic-worker")]
13392 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13393 #[cfg(feature = "agentic-worker")]
13394 agent_node_handler: None,
13395 #[cfg(feature = "agentic-worker")]
13396 graph_node_handler: None,
13397 #[cfg(feature = "agentic-worker")]
13398 mcp_tool_source: None,
13399 #[cfg(feature = "agentic-worker")]
13400 mcp_secrets: None,
13401 #[cfg(feature = "agentic-worker")]
13402 a2a_sources: RwLock::new(HashMap::new()),
13403 #[cfg(feature = "agentic-worker")]
13404 ext_artifact_port: None,
13405 operala_node_handler: None,
13406 };
13407 let observer = CountingObserver::new();
13408 let ctx = FlowContext {
13409 tenant: "demo",
13410 pack_id: "test-pack",
13411 flow_id: "var.set.flow",
13412 node_id: None,
13413 tool: None,
13414 action: None,
13415 session_id: None,
13416 provider_id: None,
13417 reply_scope: None,
13418 retry_config: RetryConfig {
13419 max_attempts: 1,
13420 base_delay_ms: 1,
13421 },
13422 attempt: 1,
13423 observer: Some(&observer),
13424 mocks: None,
13425 caller: None,
13426 };
13427 let rt = Runtime::new().unwrap();
13428 let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
13429 let ends = observer.ends.lock().unwrap().clone();
13430 (result.status, ends)
13431 }
13432
13433 #[test]
13434 fn var_set_node_writes_literal_value_into_vars() {
13435 let flow = var_set_flow(
13439 json!({ "name": "greeting", "value": "hi" }),
13440 json!({ "message": "{{vars.greeting}}" }),
13441 None,
13442 );
13443 let (status, ends) = run_var_set_flow(flow);
13444
13445 assert!(
13446 matches!(status, FlowStatus::Completed),
13447 "flow must complete"
13448 );
13449 assert_eq!(ends.len(), 2, "both nodes must fire");
13450 assert_eq!(ends[0].get("ok"), Some(&json!(true)), "var_set output ok");
13452 assert_eq!(
13454 ends[1].get("message").and_then(Value::as_str),
13455 Some("hi"),
13456 "vars.greeting must be written and renderable in the next node"
13457 );
13458 }
13459
13460 #[test]
13461 fn var_set_node_writes_templated_value_with_type_preserved() {
13462 let flow = var_set_flow(
13467 json!({ "name": "copy", "value": "{{vars.counter}}" }),
13468 json!({ "message": "{{vars.copy}}" }),
13469 Some(json!({
13470 "vars_init": {
13471 "counter": { "type": "number", "default": 1 }
13472 }
13473 })),
13474 );
13475 let (status, ends) = run_var_set_flow(flow);
13476
13477 assert!(
13478 matches!(status, FlowStatus::Completed),
13479 "flow must complete"
13480 );
13481 assert_eq!(ends.len(), 2, "both nodes must fire");
13482 assert_eq!(
13484 ends[1].get("message"),
13485 Some(&json!(1)),
13486 "vars.copy must preserve the JSON number type from vars.counter"
13487 );
13488 }
13489
13490 #[test]
13491 fn var_set_empty_name_is_skipped_not_written() {
13492 let engine = minimal_engine();
13495 let rt = Runtime::new().unwrap();
13496 let retry_config = RetryConfig {
13497 max_attempts: 1,
13498 base_delay_ms: 1,
13499 };
13500 let ctx = FlowContext {
13501 tenant: "demo",
13502 pack_id: "test-pack",
13503 flow_id: "var.set.flow",
13504 node_id: Some("set1"),
13505 tool: None,
13506 action: None,
13507 session_id: None,
13508 provider_id: None,
13509 reply_scope: None,
13510 retry_config,
13511 attempt: 1,
13512 observer: None,
13513 mocks: None,
13514 caller: None,
13515 };
13516 let node = HostNode {
13517 kind: NodeKind::VarSet {
13518 name: "".to_string(),
13519 value: json!("garbage"),
13520 },
13521 component: "var.set".into(),
13522 component_id: "var.set".into(),
13523 operation_name: None,
13524 operation_in_mapping: None,
13525 payload_expr: Value::Null,
13526 routing: Routing::End,
13527 vars_out: None,
13528 response_timeout_secs: None,
13529 };
13530 let mut state = ExecutionState::new(Value::Null);
13531 let payload = Value::Null;
13532 let event = NodeEvent {
13533 context: &ctx,
13534 node_id: "set1",
13535 node: &node,
13536 payload: &payload,
13537 };
13538
13539 let outcome = rt
13540 .block_on(engine.dispatch_node(
13541 &ctx,
13542 "set1",
13543 &node,
13544 &mut state,
13545 payload.clone(),
13546 &event,
13547 ))
13548 .expect("dispatch_node must not error on empty var name");
13549
13550 assert_eq!(
13552 outcome.output.payload,
13553 json!({ "ok": true }),
13554 "dispatch must return ok:true even when name is empty"
13555 );
13556 assert!(
13558 state.vars.get("").is_none(),
13559 "empty var name must not create a \"\" key in state.vars"
13560 );
13561 }
13562
13563 #[test]
13564 fn var_set_node_has_empty_payload_expr() {
13565 let node_id = NodeId::from_str("set1").unwrap();
13569 let node = Node {
13570 id: node_id.clone(),
13571 component: FlowComponentRef {
13572 id: "var.set".parse().unwrap(),
13573 pack_alias: None,
13574 operation: None,
13575 },
13576 input: InputMapping {
13577 mapping: json!({ "name": "greeting", "value": "hi" }),
13578 },
13579 output: OutputMapping {
13580 mapping: Value::Null,
13581 },
13582 err_map: None,
13583 routing: Routing::End,
13584 telemetry: TelemetryHints::default(),
13585 conversational: false,
13586 };
13587
13588 let host_node = HostNode::from(node);
13589
13590 assert_eq!(
13592 host_node.payload_expr,
13593 Value::Null,
13594 "var.set node must have Null payload_expr after lowering"
13595 );
13596 match &host_node.kind {
13598 NodeKind::VarSet { name, value } => {
13599 assert_eq!(name.as_str(), "greeting", "name must be preserved in kind");
13600 assert_eq!(value, &json!("hi"), "value must be preserved in kind");
13601 }
13602 other => panic!("expected NodeKind::VarSet, got {other:?}"),
13603 }
13604 }
13605
13606 fn vars_out_flow(emit1_input: Value, emit2_input: Value) -> Flow {
13615 let emit1_id = NodeId::from_str("emit1").unwrap();
13616 let emit2_id = NodeId::from_str("emit2").unwrap();
13617
13618 let emit1_node = Node {
13619 id: emit1_id.clone(),
13620 component: FlowComponentRef {
13621 id: "emit.log".parse().unwrap(),
13622 pack_alias: None,
13623 operation: None,
13624 },
13625 input: InputMapping {
13626 mapping: emit1_input,
13627 },
13628 output: OutputMapping {
13629 mapping: Value::Null,
13630 },
13631 err_map: None,
13632 routing: Routing::Next {
13633 node_id: emit2_id.clone(),
13634 },
13635 telemetry: TelemetryHints::default(),
13636 conversational: false,
13637 };
13638
13639 let emit2_node = Node {
13640 id: emit2_id.clone(),
13641 component: FlowComponentRef {
13642 id: "emit.log".parse().unwrap(),
13643 pack_alias: None,
13644 operation: None,
13645 },
13646 input: InputMapping {
13647 mapping: emit2_input,
13648 },
13649 output: OutputMapping {
13650 mapping: Value::Null,
13651 },
13652 err_map: None,
13653 routing: Routing::End,
13654 telemetry: TelemetryHints::default(),
13655 conversational: false,
13656 };
13657
13658 let mut nodes = indexmap::IndexMap::default();
13659 nodes.insert(emit1_id.clone(), emit1_node);
13660 nodes.insert(emit2_id.clone(), emit2_node);
13661
13662 Flow {
13665 schema_version: "1.0".into(),
13666 id: FlowId::from_str("var.set.flow").unwrap(),
13667 kind: FlowKind::Messaging,
13668 entrypoints: BTreeMap::from([(
13669 "default".to_string(),
13670 Value::String(emit1_id.to_string()),
13671 )]),
13672 nodes,
13673 metadata: FlowMetadata {
13674 title: None,
13675 description: None,
13676 tags: Default::default(),
13677 extra: serde_json::json!({}),
13678 },
13679 }
13680 }
13681
13682 #[test]
13683 fn vars_out_binds_node_output_into_vars() {
13684 let flow = vars_out_flow(
13690 json!({
13691 "message": "hello",
13692 "vars_out": { "lastReply": "{{prev.message}}" }
13693 }),
13694 json!({ "message": "{{vars.lastReply}}" }),
13695 );
13696 let (status, ends) = run_var_set_flow(flow);
13697
13698 assert!(
13699 matches!(status, FlowStatus::Completed),
13700 "flow must complete"
13701 );
13702 assert_eq!(ends.len(), 2, "both nodes must fire");
13703 assert_eq!(
13705 ends[1].get("message").and_then(Value::as_str),
13706 Some("hello"),
13707 "vars_out binding from node 1 must be readable in node 2"
13708 );
13709 }
13710
13711 #[test]
13712 fn vars_out_is_stripped_from_component_node_payload() {
13713 let node_id = NodeId::from_str("comp1").unwrap();
13721 let node = Node {
13722 id: node_id.clone(),
13723 component: FlowComponentRef {
13724 id: "my.component".parse().unwrap(),
13725 pack_alias: None,
13726 operation: None,
13727 },
13728 input: InputMapping {
13729 mapping: json!({
13730 "message": "hello",
13731 "vars_out": { "lastReply": "{{prev.message}}" }
13732 }),
13733 },
13734 output: OutputMapping {
13735 mapping: Value::Null,
13736 },
13737 err_map: None,
13738 routing: Routing::End,
13739 telemetry: TelemetryHints::default(),
13740 conversational: false,
13741 };
13742
13743 let host_node = HostNode::from(node);
13744
13745 assert!(
13747 host_node.vars_out.is_some(),
13748 "vars_out binding must be carried on the HostNode"
13749 );
13750 assert!(
13751 host_node
13752 .vars_out
13753 .as_ref()
13754 .unwrap()
13755 .contains_key("lastReply"),
13756 "vars_out must contain the declared binding"
13757 );
13758
13759 assert!(
13761 host_node.payload_expr.get("vars_out").is_none(),
13762 "vars_out must not appear in payload_expr (would leak to wasm component input)"
13763 );
13764
13765 assert_eq!(
13767 host_node
13768 .payload_expr
13769 .get("message")
13770 .and_then(Value::as_str),
13771 Some("hello"),
13772 "real input fields must remain in payload_expr"
13773 );
13774 }
13775
13776 #[test]
13777 fn dotted_component_id_is_not_split_when_mapping_carries_operation() {
13778 let node_id = NodeId::from_str("present_koncar").unwrap();
13785 let node = Node {
13786 id: node_id,
13787 component: FlowComponentRef {
13788 id: "ai.greentic.koncar.component-present".parse().unwrap(),
13789 pack_alias: None,
13790 operation: None,
13791 },
13792 input: InputMapping {
13793 mapping: json!({
13794 "component": "ai.greentic.koncar.component-present",
13795 "operation": "present",
13796 "query": "hello"
13797 }),
13798 },
13799 output: OutputMapping {
13800 mapping: Value::Null,
13801 },
13802 err_map: None,
13803 routing: Routing::End,
13804 telemetry: TelemetryHints::default(),
13805 conversational: false,
13806 };
13807
13808 let host_node = HostNode::from(node);
13809
13810 assert_eq!(
13811 host_node.component_id(),
13812 "ai.greentic.koncar.component-present",
13813 "dotted component id must survive lowering intact"
13814 );
13815 match &host_node.kind {
13816 NodeKind::PackComponent { component_ref } => assert_eq!(
13817 component_ref, "ai.greentic.koncar.component-present",
13818 "PackComponent must look up the full id, not a dot-split prefix"
13819 ),
13820 other => panic!("expected NodeKind::PackComponent, got {other:?}"),
13821 }
13822 assert_eq!(
13823 host_node.operation_in_mapping(),
13824 Some("present"),
13825 "the operation must still be readable from the mapping"
13826 );
13827 }
13828
13829 fn vars_survive_flow() -> Flow {
13833 let set_id = NodeId::from_str("set1").unwrap();
13834 let wait_id = NodeId::from_str("wait1").unwrap();
13835 let emit_id = NodeId::from_str("emit1").unwrap();
13836
13837 let set_node = Node {
13838 id: set_id.clone(),
13839 component: FlowComponentRef {
13840 id: "var.set".parse().unwrap(),
13841 pack_alias: None,
13842 operation: None,
13843 },
13844 input: InputMapping {
13845 mapping: json!({ "name": "greeting", "value": "hello" }),
13846 },
13847 output: OutputMapping {
13848 mapping: Value::Null,
13849 },
13850 err_map: None,
13851 routing: Routing::Next {
13852 node_id: wait_id.clone(),
13853 },
13854 telemetry: TelemetryHints::default(),
13855 conversational: false,
13856 };
13857
13858 let wait_node = Node {
13859 id: wait_id.clone(),
13860 component: FlowComponentRef {
13861 id: "session.wait".parse().unwrap(),
13862 pack_alias: None,
13863 operation: None,
13864 },
13865 input: InputMapping {
13866 mapping: Value::Null,
13867 },
13868 output: OutputMapping {
13869 mapping: Value::Null,
13870 },
13871 err_map: None,
13872 routing: Routing::Next {
13873 node_id: emit_id.clone(),
13874 },
13875 telemetry: TelemetryHints::default(),
13876 conversational: false,
13877 };
13878
13879 let emit_node = Node {
13880 id: emit_id.clone(),
13881 component: FlowComponentRef {
13882 id: "emit.log".parse().unwrap(),
13883 pack_alias: None,
13884 operation: None,
13885 },
13886 input: InputMapping {
13887 mapping: json!({
13888 "greeting": "{{vars.greeting}}",
13889 "counter": "{{vars.counter}}"
13890 }),
13891 },
13892 output: OutputMapping {
13893 mapping: Value::Null,
13894 },
13895 err_map: None,
13896 routing: Routing::End,
13897 telemetry: TelemetryHints::default(),
13898 conversational: false,
13899 };
13900
13901 let mut nodes = indexmap::IndexMap::default();
13902 nodes.insert(set_id.clone(), set_node);
13903 nodes.insert(wait_id.clone(), wait_node);
13904 nodes.insert(emit_id.clone(), emit_node);
13905
13906 Flow {
13907 schema_version: "1.0".into(),
13908 id: FlowId::from_str("vars.survive.flow").unwrap(),
13909 kind: FlowKind::Messaging,
13910 entrypoints: BTreeMap::from([(
13911 "default".to_string(),
13912 Value::String(set_id.to_string()),
13913 )]),
13914 nodes,
13915 metadata: FlowMetadata {
13916 title: None,
13917 description: None,
13918 tags: Default::default(),
13919 extra: json!({
13920 "vars_init": {
13921 "counter": { "type": "number", "default": 1 }
13922 }
13923 }),
13924 },
13925 }
13926 }
13927
13928 #[test]
13929 fn vars_survive_park_and_resume_end_to_end() {
13930 let flow = vars_survive_flow();
13933 let host_flow = HostFlow::from(flow);
13934 let flow_id = "vars.survive.flow";
13935 let pack_id = "test-pack";
13936 let engine = FlowEngine {
13937 messaging_provider_pack_ids: Default::default(),
13938 rollout_ids: RolloutIds::default(),
13939 packs: Vec::new(),
13940 flows: Vec::new(),
13941 flow_sources: StdHashMap::new(),
13942 flow_cache: RwLock::new(StdHashMap::from([(
13943 FlowKey {
13944 pack_id: pack_id.to_string(),
13945 flow_id: flow_id.to_string(),
13946 },
13947 host_flow,
13948 )])),
13949 default_env: "local".to_string(),
13950 validation: ValidationConfig {
13951 mode: ValidationMode::Off,
13952 },
13953 cross_pack_resolver: None,
13954 approval_dispatch_handler: None,
13955 remote_dispatch_handler: None,
13956 #[cfg(feature = "agentic-worker")]
13957 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13958 #[cfg(feature = "agentic-worker")]
13959 agent_node_handler: None,
13960 #[cfg(feature = "agentic-worker")]
13961 graph_node_handler: None,
13962 #[cfg(feature = "agentic-worker")]
13963 mcp_tool_source: None,
13964 #[cfg(feature = "agentic-worker")]
13965 mcp_secrets: None,
13966 #[cfg(feature = "agentic-worker")]
13967 a2a_sources: RwLock::new(HashMap::new()),
13968 #[cfg(feature = "agentic-worker")]
13969 ext_artifact_port: None,
13970 operala_node_handler: None,
13971 };
13972 let rt = Runtime::new().unwrap();
13973
13974 let ctx1 = FlowContext {
13976 tenant: "demo",
13977 pack_id,
13978 flow_id,
13979 node_id: None,
13980 tool: None,
13981 action: None,
13982 session_id: None,
13983 provider_id: None,
13984 reply_scope: None,
13985 retry_config: RetryConfig {
13986 max_attempts: 1,
13987 base_delay_ms: 1,
13988 },
13989 attempt: 1,
13990 observer: None,
13991 mocks: None,
13992 caller: None,
13993 };
13994 let result1 = rt.block_on(engine.execute(ctx1, Value::Null)).unwrap();
13995 let snapshot = match result1.status {
13996 FlowStatus::Waiting(w) => w.snapshot,
13997 other => panic!("expected Waiting after session.wait, got {other:?}"),
13998 };
13999
14000 assert_eq!(
14002 snapshot.state.vars.get("greeting"),
14003 Some(&json!("hello")),
14004 "greeting var must be in snapshot"
14005 );
14006 assert_eq!(
14007 snapshot.state.vars.get("counter"),
14008 Some(&json!(1)),
14009 "counter var (from vars_init) must be in snapshot"
14010 );
14011
14012 let observer2 = CountingObserver::new();
14014 let ctx2 = FlowContext {
14015 tenant: "demo",
14016 pack_id,
14017 flow_id,
14018 node_id: None,
14019 tool: None,
14020 action: None,
14021 session_id: None,
14022 provider_id: None,
14023 reply_scope: None,
14024 retry_config: RetryConfig {
14025 max_attempts: 1,
14026 base_delay_ms: 1,
14027 },
14028 attempt: 1,
14029 observer: Some(&observer2),
14030 mocks: None,
14031 caller: None,
14032 };
14033 let result2 = rt
14034 .block_on(engine.resume(ctx2, snapshot, Value::Null))
14035 .unwrap();
14036 assert!(
14037 matches!(result2.status, FlowStatus::Completed),
14038 "flow must complete after resume"
14039 );
14040 let ends2 = observer2.ends.lock().unwrap().clone();
14041 assert_eq!(ends2.len(), 1, "only emit.log fires after resume");
14042 assert_eq!(
14043 ends2[0].get("greeting").and_then(Value::as_str),
14044 Some("hello"),
14045 "vars.greeting must survive the park/resume"
14046 );
14047 assert_eq!(
14048 ends2[0].get("counter"),
14049 Some(&json!(1)),
14050 "vars.counter (vars_init) must survive the park/resume"
14051 );
14052 }
14053
14054 #[cfg(feature = "agentic-worker")]
14055 struct StubAgentHandler {
14056 payload: serde_json::Value,
14057 }
14058 #[cfg(feature = "agentic-worker")]
14059 #[async_trait::async_trait]
14060 impl crate::runner::agent_node::AgentNodeHandler for StubAgentHandler {
14061 async fn execute(
14062 &self,
14063 _tenant_id: &str,
14064 _env_id: &str,
14065 _agent_id: &str,
14066 _session_id: &str,
14067 _flow_input: &serde_json::Value,
14068 _conversational: bool,
14069 _caller: Option<&serde_json::Value>,
14070 ) -> anyhow::Result<serde_json::Value> {
14071 Ok(self.payload.clone())
14072 }
14073 }
14074
14075 #[cfg(feature = "agentic-worker")]
14078 fn conversational_dw_flow(conversational: bool) -> HostFlow {
14079 let mut nodes = IndexMap::new();
14080 let agent_id = NodeId::from_str("agent").unwrap();
14081 let thanks_id = NodeId::from_str("thanks").unwrap();
14082 nodes.insert(
14083 agent_id.clone(),
14084 HostNode {
14085 kind: NodeKind::DwAgent {
14086 agent_id: "a".to_string(),
14087 conversational,
14088 },
14089 component: "dw.agent".to_string(),
14090 component_id: "dw.agent".to_string(),
14091 operation_name: Some("a".to_string()),
14092 operation_in_mapping: None,
14093 payload_expr: json!({ "user_text": "hi" }),
14094 routing: Routing::Next {
14095 node_id: thanks_id.clone(),
14096 },
14097 vars_out: None,
14098 response_timeout_secs: None,
14099 },
14100 );
14101 nodes.insert(
14102 thanks_id.clone(),
14103 HostNode {
14104 kind: NodeKind::BuiltinEmit {
14105 kind: EmitKind::Response,
14106 },
14107 component: "emit.response".to_string(),
14108 component_id: "emit.response".to_string(),
14109 operation_name: None,
14110 operation_in_mapping: None,
14111 payload_expr: json!({ "text": "thanks" }),
14112 routing: Routing::End,
14113 vars_out: None,
14114 response_timeout_secs: None,
14115 },
14116 );
14117 HostFlow {
14118 slot_schema: None,
14119 id: "conv.flow".to_string(),
14120 start: Some(agent_id),
14121 nodes,
14122 vars_init: JsonMap::new(),
14123 required_vars: Vec::new(),
14124 }
14125 }
14126
14127 #[cfg(feature = "agentic-worker")]
14130 fn conv_engine(flow: HostFlow, payload: serde_json::Value) -> FlowEngine {
14131 conv_engine_with(flow, std::sync::Arc::new(StubAgentHandler { payload }))
14132 }
14133
14134 #[cfg(feature = "agentic-worker")]
14136 fn conv_engine_with(
14137 flow: HostFlow,
14138 handler: std::sync::Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
14139 ) -> FlowEngine {
14140 FlowEngine {
14141 messaging_provider_pack_ids: Default::default(),
14142 rollout_ids: RolloutIds::default(),
14143 packs: Vec::new(),
14144 flows: Vec::new(),
14145 flow_sources: StdHashMap::new(),
14146 flow_cache: RwLock::new(StdHashMap::from([(
14147 FlowKey {
14148 pack_id: "test-pack".to_string(),
14149 flow_id: "conv.flow".to_string(),
14150 },
14151 flow,
14152 )])),
14153 default_env: "local".to_string(),
14154 validation: ValidationConfig {
14155 mode: ValidationMode::Off,
14156 },
14157 cross_pack_resolver: None,
14158 approval_dispatch_handler: None,
14159 remote_dispatch_handler: None,
14160 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
14161 agent_node_handler: Some(handler),
14162 graph_node_handler: None,
14163 mcp_tool_source: None,
14164 mcp_secrets: None,
14165 #[cfg(feature = "agentic-worker")]
14166 a2a_sources: RwLock::new(HashMap::new()),
14167 #[cfg(feature = "agentic-worker")]
14168 ext_artifact_port: None,
14169 operala_node_handler: None,
14170 }
14171 }
14172
14173 #[cfg(feature = "agentic-worker")]
14174 fn conv_ctx<'a>() -> FlowContext<'a> {
14175 FlowContext {
14176 tenant: "demo",
14177 pack_id: "test-pack",
14178 flow_id: "conv.flow",
14179 node_id: None,
14180 tool: None,
14181 action: None,
14182 session_id: Some("sess-conv"),
14183 provider_id: None,
14184 reply_scope: None,
14185 retry_config: RetryConfig {
14186 max_attempts: 1,
14187 base_delay_ms: 1,
14188 },
14189 attempt: 1,
14190 observer: None,
14191 mocks: None,
14192 caller: None,
14193 }
14194 }
14195
14196 #[cfg(feature = "agentic-worker")]
14197 #[test]
14198 fn conversational_dw_agent_parks_and_loops_on_normal_reply() {
14199 let engine = conv_engine(
14200 conversational_dw_flow(true),
14201 json!({ "reply": "hello there", "trail": [], "terminated_by": "final_reply" }),
14202 );
14203 let rt = Runtime::new().unwrap();
14204 let result = rt
14205 .block_on(engine.execute(conv_ctx(), Value::Null))
14206 .unwrap();
14207 let snapshot = match result.status {
14208 FlowStatus::Waiting(w) => w.snapshot,
14209 other => panic!("expected Waiting (park-loop), got {other:?}"),
14210 };
14211 assert_eq!(
14212 snapshot.next_node, "agent",
14213 "must re-enter the dw.agent node itself"
14214 );
14215 assert!(
14217 serde_json::to_string(&result.output)
14218 .unwrap()
14219 .contains("hello there"),
14220 "the agent reply must be rendered before parking: {:?}",
14221 result.output
14222 );
14223 }
14224
14225 #[cfg(feature = "agentic-worker")]
14226 #[test]
14227 fn conversational_dw_agent_advances_on_conversation_ended() {
14228 let engine = conv_engine(
14229 conversational_dw_flow(true),
14230 json!({ "reply": "bye", "trail": [], "terminated_by": "conversation_ended" }),
14231 );
14232 let rt = Runtime::new().unwrap();
14233 let result = rt
14234 .block_on(engine.execute(conv_ctx(), Value::Null))
14235 .unwrap();
14236 assert!(
14237 matches!(result.status, FlowStatus::Completed),
14238 "conversation_ended must advance to the successor and complete, got {:?}",
14239 result.status
14240 );
14241 }
14242
14243 #[cfg(feature = "agentic-worker")]
14244 #[test]
14245 fn non_conversational_dw_agent_never_loops() {
14246 for tb in ["final_reply", "conversation_ended"] {
14249 let engine = conv_engine(
14250 conversational_dw_flow(false),
14251 json!({ "reply": "x", "trail": [], "terminated_by": tb }),
14252 );
14253 let rt = Runtime::new().unwrap();
14254 let result = rt
14255 .block_on(engine.execute(conv_ctx(), Value::Null))
14256 .unwrap();
14257 assert!(
14258 matches!(result.status, FlowStatus::Completed),
14259 "non-conversational must complete (route onward) for terminated_by={tb}, got {:?}",
14260 result.status
14261 );
14262 }
14263 }
14264
14265 #[cfg(feature = "agentic-worker")]
14268 struct ToolParkAgentHandler {
14269 outputs: std::sync::Mutex<Vec<serde_json::Value>>,
14270 resumes: std::sync::Mutex<Vec<Option<serde_json::Value>>>,
14271 }
14272 #[cfg(feature = "agentic-worker")]
14273 impl ToolParkAgentHandler {
14274 fn new(outputs: Vec<serde_json::Value>) -> Self {
14275 Self {
14276 outputs: std::sync::Mutex::new(outputs),
14277 resumes: std::sync::Mutex::new(Vec::new()),
14278 }
14279 }
14280 }
14281 #[cfg(feature = "agentic-worker")]
14282 #[async_trait::async_trait]
14283 impl crate::runner::agent_node::AgentNodeHandler for ToolParkAgentHandler {
14284 async fn execute(
14285 &self,
14286 _tenant_id: &str,
14287 _env_id: &str,
14288 _agent_id: &str,
14289 _session_id: &str,
14290 _flow_input: &serde_json::Value,
14291 _conversational: bool,
14292 _caller: Option<&serde_json::Value>,
14293 ) -> anyhow::Result<serde_json::Value> {
14294 anyhow::bail!("the engine must call execute_with_resume")
14295 }
14296
14297 async fn execute_with_resume(
14298 &self,
14299 _tenant_id: &str,
14300 _env_id: &str,
14301 _agent_id: &str,
14302 _session_id: &str,
14303 _flow_input: &serde_json::Value,
14304 _conversational: bool,
14305 _caller: Option<&serde_json::Value>,
14306 resume_payload: Option<&serde_json::Value>,
14307 ) -> anyhow::Result<serde_json::Value> {
14308 self.resumes.lock().unwrap().push(resume_payload.cloned());
14309 let mut outputs = self.outputs.lock().unwrap();
14310 anyhow::ensure!(!outputs.is_empty(), "no scripted agent output");
14311 Ok(outputs.remove(0))
14312 }
14313 }
14314
14315 #[cfg(feature = "agentic-worker")]
14316 fn awaiting_tool_output() -> serde_json::Value {
14317 json!({
14318 "reply": "please pick a room",
14319 "trail": [],
14320 "terminated_by": "awaiting_tool_input",
14321 "pending_presentation": { "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }
14322 })
14323 }
14324
14325 #[cfg(feature = "agentic-worker")]
14331 #[test]
14332 fn dw_agent_awaiting_tool_input_parks_renders_the_card_and_resumes_with_the_submit() {
14333 let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14334 awaiting_tool_output(),
14335 json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
14336 ]));
14337 let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14338 let rt = Runtime::new().unwrap();
14339
14340 let first = rt
14341 .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14342 .unwrap();
14343 let snapshot = match first.status {
14344 FlowStatus::Waiting(w) => w.snapshot,
14345 other => panic!("expected the flow to park on the tool, got {other:?}"),
14346 };
14347 assert_eq!(snapshot.next_node, "agent", "re-enter the agent node");
14348 assert_eq!(
14349 first.output,
14350 json!({ "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }),
14351 "the card, not the agent envelope, is the turn output"
14352 );
14353 assert_eq!(
14354 first.node_outputs["agent"]["pending_presentation"]["type"], "AdaptiveCard",
14355 "the node output keeps the full envelope: {:?}",
14356 first.node_outputs
14357 );
14358 assert!(snapshot.state.pending_tool_await.contains_key("agent"));
14359 assert!(
14360 snapshot.state.park_turns.is_empty(),
14361 "a tool park is not a conversational turn"
14362 );
14363
14364 let submit = json!({ "metadata": { "action": "submit" }, "room": "101" });
14365 let second = rt
14366 .block_on(engine.resume(conv_ctx(), snapshot, submit.clone()))
14367 .unwrap();
14368 assert!(
14369 matches!(second.status, FlowStatus::Completed),
14370 "the resumed non-conversational agent routes onward, got {:?}",
14371 second.status
14372 );
14373 assert_eq!(*handler.resumes.lock().unwrap(), vec![None, Some(submit)]);
14374 }
14375
14376 #[cfg(feature = "agentic-worker")]
14380 #[test]
14381 fn an_agent_chat_resume_payload_reaches_the_parked_agent() {
14382 let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14383 awaiting_tool_output(),
14384 json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
14385 ]));
14386 let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14387 let rt = Runtime::new().unwrap();
14388 let first = rt
14389 .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14390 .unwrap();
14391 let FlowStatus::Waiting(wait) = first.status else {
14392 panic!("expected a park");
14393 };
14394 let submit = json!({ "metadata": { "action": "submit" }, "room": "101" });
14395 let payload =
14396 crate::http::agent_chat::turn_payload(String::new(), submit.as_object().cloned());
14397 rt.block_on(engine.resume(conv_ctx(), wait.snapshot, payload))
14398 .unwrap();
14399 assert_eq!(*handler.resumes.lock().unwrap(), vec![None, Some(submit)]);
14400 }
14401
14402 #[cfg(feature = "agentic-worker")]
14405 #[test]
14406 fn a_typed_message_during_a_tool_park_is_not_a_resume_payload() {
14407 let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14408 awaiting_tool_output(),
14409 json!({ "reply": "ok, cancelled", "trail": [], "terminated_by": "final_reply" }),
14410 ]));
14411 let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14412 let rt = Runtime::new().unwrap();
14413 let first = rt
14414 .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14415 .unwrap();
14416 let FlowStatus::Waiting(wait) = first.status else {
14417 panic!("expected a park");
14418 };
14419 rt.block_on(engine.resume(conv_ctx(), wait.snapshot, json!({ "text": "never mind" })))
14420 .unwrap();
14421 assert_eq!(*handler.resumes.lock().unwrap(), vec![None, None]);
14422 }
14423
14424 #[cfg(feature = "agentic-worker")]
14425 fn side_turn_output() -> serde_json::Value {
14426 json!({
14427 "reply": "the signature is in Settings",
14428 "trail": [],
14429 "terminated_by": "awaiting_tool_input",
14430 "side_turn": true,
14431 "pending_presentation": { "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }
14432 })
14433 }
14434
14435 #[cfg(feature = "agentic-worker")]
14436 #[test]
14437 fn a_plain_park_still_renders_only_the_card() {
14438 let out = awaiting_tool_output();
14439 assert_eq!(rendered_park(&out), out["pending_presentation"]);
14440 }
14441
14442 #[cfg(feature = "agentic-worker")]
14443 #[test]
14444 fn a_side_turn_park_renders_the_reply_then_the_card() {
14445 let out = side_turn_output();
14446 let rendered = rendered_park(&out);
14447 let items = rendered.as_array().expect("reply + card");
14448 assert_eq!(items.len(), 2);
14449 assert_eq!(items[0]["reply"], "the signature is in Settings");
14450 assert!(items[0].get("pending_presentation").is_none());
14451 assert_eq!(items[1], out["pending_presentation"]);
14452 }
14453
14454 #[cfg(feature = "agentic-worker")]
14459 #[test]
14460 fn a_side_turn_with_a_list_card_renders_one_flat_list() {
14461 let mut out = side_turn_output();
14462 out["pending_presentation"] = json!([{ "text": "pick a room" }, { "text": "or cancel" }]);
14463 let rendered = rendered_park(&out);
14464 let items = rendered.as_array().expect("flat list");
14465 assert_eq!(items.len(), 3, "reply + both card messages: {rendered}");
14466 assert_eq!(items[0]["reply"], "the signature is in Settings");
14467 assert_eq!(items[1], json!({ "text": "pick a room" }));
14468 assert_eq!(items[2], json!({ "text": "or cancel" }));
14469 assert!(items.iter().all(|item| !item.is_array()), "no nested list");
14470 }
14471
14472 #[cfg(feature = "agentic-worker")]
14476 #[test]
14477 fn a_side_turn_keeps_the_await_armed_so_a_submit_still_resumes() {
14478 let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14479 awaiting_tool_output(),
14480 side_turn_output(),
14481 json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
14482 ]));
14483 let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14484 let rt = Runtime::new().unwrap();
14485 let first = rt
14486 .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14487 .unwrap();
14488 let FlowStatus::Waiting(wait) = first.status else {
14489 panic!("expected a park");
14490 };
14491 let second = rt
14492 .block_on(engine.resume(
14493 conv_ctx(),
14494 wait.snapshot,
14495 json!({ "text": "how do I get a signature?" }),
14496 ))
14497 .unwrap();
14498 assert!(
14499 second.output.is_array(),
14500 "reply and card: {}",
14501 second.output
14502 );
14503 let FlowStatus::Waiting(wait) = second.status else {
14504 panic!("the side turn must keep the flow parked");
14505 };
14506 rt.block_on(engine.resume(
14507 conv_ctx(),
14508 wait.snapshot,
14509 json!({ "metadata": { "action": "submit" } }),
14510 ))
14511 .unwrap();
14512 let resumes = handler.resumes.lock().unwrap();
14513 assert_eq!(resumes.len(), 3);
14514 assert!(resumes[0].is_none() && resumes[1].is_none());
14515 assert!(resumes[2].is_some(), "the submit must resume the tool");
14516 }
14517
14518 #[cfg(any(feature = "agentic-worker", test))]
14523 fn wrapped_typed_message(text: &str) -> serde_json::Value {
14524 json!({
14525 "input": {
14526 "id": "msg-2",
14527 "tenant": { "env": "local", "tenant": "acme", "tenant_id": "acme" },
14528 "channel": "webchat",
14529 "session_id": "sess-1",
14530 "from": { "id": "user-1", "kind": "user" },
14531 "to": [],
14532 "correlation_id": "corr-1",
14533 "attachments": [],
14534 "metadata": {},
14535 "extensions": { "caller": { "sub": "user-1", "user_verified": true } },
14536 "text": text
14537 }
14538 })
14539 }
14540
14541 #[test]
14547 fn a_typed_message_in_a_channel_envelope_is_not_a_card_submit() {
14548 assert!(!is_card_submit(&wrapped_typed_message("2+2 berapa?")));
14549 let mut with_context = wrapped_typed_message("hi");
14551 with_context["input"]["metadata"] =
14552 json!({ "locale": "en-US", "team": "support", "env": "prod", "autoStart": false });
14553 assert!(!is_card_submit(&with_context));
14554 let mut by_action = wrapped_typed_message("");
14557 by_action["input"]["metadata"] = json!({ "action": "start_request" });
14558 assert!(is_card_submit(&by_action));
14559 let mut by_values = wrapped_typed_message("");
14560 by_values["input"]["metadata"] = json!({ "room": "101" });
14561 assert!(is_card_submit(&by_values));
14562 let flat_typed = wrapped_typed_message("2+2 berapa?")["input"].clone();
14565 assert!(!is_card_submit(&flat_typed));
14566 let mut flat_submit = flat_typed.clone();
14567 flat_submit["metadata"] = json!({ "action": "start_request" });
14568 assert!(is_card_submit(&flat_submit));
14569 assert!(is_card_submit(
14572 &json!({ "channel": "email", "metadata": {} })
14573 ));
14574 }
14575
14576 #[cfg(any(feature = "agentic-worker", test))]
14582 fn provider_stamped_metadata() -> serde_json::Value {
14583 json!({
14584 "universal": "true",
14585 "env": "prod",
14586 "tenant": "acme",
14587 "route": "sess-1",
14588 "user_id": "user-1",
14589 "user_verified": "true",
14590 "flow_hint": "main",
14591 "locale": "en-US",
14592 "extensions": "{\"caller\":{\"sub\":\"user-1\"}}",
14593 "channel.channel_data": "{}"
14594 })
14595 }
14596
14597 #[test]
14598 fn a_typed_message_with_provider_stamped_metadata_is_not_a_card_submit() {
14599 let mut typed = wrapped_typed_message("how do I get a mail signature?");
14600 typed["input"]["metadata"] = provider_stamped_metadata();
14601 assert!(!is_card_submit(&typed));
14602 let flat = typed["input"].clone();
14604 assert!(!is_card_submit(&flat));
14605 }
14606
14607 #[test]
14608 fn a_click_is_still_a_card_submit_beside_provider_stamped_metadata() {
14609 let mut by_action = wrapped_typed_message("");
14610 let mut meta = provider_stamped_metadata();
14611 meta["action"] = json!("start_request");
14612 by_action["input"]["metadata"] = meta;
14613 assert!(is_card_submit(&by_action));
14614
14615 let mut by_values = wrapped_typed_message("");
14616 let mut meta = provider_stamped_metadata();
14617 meta["room"] = json!("101");
14618 by_values["input"]["metadata"] = meta;
14619 assert!(is_card_submit(&by_values));
14620 }
14621
14622 #[test]
14623 fn channel_context_prefix_matches_only_the_channel_namespace() {
14624 let mut typed = wrapped_typed_message("hi");
14625 typed["input"]["metadata"] = json!({ "mychannel.x": "1" });
14626 assert!(is_card_submit(&typed));
14627 typed["input"]["metadata"] = json!({ "channel.x": "1" });
14628 assert!(!is_card_submit(&typed));
14629 }
14630
14631 #[test]
14634 fn the_provider_submit_marker_makes_an_empty_submit_a_submit() {
14635 let mut click = wrapped_typed_message("message");
14636 let mut meta = provider_stamped_metadata();
14637 meta["greentic_submit"] = json!("true");
14638 click["input"]["metadata"] = meta;
14639 assert!(is_card_submit(&click));
14640 let flat = click["input"].clone();
14641 assert!(is_card_submit(&flat));
14642 let mut typed = wrapped_typed_message("message");
14644 typed["input"]["metadata"] = provider_stamped_metadata();
14645 assert!(!is_card_submit(&typed));
14646 let mut other = wrapped_typed_message("message");
14648 let mut meta = provider_stamped_metadata();
14649 meta["greentic_submit"] = json!("false");
14650 other["input"]["metadata"] = meta;
14651 assert!(!is_card_submit(&other));
14652 }
14653
14654 #[test]
14655 fn the_submit_marker_is_not_a_submitted_answer() {
14656 let entry = json!({ "metadata": { "room": "101", "greentic_submit": "true" } });
14657 let fields = submitted_fields(&entry);
14658 assert!(fields.contains_key("room"));
14659 assert!(!fields.contains_key("greentic_submit"));
14660 }
14661
14662 #[test]
14668 fn a_card_input_named_like_a_stamped_key_with_its_own_value_is_a_submit() {
14669 for (key, value) in [("route", "billing"), ("tenant", "other-corp")] {
14670 let mut click = wrapped_typed_message("");
14671 click["input"]["metadata"] = json!({ key: value });
14672 assert!(is_card_submit(&click), "{key}={value} must count as input");
14673 let flat = click["input"].clone();
14674 assert!(
14675 is_card_submit(&flat),
14676 "flat {key}={value} must count as input"
14677 );
14678 }
14679 let mut typed = wrapped_typed_message("hi");
14681 typed["input"]["metadata"] = json!({ "route": "sess-1", "tenant": "acme" });
14682 assert!(!is_card_submit(&typed));
14683 }
14684
14685 #[test]
14689 fn keys_the_activities_path_never_stamps_are_input() {
14690 for key in ["tenant_id", "conversation_id", "tenant_channel_id"] {
14691 let mut click = wrapped_typed_message("");
14692 click["input"]["metadata"] = json!({ key: "x" });
14693 assert!(is_card_submit(&click), "{key} must count as input");
14694 }
14695 }
14696
14697 #[cfg(feature = "agentic-worker")]
14701 #[test]
14702 fn a_typed_envelope_message_during_a_tool_park_is_not_a_resume_payload() {
14703 let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14704 awaiting_tool_output(),
14705 json!({ "reply": "that is outside my scope", "trail": [], "terminated_by": "final_reply" }),
14706 ]));
14707 let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14708 let rt = Runtime::new().unwrap();
14709 let first = rt
14710 .block_on(engine.execute(conv_ctx(), wrapped_typed_message("book a room")))
14711 .unwrap();
14712 let FlowStatus::Waiting(wait) = first.status else {
14713 panic!("expected a park");
14714 };
14715 rt.block_on(engine.resume(
14716 conv_ctx(),
14717 wait.snapshot,
14718 wrapped_typed_message("2+2 berapa?"),
14719 ))
14720 .unwrap();
14721 assert_eq!(*handler.resumes.lock().unwrap(), vec![None, None]);
14722 }
14723
14724 #[test]
14725 fn is_card_submit_tells_a_submit_from_a_typed_message() {
14726 assert!(is_card_submit(
14727 &json!({ "metadata": { "action": "submit" } })
14728 ));
14729 assert!(is_card_submit(
14730 &json!({ "input": { "metadata": { "action": "go" } } })
14731 ));
14732 assert!(is_card_submit(&json!({ "room": "101", "metadata": {} })));
14733 assert!(!is_card_submit(&json!({ "text": "never mind" })));
14734 assert!(!is_card_submit(
14735 &json!({ "text": "hi", "metadata": { "action": " " } })
14736 ));
14737 }
14738
14739 #[test]
14740 fn pending_tool_await_mark_take_and_legacy_snapshot() {
14741 let mut st = ExecutionState::new(json!({}));
14742 assert!(!st.take_tool_await("agent"));
14743 st.mark_tool_await("agent");
14744 let back: ExecutionState =
14745 serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap();
14746 let mut back = back;
14747 assert!(back.take_tool_await("agent"), "survives the snapshot");
14748 assert!(!back.take_tool_await("agent"), "take clears it");
14749 let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
14750 let legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
14751 assert!(legacy.pending_tool_await.is_empty());
14752 }
14753
14754 #[cfg(feature = "agentic-worker")]
14759 #[test]
14760 fn conversational_dw_agent_force_advances_after_park_loop_cap() {
14761 let engine = conv_engine(
14762 conversational_dw_flow(true),
14763 json!({ "reply": "still thinking", "trail": [], "terminated_by": "final_reply" }),
14764 );
14765 let rt = Runtime::new().unwrap();
14766
14767 let result = rt
14768 .block_on(engine.execute(conv_ctx(), Value::Null))
14769 .unwrap();
14770 let mut snapshot = match result.status {
14771 FlowStatus::Waiting(w) => w.snapshot,
14772 other => panic!("expected Waiting after turn 1, got {other:?}"),
14773 };
14774
14775 for turn in 2..MAX_PARK_TURNS {
14777 let result = rt
14778 .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
14779 .unwrap();
14780 snapshot = match result.status {
14781 FlowStatus::Waiting(w) => w.snapshot,
14782 other => panic!("expected Waiting at turn {turn}, got {other:?}"),
14783 };
14784 }
14785
14786 let result = rt
14788 .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
14789 .unwrap();
14790 assert!(
14791 matches!(result.status, FlowStatus::Completed),
14792 "park-loop cap must force-advance to the successor at turn {MAX_PARK_TURNS}, got {:?}",
14793 result.status
14794 );
14795 }
14796
14797 #[cfg(feature = "agentic-worker")]
14815 struct ScriptedNatsDispatcher {
14816 calls: Mutex<Vec<crate::runner::remote_dispatch::RemoteDispatch>>,
14817 }
14818
14819 #[cfg(feature = "agentic-worker")]
14820 #[async_trait::async_trait]
14821 impl crate::runner::remote_dispatch::RemoteDispatchHandler for ScriptedNatsDispatcher {
14822 async fn dispatch(
14823 &self,
14824 request: crate::runner::remote_dispatch::RemoteDispatch,
14825 ) -> anyhow::Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
14826 let correlation_id = request.correlation_id.clone();
14827 self.calls.lock().unwrap().push(request);
14828 Ok(
14829 crate::runner::remote_dispatch::RemoteDispatchAction::AwaitingResponse {
14830 correlation_id,
14831 },
14832 )
14833 }
14834 }
14835
14836 #[cfg(feature = "agentic-worker")]
14840 fn nats_conv_engine(
14841 flow: HostFlow,
14842 dispatcher: std::sync::Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
14843 ) -> FlowEngine {
14844 FlowEngine {
14845 messaging_provider_pack_ids: Default::default(),
14846 rollout_ids: RolloutIds::default(),
14847 packs: Vec::new(),
14848 flows: Vec::new(),
14849 flow_sources: StdHashMap::new(),
14850 flow_cache: RwLock::new(StdHashMap::from([(
14851 FlowKey {
14852 pack_id: "test-pack".to_string(),
14853 flow_id: "conv.flow".to_string(),
14854 },
14855 flow,
14856 )])),
14857 default_env: "local".to_string(),
14858 validation: ValidationConfig {
14859 mode: ValidationMode::Off,
14860 },
14861 cross_pack_resolver: None,
14862 approval_dispatch_handler: None,
14863 remote_dispatch_handler: Some(dispatcher),
14864 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::Nats,
14865 agent_node_handler: None,
14866 graph_node_handler: None,
14867 mcp_tool_source: None,
14868 mcp_secrets: None,
14869 #[cfg(feature = "agentic-worker")]
14870 a2a_sources: RwLock::new(HashMap::new()),
14871 #[cfg(feature = "agentic-worker")]
14872 ext_artifact_port: None,
14873 operala_node_handler: None,
14874 }
14875 }
14876
14877 #[cfg(feature = "agentic-worker")]
14881 fn agent_response_envelope(reply: &str, terminated_by: &str) -> Value {
14882 json!({
14883 "ok": true,
14884 "output": { "reply": reply, "trail": [], "terminated_by": terminated_by },
14885 "events": [],
14886 "error": Value::Null,
14887 })
14888 }
14889
14890 #[cfg(feature = "agentic-worker")]
14895 #[test]
14896 fn conversational_dw_agent_nats_turn1_parks_via_await_here() {
14897 let dispatcher = Arc::new(ScriptedNatsDispatcher {
14898 calls: Mutex::new(vec![]),
14899 });
14900 let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
14901 let rt = Runtime::new().unwrap();
14902
14903 let result = rt
14904 .block_on(engine.execute(conv_ctx(), Value::Null))
14905 .unwrap();
14906 let snapshot = match result.status {
14907 FlowStatus::Waiting(w) => w.snapshot,
14908 other => panic!("expected Waiting after fresh dispatch, got {other:?}"),
14909 };
14910 assert_eq!(
14911 snapshot.next_node, "agent",
14912 "AwaitHere must resume at self, not the routing successor"
14913 );
14914 assert_eq!(
14915 dispatcher.calls.lock().unwrap().len(),
14916 1,
14917 "a fresh user turn must dispatch to NATS exactly once"
14918 );
14919 assert_eq!(
14920 result.output,
14921 Value::Null,
14922 "no reply is known yet on the initial dispatch — the async response hasn't arrived"
14923 );
14924 }
14925
14926 #[cfg(feature = "agentic-worker")]
14933 #[test]
14934 fn conversational_dw_agent_nats_park_loop_full_turn_cycle() {
14935 let dispatcher = Arc::new(ScriptedNatsDispatcher {
14936 calls: Mutex::new(vec![]),
14937 });
14938 let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
14939 let rt = Runtime::new().unwrap();
14940
14941 let result = rt
14943 .block_on(engine.execute(conv_ctx(), Value::Null))
14944 .unwrap();
14945 let snapshot = match result.status {
14946 FlowStatus::Waiting(w) => w.snapshot,
14947 other => panic!("expected Waiting (AwaitHere) after turn 1 dispatch, got {other:?}"),
14948 };
14949 assert_eq!(snapshot.next_node, "agent");
14950 assert_eq!(dispatcher.calls.lock().unwrap().len(), 1);
14951
14952 let result = rt
14955 .block_on(engine.resume(
14956 conv_ctx(),
14957 snapshot,
14958 agent_response_envelope("hello there", "final_reply"),
14959 ))
14960 .unwrap();
14961 let snapshot = match result.status {
14962 FlowStatus::Waiting(w) => w.snapshot,
14963 other => panic!("expected Waiting (LoopHere) after not-ended response, got {other:?}"),
14964 };
14965 assert_eq!(
14966 snapshot.next_node, "agent",
14967 "LoopHere also re-enters the node itself"
14968 );
14969 assert!(
14970 serde_json::to_string(&result.output)
14971 .unwrap()
14972 .contains("hello there"),
14973 "the agent's reply must be surfaced once the response resume lands: {:?}",
14974 result.output
14975 );
14976 assert_eq!(
14977 dispatcher.calls.lock().unwrap().len(),
14978 1,
14979 "the response landing must not itself trigger another NATS dispatch"
14980 );
14981
14982 let result = rt
14984 .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "user says more" })))
14985 .unwrap();
14986 let snapshot = match result.status {
14987 FlowStatus::Waiting(w) => w.snapshot,
14988 other => panic!("expected Waiting (AwaitHere) after turn 2 dispatch, got {other:?}"),
14989 };
14990 assert_eq!(snapshot.next_node, "agent");
14991 assert_eq!(
14992 dispatcher.calls.lock().unwrap().len(),
14993 2,
14994 "a second fresh user turn must dispatch to NATS again"
14995 );
14996
14997 let result = rt
15000 .block_on(engine.resume(
15001 conv_ctx(),
15002 snapshot,
15003 agent_response_envelope("bye", "conversation_ended"),
15004 ))
15005 .unwrap();
15006 assert!(
15007 matches!(result.status, FlowStatus::Completed),
15008 "conversation_ended response must advance to the successor and complete, got {:?}",
15009 result.status
15010 );
15011 assert_eq!(
15012 dispatcher.calls.lock().unwrap().len(),
15013 2,
15014 "conversation end must not trigger another NATS dispatch"
15015 );
15016 }
15017
15018 #[cfg(feature = "agentic-worker")]
15024 #[test]
15025 fn conversational_dw_agent_nats_force_advances_after_park_loop_cap() {
15026 let dispatcher = Arc::new(ScriptedNatsDispatcher {
15027 calls: Mutex::new(vec![]),
15028 });
15029 let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
15030 let rt = Runtime::new().unwrap();
15031
15032 let result = rt
15036 .block_on(engine.execute(conv_ctx(), Value::Null))
15037 .unwrap();
15038 let mut snapshot = match result.status {
15039 FlowStatus::Waiting(w) => w.snapshot,
15040 other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
15041 };
15042
15043 for turn in 1..MAX_PARK_TURNS {
15047 let result = rt
15048 .block_on(engine.resume(
15049 conv_ctx(),
15050 snapshot,
15051 agent_response_envelope("still thinking", "final_reply"),
15052 ))
15053 .unwrap();
15054 snapshot = match result.status {
15055 FlowStatus::Waiting(w) => w.snapshot,
15056 other => panic!("expected Waiting (LoopHere) at response #{turn}, got {other:?}"),
15057 };
15058 let result = rt
15059 .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
15060 .unwrap();
15061 snapshot = match result.status {
15062 FlowStatus::Waiting(w) => w.snapshot,
15063 other => {
15064 panic!("expected Waiting (AwaitHere) after user turn #{turn}, got {other:?}")
15065 }
15066 };
15067 }
15068
15069 let result = rt
15072 .block_on(engine.resume(
15073 conv_ctx(),
15074 snapshot,
15075 agent_response_envelope("still thinking", "final_reply"),
15076 ))
15077 .unwrap();
15078 assert!(
15079 matches!(result.status, FlowStatus::Completed),
15080 "park-loop cap must force-advance to the successor at response {MAX_PARK_TURNS}, got {:?}",
15081 result.status
15082 );
15083 assert_eq!(
15084 dispatcher.calls.lock().unwrap().len(),
15085 1 + (MAX_PARK_TURNS as usize - 1),
15086 "exactly one NATS dispatch per user turn across the whole park-loop"
15087 );
15088 }
15089
15090 #[cfg(feature = "agentic-worker")]
15103 #[test]
15104 fn conversational_dw_agent_nats_and_inprocess_transcripts_match_for_same_script() {
15105 let rt = Runtime::new().unwrap();
15106
15107 let inproc_handler = Arc::new(ScriptedAgentHandler {
15109 script: Mutex::new(std::collections::VecDeque::from(vec![
15110 json!({ "reply": "hello there", "trail": [], "terminated_by": "final_reply" }),
15111 json!({ "reply": "bye", "trail": [], "terminated_by": "conversation_ended" }),
15112 ])),
15113 });
15114 let inproc_engine = conv_engine_scripted(conversational_dw_flow(true), inproc_handler);
15115 let r1 = rt
15116 .block_on(inproc_engine.execute(conv_ctx(), Value::Null))
15117 .unwrap();
15118 let inproc_snapshot = match r1.status {
15119 FlowStatus::Waiting(ref w) => w.snapshot.clone(),
15120 ref other => panic!("in-process turn 1: expected Waiting, got {other:?}"),
15121 };
15122 let r2 = rt
15123 .block_on(inproc_engine.resume(conv_ctx(), inproc_snapshot, json!({ "text": "more" })))
15124 .unwrap();
15125
15126 let dispatcher = Arc::new(ScriptedNatsDispatcher {
15128 calls: Mutex::new(vec![]),
15129 });
15130 let nats_engine = nats_conv_engine(conversational_dw_flow(true), dispatcher);
15131 let n1 = rt
15132 .block_on(nats_engine.execute(conv_ctx(), Value::Null))
15133 .unwrap();
15134 let n1_snapshot = match n1.status {
15135 FlowStatus::Waiting(w) => w.snapshot,
15136 other => panic!("nats turn 1 dispatch: expected Waiting, got {other:?}"),
15137 };
15138 let n1r = rt
15139 .block_on(nats_engine.resume(
15140 conv_ctx(),
15141 n1_snapshot,
15142 agent_response_envelope("hello there", "final_reply"),
15143 ))
15144 .unwrap();
15145 let n1r_snapshot = match n1r.status {
15146 FlowStatus::Waiting(ref w) => w.snapshot.clone(),
15147 ref other => panic!("nats turn 1 response resume: expected Waiting, got {other:?}"),
15148 };
15149 let n2 = rt
15150 .block_on(nats_engine.resume(conv_ctx(), n1r_snapshot, json!({ "text": "more" })))
15151 .unwrap();
15152 let n2_snapshot = match n2.status {
15153 FlowStatus::Waiting(w) => w.snapshot,
15154 other => panic!("nats turn 2 dispatch: expected Waiting, got {other:?}"),
15155 };
15156 let n2r = rt
15157 .block_on(nats_engine.resume(
15158 conv_ctx(),
15159 n2_snapshot,
15160 agent_response_envelope("bye", "conversation_ended"),
15161 ))
15162 .unwrap();
15163
15164 assert!(matches!(r1.status, FlowStatus::Waiting(_)));
15166 assert!(
15167 matches!(n1r.status, FlowStatus::Waiting(_)),
15168 "nats turn 1's user-visible status must also be Waiting"
15169 );
15170 assert!(matches!(r2.status, FlowStatus::Completed));
15171 assert!(
15172 matches!(n2r.status, FlowStatus::Completed),
15173 "nats turn 2 must also complete, matching the in-process transcript"
15174 );
15175
15176 assert!(
15178 serde_json::to_string(&r1.output)
15179 .unwrap()
15180 .contains("hello there"),
15181 "in-process turn 1 must surface the reply: {:?}",
15182 r1.output
15183 );
15184 assert!(
15185 serde_json::to_string(&n1r.output)
15186 .unwrap()
15187 .contains("hello there"),
15188 "nats turn 1 must surface the identical reply once the response resume lands: {:?}",
15189 n1r.output
15190 );
15191 }
15192
15193 #[cfg(feature = "agentic-worker")]
15201 fn agent_error_envelope(message: &str, code: Option<&str>) -> Value {
15202 json!({
15203 "ok": false,
15204 "output": Value::Null,
15205 "events": [],
15206 "error": { "code": code, "message": message },
15207 })
15208 }
15209
15210 #[cfg(feature = "agentic-worker")]
15211 #[test]
15212 fn error_envelope_prefers_the_partial_reply_over_the_machine_string() {
15213 let entry = json!({
15214 "ok": false,
15215 "output": { "reply": "Here is what I found so far", "trail": [1] },
15216 "error": { "code": "timeout", "message": "agent step ended without a reply: timeout" },
15217 });
15218 let (message, payload) = agent_error_envelope_reply(&entry);
15219 assert_eq!(message, "Here is what I found so far");
15220 assert_eq!(payload["reply"], "Here is what I found so far");
15221 assert_eq!(payload["error"]["code"], "timeout", "error info is kept");
15222 assert_eq!(payload["trail"], json!([1]));
15223 }
15224
15225 #[cfg(feature = "agentic-worker")]
15226 #[test]
15227 fn error_envelope_without_a_usable_reply_shows_a_user_safe_line() {
15228 for output in [
15229 Value::Null,
15230 json!({ "reply": "" }),
15231 json!({ "reply": " " }),
15232 ] {
15233 let entry = json!({
15234 "ok": false, "output": output,
15235 "error": { "code": "timeout", "message": "agent step ended without a reply: timeout" },
15236 "metadata": { "locale": "id" },
15237 });
15238 let (message, payload) = agent_error_envelope_reply(&entry);
15239 assert!(
15240 !message.contains("agent step ended") && !message.trim().is_empty(),
15241 "machine string must not reach the user: {message}"
15242 );
15243 assert!(message.starts_with("Maaf"), "localized via i18n: {message}");
15244 assert_eq!(payload["reply"], message.as_str());
15245 assert_eq!(
15246 payload["error"]["code"], "timeout",
15247 "operators keep the code"
15248 );
15249 assert_eq!(
15250 payload["error"]["message"],
15251 "agent step ended without a reply: timeout"
15252 );
15253 }
15254 let (message, payload) = agent_error_envelope_reply(&json!({ "ok": false }));
15255 assert!(!message.trim().is_empty());
15256 assert_eq!(payload["reply"], message.as_str());
15257 }
15258
15259 #[cfg(feature = "agentic-worker")]
15261 #[test]
15262 fn agent_error_log_fields_are_the_machine_error() {
15263 let entry =
15264 json!({"ok": false, "error": {"code": "timeout", "message": "no reply in 30s"}});
15265 assert_eq!(
15266 agent_error_log_fields(&entry),
15267 ("timeout".to_string(), "no reply in 30s".to_string())
15268 );
15269 assert_eq!(
15270 agent_error_log_fields(&json!({"ok": false, "error": "boom"})),
15271 ("unknown".to_string(), "boom".to_string())
15272 );
15273 assert_eq!(
15274 agent_error_log_fields(&json!({"ok": false})),
15275 ("unknown".to_string(), String::new())
15276 );
15277 }
15278
15279 #[cfg(feature = "agentic-worker")]
15288 #[test]
15289 fn conversational_dw_agent_nats_interleaved_user_message_is_not_misread_as_response() {
15290 let dispatcher = Arc::new(ScriptedNatsDispatcher {
15291 calls: Mutex::new(vec![]),
15292 });
15293 let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
15294 let rt = Runtime::new().unwrap();
15295
15296 let result = rt
15298 .block_on(engine.execute(conv_ctx(), Value::Null))
15299 .unwrap();
15300 let snapshot = match result.status {
15301 FlowStatus::Waiting(w) => w.snapshot,
15302 other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
15303 };
15304 assert!(
15305 snapshot.state.pending_agent_await.contains_key("agent"),
15306 "turn 1 dispatch must mark the pending await"
15307 );
15308 assert_eq!(dispatcher.calls.lock().unwrap().len(), 1);
15309
15310 let result = rt
15313 .block_on(engine.resume(
15314 conv_ctx(),
15315 snapshot,
15316 json!({ "text": "are you still there?" }),
15317 ))
15318 .unwrap();
15319 let snapshot = match result.status {
15320 FlowStatus::Waiting(w) => w.snapshot,
15321 other => panic!(
15322 "a stray user message must re-dispatch as a fresh turn (Waiting/AwaitHere), got {other:?}"
15323 ),
15324 };
15325 assert_eq!(
15326 snapshot.next_node, "agent",
15327 "the fresh re-dispatch still awaits at self"
15328 );
15329 assert_eq!(
15330 dispatcher.calls.lock().unwrap().len(),
15331 2,
15332 "the stray user message must trigger its OWN fresh NATS dispatch, not be swallowed"
15333 );
15334 assert!(
15335 snapshot.state.pending_agent_await.contains_key("agent"),
15336 "the marker must still be set for the real response to land against"
15337 );
15338 assert_eq!(
15339 result.output,
15340 Value::Null,
15341 "no reply is surfaced — this was not a misread null agent turn"
15342 );
15343 assert!(
15344 !snapshot.state.park_turns.contains_key("agent"),
15345 "a stray user message must not touch the park-loop cap"
15346 );
15347 }
15348
15349 #[cfg(feature = "agentic-worker")]
15358 #[test]
15359 fn conversational_dw_agent_nats_error_envelope_surfaces_and_reparks_without_cap_bump() {
15360 let dispatcher = Arc::new(ScriptedNatsDispatcher {
15361 calls: Mutex::new(vec![]),
15362 });
15363 let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
15364 let rt = Runtime::new().unwrap();
15365
15366 let result = rt
15368 .block_on(engine.execute(conv_ctx(), Value::Null))
15369 .unwrap();
15370 let snapshot = match result.status {
15371 FlowStatus::Waiting(w) => w.snapshot,
15372 other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
15373 };
15374
15375 let result = rt
15377 .block_on(engine.resume(conv_ctx(), snapshot, agent_error_envelope("boom", None)))
15378 .unwrap();
15379 let snapshot = match result.status {
15380 FlowStatus::Waiting(w) => w.snapshot,
15381 other => panic!("an error envelope must re-park (Waiting/LoopHere), got {other:?}"),
15382 };
15383 assert_eq!(
15384 snapshot.next_node, "agent",
15385 "LoopHere re-enters the node itself"
15386 );
15387 assert!(
15388 serde_json::to_string(&result.output)
15389 .unwrap()
15390 .contains("boom"),
15391 "the error message must be surfaced as the reply: {:?}",
15392 result.output
15393 );
15394 assert!(
15395 !snapshot.state.park_turns.contains_key("agent"),
15396 "an error response must NOT bump the park-loop cap counter"
15397 );
15398
15399 let result = rt
15401 .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "hello?" })))
15402 .unwrap();
15403 let snapshot = match result.status {
15404 FlowStatus::Waiting(w) => w.snapshot,
15405 other => panic!("expected Waiting (AwaitHere) after user turn, got {other:?}"),
15406 };
15407 assert_eq!(dispatcher.calls.lock().unwrap().len(), 2);
15408
15409 let result = rt
15413 .block_on(engine.resume(
15414 conv_ctx(),
15415 snapshot,
15416 agent_error_envelope("timeout waiting for agent response", Some("timeout")),
15417 ))
15418 .unwrap();
15419 let snapshot = match result.status {
15420 FlowStatus::Waiting(w) => w.snapshot,
15421 other => {
15422 panic!("a timeout envelope must also re-park (Waiting/LoopHere), got {other:?}")
15423 }
15424 };
15425 assert!(
15426 serde_json::to_string(&result.output)
15427 .unwrap()
15428 .contains("timeout waiting for agent response"),
15429 "the timeout message must be surfaced as the reply: {:?}",
15430 result.output
15431 );
15432 assert!(
15433 !snapshot.state.park_turns.contains_key("agent"),
15434 "two error/timeout responses in a row (with an intervening user turn) must still \
15435 not have bumped the park-loop cap counter"
15436 );
15437 }
15438
15439 #[cfg(feature = "agentic-worker")]
15444 struct ScriptedAgentHandler {
15445 script: Mutex<std::collections::VecDeque<serde_json::Value>>,
15446 }
15447 #[cfg(feature = "agentic-worker")]
15448 #[async_trait::async_trait]
15449 impl crate::runner::agent_node::AgentNodeHandler for ScriptedAgentHandler {
15450 async fn execute(
15451 &self,
15452 _tenant_id: &str,
15453 _env_id: &str,
15454 _agent_id: &str,
15455 _session_id: &str,
15456 _flow_input: &serde_json::Value,
15457 _conversational: bool,
15458 _caller: Option<&serde_json::Value>,
15459 ) -> anyhow::Result<serde_json::Value> {
15460 Ok(self
15461 .script
15462 .lock()
15463 .unwrap()
15464 .pop_front()
15465 .expect("ScriptedAgentHandler: script exhausted"))
15466 }
15467 }
15468
15469 #[cfg(feature = "agentic-worker")]
15473 fn conv_engine_scripted(
15474 flow: HostFlow,
15475 handler: std::sync::Arc<ScriptedAgentHandler>,
15476 ) -> FlowEngine {
15477 FlowEngine {
15478 messaging_provider_pack_ids: Default::default(),
15479 rollout_ids: RolloutIds::default(),
15480 packs: Vec::new(),
15481 flows: Vec::new(),
15482 flow_sources: StdHashMap::new(),
15483 flow_cache: RwLock::new(StdHashMap::from([(
15484 FlowKey {
15485 pack_id: "test-pack".to_string(),
15486 flow_id: "conv.flow".to_string(),
15487 },
15488 flow,
15489 )])),
15490 default_env: "local".to_string(),
15491 validation: ValidationConfig {
15492 mode: ValidationMode::Off,
15493 },
15494 cross_pack_resolver: None,
15495 approval_dispatch_handler: None,
15496 remote_dispatch_handler: None,
15497 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
15498 agent_node_handler: Some(handler),
15499 graph_node_handler: None,
15500 mcp_tool_source: None,
15501 mcp_secrets: None,
15502 #[cfg(feature = "agentic-worker")]
15503 a2a_sources: RwLock::new(HashMap::new()),
15504 #[cfg(feature = "agentic-worker")]
15505 ext_artifact_port: None,
15506 operala_node_handler: None,
15507 }
15508 }
15509
15510 struct StubOperalaHandler {
15515 payload: serde_json::Value,
15516 }
15517 #[async_trait::async_trait]
15518 impl crate::runner::operala_node::OperalaNodeHandler for StubOperalaHandler {
15519 async fn execute(
15520 &self,
15521 _tenant: &str,
15522 _env: &str,
15523 _target: &str,
15524 _operation: &str,
15525 _session_id: &str,
15526 _input: &serde_json::Value,
15527 ) -> anyhow::Result<serde_json::Value> {
15528 Ok(self.payload.clone())
15529 }
15530 }
15531
15532 #[derive(Clone, Debug)]
15534 struct OperalaCallRecord {
15535 tenant: String,
15536 env: String,
15537 target: String,
15538 operation: String,
15539 session_id: String,
15540 input: serde_json::Value,
15541 }
15542
15543 #[derive(Default)]
15544 struct RecordingOperalaHandler {
15545 calls: std::sync::Mutex<Vec<OperalaCallRecord>>,
15546 }
15547
15548 #[async_trait::async_trait]
15549 impl crate::runner::operala_node::OperalaNodeHandler for RecordingOperalaHandler {
15550 async fn execute(
15551 &self,
15552 tenant: &str,
15553 env: &str,
15554 target: &str,
15555 operation: &str,
15556 session_id: &str,
15557 input: &serde_json::Value,
15558 ) -> anyhow::Result<serde_json::Value> {
15559 self.calls
15560 .lock()
15561 .map_err(|_| anyhow::anyhow!("recording handler lock poisoned"))?
15562 .push(OperalaCallRecord {
15563 tenant: tenant.to_string(),
15564 env: env.to_string(),
15565 target: target.to_string(),
15566 operation: operation.to_string(),
15567 session_id: session_id.to_string(),
15568 input: input.clone(),
15569 });
15570 Ok(json!({ "ok": true, "reply": "recorded" }))
15571 }
15572 }
15573
15574 fn operala_flow(target: &str) -> HostFlow {
15578 operala_flow_with_payload(
15579 target,
15580 json!({ "operation": "", "input": { "goal": "hi" } }),
15581 )
15582 }
15583
15584 fn operala_flow_with_payload(target: &str, payload_expr: Value) -> HostFlow {
15586 let mut nodes = IndexMap::new();
15587 let node_id = NodeId::from_str("op").unwrap();
15588 nodes.insert(
15589 node_id.clone(),
15590 HostNode {
15591 kind: NodeKind::OperalaCall {
15592 target: target.to_string(),
15593 },
15594 component: "operala.call".to_string(),
15595 component_id: "operala.call".to_string(),
15596 operation_name: Some(target.to_string()),
15597 operation_in_mapping: None,
15598 payload_expr,
15599 routing: Routing::End,
15600 vars_out: None,
15601 response_timeout_secs: None,
15602 },
15603 );
15604 HostFlow {
15605 slot_schema: None,
15606 id: "operala.flow".to_string(),
15607 start: Some(node_id),
15608 nodes,
15609 vars_init: JsonMap::new(),
15610 required_vars: Vec::new(),
15611 }
15612 }
15613
15614 fn operala_engine(
15618 flow: HostFlow,
15619 handler: Option<std::sync::Arc<dyn crate::runner::operala_node::OperalaNodeHandler>>,
15620 ) -> FlowEngine {
15621 FlowEngine {
15622 messaging_provider_pack_ids: Default::default(),
15623 rollout_ids: RolloutIds::default(),
15624 packs: Vec::new(),
15625 flows: Vec::new(),
15626 flow_sources: StdHashMap::new(),
15627 flow_cache: RwLock::new(StdHashMap::from([(
15628 FlowKey {
15629 pack_id: "test-pack".to_string(),
15630 flow_id: "operala.flow".to_string(),
15631 },
15632 flow,
15633 )])),
15634 default_env: "local".to_string(),
15635 validation: ValidationConfig {
15636 mode: ValidationMode::Off,
15637 },
15638 cross_pack_resolver: None,
15639 approval_dispatch_handler: None,
15640 remote_dispatch_handler: None,
15641 #[cfg(feature = "agentic-worker")]
15642 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
15643 #[cfg(feature = "agentic-worker")]
15644 agent_node_handler: None,
15645 #[cfg(feature = "agentic-worker")]
15646 graph_node_handler: None,
15647 #[cfg(feature = "agentic-worker")]
15648 mcp_tool_source: None,
15649 #[cfg(feature = "agentic-worker")]
15650 mcp_secrets: None,
15651 #[cfg(feature = "agentic-worker")]
15652 a2a_sources: RwLock::new(HashMap::new()),
15653 #[cfg(feature = "agentic-worker")]
15654 ext_artifact_port: None,
15655 operala_node_handler: handler,
15656 }
15657 }
15658
15659 fn operala_ctx<'a>() -> FlowContext<'a> {
15660 FlowContext {
15661 tenant: "demo",
15662 pack_id: "test-pack",
15663 flow_id: "operala.flow",
15664 node_id: None,
15665 tool: None,
15666 action: None,
15667 session_id: Some("sess-op"),
15668 provider_id: None,
15669 reply_scope: None,
15670 retry_config: RetryConfig {
15671 max_attempts: 1,
15672 base_delay_ms: 1,
15673 },
15674 attempt: 1,
15675 observer: None,
15676 mocks: None,
15677 caller: None,
15678 }
15679 }
15680
15681 #[test]
15682 fn operala_call_with_in_process_handler_completes_inline() {
15683 let handler = std::sync::Arc::new(StubOperalaHandler {
15684 payload: json!({ "reply": "stub" }),
15685 });
15686 let engine = operala_engine(operala_flow("deep_worker"), Some(handler));
15687 let execution = tokio::runtime::Runtime::new()
15688 .unwrap()
15689 .block_on(engine.execute(operala_ctx(), Value::Null))
15690 .expect("operala.call with an in-process handler must complete");
15691 assert!(matches!(execution.status, FlowStatus::Completed));
15692 assert_eq!(execution.output, json!({ "reply": "stub" }));
15693 }
15694
15695 #[test]
15696 fn operala_call_hands_the_handler_run_and_the_nodes_input() {
15697 let deep_worker = json!({ "iterationBudget": 3, "reflection": false, "delegation": false });
15700 let recorder = std::sync::Arc::new(RecordingOperalaHandler::default());
15701 let engine = operala_engine(
15702 operala_flow_with_payload(
15703 "w1",
15704 json!({
15705 "operation": "invoke",
15706 "input": { "goal": "summarise the quarter", "deep_worker": deep_worker.clone() }
15707 }),
15708 ),
15709 Some(recorder.clone()),
15710 );
15711 let execution = tokio::runtime::Runtime::new()
15712 .unwrap()
15713 .block_on(engine.execute(operala_ctx(), Value::Null))
15714 .expect("operala.call with an in-process handler must complete");
15715 assert!(matches!(execution.status, FlowStatus::Completed));
15716
15717 let calls = recorder.calls.lock().unwrap().clone();
15718 assert_eq!(calls.len(), 1, "exactly one dispatch: {calls:?}");
15719 let call = &calls[0];
15720 assert_eq!(call.operation, "run", "invoke must be normalised to run");
15721 assert_eq!(call.target, "w1");
15722 assert_eq!(call.tenant, "demo");
15723 assert_eq!(call.env, "local");
15724 assert_eq!(call.session_id, "sess-op");
15725 assert_eq!(call.input["goal"], json!("summarise the quarter"));
15726 assert_eq!(
15727 call.input["deep_worker"], deep_worker,
15728 "settings must reach the invoker verbatim"
15729 );
15730 assert!(
15731 call.input.get("operation").is_none(),
15732 "the handler gets payload.input, not the envelope"
15733 );
15734 }
15735
15736 #[test]
15737 fn operala_call_without_handler_or_nats_fails() {
15738 let engine = operala_engine(operala_flow("deep_worker"), None);
15739 let execution = tokio::runtime::Runtime::new()
15740 .unwrap()
15741 .block_on(engine.execute(operala_ctx(), Value::Null))
15742 .expect("session flow returns a completed error envelope, not an Err");
15743 assert!(matches!(execution.status, FlowStatus::Completed));
15749 let msg = execution.output["metadata"]["error_message"]
15750 .as_str()
15751 .unwrap_or_default();
15752 assert!(
15753 msg.contains("operala.call node dispatched but no RemoteDispatchHandler configured"),
15754 "unexpected output: {:?}",
15755 execution.output
15756 );
15757 }
15758
15759 #[test]
15760 fn submitted_fields_reads_root_inputs_on_the_demo_path() {
15761 let entry = json!({
15764 "amount": "500",
15765 "reason": "looks good",
15766 "metadata": { "action": "approve" }
15767 });
15768 let fields = submitted_fields(&entry);
15769 assert_eq!(fields.get("amount"), Some(&json!("500")));
15770 assert_eq!(fields.get("reason"), Some(&json!("looks good")));
15771 assert!(
15772 !fields.contains_key("metadata"),
15773 "the envelope key is not a field"
15774 );
15775 assert!(
15776 !fields.contains_key("action"),
15777 "the route discriminator is not a field"
15778 );
15779 }
15780
15781 #[test]
15782 fn submitted_fields_reads_metadata_on_the_wrapped_path() {
15783 let entry = json!({
15785 "input": {
15786 "metadata": { "action": "approve", "email": "a@b.c" },
15787 "text": "hi"
15788 }
15789 });
15790 let fields = submitted_fields(&entry);
15791 assert_eq!(fields.get("email"), Some(&json!("a@b.c")));
15792 assert!(!fields.contains_key("action"));
15793 assert!(!fields.contains_key("text"), "envelope text is not a field");
15794 assert!(
15795 !fields.contains_key("input"),
15796 "the envelope root must be resolved, or `input` becomes one giant field"
15797 );
15798 }
15799
15800 #[test]
15801 fn submitted_fields_lets_the_envelope_root_win_a_collision() {
15802 let entry = json!({
15803 "email": "root@x",
15804 "metadata": { "action": "go", "email": "meta@x" }
15805 });
15806 assert_eq!(
15807 submitted_fields(&entry).get("email"),
15808 Some(&json!("root@x"))
15809 );
15810 }
15811
15812 #[test]
15813 fn submitted_fields_counts_a_root_input_named_action() {
15814 let entry = json!({ "action": "typed", "metadata": { "action": "approve" } });
15817 assert_eq!(
15818 submitted_fields(&entry).get("action"),
15819 Some(&json!("typed"))
15820 );
15821 }
15822
15823 #[test]
15824 fn submitted_fields_is_empty_for_a_button_with_no_inputs() {
15825 let entry = json!({ "metadata": { "action": "approve" } });
15826 assert!(submitted_fields(&entry).is_empty());
15827 }
15828
15829 fn plain_card_node() -> HostNode {
15833 HostNode {
15834 kind: NodeKind::Exec {
15835 target_component: "card".to_string(),
15836 },
15837 component: "component.exec".to_string(),
15838 component_id: "component.exec".to_string(),
15839 operation_name: None,
15840 operation_in_mapping: None,
15841 payload_expr: Value::Null,
15842 routing: Routing::End,
15843 vars_out: None,
15844 response_timeout_secs: None,
15845 }
15846 }
15847
15848 #[test]
15849 fn an_old_snapshot_without_the_flag_deserializes_as_not_awaiting_submit() {
15850 let raw = json!({
15853 "pack_id": "p",
15854 "flow_id": "f",
15855 "next_node": "card",
15856 "state": {}
15857 });
15858 let snap: FlowSnapshot = serde_json::from_value(raw).expect("legacy snapshot decodes");
15859 assert!(!snap.awaiting_submit);
15860 }
15861
15862 #[test]
15870 fn submitted_answers_survive_the_resume_redispatch_and_reach_a_later_node() {
15871 let mut state = ExecutionState::new(json!({}));
15872 state.nodes.insert(
15875 "card".to_string(),
15876 NodeOutput::new(json!({ "event": "rendered" })),
15877 );
15878 state.pending_card_answers = Some(PendingCardAnswers {
15879 node_id: "card".to_string(),
15880 answers: submitted_fields(&json!({
15881 "email": "a@b.c",
15882 "metadata": { "action": "submit" }
15883 })),
15884 });
15885
15886 let mut fresh = NodeOutput::new(json!({ "event": "rendered" }));
15889 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut fresh);
15890 state.nodes.insert("card".to_string(), fresh);
15891
15892 let ctx = template_context(&state, Value::Null);
15894 let rendered = render_template_value(
15895 &json!("{{node.card.answers.email}}"),
15896 &ctx,
15897 TemplateOptions::default(),
15898 )
15899 .expect("render");
15900 assert_eq!(rendered, json!("a@b.c"));
15901 }
15902
15903 #[test]
15904 fn the_card_render_context_carries_the_answers_too() {
15905 let mut state = ExecutionState::new(json!({}));
15908 state.pending_card_answers = Some(PendingCardAnswers {
15909 node_id: "card".to_string(),
15910 answers: submitted_fields(&json!({ "email": "a@b.c" })),
15911 });
15912 let mut output = NodeOutput::new(json!({ "event": "rendered" }));
15913 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15914 state.nodes.insert("card".to_string(), output);
15915
15916 let ctx = state.context();
15917 assert_eq!(
15918 ctx["nodes"]["card"]["payload"]["answers"]["email"],
15919 json!("a@b.c")
15920 );
15921 }
15922
15923 #[test]
15924 fn answers_are_absent_before_any_submit() {
15925 let mut state = ExecutionState::new(json!({}));
15928 let mut output = NodeOutput::new(json!({ "event": "rendered" }));
15929 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15930 assert!(output.payload.get("answers").is_none());
15931 }
15932
15933 #[test]
15934 fn a_button_with_no_inputs_yields_an_empty_answers_object() {
15935 let mut state = ExecutionState::new(json!({}));
15936 state.pending_card_answers = Some(PendingCardAnswers {
15937 node_id: "card".to_string(),
15938 answers: submitted_fields(&json!({ "metadata": { "action": "approve" } })),
15939 });
15940 let mut output = NodeOutput::new(json!({ "event": "rendered" }));
15941 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15942 assert_eq!(output.payload["answers"], json!({}));
15943 }
15944
15945 #[test]
15946 fn the_pending_answers_are_consumed_exactly_once() {
15947 let mut state = ExecutionState::new(json!({}));
15950 state.pending_card_answers = Some(PendingCardAnswers {
15951 node_id: "card".to_string(),
15952 answers: submitted_fields(&json!({ "email": "a@b.c" })),
15953 });
15954 let mut first = NodeOutput::new(json!({ "event": "rendered" }));
15955 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut first);
15956 assert!(first.payload.get("answers").is_some());
15957
15958 let mut second = NodeOutput::new(json!({ "event": "rendered" }));
15959 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut second);
15960 assert!(
15961 second.payload.get("answers").is_none(),
15962 "consumed, not read"
15963 );
15964 }
15965
15966 #[test]
15967 fn answers_attach_even_when_the_redispatch_failed() {
15968 let mut state = ExecutionState::new(json!({}));
15972 state.pending_card_answers = Some(PendingCardAnswers {
15973 node_id: "card".to_string(),
15974 answers: submitted_fields(&json!({ "email": "a@b.c" })),
15975 });
15976 let mut output = NodeOutput::new(json!({ "ok": false, "error": { "code": "boom" } }));
15977 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15978 assert_eq!(output.payload["answers"]["email"], json!("a@b.c"));
15979 }
15980
15981 #[test]
15982 fn answers_are_not_attached_to_a_different_node() {
15983 let mut state = ExecutionState::new(json!({}));
15984 state.pending_card_answers = Some(PendingCardAnswers {
15985 node_id: "card".to_string(),
15986 answers: submitted_fields(&json!({ "email": "a@b.c" })),
15987 });
15988 let mut other = NodeOutput::new(json!({ "event": "rendered" }));
15989 attach_pending_card_answers(&mut state, "next_step", &plain_card_node(), &mut other);
15990 assert!(other.payload.get("answers").is_none());
15991 assert!(
15992 state.pending_card_answers.is_some(),
15993 "still pending for its own node"
15994 );
15995 }
15996
15997 #[test]
16010 fn answers_intersect_the_declared_allow_list_on_a_wrapped_start_envelope() {
16011 let entry = json!({
16012 "input": {
16013 "id": "msg-1",
16014 "tenant": "acme",
16015 "channel": "webchat",
16016 "session_id": "sess-1",
16017 "from": "user-1",
16018 "to": "bot-1",
16019 "correlation_id": "corr-1",
16020 "attachments": [],
16021 "metadata": {
16022 "action": "submit",
16023 "nextCardId": "confirm",
16024 "route": "default",
16025 "env": "prod",
16026 "team": "support",
16027 "locale": "en-US",
16028 "autoStart": true,
16029 "url": "https://api.example.com",
16030 "model": "gpt-4",
16031 "provider": "openai",
16032 "api_key_secret": "secrets://tenant/acme/openai_key",
16033 "full_name": "Ada Lovelace",
16034 "email": "ada@example.com"
16035 },
16036 "text": "submitted"
16037 }
16038 });
16039
16040 let mut state = ExecutionState::new(json!({}));
16041 state.pending_card_answers = Some(PendingCardAnswers {
16042 node_id: "card".to_string(),
16043 answers: submitted_fields(&entry),
16044 });
16045
16046 let node = HostNode {
16047 payload_expr: json!({ "answer_fields": ["full_name", "email"] }),
16048 ..plain_card_node()
16049 };
16050 let mut output = NodeOutput::new(json!({ "event": "rendered" }));
16051 attach_pending_card_answers(&mut state, "card", &node, &mut output);
16052
16053 let answers = output.payload["answers"]
16054 .as_object()
16055 .expect("answers must be an object");
16056 assert_eq!(
16057 answers,
16058 &serde_json::Map::from_iter([
16059 ("full_name".to_string(), json!("Ada Lovelace")),
16060 ("email".to_string(), json!("ada@example.com")),
16061 ]),
16062 "answers must contain exactly the two declared card inputs, and \
16063 nothing from transport identity, routing, or pack config: {answers:?}"
16064 );
16065 }
16066
16067 #[test]
16068 fn answer_fields_absent_keeps_todays_permissive_behaviour() {
16069 let entry = json!({
16073 "input": {
16074 "tenant": "acme",
16075 "metadata": { "action": "submit", "email": "a@b.c" },
16076 "text": "hi"
16077 }
16078 });
16079 let mut state = ExecutionState::new(json!({}));
16080 state.pending_card_answers = Some(PendingCardAnswers {
16081 node_id: "card".to_string(),
16082 answers: submitted_fields(&entry),
16083 });
16084 let mut output = NodeOutput::new(json!({ "event": "rendered" }));
16085 attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
16086
16087 assert_eq!(output.payload["answers"]["tenant"], json!("acme"));
16088 assert_eq!(output.payload["answers"]["email"], json!("a@b.c"));
16089 }
16090
16091 #[test]
16092 fn answer_fields_declared_empty_yields_no_answers() {
16093 let mut state = ExecutionState::new(json!({}));
16097 state.pending_card_answers = Some(PendingCardAnswers {
16098 node_id: "card".to_string(),
16099 answers: submitted_fields(&json!({
16100 "email": "a@b.c",
16101 "metadata": { "action": "approve" }
16102 })),
16103 });
16104 let node = HostNode {
16105 payload_expr: json!({ "answer_fields": [] }),
16106 ..plain_card_node()
16107 };
16108 let mut output = NodeOutput::new(json!({ "event": "rendered" }));
16109 attach_pending_card_answers(&mut state, "card", &node, &mut output);
16110
16111 assert_eq!(output.payload["answers"], json!({}));
16112 }
16113
16114 #[test]
16128 fn absent_and_malformed_answer_fields_both_stay_permissive_but_declared_filters() {
16129 let entry = json!({ "email": "a@b.c", "phone": "555-1234" });
16130
16131 let mut absent_state = ExecutionState::new(json!({}));
16133 absent_state.pending_card_answers = Some(PendingCardAnswers {
16134 node_id: "card".to_string(),
16135 answers: submitted_fields(&entry),
16136 });
16137 let mut absent_output = NodeOutput::new(json!({ "event": "rendered" }));
16138 attach_pending_card_answers(
16139 &mut absent_state,
16140 "card",
16141 &plain_card_node(),
16142 &mut absent_output,
16143 );
16144 assert_eq!(
16145 absent_output.payload["answers"],
16146 json!({ "email": "a@b.c", "phone": "555-1234" }),
16147 "absent must stay fully permissive"
16148 );
16149
16150 let mut malformed_state = ExecutionState::new(json!({}));
16153 malformed_state.pending_card_answers = Some(PendingCardAnswers {
16154 node_id: "card".to_string(),
16155 answers: submitted_fields(&entry),
16156 });
16157 let malformed_node = HostNode {
16158 payload_expr: json!({ "answer_fields": "{{unresolved.template}}" }),
16159 ..plain_card_node()
16160 };
16161 let mut malformed_output = NodeOutput::new(json!({ "event": "rendered" }));
16162 attach_pending_card_answers(
16163 &mut malformed_state,
16164 "card",
16165 &malformed_node,
16166 &mut malformed_output,
16167 );
16168 assert_eq!(
16169 malformed_output.payload["answers"],
16170 json!({ "email": "a@b.c", "phone": "555-1234" }),
16171 "malformed must ALSO stay fully permissive, same as absent"
16172 );
16173
16174 let mut declared_state = ExecutionState::new(json!({}));
16176 declared_state.pending_card_answers = Some(PendingCardAnswers {
16177 node_id: "card".to_string(),
16178 answers: submitted_fields(&entry),
16179 });
16180 let declared_node = HostNode {
16181 payload_expr: json!({ "answer_fields": ["email"] }),
16182 ..plain_card_node()
16183 };
16184 let mut declared_output = NodeOutput::new(json!({ "event": "rendered" }));
16185 attach_pending_card_answers(
16186 &mut declared_state,
16187 "card",
16188 &declared_node,
16189 &mut declared_output,
16190 );
16191 assert_eq!(
16192 declared_output.payload["answers"],
16193 json!({ "email": "a@b.c" }),
16194 "declared must filter down to exactly the allow-listed keys"
16195 );
16196 }
16197
16198 #[test]
16199 fn pending_from_snapshot_names_next_node_when_awaiting_submit() {
16200 let snapshot = FlowSnapshot {
16201 pack_id: "p".to_string(),
16202 flow_id: "f".to_string(),
16203 next_flow: None,
16204 next_node: "card".to_string(),
16205 awaiting_submit: true,
16206 state: ExecutionState::new(json!({})),
16207 };
16208 let input = json!({ "email": "a@b.c", "metadata": { "action": "submit" } });
16209 let pending = pending_from_snapshot(&snapshot, &input).expect("should park answers");
16210 assert_eq!(pending.node_id, "card");
16211 assert_eq!(pending.answers.get("email"), Some(&json!("a@b.c")));
16212 }
16213
16214 #[test]
16215 fn pending_from_snapshot_is_none_when_not_awaiting_submit() {
16216 let snapshot = FlowSnapshot {
16217 pack_id: "p".to_string(),
16218 flow_id: "f".to_string(),
16219 next_flow: None,
16220 next_node: "successor".to_string(),
16221 awaiting_submit: false,
16222 state: ExecutionState::new(json!({})),
16223 };
16224 let input = json!({ "email": "a@b.c" });
16225 assert!(pending_from_snapshot(&snapshot, &input).is_none());
16226 }
16227
16228 fn card_answers_flow() -> Flow {
16234 let card_id = NodeId::from_str("card").unwrap();
16235 let next_id = NodeId::from_str("next").unwrap();
16236
16237 let card_node = Node {
16238 id: card_id.clone(),
16239 component: FlowComponentRef {
16240 id: "emit.log".parse().unwrap(),
16241 pack_alias: None,
16242 operation: None,
16243 },
16244 input: InputMapping {
16245 mapping: json!({ "event": "rendered" }),
16246 },
16247 output: OutputMapping {
16248 mapping: Value::Null,
16249 },
16250 err_map: None,
16251 routing: Routing::Custom(json!([
16252 { "condition": "response.action == \"submit\"", "to": next_id.to_string() }
16253 ])),
16254 telemetry: TelemetryHints::default(),
16255 conversational: false,
16256 };
16257
16258 let next_node = Node {
16259 id: next_id.clone(),
16260 component: FlowComponentRef {
16261 id: "emit.log".parse().unwrap(),
16262 pack_alias: None,
16263 operation: None,
16264 },
16265 input: InputMapping {
16266 mapping: json!({ "got_email": "{{node.card.answers.email}}" }),
16267 },
16268 output: OutputMapping {
16269 mapping: Value::Null,
16270 },
16271 err_map: None,
16272 routing: Routing::End,
16273 telemetry: TelemetryHints::default(),
16274 conversational: false,
16275 };
16276
16277 let mut nodes = indexmap::IndexMap::default();
16278 nodes.insert(card_id.clone(), card_node);
16279 nodes.insert(next_id.clone(), next_node);
16280
16281 Flow {
16282 schema_version: "1.0".into(),
16283 id: FlowId::from_str("card.answers.flow").unwrap(),
16284 kind: FlowKind::Messaging,
16285 entrypoints: BTreeMap::from([(
16286 "default".to_string(),
16287 Value::String(card_id.to_string()),
16288 )]),
16289 nodes,
16290 metadata: FlowMetadata {
16291 title: None,
16292 description: None,
16293 tags: Default::default(),
16294 extra: json!({}),
16295 },
16296 }
16297 }
16298
16299 #[test]
16310 fn card_answers_survive_a_real_park_and_resume_and_reach_a_later_node() {
16311 let flow = card_answers_flow();
16312 let host_flow = HostFlow::from(flow);
16313 let flow_id = "card.answers.flow";
16314 let pack_id = "test-pack";
16315 let engine = FlowEngine {
16316 messaging_provider_pack_ids: Default::default(),
16317 rollout_ids: RolloutIds::default(),
16318 packs: Vec::new(),
16319 flows: Vec::new(),
16320 flow_sources: StdHashMap::new(),
16321 flow_cache: RwLock::new(StdHashMap::from([(
16322 FlowKey {
16323 pack_id: pack_id.to_string(),
16324 flow_id: flow_id.to_string(),
16325 },
16326 host_flow,
16327 )])),
16328 default_env: "local".to_string(),
16329 validation: ValidationConfig {
16330 mode: ValidationMode::Off,
16331 },
16332 cross_pack_resolver: None,
16333 approval_dispatch_handler: None,
16334 remote_dispatch_handler: None,
16335 #[cfg(feature = "agentic-worker")]
16336 dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
16337 #[cfg(feature = "agentic-worker")]
16338 agent_node_handler: None,
16339 #[cfg(feature = "agentic-worker")]
16340 graph_node_handler: None,
16341 #[cfg(feature = "agentic-worker")]
16342 mcp_tool_source: None,
16343 #[cfg(feature = "agentic-worker")]
16344 mcp_secrets: None,
16345 #[cfg(feature = "agentic-worker")]
16346 a2a_sources: RwLock::new(HashMap::new()),
16347 #[cfg(feature = "agentic-worker")]
16348 ext_artifact_port: None,
16349 operala_node_handler: None,
16350 };
16351 let rt = Runtime::new().unwrap();
16352
16353 let ctx1 = FlowContext {
16354 tenant: "demo",
16355 pack_id,
16356 flow_id,
16357 node_id: None,
16358 tool: None,
16359 action: None,
16360 session_id: None,
16361 provider_id: None,
16362 reply_scope: None,
16363 retry_config: RetryConfig {
16364 max_attempts: 1,
16365 base_delay_ms: 1,
16366 },
16367 attempt: 1,
16368 observer: None,
16369 mocks: None,
16370 caller: None,
16371 };
16372 let result1 = rt.block_on(engine.execute(ctx1, Value::Null)).unwrap();
16375 let snapshot = match result1.status {
16376 FlowStatus::Waiting(w) => w.snapshot,
16377 other => panic!("expected Waiting at the card node, got {other:?}"),
16378 };
16379 assert!(
16380 snapshot.awaiting_submit,
16381 "the card's conditional fall-through must set awaiting_submit"
16382 );
16383 assert_eq!(snapshot.next_node, "card");
16384
16385 let ctx2 = FlowContext {
16390 tenant: "demo",
16391 pack_id,
16392 flow_id,
16393 node_id: None,
16394 tool: None,
16395 action: None,
16396 session_id: None,
16397 provider_id: None,
16398 reply_scope: None,
16399 retry_config: RetryConfig {
16400 max_attempts: 1,
16401 base_delay_ms: 1,
16402 },
16403 attempt: 1,
16404 observer: None,
16405 mocks: None,
16406 caller: None,
16407 };
16408 let input = json!({ "email": "a@b.c", "metadata": { "action": "submit" } });
16409 let result2 = rt.block_on(engine.resume(ctx2, snapshot, input)).unwrap();
16410 assert!(
16411 matches!(result2.status, FlowStatus::Completed),
16412 "the submit must route past the card to `next`"
16413 );
16414 assert_eq!(
16415 result2.node_outputs["card"]["answers"]["email"],
16416 json!("a@b.c"),
16417 "the card's own re-dispatched output must carry the merged answers"
16418 );
16419 assert_eq!(
16420 result2.node_outputs["next"]["got_email"],
16421 json!("a@b.c"),
16422 "`next`, a LATER node, must read the answers through {{node.card.answers.email}}"
16423 );
16424 }
16425}
16426
16427use tracing::Instrument;
16428
16429pub struct FlowContext<'a> {
16430 pub tenant: &'a str,
16431 pub pack_id: &'a str,
16432 pub flow_id: &'a str,
16433 pub node_id: Option<&'a str>,
16434 pub tool: Option<&'a str>,
16435 pub action: Option<&'a str>,
16436 pub session_id: Option<&'a str>,
16437 pub provider_id: Option<&'a str>,
16438 pub reply_scope: Option<&'a greentic_types::ReplyScope>,
16446 pub retry_config: RetryConfig,
16447 pub attempt: u32,
16448 pub observer: Option<&'a dyn ExecutionObserver>,
16449 pub mocks: Option<&'a MockLayer>,
16450 pub caller: Option<&'a serde_json::Value>,
16465}
16466
16467#[derive(Copy, Clone)]
16468pub struct RetryConfig {
16469 pub max_attempts: u32,
16470 pub base_delay_ms: u64,
16471}
16472
16473#[cfg(test)]
16488fn lift_first_node_error_from_nodes(output: Value, nodes: &HashMap<String, NodeOutput>) -> Value {
16489 let failure = nodes
16491 .iter()
16492 .filter(|(_, out)| !out.ok)
16493 .min_by(|a, b| a.0.cmp(b.0))
16494 .map(|(id, out)| (id.clone(), out.clone()));
16495 lift_node_error(output, failure.as_ref())
16496}
16497
16498fn lift_node_error(output: Value, failure: Option<&(String, NodeOutput)>) -> Value {
16503 let Some((node_id, failed)) = failure else {
16504 return output;
16505 };
16506 let err_meta = failed.meta.get("error");
16507 let message = err_meta
16508 .and_then(|e| e.get("message"))
16509 .and_then(|v| v.as_str())
16510 .unwrap_or("flow node failed");
16511 let kind = err_meta
16512 .and_then(|e| e.get("kind"))
16513 .and_then(|v| v.as_str())
16514 .unwrap_or("flow_node_failed");
16515
16516 let mut output = match output {
16517 Value::Object(map) => map,
16518 Value::Null => JsonMap::new(),
16519 other => {
16520 let mut wrap = JsonMap::new();
16521 wrap.insert("payload".to_string(), other);
16522 wrap
16523 }
16524 };
16525 let metadata_entry = output
16526 .entry("metadata".to_string())
16527 .or_insert_with(|| Value::Object(JsonMap::new()));
16528 let metadata_map = match metadata_entry {
16529 Value::Object(map) => map,
16530 _ => {
16531 *metadata_entry = Value::Object(JsonMap::new());
16532 metadata_entry.as_object_mut().unwrap()
16533 }
16534 };
16535 metadata_map
16536 .entry("error_kind".to_string())
16537 .or_insert(Value::String(kind.to_string()));
16538 metadata_map
16539 .entry("error_message".to_string())
16540 .or_insert(Value::String(message.to_string()));
16541 metadata_map
16542 .entry("node_id".to_string())
16543 .or_insert(Value::String(node_id.clone()));
16544 Value::Object(output)
16545}
16546
16547#[derive(Debug, thiserror::Error)]
16551#[error("{0}")]
16552pub struct TransientFlowError(pub String);
16553
16554#[derive(Debug)]
16561pub struct PreEffectError(anyhow::Error);
16562
16563impl std::fmt::Display for PreEffectError {
16564 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16565 std::fmt::Display::fmt(&self.0, f)
16566 }
16567}
16568
16569impl std::error::Error for PreEffectError {
16570 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
16571 self.0.source()
16574 }
16575}
16576
16577pub fn pre_effect(err: impl Into<anyhow::Error>) -> anyhow::Error {
16581 anyhow::Error::new(PreEffectError(err.into()))
16582}
16583
16584pub fn is_pre_effect_error(err: &anyhow::Error) -> bool {
16586 err.chain().any(|cause| cause.is::<PreEffectError>())
16587}
16588
16589fn error_causes(err: &anyhow::Error) -> Vec<&(dyn std::error::Error + 'static)> {
16592 fn walk<'a>(err: &'a anyhow::Error, out: &mut Vec<&'a (dyn std::error::Error + 'static)>) {
16593 for cause in err.chain() {
16594 out.push(cause);
16595 if let Some(wrapped) = cause.downcast_ref::<PreEffectError>() {
16596 walk(&wrapped.0, out);
16597 }
16598 }
16599 }
16600 let mut out = Vec::new();
16601 walk(err, &mut out);
16602 out
16603}
16604
16605#[derive(Debug)]
16620pub struct TerminalFlowError {
16621 message: String,
16622 original: Option<anyhow::Error>,
16623 after_effects: bool,
16628}
16629
16630impl std::fmt::Display for TerminalFlowError {
16631 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16632 f.write_str(&self.message)
16633 }
16634}
16635
16636impl std::error::Error for TerminalFlowError {
16637 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
16638 self.original.as_ref().and_then(|err| {
16641 let top: &(dyn std::error::Error + 'static) = err.as_ref();
16642 top.source()
16643 })
16644 }
16645}
16646
16647pub(crate) fn terminal_flow_error(message: impl Into<String>) -> anyhow::Error {
16649 anyhow::Error::new(TerminalFlowError {
16650 message: message.into(),
16651 original: None,
16652 after_effects: false,
16653 })
16654}
16655
16656fn terminal_flow_error_from_after_effects(err: anyhow::Error) -> anyhow::Error {
16661 anyhow::Error::new(TerminalFlowError {
16662 message: err.to_string(),
16663 original: Some(err),
16664 after_effects: true,
16665 })
16666}
16667
16668pub fn is_after_effects_failure(err: &anyhow::Error) -> bool {
16673 error_causes(err).into_iter().any(|cause| {
16674 cause
16675 .downcast_ref::<TerminalFlowError>()
16676 .is_some_and(|terminal| terminal.after_effects)
16677 })
16678}
16679
16680pub fn is_terminal_flow_error(err: &anyhow::Error) -> bool {
16682 error_causes(err)
16683 .into_iter()
16684 .any(|cause| cause.is::<TerminalFlowError>())
16685}
16686
16687fn should_retry(err: &anyhow::Error) -> bool {
16693 if is_terminal_flow_error(err) {
16695 return false;
16696 }
16697 let typed = error_causes(err).into_iter().any(|cause| {
16698 if cause.is::<TransientFlowError>() || cause.is::<tokio::time::error::Elapsed>() {
16699 return true;
16700 }
16701 cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
16702 matches!(
16703 io.kind(),
16704 std::io::ErrorKind::TimedOut
16705 | std::io::ErrorKind::ConnectionReset
16706 | std::io::ErrorKind::ConnectionAborted
16707 | std::io::ErrorKind::ConnectionRefused
16708 | std::io::ErrorKind::Interrupted
16709 | std::io::ErrorKind::WouldBlock
16710 )
16711 })
16712 });
16713 if typed {
16714 return true;
16715 }
16716 let lower = err.to_string().to_lowercase();
16717 lower.contains("transient")
16718 || lower.contains("unavailable")
16719 || lower.contains("internal")
16720 || lower.contains("timeout")
16721}
16722
16723#[cfg(feature = "fault-injection")]
16724fn injected_error(err: crate::testing::fault_injection::InjectedError) -> anyhow::Error {
16725 use crate::testing::fault_injection::FaultErrorKind;
16726 match err.kind {
16727 FaultErrorKind::Transient | FaultErrorKind::Timeout => {
16728 anyhow::Error::new(TransientFlowError(err.to_string()))
16729 }
16730 _ => anyhow!(err.to_string()),
16731 }
16732}
16733
16734impl From<FlowRetryConfig> for RetryConfig {
16735 fn from(value: FlowRetryConfig) -> Self {
16736 Self {
16737 max_attempts: value.max_attempts.max(1),
16738 base_delay_ms: value.base_delay_ms.max(50),
16739 }
16740 }
16741}