greentic_runner_host/runner/
engine.rs

1use std::collections::HashMap;
2use std::env;
3use std::error::Error as StdError;
4use std::str::FromStr;
5use std::sync::Arc;
6use std::time::Duration;
7
8use crate::component_api::node::{ExecCtx as ComponentExecCtx, TenantCtx as ComponentTenantCtx};
9use anyhow::{Context, Result, anyhow, bail};
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::telemetry::{FlowSpanAttributes, annotate_span, backoff_delay_ms, set_flow_context};
21use crate::validate::{
22    ValidationConfig, ValidationIssue, ValidationMode, validate_component_envelope,
23    validate_tool_envelope,
24};
25use greentic_types::{Flow, Node, NodeId, Routing};
26
27pub struct FlowEngine {
28    packs: Vec<Arc<PackRuntime>>,
29    flows: Vec<FlowDescriptor>,
30    flow_sources: HashMap<FlowKey, usize>,
31    flow_cache: RwLock<HashMap<FlowKey, HostFlow>>,
32    default_env: String,
33    validation: ValidationConfig,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq, Hash)]
37struct FlowKey {
38    pack_id: String,
39    flow_id: String,
40}
41
42#[derive(Clone, Debug, Serialize, Deserialize)]
43pub struct FlowSnapshot {
44    pub pack_id: String,
45    pub flow_id: String,
46    pub next_node: String,
47    pub state: ExecutionState,
48}
49
50#[derive(Clone, Debug)]
51pub struct FlowWait {
52    pub reason: Option<String>,
53    pub snapshot: FlowSnapshot,
54}
55
56#[derive(Clone, Debug)]
57pub enum FlowStatus {
58    Completed,
59    Waiting(Box<FlowWait>),
60}
61
62#[derive(Clone, Debug)]
63pub struct FlowExecution {
64    pub output: Value,
65    pub status: FlowStatus,
66}
67
68#[derive(Clone, Debug)]
69struct HostFlow {
70    id: String,
71    start: Option<NodeId>,
72    nodes: IndexMap<NodeId, HostNode>,
73}
74
75#[derive(Clone, Debug)]
76pub struct HostNode {
77    kind: NodeKind,
78    /// Backwards-compatible component label for observers/transcript.
79    pub component: String,
80    component_id: String,
81    operation_name: Option<String>,
82    operation_in_mapping: Option<String>,
83    payload_expr: Value,
84    routing: Routing,
85}
86
87impl HostNode {
88    pub fn component_id(&self) -> &str {
89        &self.component_id
90    }
91
92    pub fn operation_name(&self) -> Option<&str> {
93        self.operation_name.as_deref()
94    }
95
96    pub fn operation_in_mapping(&self) -> Option<&str> {
97        self.operation_in_mapping.as_deref()
98    }
99}
100
101#[derive(Clone, Debug)]
102enum NodeKind {
103    Exec { target_component: String },
104    PackComponent { component_ref: String },
105    ProviderInvoke,
106    FlowCall,
107    BuiltinEmit { kind: EmitKind },
108    Wait,
109}
110
111#[derive(Clone, Debug)]
112enum EmitKind {
113    Log,
114    Response,
115    Other(String),
116}
117
118struct ComponentOverrides<'a> {
119    component: Option<&'a str>,
120    operation: Option<&'a str>,
121}
122
123struct ComponentCall {
124    component_ref: String,
125    operation: String,
126    input: Value,
127    config: Value,
128}
129
130impl FlowExecution {
131    fn completed(output: Value) -> Self {
132        Self {
133            output,
134            status: FlowStatus::Completed,
135        }
136    }
137
138    fn waiting(output: Value, wait: FlowWait) -> Self {
139        Self {
140            output,
141            status: FlowStatus::Waiting(Box::new(wait)),
142        }
143    }
144}
145
146impl FlowEngine {
147    pub async fn new(packs: Vec<Arc<PackRuntime>>, config: Arc<HostConfig>) -> Result<Self> {
148        let mut flow_sources: HashMap<FlowKey, usize> = HashMap::new();
149        let mut descriptors = Vec::new();
150        let mut bindings = HashMap::new();
151        for pack in &config.pack_bindings {
152            bindings.insert(pack.pack_id.clone(), pack.flows.clone());
153        }
154        let enforce_bindings = !bindings.is_empty();
155        for (idx, pack) in packs.iter().enumerate() {
156            let pack_id = pack.metadata().pack_id.clone();
157            if enforce_bindings && !bindings.contains_key(&pack_id) {
158                bail!("no gtbind entries found for pack {}", pack_id);
159            }
160            let flows = pack.list_flows().await?;
161            let allowed = bindings.get(&pack_id).map(|flows| {
162                flows
163                    .iter()
164                    .cloned()
165                    .collect::<std::collections::HashSet<_>>()
166            });
167            let mut seen = std::collections::HashSet::new();
168            for flow in flows {
169                if let Some(ref allow) = allowed
170                    && !allow.contains(&flow.id)
171                {
172                    continue;
173                }
174                seen.insert(flow.id.clone());
175                tracing::info!(
176                    flow_id = %flow.id,
177                    flow_type = %flow.flow_type,
178                    pack_id = %flow.pack_id,
179                    pack_index = idx,
180                    "registered flow"
181                );
182                flow_sources.insert(
183                    FlowKey {
184                        pack_id: flow.pack_id.clone(),
185                        flow_id: flow.id.clone(),
186                    },
187                    idx,
188                );
189                descriptors.retain(|existing: &FlowDescriptor| {
190                    !(existing.id == flow.id && existing.pack_id == flow.pack_id)
191                });
192                descriptors.push(flow);
193            }
194            if let Some(allow) = allowed {
195                let missing = allow.difference(&seen).cloned().collect::<Vec<_>>();
196                if !missing.is_empty() {
197                    bail!(
198                        "gtbind flow ids missing in pack {}: {}",
199                        pack_id,
200                        missing.join(", ")
201                    );
202                }
203            }
204        }
205
206        let mut flow_map = HashMap::new();
207        for flow in &descriptors {
208            let pack_id = flow.pack_id.clone();
209            if let Some(&pack_idx) = flow_sources.get(&FlowKey {
210                pack_id: pack_id.clone(),
211                flow_id: flow.id.clone(),
212            }) {
213                let pack_clone = Arc::clone(&packs[pack_idx]);
214                let flow_id = flow.id.clone();
215                let task_flow_id = flow_id.clone();
216                match task::spawn_blocking(move || pack_clone.load_flow(&task_flow_id)).await {
217                    Ok(Ok(loaded_flow)) => {
218                        flow_map.insert(
219                            FlowKey {
220                                pack_id: pack_id.clone(),
221                                flow_id,
222                            },
223                            HostFlow::from(loaded_flow),
224                        );
225                    }
226                    Ok(Err(err)) => {
227                        tracing::warn!(flow_id = %flow.id, error = %err, "failed to load flow metadata");
228                    }
229                    Err(err) => {
230                        tracing::warn!(flow_id = %flow.id, error = %err, "join error loading flow metadata");
231                    }
232                }
233            }
234        }
235
236        Ok(Self {
237            packs,
238            flows: descriptors,
239            flow_sources,
240            flow_cache: RwLock::new(flow_map),
241            default_env: env::var("GREENTIC_ENV").unwrap_or_else(|_| "local".to_string()),
242            validation: config.validation.clone(),
243        })
244    }
245
246    async fn get_or_load_flow(&self, pack_id: &str, flow_id: &str) -> Result<HostFlow> {
247        let key = FlowKey {
248            pack_id: pack_id.to_string(),
249            flow_id: flow_id.to_string(),
250        };
251        if let Some(flow) = self.flow_cache.read().get(&key).cloned() {
252            return Ok(flow);
253        }
254
255        let pack_idx = *self
256            .flow_sources
257            .get(&key)
258            .with_context(|| format!("flow {pack_id}:{flow_id} not registered"))?;
259        let pack = Arc::clone(&self.packs[pack_idx]);
260        let flow_id_owned = flow_id.to_string();
261        let task_flow_id = flow_id_owned.clone();
262        let flow = task::spawn_blocking(move || pack.load_flow(&task_flow_id))
263            .await
264            .context("failed to join flow metadata task")??;
265        let host_flow = HostFlow::from(flow);
266        self.flow_cache.write().insert(
267            FlowKey {
268                pack_id: pack_id.to_string(),
269                flow_id: flow_id_owned.clone(),
270            },
271            host_flow.clone(),
272        );
273        Ok(host_flow)
274    }
275
276    pub async fn execute(&self, ctx: FlowContext<'_>, input: Value) -> Result<FlowExecution> {
277        let span = tracing::info_span!(
278            "flow.execute",
279            tenant = tracing::field::Empty,
280            flow_id = tracing::field::Empty,
281            node_id = tracing::field::Empty,
282            tool = tracing::field::Empty,
283            action = tracing::field::Empty
284        );
285        annotate_span(
286            &span,
287            &FlowSpanAttributes {
288                tenant: ctx.tenant,
289                flow_id: ctx.flow_id,
290                node_id: ctx.node_id,
291                tool: ctx.tool,
292                action: ctx.action,
293            },
294        );
295        set_flow_context(
296            &self.default_env,
297            ctx.tenant,
298            ctx.flow_id,
299            ctx.node_id,
300            ctx.provider_id,
301            ctx.session_id,
302        );
303        let retry_config = ctx.retry_config;
304        let original_input = input;
305        async move {
306            let mut attempt = 0u32;
307            loop {
308                attempt += 1;
309                match self.execute_once(&ctx, original_input.clone()).await {
310                    Ok(value) => return Ok(value),
311                    Err(err) => {
312                        if attempt >= retry_config.max_attempts || !should_retry(&err) {
313                            return Err(err);
314                        }
315                        let delay = backoff_delay_ms(retry_config.base_delay_ms, attempt - 1);
316                        tracing::warn!(
317                            tenant = ctx.tenant,
318                            flow_id = ctx.flow_id,
319                            attempt,
320                            max_attempts = retry_config.max_attempts,
321                            delay_ms = delay,
322                            error = %err,
323                            "transient flow execution failure, backing off"
324                        );
325                        tokio::time::sleep(Duration::from_millis(delay)).await;
326                    }
327                }
328            }
329        }
330        .instrument(span)
331        .await
332    }
333
334    pub async fn resume(
335        &self,
336        ctx: FlowContext<'_>,
337        snapshot: FlowSnapshot,
338        input: Value,
339    ) -> Result<FlowExecution> {
340        if snapshot.pack_id != ctx.pack_id {
341            bail!(
342                "snapshot pack {} does not match requested {}",
343                snapshot.pack_id,
344                ctx.pack_id
345            );
346        }
347        if snapshot.flow_id != ctx.flow_id {
348            bail!(
349                "snapshot flow {} does not match requested {}",
350                snapshot.flow_id,
351                ctx.flow_id
352            );
353        }
354        let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
355        let mut state = snapshot.state;
356        state.replace_input(input);
357        state.ensure_entry();
358        self.drive_flow(&ctx, flow_ir, state, Some(snapshot.next_node))
359            .await
360    }
361
362    async fn execute_once(&self, ctx: &FlowContext<'_>, input: Value) -> Result<FlowExecution> {
363        let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
364        let state = ExecutionState::new(input);
365        self.drive_flow(ctx, flow_ir, state, None).await
366    }
367
368    async fn drive_flow(
369        &self,
370        ctx: &FlowContext<'_>,
371        flow_ir: HostFlow,
372        mut state: ExecutionState,
373        resume_from: Option<String>,
374    ) -> Result<FlowExecution> {
375        let mut current = match resume_from {
376            Some(node) => NodeId::from_str(&node)
377                .with_context(|| format!("invalid resume node id `{node}`"))?,
378            None => flow_ir
379                .start
380                .clone()
381                .or_else(|| flow_ir.nodes.keys().next().cloned())
382                .with_context(|| format!("flow {} has no start node", flow_ir.id))?,
383        };
384
385        loop {
386            let node = flow_ir
387                .nodes
388                .get(&current)
389                .with_context(|| format!("node {} not found", current.as_str()))?;
390
391            let payload_template = node.payload_expr.clone();
392            let prev = state
393                .last_output
394                .as_ref()
395                .cloned()
396                .unwrap_or_else(|| Value::Object(JsonMap::new()));
397            let ctx_value = template_context(&state, prev);
398            let payload =
399                render_template_value(&payload_template, &ctx_value, TemplateOptions::default())
400                    .context("failed to render node input template")?;
401            let observed_payload = payload.clone();
402            let node_id = current.clone();
403            let event = NodeEvent {
404                context: ctx,
405                node_id: node_id.as_str(),
406                node,
407                payload: &observed_payload,
408            };
409            if let Some(observer) = ctx.observer {
410                observer.on_node_start(&event);
411            }
412            let dispatch = self
413                .dispatch_node(ctx, node_id.as_str(), node, &mut state, payload, &event)
414                .await;
415            let DispatchOutcome {
416                output,
417                wait_reason,
418            } = match dispatch {
419                Ok(outcome) => outcome,
420                Err(err) => {
421                    if let Some(observer) = ctx.observer {
422                        observer.on_node_error(&event, err.as_ref());
423                    }
424                    return Err(err);
425                }
426            };
427
428            state.nodes.insert(node_id.clone().into(), output.clone());
429            state.last_output = Some(output.payload.clone());
430            if let Some(observer) = ctx.observer {
431                observer.on_node_end(&event, &output.payload);
432            }
433
434            let (next, should_exit) = match &node.routing {
435                Routing::Next { node_id } => (Some(node_id.clone()), false),
436                Routing::End | Routing::Reply => (None, true),
437                Routing::Branch { default, .. } => (default.clone(), default.is_none()),
438                Routing::Custom(raw) => {
439                    tracing::warn!(
440                        flow_id = %flow_ir.id,
441                        node_id = %node_id,
442                        routing = ?raw,
443                        "unsupported routing; terminating flow"
444                    );
445                    (None, true)
446                }
447            };
448
449            if let Some(wait_reason) = wait_reason {
450                let resume_target = next.clone().ok_or_else(|| {
451                    anyhow!(
452                        "session.wait node {} requires a non-empty route",
453                        current.as_str()
454                    )
455                })?;
456                let mut snapshot_state = state.clone();
457                snapshot_state.clear_egress();
458                let snapshot = FlowSnapshot {
459                    pack_id: ctx.pack_id.to_string(),
460                    flow_id: ctx.flow_id.to_string(),
461                    next_node: resume_target.as_str().to_string(),
462                    state: snapshot_state,
463                };
464                let output_value = state.clone().finalize_with(None);
465                return Ok(FlowExecution::waiting(
466                    output_value,
467                    FlowWait {
468                        reason: Some(wait_reason),
469                        snapshot,
470                    },
471                ));
472            }
473
474            if should_exit {
475                return Ok(FlowExecution::completed(
476                    state.finalize_with(Some(output.payload.clone())),
477                ));
478            }
479
480            match next {
481                Some(n) => current = n,
482                None => {
483                    return Ok(FlowExecution::completed(
484                        state.finalize_with(Some(output.payload.clone())),
485                    ));
486                }
487            }
488        }
489    }
490
491    async fn dispatch_node(
492        &self,
493        ctx: &FlowContext<'_>,
494        node_id: &str,
495        node: &HostNode,
496        state: &mut ExecutionState,
497        payload: Value,
498        event: &NodeEvent<'_>,
499    ) -> Result<DispatchOutcome> {
500        match &node.kind {
501            NodeKind::Exec { target_component } => self
502                .execute_component_exec(
503                    ctx,
504                    node_id,
505                    node,
506                    payload,
507                    event,
508                    ComponentOverrides {
509                        component: Some(target_component.as_str()),
510                        operation: node.operation_name.as_deref(),
511                    },
512                )
513                .await
514                .map(DispatchOutcome::complete),
515            NodeKind::PackComponent { component_ref } => self
516                .execute_component_call(ctx, node_id, node, payload, component_ref.as_str(), event)
517                .await
518                .map(DispatchOutcome::complete),
519            NodeKind::FlowCall => self
520                .execute_flow_call(ctx, payload)
521                .await
522                .map(DispatchOutcome::complete),
523            NodeKind::ProviderInvoke => self
524                .execute_provider_invoke(ctx, node_id, state, payload, event)
525                .await
526                .map(DispatchOutcome::complete),
527            NodeKind::BuiltinEmit { kind } => {
528                match kind {
529                    EmitKind::Log | EmitKind::Response => {}
530                    EmitKind::Other(component) => {
531                        tracing::debug!(%component, "handling emit.* as builtin");
532                    }
533                }
534                state.push_egress(payload.clone());
535                Ok(DispatchOutcome::complete(NodeOutput::new(payload)))
536            }
537            NodeKind::Wait => {
538                let reason = extract_wait_reason(&payload);
539                Ok(DispatchOutcome::wait(NodeOutput::new(payload), reason))
540            }
541        }
542    }
543
544    async fn execute_flow_call(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
545        #[derive(Deserialize)]
546        struct FlowCallPayload {
547            #[serde(alias = "flow")]
548            flow_id: String,
549            #[serde(default)]
550            input: Value,
551        }
552
553        let call: FlowCallPayload =
554            serde_json::from_value(payload).context("invalid payload for flow.call node")?;
555        if call.flow_id.trim().is_empty() {
556            bail!("flow.call requires a non-empty flow_id");
557        }
558
559        let sub_input = if call.input.is_null() {
560            Value::Null
561        } else {
562            call.input
563        };
564
565        let flow_id_owned = call.flow_id;
566        let action = "flow.call";
567        let sub_ctx = FlowContext {
568            tenant: ctx.tenant,
569            pack_id: ctx.pack_id,
570            flow_id: flow_id_owned.as_str(),
571            node_id: None,
572            tool: ctx.tool,
573            action: Some(action),
574            session_id: ctx.session_id,
575            provider_id: ctx.provider_id,
576            retry_config: ctx.retry_config,
577            observer: ctx.observer,
578            mocks: ctx.mocks,
579        };
580
581        let execution = Box::pin(self.execute(sub_ctx, sub_input))
582            .await
583            .with_context(|| format!("flow.call failed for {}", flow_id_owned))?;
584        match execution.status {
585            FlowStatus::Completed => Ok(NodeOutput::new(execution.output)),
586            FlowStatus::Waiting(wait) => bail!(
587                "flow.call cannot pause (flow {} waiting {:?})",
588                flow_id_owned,
589                wait.reason
590            ),
591        }
592    }
593
594    async fn execute_component_exec(
595        &self,
596        ctx: &FlowContext<'_>,
597        node_id: &str,
598        node: &HostNode,
599        payload: Value,
600        event: &NodeEvent<'_>,
601        overrides: ComponentOverrides<'_>,
602    ) -> Result<NodeOutput> {
603        #[derive(Deserialize)]
604        struct ComponentPayload {
605            #[serde(default, alias = "component_ref", alias = "component")]
606            component: Option<String>,
607            #[serde(alias = "op")]
608            operation: Option<String>,
609            #[serde(default)]
610            input: Value,
611            #[serde(default)]
612            config: Value,
613        }
614
615        let payload: ComponentPayload =
616            serde_json::from_value(payload).context("invalid payload for component.exec")?;
617        let component_ref = overrides
618            .component
619            .map(str::to_string)
620            .or_else(|| payload.component.filter(|v| !v.trim().is_empty()))
621            .with_context(|| "component.exec requires a component_ref")?;
622        let operation = resolve_component_operation(
623            node_id,
624            node.component_id.as_str(),
625            payload.operation,
626            overrides.operation,
627            node.operation_in_mapping.as_deref(),
628        )?;
629        let call = ComponentCall {
630            component_ref,
631            operation,
632            input: payload.input,
633            config: payload.config,
634        };
635
636        self.invoke_component_call(ctx, node_id, call, event).await
637    }
638
639    async fn execute_component_call(
640        &self,
641        ctx: &FlowContext<'_>,
642        node_id: &str,
643        node: &HostNode,
644        payload: Value,
645        component_ref: &str,
646        event: &NodeEvent<'_>,
647    ) -> Result<NodeOutput> {
648        let payload_operation = extract_operation_from_mapping(&payload);
649        let (input, config) = split_operation_payload(payload);
650        let operation = resolve_component_operation(
651            node_id,
652            node.component_id.as_str(),
653            payload_operation,
654            node.operation_name.as_deref(),
655            node.operation_in_mapping.as_deref(),
656        )?;
657        let call = ComponentCall {
658            component_ref: component_ref.to_string(),
659            operation,
660            input,
661            config,
662        };
663        self.invoke_component_call(ctx, node_id, call, event).await
664    }
665
666    async fn invoke_component_call(
667        &self,
668        ctx: &FlowContext<'_>,
669        node_id: &str,
670        call: ComponentCall,
671        event: &NodeEvent<'_>,
672    ) -> Result<NodeOutput> {
673        self.validate_component(ctx, event, &call)?;
674        let input_json = serde_json::to_string(&call.input)?;
675        let config_json = if call.config.is_null() {
676            None
677        } else {
678            Some(serde_json::to_string(&call.config)?)
679        };
680
681        let key = FlowKey {
682            pack_id: ctx.pack_id.to_string(),
683            flow_id: ctx.flow_id.to_string(),
684        };
685        let pack_idx = *self.flow_sources.get(&key).with_context(|| {
686            format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
687        })?;
688        let pack = Arc::clone(&self.packs[pack_idx]);
689        let exec_ctx = component_exec_ctx(ctx, node_id);
690        let value = pack
691            .invoke_component(
692                call.component_ref.as_str(),
693                exec_ctx,
694                call.operation.as_str(),
695                config_json,
696                input_json,
697            )
698            .await?;
699
700        Ok(NodeOutput::new(value))
701    }
702
703    async fn execute_provider_invoke(
704        &self,
705        ctx: &FlowContext<'_>,
706        node_id: &str,
707        state: &ExecutionState,
708        payload: Value,
709        event: &NodeEvent<'_>,
710    ) -> Result<NodeOutput> {
711        #[derive(Deserialize)]
712        struct ProviderPayload {
713            #[serde(default)]
714            provider_id: Option<String>,
715            #[serde(default)]
716            provider_type: Option<String>,
717            #[serde(default, alias = "operation")]
718            op: Option<String>,
719            #[serde(default)]
720            input: Value,
721            #[serde(default)]
722            in_map: Value,
723            #[serde(default)]
724            out_map: Value,
725            #[serde(default)]
726            err_map: Value,
727        }
728
729        let payload: ProviderPayload =
730            serde_json::from_value(payload).context("invalid payload for provider.invoke")?;
731        let op = payload
732            .op
733            .as_deref()
734            .filter(|v| !v.trim().is_empty())
735            .with_context(|| "provider.invoke requires an op")?
736            .to_string();
737
738        let prev = state
739            .last_output
740            .as_ref()
741            .cloned()
742            .unwrap_or_else(|| Value::Object(JsonMap::new()));
743        let base_ctx = template_context(state, prev);
744
745        let input_value = if !payload.in_map.is_null() {
746            let mut ctx_value = base_ctx.clone();
747            if let Value::Object(ref mut map) = ctx_value {
748                map.insert("input".into(), payload.input.clone());
749                map.insert("result".into(), payload.input.clone());
750            }
751            render_template_value(
752                &payload.in_map,
753                &ctx_value,
754                TemplateOptions {
755                    allow_pointer: true,
756                },
757            )
758            .context("failed to render provider.invoke in_map")?
759        } else if !payload.input.is_null() {
760            payload.input
761        } else {
762            Value::Null
763        };
764        let input_json = serde_json::to_vec(&input_value)?;
765
766        self.validate_tool(
767            ctx,
768            event,
769            payload.provider_id.as_deref(),
770            payload.provider_type.as_deref(),
771            &op,
772            &input_value,
773        )?;
774
775        let key = FlowKey {
776            pack_id: ctx.pack_id.to_string(),
777            flow_id: ctx.flow_id.to_string(),
778        };
779        let pack_idx = *self.flow_sources.get(&key).with_context(|| {
780            format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
781        })?;
782        let pack = Arc::clone(&self.packs[pack_idx]);
783        let binding = pack.resolve_provider(
784            payload.provider_id.as_deref(),
785            payload.provider_type.as_deref(),
786        )?;
787        let exec_ctx = component_exec_ctx(ctx, node_id);
788        let result = pack
789            .invoke_provider(&binding, exec_ctx, &op, input_json)
790            .await?;
791
792        let output = if payload.out_map.is_null() {
793            result
794        } else {
795            let mut ctx_value = base_ctx;
796            if let Value::Object(ref mut map) = ctx_value {
797                map.insert("input".into(), result.clone());
798                map.insert("result".into(), result.clone());
799            }
800            render_template_value(
801                &payload.out_map,
802                &ctx_value,
803                TemplateOptions {
804                    allow_pointer: true,
805                },
806            )
807            .context("failed to render provider.invoke out_map")?
808        };
809        let _ = payload.err_map;
810        Ok(NodeOutput::new(output))
811    }
812
813    fn validate_component(
814        &self,
815        ctx: &FlowContext<'_>,
816        event: &NodeEvent<'_>,
817        call: &ComponentCall,
818    ) -> Result<()> {
819        if self.validation.mode == ValidationMode::Off {
820            return Ok(());
821        }
822        let mut metadata = JsonMap::new();
823        metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
824        if let Some(id) = ctx.session_id {
825            metadata.insert("session".to_string(), json!({ "id": id }));
826        }
827        let envelope = json!({
828            "component_id": call.component_ref,
829            "operation": call.operation,
830            "input": call.input,
831            "config": call.config,
832            "metadata": Value::Object(metadata),
833        });
834        let issues = validate_component_envelope(&envelope);
835        self.report_validation(ctx, event, "component", issues)
836    }
837
838    fn validate_tool(
839        &self,
840        ctx: &FlowContext<'_>,
841        event: &NodeEvent<'_>,
842        provider_id: Option<&str>,
843        provider_type: Option<&str>,
844        operation: &str,
845        input: &Value,
846    ) -> Result<()> {
847        if self.validation.mode == ValidationMode::Off {
848            return Ok(());
849        }
850        let tool_id = provider_id.or(provider_type).unwrap_or("provider.invoke");
851        let mut metadata = JsonMap::new();
852        metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
853        if let Some(id) = ctx.session_id {
854            metadata.insert("session".to_string(), json!({ "id": id }));
855        }
856        let envelope = json!({
857            "tool_id": tool_id,
858            "operation": operation,
859            "input": input,
860            "metadata": Value::Object(metadata),
861        });
862        let issues = validate_tool_envelope(&envelope);
863        self.report_validation(ctx, event, "tool", issues)
864    }
865
866    fn report_validation(
867        &self,
868        ctx: &FlowContext<'_>,
869        event: &NodeEvent<'_>,
870        kind: &str,
871        issues: Vec<ValidationIssue>,
872    ) -> Result<()> {
873        if issues.is_empty() {
874            return Ok(());
875        }
876        if let Some(observer) = ctx.observer {
877            observer.on_validation(event, &issues);
878        }
879        match self.validation.mode {
880            ValidationMode::Warn => {
881                tracing::warn!(
882                    tenant = ctx.tenant,
883                    flow_id = ctx.flow_id,
884                    node_id = event.node_id,
885                    kind,
886                    issues = ?issues,
887                    "invocation envelope validation issues"
888                );
889                Ok(())
890            }
891            ValidationMode::Error => {
892                tracing::error!(
893                    tenant = ctx.tenant,
894                    flow_id = ctx.flow_id,
895                    node_id = event.node_id,
896                    kind,
897                    issues = ?issues,
898                    "invocation envelope validation failed"
899                );
900                bail!("invocation_validation_failed");
901            }
902            ValidationMode::Off => Ok(()),
903        }
904    }
905
906    pub fn flows(&self) -> &[FlowDescriptor] {
907        &self.flows
908    }
909
910    pub fn flow_by_key(&self, pack_id: &str, flow_id: &str) -> Option<&FlowDescriptor> {
911        self.flows
912            .iter()
913            .find(|descriptor| descriptor.pack_id == pack_id && descriptor.id == flow_id)
914    }
915
916    pub fn flow_by_type(&self, flow_type: &str) -> Option<&FlowDescriptor> {
917        let mut matches = self
918            .flows
919            .iter()
920            .filter(|descriptor| descriptor.flow_type == flow_type);
921        let first = matches.next()?;
922        if matches.next().is_some() {
923            return None;
924        }
925        Some(first)
926    }
927
928    pub fn flow_by_id(&self, flow_id: &str) -> Option<&FlowDescriptor> {
929        let mut matches = self
930            .flows
931            .iter()
932            .filter(|descriptor| descriptor.id == flow_id);
933        let first = matches.next()?;
934        if matches.next().is_some() {
935            return None;
936        }
937        Some(first)
938    }
939}
940
941pub trait ExecutionObserver: Send + Sync {
942    fn on_node_start(&self, event: &NodeEvent<'_>);
943    fn on_node_end(&self, event: &NodeEvent<'_>, output: &Value);
944    fn on_node_error(&self, event: &NodeEvent<'_>, error: &dyn StdError);
945    fn on_validation(&self, _event: &NodeEvent<'_>, _issues: &[ValidationIssue]) {}
946}
947
948pub struct NodeEvent<'a> {
949    pub context: &'a FlowContext<'a>,
950    pub node_id: &'a str,
951    pub node: &'a HostNode,
952    pub payload: &'a Value,
953}
954
955#[derive(Clone, Debug, Serialize, Deserialize)]
956pub struct ExecutionState {
957    #[serde(default)]
958    entry: Value,
959    #[serde(default)]
960    input: Value,
961    #[serde(default)]
962    nodes: HashMap<String, NodeOutput>,
963    #[serde(default)]
964    egress: Vec<Value>,
965    #[serde(default, skip_serializing_if = "Option::is_none")]
966    last_output: Option<Value>,
967}
968
969impl ExecutionState {
970    fn new(input: Value) -> Self {
971        Self {
972            entry: input.clone(),
973            input,
974            nodes: HashMap::new(),
975            egress: Vec::new(),
976            last_output: None,
977        }
978    }
979
980    fn ensure_entry(&mut self) {
981        if self.entry.is_null() {
982            self.entry = self.input.clone();
983        }
984    }
985
986    fn context(&self) -> Value {
987        let mut nodes = JsonMap::new();
988        for (id, output) in &self.nodes {
989            nodes.insert(
990                id.clone(),
991                json!({
992                    "ok": output.ok,
993                    "payload": output.payload.clone(),
994                    "meta": output.meta.clone(),
995                }),
996            );
997        }
998        json!({
999            "entry": self.entry.clone(),
1000            "input": self.input.clone(),
1001            "nodes": nodes,
1002        })
1003    }
1004
1005    fn outputs_map(&self) -> JsonMap<String, Value> {
1006        let mut outputs = JsonMap::new();
1007        for (id, output) in &self.nodes {
1008            outputs.insert(id.clone(), output.payload.clone());
1009        }
1010        outputs
1011    }
1012    fn push_egress(&mut self, payload: Value) {
1013        self.egress.push(payload);
1014    }
1015
1016    fn replace_input(&mut self, input: Value) {
1017        self.input = input;
1018    }
1019
1020    fn clear_egress(&mut self) {
1021        self.egress.clear();
1022    }
1023
1024    fn finalize_with(mut self, final_payload: Option<Value>) -> Value {
1025        if self.egress.is_empty() {
1026            return final_payload.unwrap_or(Value::Null);
1027        }
1028        let mut emitted = std::mem::take(&mut self.egress);
1029        if let Some(value) = final_payload {
1030            match value {
1031                Value::Null => {}
1032                Value::Array(items) => emitted.extend(items),
1033                other => emitted.push(other),
1034            }
1035        }
1036        Value::Array(emitted)
1037    }
1038}
1039
1040#[derive(Clone, Debug, Serialize, Deserialize)]
1041struct NodeOutput {
1042    ok: bool,
1043    payload: Value,
1044    meta: Value,
1045}
1046
1047impl NodeOutput {
1048    fn new(payload: Value) -> Self {
1049        Self {
1050            ok: true,
1051            payload,
1052            meta: Value::Null,
1053        }
1054    }
1055}
1056
1057struct DispatchOutcome {
1058    output: NodeOutput,
1059    wait_reason: Option<String>,
1060}
1061
1062impl DispatchOutcome {
1063    fn complete(output: NodeOutput) -> Self {
1064        Self {
1065            output,
1066            wait_reason: None,
1067        }
1068    }
1069
1070    fn wait(output: NodeOutput, reason: Option<String>) -> Self {
1071        Self {
1072            output,
1073            wait_reason: reason,
1074        }
1075    }
1076}
1077
1078fn component_exec_ctx(ctx: &FlowContext<'_>, node_id: &str) -> ComponentExecCtx {
1079    ComponentExecCtx {
1080        tenant: ComponentTenantCtx {
1081            tenant: ctx.tenant.to_string(),
1082            team: None,
1083            user: ctx.provider_id.map(str::to_string),
1084            trace_id: None,
1085            correlation_id: ctx.session_id.map(str::to_string),
1086            deadline_unix_ms: None,
1087            attempt: 1,
1088            idempotency_key: ctx.session_id.map(str::to_string),
1089        },
1090        flow_id: ctx.flow_id.to_string(),
1091        node_id: Some(node_id.to_string()),
1092    }
1093}
1094
1095fn extract_wait_reason(payload: &Value) -> Option<String> {
1096    match payload {
1097        Value::String(s) => Some(s.clone()),
1098        Value::Object(map) => map
1099            .get("reason")
1100            .and_then(Value::as_str)
1101            .map(|value| value.to_string()),
1102        _ => None,
1103    }
1104}
1105
1106fn template_context(state: &ExecutionState, prev: Value) -> Value {
1107    let entry = if state.entry.is_null() {
1108        Value::Object(JsonMap::new())
1109    } else {
1110        state.entry.clone()
1111    };
1112    let mut ctx = JsonMap::new();
1113    ctx.insert("entry".into(), entry);
1114    ctx.insert("prev".into(), prev);
1115    ctx.insert("node".into(), Value::Object(state.outputs_map()));
1116    ctx.insert("state".into(), state.context());
1117    Value::Object(ctx)
1118}
1119
1120impl From<Flow> for HostFlow {
1121    fn from(value: Flow) -> Self {
1122        let mut nodes = IndexMap::new();
1123        for (id, node) in value.nodes {
1124            nodes.insert(id.clone(), HostNode::from(node));
1125        }
1126        let start = value
1127            .entrypoints
1128            .get("default")
1129            .and_then(Value::as_str)
1130            .and_then(|id| NodeId::from_str(id).ok())
1131            .or_else(|| nodes.keys().next().cloned());
1132        Self {
1133            id: value.id.as_str().to_string(),
1134            start,
1135            nodes,
1136        }
1137    }
1138}
1139
1140impl From<Node> for HostNode {
1141    fn from(node: Node) -> Self {
1142        let component_ref = node.component.id.as_str().to_string();
1143        let raw_operation = node.component.operation.clone();
1144        let operation_in_mapping = extract_operation_from_mapping(&node.input.mapping);
1145        let operation_is_component_exec = raw_operation.as_deref() == Some("component.exec");
1146        let operation_is_emit = raw_operation
1147            .as_deref()
1148            .map(|op| op.starts_with("emit."))
1149            .unwrap_or(false);
1150        let is_component_exec = component_ref == "component.exec" || operation_is_component_exec;
1151
1152        let kind = if is_component_exec {
1153            let target = if component_ref == "component.exec" {
1154                if let Some(op) = raw_operation
1155                    .as_deref()
1156                    .filter(|op| op.starts_with("emit."))
1157                {
1158                    op.to_string()
1159                } else {
1160                    extract_target_component(&node.input.mapping)
1161                        .unwrap_or_else(|| "component.exec".to_string())
1162                }
1163            } else {
1164                extract_target_component(&node.input.mapping)
1165                    .unwrap_or_else(|| component_ref.clone())
1166            };
1167            if target.starts_with("emit.") {
1168                NodeKind::BuiltinEmit {
1169                    kind: emit_kind_from_ref(&target),
1170                }
1171            } else {
1172                NodeKind::Exec {
1173                    target_component: target,
1174                }
1175            }
1176        } else if operation_is_emit {
1177            NodeKind::BuiltinEmit {
1178                kind: emit_kind_from_ref(raw_operation.as_deref().unwrap_or("emit.log")),
1179            }
1180        } else {
1181            match component_ref.as_str() {
1182                "flow.call" => NodeKind::FlowCall,
1183                "provider.invoke" => NodeKind::ProviderInvoke,
1184                "session.wait" => NodeKind::Wait,
1185                comp if comp.starts_with("emit.") => NodeKind::BuiltinEmit {
1186                    kind: emit_kind_from_ref(comp),
1187                },
1188                other => NodeKind::PackComponent {
1189                    component_ref: other.to_string(),
1190                },
1191            }
1192        };
1193        let component_label = match &kind {
1194            NodeKind::Exec { .. } => "component.exec".to_string(),
1195            NodeKind::PackComponent { component_ref } => component_ref.clone(),
1196            NodeKind::ProviderInvoke => "provider.invoke".to_string(),
1197            NodeKind::FlowCall => "flow.call".to_string(),
1198            NodeKind::BuiltinEmit { kind } => emit_ref_from_kind(kind),
1199            NodeKind::Wait => "session.wait".to_string(),
1200        };
1201        let operation_name = if is_component_exec && operation_is_component_exec {
1202            None
1203        } else {
1204            raw_operation.clone()
1205        };
1206        let payload_expr = match kind {
1207            NodeKind::BuiltinEmit { .. } => extract_emit_payload(&node.input.mapping),
1208            _ => node.input.mapping.clone(),
1209        };
1210        Self {
1211            kind,
1212            component: component_label,
1213            component_id: if is_component_exec {
1214                "component.exec".to_string()
1215            } else {
1216                component_ref
1217            },
1218            operation_name,
1219            operation_in_mapping,
1220            payload_expr,
1221            routing: node.routing,
1222        }
1223    }
1224}
1225
1226fn extract_target_component(payload: &Value) -> Option<String> {
1227    match payload {
1228        Value::Object(map) => map
1229            .get("component")
1230            .or_else(|| map.get("component_ref"))
1231            .and_then(Value::as_str)
1232            .map(|s| s.to_string()),
1233        _ => None,
1234    }
1235}
1236
1237fn extract_operation_from_mapping(payload: &Value) -> Option<String> {
1238    match payload {
1239        Value::Object(map) => map
1240            .get("operation")
1241            .or_else(|| map.get("op"))
1242            .and_then(Value::as_str)
1243            .map(str::trim)
1244            .filter(|value| !value.is_empty())
1245            .map(|value| value.to_string()),
1246        _ => None,
1247    }
1248}
1249
1250fn extract_emit_payload(payload: &Value) -> Value {
1251    if let Value::Object(map) = payload {
1252        if let Some(input) = map.get("input") {
1253            return input.clone();
1254        }
1255        if let Some(inner) = map.get("payload") {
1256            return inner.clone();
1257        }
1258    }
1259    payload.clone()
1260}
1261
1262fn split_operation_payload(payload: Value) -> (Value, Value) {
1263    if let Value::Object(mut map) = payload.clone()
1264        && map.contains_key("input")
1265    {
1266        let input = map.remove("input").unwrap_or(Value::Null);
1267        let config = map.remove("config").unwrap_or(Value::Null);
1268        let legacy_only = map.keys().all(|key| {
1269            matches!(
1270                key.as_str(),
1271                "operation" | "op" | "component" | "component_ref"
1272            )
1273        });
1274        if legacy_only {
1275            return (input, config);
1276        }
1277    }
1278    (payload, Value::Null)
1279}
1280
1281fn resolve_component_operation(
1282    node_id: &str,
1283    component_label: &str,
1284    payload_operation: Option<String>,
1285    operation_override: Option<&str>,
1286    operation_in_mapping: Option<&str>,
1287) -> Result<String> {
1288    if let Some(op) = operation_override
1289        .map(str::trim)
1290        .filter(|value| !value.is_empty())
1291    {
1292        return Ok(op.to_string());
1293    }
1294
1295    if let Some(op) = payload_operation
1296        .as_deref()
1297        .map(str::trim)
1298        .filter(|value| !value.is_empty())
1299    {
1300        return Ok(op.to_string());
1301    }
1302
1303    let mut message = format!(
1304        "missing operation for node `{}` (component `{}`); expected node.component.operation to be set",
1305        node_id, component_label,
1306    );
1307    if let Some(found) = operation_in_mapping {
1308        message.push_str(&format!(
1309            ". Found operation in input.mapping (`{}`) but this is not used; pack compiler must preserve node.component.operation.",
1310            found
1311        ));
1312    }
1313    bail!(message);
1314}
1315
1316fn emit_kind_from_ref(component_ref: &str) -> EmitKind {
1317    match component_ref {
1318        "emit.log" => EmitKind::Log,
1319        "emit.response" => EmitKind::Response,
1320        other => EmitKind::Other(other.to_string()),
1321    }
1322}
1323
1324fn emit_ref_from_kind(kind: &EmitKind) -> String {
1325    match kind {
1326        EmitKind::Log => "emit.log".to_string(),
1327        EmitKind::Response => "emit.response".to_string(),
1328        EmitKind::Other(other) => other.clone(),
1329    }
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334    use super::*;
1335    use crate::validate::{ValidationConfig, ValidationMode};
1336    use greentic_types::{
1337        Flow, FlowComponentRef, FlowId, FlowKind, InputMapping, Node, NodeId, OutputMapping,
1338        Routing, TelemetryHints,
1339    };
1340    use serde_json::json;
1341    use std::collections::BTreeMap;
1342    use std::str::FromStr;
1343    use std::sync::Mutex;
1344    use tokio::runtime::Runtime;
1345
1346    fn minimal_engine() -> FlowEngine {
1347        FlowEngine {
1348            packs: Vec::new(),
1349            flows: Vec::new(),
1350            flow_sources: HashMap::new(),
1351            flow_cache: RwLock::new(HashMap::new()),
1352            default_env: "local".to_string(),
1353            validation: ValidationConfig {
1354                mode: ValidationMode::Off,
1355            },
1356        }
1357    }
1358
1359    #[test]
1360    fn templating_renders_with_partials_and_data() {
1361        let mut state = ExecutionState::new(json!({ "city": "London" }));
1362        state.nodes.insert(
1363            "forecast".to_string(),
1364            NodeOutput::new(json!({ "temp": "20C" })),
1365        );
1366
1367        // templating context includes node outputs for runner-side payload rendering.
1368        let ctx = state.context();
1369        assert_eq!(ctx["nodes"]["forecast"]["payload"]["temp"], json!("20C"));
1370    }
1371
1372    #[test]
1373    fn finalize_wraps_emitted_payloads() {
1374        let mut state = ExecutionState::new(json!({}));
1375        state.push_egress(json!({ "text": "first" }));
1376        state.push_egress(json!({ "text": "second" }));
1377        let result = state.finalize_with(Some(json!({ "text": "final" })));
1378        assert_eq!(
1379            result,
1380            json!([
1381                { "text": "first" },
1382                { "text": "second" },
1383                { "text": "final" }
1384            ])
1385        );
1386    }
1387
1388    #[test]
1389    fn finalize_flattens_final_array() {
1390        let mut state = ExecutionState::new(json!({}));
1391        state.push_egress(json!({ "text": "only" }));
1392        let result = state.finalize_with(Some(json!([
1393            { "text": "extra-1" },
1394            { "text": "extra-2" }
1395        ])));
1396        assert_eq!(
1397            result,
1398            json!([
1399                { "text": "only" },
1400                { "text": "extra-1" },
1401                { "text": "extra-2" }
1402            ])
1403        );
1404    }
1405
1406    #[test]
1407    fn missing_operation_reports_node_and_component() {
1408        let engine = minimal_engine();
1409        let rt = Runtime::new().unwrap();
1410        let retry_config = RetryConfig {
1411            max_attempts: 1,
1412            base_delay_ms: 1,
1413        };
1414        let ctx = FlowContext {
1415            tenant: "tenant",
1416            pack_id: "test-pack",
1417            flow_id: "flow",
1418            node_id: Some("missing-op"),
1419            tool: None,
1420            action: None,
1421            session_id: None,
1422            provider_id: None,
1423            retry_config,
1424            observer: None,
1425            mocks: None,
1426        };
1427        let node = HostNode {
1428            kind: NodeKind::Exec {
1429                target_component: "qa.process".into(),
1430            },
1431            component: "component.exec".into(),
1432            component_id: "component.exec".into(),
1433            operation_name: None,
1434            operation_in_mapping: None,
1435            payload_expr: Value::Null,
1436            routing: Routing::End,
1437        };
1438        let _state = ExecutionState::new(Value::Null);
1439        let payload = json!({ "component": "qa.process" });
1440        let event = NodeEvent {
1441            context: &ctx,
1442            node_id: "missing-op",
1443            node: &node,
1444            payload: &payload,
1445        };
1446        let err = rt
1447            .block_on(engine.execute_component_exec(
1448                &ctx,
1449                "missing-op",
1450                &node,
1451                payload.clone(),
1452                &event,
1453                ComponentOverrides {
1454                    component: None,
1455                    operation: None,
1456                },
1457            ))
1458            .unwrap_err();
1459        let message = err.to_string();
1460        assert!(
1461            message.contains("missing operation for node `missing-op`"),
1462            "unexpected message: {message}"
1463        );
1464        assert!(
1465            message.contains("(component `component.exec`)"),
1466            "unexpected message: {message}"
1467        );
1468    }
1469
1470    #[test]
1471    fn missing_operation_mentions_mapping_hint() {
1472        let engine = minimal_engine();
1473        let rt = Runtime::new().unwrap();
1474        let retry_config = RetryConfig {
1475            max_attempts: 1,
1476            base_delay_ms: 1,
1477        };
1478        let ctx = FlowContext {
1479            tenant: "tenant",
1480            pack_id: "test-pack",
1481            flow_id: "flow",
1482            node_id: Some("missing-op-hint"),
1483            tool: None,
1484            action: None,
1485            session_id: None,
1486            provider_id: None,
1487            retry_config,
1488            observer: None,
1489            mocks: None,
1490        };
1491        let node = HostNode {
1492            kind: NodeKind::Exec {
1493                target_component: "qa.process".into(),
1494            },
1495            component: "component.exec".into(),
1496            component_id: "component.exec".into(),
1497            operation_name: None,
1498            operation_in_mapping: Some("render".into()),
1499            payload_expr: Value::Null,
1500            routing: Routing::End,
1501        };
1502        let _state = ExecutionState::new(Value::Null);
1503        let payload = json!({ "component": "qa.process" });
1504        let event = NodeEvent {
1505            context: &ctx,
1506            node_id: "missing-op-hint",
1507            node: &node,
1508            payload: &payload,
1509        };
1510        let err = rt
1511            .block_on(engine.execute_component_exec(
1512                &ctx,
1513                "missing-op-hint",
1514                &node,
1515                payload.clone(),
1516                &event,
1517                ComponentOverrides {
1518                    component: None,
1519                    operation: None,
1520                },
1521            ))
1522            .unwrap_err();
1523        let message = err.to_string();
1524        assert!(
1525            message.contains("missing operation for node `missing-op-hint`"),
1526            "unexpected message: {message}"
1527        );
1528        assert!(
1529            message.contains("Found operation in input.mapping (`render`)"),
1530            "unexpected message: {message}"
1531        );
1532    }
1533
1534    struct CountingObserver {
1535        starts: Mutex<Vec<String>>,
1536        ends: Mutex<Vec<Value>>,
1537    }
1538
1539    impl CountingObserver {
1540        fn new() -> Self {
1541            Self {
1542                starts: Mutex::new(Vec::new()),
1543                ends: Mutex::new(Vec::new()),
1544            }
1545        }
1546    }
1547
1548    impl ExecutionObserver for CountingObserver {
1549        fn on_node_start(&self, event: &NodeEvent<'_>) {
1550            self.starts.lock().unwrap().push(event.node_id.to_string());
1551        }
1552
1553        fn on_node_end(&self, _event: &NodeEvent<'_>, output: &Value) {
1554            self.ends.lock().unwrap().push(output.clone());
1555        }
1556
1557        fn on_node_error(&self, _event: &NodeEvent<'_>, _error: &dyn StdError) {}
1558    }
1559
1560    #[test]
1561    fn emits_end_event_for_successful_node() {
1562        let node_id = NodeId::from_str("emit").unwrap();
1563        let node = Node {
1564            id: node_id.clone(),
1565            component: FlowComponentRef {
1566                id: "emit.log".parse().unwrap(),
1567                pack_alias: None,
1568                operation: None,
1569            },
1570            input: InputMapping {
1571                mapping: json!({ "message": "logged" }),
1572            },
1573            output: OutputMapping {
1574                mapping: Value::Null,
1575            },
1576            routing: Routing::End,
1577            telemetry: TelemetryHints::default(),
1578        };
1579        let mut nodes = indexmap::IndexMap::default();
1580        nodes.insert(node_id.clone(), node);
1581        let flow = Flow {
1582            schema_version: "1.0".into(),
1583            id: FlowId::from_str("emit.flow").unwrap(),
1584            kind: FlowKind::Messaging,
1585            entrypoints: BTreeMap::from([(
1586                "default".to_string(),
1587                Value::String(node_id.to_string()),
1588            )]),
1589            nodes,
1590            metadata: Default::default(),
1591        };
1592        let host_flow = HostFlow::from(flow);
1593
1594        let engine = FlowEngine {
1595            packs: Vec::new(),
1596            flows: Vec::new(),
1597            flow_sources: HashMap::new(),
1598            flow_cache: RwLock::new(HashMap::from([(
1599                FlowKey {
1600                    pack_id: "test-pack".to_string(),
1601                    flow_id: "emit.flow".to_string(),
1602                },
1603                host_flow,
1604            )])),
1605            default_env: "local".to_string(),
1606            validation: ValidationConfig {
1607                mode: ValidationMode::Off,
1608            },
1609        };
1610        let observer = CountingObserver::new();
1611        let ctx = FlowContext {
1612            tenant: "demo",
1613            pack_id: "test-pack",
1614            flow_id: "emit.flow",
1615            node_id: None,
1616            tool: None,
1617            action: None,
1618            session_id: None,
1619            provider_id: None,
1620            retry_config: RetryConfig {
1621                max_attempts: 1,
1622                base_delay_ms: 1,
1623            },
1624            observer: Some(&observer),
1625            mocks: None,
1626        };
1627
1628        let rt = Runtime::new().unwrap();
1629        let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
1630        assert!(matches!(result.status, FlowStatus::Completed));
1631
1632        let starts = observer.starts.lock().unwrap();
1633        let ends = observer.ends.lock().unwrap();
1634        assert_eq!(starts.len(), 1);
1635        assert_eq!(ends.len(), 1);
1636        assert_eq!(ends[0], json!({ "message": "logged" }));
1637    }
1638}
1639
1640use tracing::Instrument;
1641
1642pub struct FlowContext<'a> {
1643    pub tenant: &'a str,
1644    pub pack_id: &'a str,
1645    pub flow_id: &'a str,
1646    pub node_id: Option<&'a str>,
1647    pub tool: Option<&'a str>,
1648    pub action: Option<&'a str>,
1649    pub session_id: Option<&'a str>,
1650    pub provider_id: Option<&'a str>,
1651    pub retry_config: RetryConfig,
1652    pub observer: Option<&'a dyn ExecutionObserver>,
1653    pub mocks: Option<&'a MockLayer>,
1654}
1655
1656#[derive(Copy, Clone)]
1657pub struct RetryConfig {
1658    pub max_attempts: u32,
1659    pub base_delay_ms: u64,
1660}
1661
1662fn should_retry(err: &anyhow::Error) -> bool {
1663    let lower = err.to_string().to_lowercase();
1664    lower.contains("transient") || lower.contains("unavailable") || lower.contains("internal")
1665}
1666
1667impl From<FlowRetryConfig> for RetryConfig {
1668    fn from(value: FlowRetryConfig) -> Self {
1669        Self {
1670            max_attempts: value.max_attempts.max(1),
1671            base_delay_ms: value.base_delay_ms.max(50),
1672        }
1673    }
1674}