use std::collections::HashMap;
use std::env;
use std::error::Error as StdError;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use crate::component_api::node::{ExecCtx as ComponentExecCtx, TenantCtx as ComponentTenantCtx};
use anyhow::{Context, Result, anyhow, bail};
use chrono::{DateTime, SecondsFormat, Utc};
use indexmap::IndexMap;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use serde_json::{Map as JsonMap, Value, json};
use tokio::task;
use super::mocks::MockLayer;
use super::templating::{TemplateOptions, render_template_value};
use crate::config::{FlowRetryConfig, HostConfig};
use crate::pack::{FlowDescriptor, PackRuntime};
use crate::runner::approval_token;
use crate::runner::invocation::{InvocationMeta, build_invocation_envelope_as};
use crate::telemetry::{
FlowSpanAttributes, RolloutIds, annotate_span, backoff_delay_ms, set_flow_context,
};
#[cfg(feature = "fault-injection")]
use crate::testing::fault_injection::{FaultContext, FaultPoint, maybe_fail};
use crate::validate::{
ValidationConfig, ValidationIssue, ValidationMode, validate_component_envelope,
validate_tool_envelope,
};
use greentic_flow::SLOT_SCHEMA_METADATA_KEY;
use greentic_types::{Flow, Node, NodeId, Routing};
const SLOT_EXTRACTOR_COMPONENT_ID: &str = "ai.greentic.component-slot-extractor";
pub trait CrossPackResolver: Send + Sync {
fn invoke(
&self,
provider_id: &str,
provider_type: Option<&str>,
op: &str,
input: &[u8],
tenant: &str,
team: Option<&str>,
) -> Result<Value>;
}
pub struct FlowEngine {
packs: Vec<Arc<PackRuntime>>,
flows: Vec<FlowDescriptor>,
flow_sources: HashMap<FlowKey, usize>,
messaging_provider_pack_ids: std::collections::HashSet<String>,
flow_cache: RwLock<HashMap<FlowKey, HostFlow>>,
default_env: String,
validation: ValidationConfig,
cross_pack_resolver: Option<Arc<dyn CrossPackResolver>>,
rollout_ids: RolloutIds,
remote_dispatch_handler: Option<Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>>,
approval_dispatch_handler:
Option<Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>>,
operala_node_handler: Option<Arc<dyn crate::runner::operala_node::OperalaNodeHandler>>,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch,
#[cfg(feature = "agentic-worker")]
agent_node_handler: Option<Arc<dyn crate::runner::agent_node::AgentNodeHandler>>,
#[cfg(feature = "agentic-worker")]
graph_node_handler: Option<Arc<dyn crate::runner::graph_node::GraphNodeHandler>>,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
#[cfg(feature = "agentic-worker")]
mcp_secrets: Option<crate::secrets::DynSecretsManager>,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock<HashMap<(String, String), Arc<greentic_aw_runtime::A2aToolSource>>>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct FlowKey {
pack_id: String,
flow_id: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FlowSnapshot {
pub pack_id: String,
pub flow_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_flow: Option<String>,
pub next_node: String,
#[serde(default)]
pub awaiting_submit: bool,
pub state: ExecutionState,
}
#[derive(Clone, Debug)]
pub struct FlowWait {
pub reason: Option<String>,
pub snapshot: FlowSnapshot,
}
#[derive(Clone, Debug)]
pub enum FlowStatus {
Completed,
Waiting(Box<FlowWait>),
}
#[derive(Clone, Debug)]
pub struct FlowExecution {
pub output: Value,
pub status: FlowStatus,
pub node_outputs: JsonMap<String, Value>,
}
#[derive(Clone, Debug)]
struct HostFlow {
id: String,
start: Option<NodeId>,
nodes: IndexMap<NodeId, HostNode>,
vars_init: JsonMap<String, Value>,
#[allow(dead_code)]
required_vars: Vec<String>,
slot_schema: Option<Value>,
}
#[derive(Clone, Debug)]
pub struct HostNode {
kind: NodeKind,
pub component: String,
component_id: String,
operation_name: Option<String>,
operation_in_mapping: Option<String>,
payload_expr: Value,
routing: Routing,
vars_out: Option<JsonMap<String, Value>>,
response_timeout_secs: Option<u64>,
}
impl HostNode {
pub fn component_id(&self) -> &str {
&self.component_id
}
pub fn operation_name(&self) -> Option<&str> {
self.operation_name.as_deref()
}
pub fn operation_in_mapping(&self) -> Option<&str> {
self.operation_in_mapping.as_deref()
}
pub(crate) fn is_approval(&self) -> bool {
matches!(self.kind, NodeKind::ApprovalCall { .. })
}
pub(crate) fn agent_ref(&self) -> Option<&str> {
match &self.kind {
NodeKind::DwAgent { agent_id, .. } => Some(agent_id.as_str()),
NodeKind::DwAgentGraph { graph_id } => Some(graph_id.as_str()),
NodeKind::OperalaCall { target } | NodeKind::AgenticCall { target } => {
Some(target.as_str())
}
_ => None,
}
.map(str::trim)
.filter(|id| !id.is_empty())
}
pub(crate) fn response_timeout_secs(&self) -> Option<u64> {
self.response_timeout_secs
}
pub(crate) fn is_agentic(&self) -> bool {
matches!(
self.kind,
NodeKind::DwAgent { .. }
| NodeKind::DwAgentGraph { .. }
| NodeKind::OperalaCall { .. }
| NodeKind::AgenticCall { .. }
)
}
}
#[cfg(test)]
impl HostNode {
pub(crate) fn for_test(component_id: &str, operation_name: Option<&str>) -> Self {
HostNode {
kind: NodeKind::Exec {
target_component: component_id.to_string(),
},
component: component_id.to_string(),
component_id: component_id.to_string(),
operation_name: operation_name.map(str::to_string),
operation_in_mapping: None,
payload_expr: Value::Null,
routing: Routing::End,
vars_out: None,
response_timeout_secs: None,
}
}
pub(crate) fn for_test_approval(target: &str) -> Self {
HostNode {
kind: NodeKind::ApprovalCall {
target: target.to_string(),
},
..Self::for_test("approval.call", Some(target))
}
}
pub(crate) fn with_response_timeout(mut self, secs: u64) -> Self {
self.response_timeout_secs = Some(secs);
self
}
pub(crate) fn for_test_dw_agent(agent_id: &str) -> Self {
HostNode {
kind: NodeKind::DwAgent {
agent_id: agent_id.to_string(),
conversational: false,
},
..Self::for_test("dw.agent", Some(agent_id))
}
}
}
#[derive(Clone, Debug)]
enum NodeKind {
Exec {
target_component: String,
},
PackComponent {
component_ref: String,
},
ProviderInvoke,
FlowCall,
FlowGoto,
BuiltinEmit {
kind: EmitKind,
},
BuiltinStateGet,
BuiltinStateSet,
VarSet {
name: String,
value: Value,
},
Wait,
DwAgent {
agent_id: String,
conversational: bool,
},
DwAgentGraph {
graph_id: String,
},
SorlaCall {
target: String,
},
OperalaCall {
target: String,
},
AgenticCall {
target: String,
},
TelcoXCall {
target: String,
},
ApprovalCall {
target: String,
},
Mcp {
server_id: String,
tool: String,
},
A2a {
agent_id: String,
},
}
#[derive(Clone, Debug)]
enum EmitKind {
Log,
Response,
Other(String),
}
struct ComponentOverrides<'a> {
component: Option<&'a str>,
operation: Option<&'a str>,
}
struct ComponentCall {
component_ref: String,
operation: String,
input: Value,
config: Value,
has_error_route: bool,
}
struct FlowFailure {
error: anyhow::Error,
node_outputs: JsonMap<String, Value>,
}
impl From<anyhow::Error> for FlowFailure {
fn from(error: anyhow::Error) -> Self {
Self {
error,
node_outputs: JsonMap::new(),
}
}
}
impl FlowExecution {
fn completed(output: Value, node_outputs: JsonMap<String, Value>) -> Self {
Self {
output,
status: FlowStatus::Completed,
node_outputs,
}
}
fn waiting(output: Value, wait: FlowWait, node_outputs: JsonMap<String, Value>) -> Self {
Self {
output,
status: FlowStatus::Waiting(Box::new(wait)),
node_outputs,
}
}
}
const USER_FACING_FLOW_FAILURE_KEY: &str = "runner.flow.execution_failed";
pub(crate) const APPROVAL_RUNTIME: &str = "approval";
fn user_facing_flow_failure_text_for(locale: &str) -> String {
let text = crate::runner::i18n::resolve_message(
USER_FACING_FLOW_FAILURE_KEY,
crate::runner::i18n::FLOW_EXECUTION_FAILED_EN,
locale,
);
if text.trim().is_empty() {
return crate::runner::i18n::FLOW_EXECUTION_FAILED_EN.to_string();
}
text
}
fn user_facing_flow_failure_text(entry: &Value) -> String {
let locale = activity_locale(entry)
.map(str::to_owned)
.unwrap_or_else(|| crate::runner::i18n::select_locale(None));
user_facing_flow_failure_text_for(&locale)
}
impl FlowEngine {
pub async fn new(packs: Vec<Arc<PackRuntime>>, config: Arc<HostConfig>) -> Result<Self> {
let mut flow_sources: HashMap<FlowKey, usize> = HashMap::new();
let mut messaging_provider_pack_ids: std::collections::HashSet<String> =
std::collections::HashSet::new();
let mut descriptors = Vec::new();
let mut bindings = HashMap::new();
for pack in &config.pack_bindings {
bindings.insert(pack.pack_id.clone(), pack.flows.clone());
}
let enforce_bindings = !bindings.is_empty();
for (idx, pack) in packs.iter().enumerate() {
let pack_id = pack.metadata().pack_id.clone();
if enforce_bindings && !bindings.contains_key(&pack_id) {
bail!("no gtbind entries found for pack {}", pack_id);
}
let declares_messaging_provider = pack
.provider_registry_optional()
.ok()
.flatten()
.map(|registry| {
registry
.operator_metadata()
.iter()
.any(|meta| meta.provider_type.starts_with("messaging."))
})
.unwrap_or(false);
if declares_messaging_provider {
messaging_provider_pack_ids.insert(pack_id.clone());
}
let flows = pack.list_flows().await?;
let allowed = bindings.get(&pack_id).map(|flows| {
flows
.iter()
.cloned()
.collect::<std::collections::HashSet<_>>()
});
let mut seen = std::collections::HashSet::new();
for flow in flows {
if let Some(ref allow) = allowed
&& !allow.contains(&flow.id)
{
continue;
}
seen.insert(flow.id.clone());
tracing::info!(
flow_id = %flow.id,
flow_type = %flow.flow_type,
pack_id = %flow.pack_id,
pack_index = idx,
"registered flow"
);
if let Ok(flow_ir) = pack.load_flow(&flow.id) {
for node in flow_ir.nodes.values() {
config
.secrets_policy
.register_flow_secret_refs(&node.input.mapping);
config
.secrets_policy
.register_flow_secret_refs(&node.output.mapping);
}
}
flow_sources.insert(
FlowKey {
pack_id: flow.pack_id.clone(),
flow_id: flow.id.clone(),
},
idx,
);
descriptors.retain(|existing: &FlowDescriptor| {
!(existing.id == flow.id && existing.pack_id == flow.pack_id)
});
descriptors.push(flow);
}
if let Some(allow) = allowed {
let missing = allow.difference(&seen).cloned().collect::<Vec<_>>();
if !missing.is_empty() {
bail!(
"gtbind flow ids missing in pack {}: {}",
pack_id,
missing.join(", ")
);
}
}
}
let mut flow_map = HashMap::new();
for flow in &descriptors {
let pack_id = flow.pack_id.clone();
if let Some(&pack_idx) = flow_sources.get(&FlowKey {
pack_id: pack_id.clone(),
flow_id: flow.id.clone(),
}) {
let pack_clone = Arc::clone(&packs[pack_idx]);
let flow_id = flow.id.clone();
let task_flow_id = flow_id.clone();
match task::spawn_blocking(move || pack_clone.load_flow(&task_flow_id)).await {
Ok(Ok(loaded_flow)) => {
flow_map.insert(
FlowKey {
pack_id: pack_id.clone(),
flow_id,
},
HostFlow::from(loaded_flow),
);
}
Ok(Err(err)) => {
tracing::warn!(flow_id = %flow.id, error = %err, "failed to load flow metadata");
}
Err(err) => {
tracing::warn!(flow_id = %flow.id, error = %err, "join error loading flow metadata");
}
}
}
}
Ok(Self {
packs,
flows: descriptors,
flow_sources,
messaging_provider_pack_ids,
flow_cache: RwLock::new(flow_map),
default_env: env::var("GREENTIC_ENV").unwrap_or_else(|_| "local".to_string()),
validation: config.validation.clone(),
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
rollout_ids: RolloutIds::default(),
operala_node_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: crate::runner::mcp_node::source_from_env(),
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
})
}
pub fn with_rollout_ids(mut self, rollout_ids: RolloutIds) -> Self {
self.rollout_ids = rollout_ids;
self
}
pub fn rollout_ids(&self) -> &RolloutIds {
&self.rollout_ids
}
#[cfg(feature = "agentic-worker")]
pub(crate) fn mcp_credential_unit(&self) -> Option<&str> {
self.rollout_ids.bundle_id.as_deref()
}
#[cfg(feature = "agentic-worker")]
pub fn with_mcp_source(
mut self,
source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
) -> Self {
if let Some(source) = source {
self.mcp_tool_source = Some(source);
}
self
}
#[cfg(feature = "agentic-worker")]
pub fn with_mcp_secrets(mut self, secrets: Option<crate::secrets::DynSecretsManager>) -> Self {
if let Some(secrets) = secrets {
self.mcp_secrets = Some(secrets);
}
self
}
#[cfg(feature = "agentic-worker")]
fn mcp_secrets_for_dispatch(&self) -> Option<crate::secrets::DynSecretsManager> {
let requested = std::env::var("SECRETS_BACKEND").ok();
crate::runner::mcp_node::aw::choose_mcp_secrets(
requested.as_deref(),
crate::runner::mcp_node::aw::secrets_from_env(),
self.mcp_secrets.as_ref(),
)
}
pub fn set_cross_pack_resolver(&mut self, resolver: Arc<dyn CrossPackResolver>) {
self.cross_pack_resolver = Some(resolver);
}
pub fn set_remote_dispatch_handler(
&mut self,
handler: Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
) {
self.remote_dispatch_handler = Some(handler);
}
pub fn set_approval_dispatch_handler(
&mut self,
handler: Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
) {
self.approval_dispatch_handler = Some(handler);
}
fn dispatch_handler_for(
&self,
runtime: &str,
) -> Option<&Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>> {
if runtime == APPROVAL_RUNTIME {
self.approval_dispatch_handler
.as_ref()
.or(self.remote_dispatch_handler.as_ref())
} else {
self.remote_dispatch_handler.as_ref()
}
}
fn remote_dispatch_configured(&self) -> bool {
self.remote_dispatch_handler.is_some()
}
pub fn set_operala_node_handler(
&mut self,
handler: Arc<dyn crate::runner::operala_node::OperalaNodeHandler>,
) {
self.operala_node_handler = Some(handler);
}
#[cfg(feature = "agentic-worker")]
pub fn set_agent_node_handler(
&mut self,
handler: Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
) {
self.agent_node_handler = Some(handler);
}
#[cfg(feature = "agentic-worker")]
pub fn set_graph_node_handler(
&mut self,
handler: Arc<dyn crate::runner::graph_node::GraphNodeHandler>,
) {
self.graph_node_handler = Some(handler);
}
#[cfg(feature = "agentic-worker")]
pub fn set_dw_agent_dispatch(&mut self, mode: crate::runner::agent_node::DwAgentDispatch) {
self.dw_agent_dispatch = mode;
}
async fn get_or_load_flow(&self, pack_id: &str, flow_id: &str) -> Result<HostFlow> {
let key = FlowKey {
pack_id: pack_id.to_string(),
flow_id: flow_id.to_string(),
};
if let Some(flow) = self.flow_cache.read().get(&key).cloned() {
return Ok(flow);
}
let pack_idx = *self
.flow_sources
.get(&key)
.with_context(|| format!("flow {pack_id}:{flow_id} not registered"))?;
let pack = Arc::clone(&self.packs[pack_idx]);
let flow_id_owned = flow_id.to_string();
let task_flow_id = flow_id_owned.clone();
let flow = task::spawn_blocking(move || pack.load_flow(&task_flow_id))
.await
.context("failed to join flow metadata task")??;
let host_flow = HostFlow::from(flow);
self.flow_cache.write().insert(
FlowKey {
pack_id: pack_id.to_string(),
flow_id: flow_id_owned.clone(),
},
host_flow.clone(),
);
Ok(host_flow)
}
fn flow_execute_span(&self, ctx: &FlowContext<'_>) -> tracing::Span {
let span = tracing::info_span!(
"flow.execute",
tenant = tracing::field::Empty,
flow_id = tracing::field::Empty,
node_id = tracing::field::Empty,
tool = tracing::field::Empty,
action = tracing::field::Empty
);
annotate_span(
&span,
&FlowSpanAttributes {
tenant: ctx.tenant,
flow_id: ctx.flow_id,
node_id: ctx.node_id,
tool: ctx.tool,
action: ctx.action,
},
);
set_flow_context(
&span,
&self.default_env,
ctx.tenant,
ctx.flow_id,
ctx.node_id,
ctx.provider_id,
ctx.session_id,
ctx.pack_id,
&self.rollout_ids,
);
span
}
pub async fn execute(&self, ctx: FlowContext<'_>, input: Value) -> Result<FlowExecution> {
self.execute_with_entry(ctx, input, None).await
}
pub async fn execute_from(
&self,
ctx: FlowContext<'_>,
input: Value,
entry_node: &str,
) -> Result<FlowExecution> {
self.execute_with_entry(ctx, input, Some(entry_node.to_string()))
.await
}
async fn execute_with_entry(
&self,
ctx: FlowContext<'_>,
input: Value,
entry_node: Option<String>,
) -> Result<FlowExecution> {
if let Some(node) = entry_node.as_deref() {
let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
let node_id = NodeId::from_str(node)
.with_context(|| format!("invalid entry node id `{node}`"))?;
if !flow_ir.nodes.contains_key(&node_id) {
bail!("flow {} has no node `{}`", ctx.flow_id, node);
}
}
let span = self.flow_execute_span(&ctx);
let retry_config = ctx.retry_config;
let original_input = input;
let mut ctx = ctx;
let metric_tenant = ctx.tenant.to_string();
let metric_flow_id = ctx.flow_id.to_string();
let started = std::time::Instant::now();
let observer = ctx.observer;
let result = async move {
let mut attempt = 0u32;
loop {
attempt += 1;
ctx.attempt = attempt;
if let Some(observer) = ctx.observer {
observer.on_flow_attempt(ctx.flow_id, attempt);
}
#[cfg(feature = "fault-injection")]
{
let fault_ctx = FaultContext {
pack_id: ctx.pack_id,
flow_id: ctx.flow_id,
node_id: ctx.node_id,
attempt: ctx.attempt,
};
maybe_fail(FaultPoint::Timeout, fault_ctx)
.map_err(|err| anyhow!(err.to_string()))?;
}
match self
.execute_once(&ctx, original_input.clone(), entry_node.clone())
.await
{
Ok(value) => return Ok(value),
Err(FlowFailure {
error: err,
node_outputs,
}) => {
if attempt >= retry_config.max_attempts || !should_retry(&err) {
if ctx.session_id.is_some() {
return Ok(FlowExecution::completed(
json!({
"text": user_facing_flow_failure_text(&original_input),
"metadata": {
"error_kind": "flow_execution_failed",
"error_message": err.to_string(),
"flow_id": ctx.flow_id,
}
}),
node_outputs,
));
}
return Err(err);
}
let delay = backoff_delay_ms(retry_config.base_delay_ms, attempt - 1);
tracing::warn!(
tenant = ctx.tenant,
flow_id = ctx.flow_id,
attempt,
max_attempts = retry_config.max_attempts,
delay_ms = delay,
error = %err,
"transient flow execution failure, backing off"
);
tokio::time::sleep(Duration::from_millis(delay)).await;
}
}
}
}
.instrument(span)
.await;
if let Some(observer) = observer {
observer.on_flow_exit(&metric_flow_id);
}
let status = if result.is_ok() { "ok" } else { "err" };
let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
crate::metrics::record_flow_execution(&metric_tenant, &metric_flow_id, status, duration_ms);
result
}
pub async fn resume(
&self,
ctx: FlowContext<'_>,
snapshot: FlowSnapshot,
input: Value,
) -> Result<FlowExecution> {
if snapshot.pack_id != ctx.pack_id {
bail!(
"snapshot pack {} does not match requested {}",
snapshot.pack_id,
ctx.pack_id
);
}
let resume_flow = snapshot
.next_flow
.clone()
.unwrap_or_else(|| snapshot.flow_id.clone());
let flow_ir = self.get_or_load_flow(ctx.pack_id, &resume_flow).await?;
let pending_card_answers = pending_from_snapshot(&snapshot, &input);
let resumed_at = resumed_card_node(&snapshot);
let mut state = snapshot.state;
state.resumed_at = resumed_at;
state.replace_input(input.clone());
state.pending_card_answers = pending_card_answers;
state.entry = input;
let span = self.flow_execute_span(&ctx);
self.drive_flow(&ctx, flow_ir, state, Some(snapshot.next_node), resume_flow)
.instrument(span)
.await
.map_err(|failure| failure.error)
}
async fn execute_once(
&self,
ctx: &FlowContext<'_>,
input: Value,
entry_node: Option<String>,
) -> Result<FlowExecution, FlowFailure> {
let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
let mut state = ExecutionState::new(input);
let missing = seed_vars_and_collect_missing_required(
&flow_ir.vars_init,
&flow_ir.required_vars,
&mut state.vars,
);
if !missing.is_empty() {
let label = crate::runner::i18n::resolve_message(
"runner.flow.required_var_missing",
"required flow variable not provided",
"en",
);
return Err(anyhow!("{label}: {}", missing.join(", ")).into());
}
self.drive_flow(ctx, flow_ir, state, entry_node, ctx.flow_id.to_string())
.await
}
async fn drive_flow(
&self,
ctx: &FlowContext<'_>,
mut flow_ir: HostFlow,
mut state: ExecutionState,
resume_from: Option<String>,
mut current_flow_id: String,
) -> Result<FlowExecution, FlowFailure> {
let mut current = match resume_from {
Some(node) => NodeId::from_str(&node)
.with_context(|| format!("invalid resume node id `{node}`"))?,
None => flow_ir
.start
.clone()
.or_else(|| flow_ir.nodes.keys().next().cloned())
.with_context(|| format!("flow {} has no start node", flow_ir.id))?,
};
loop {
let step_ctx = FlowContext {
tenant: ctx.tenant,
pack_id: ctx.pack_id,
flow_id: current_flow_id.as_str(),
node_id: ctx.node_id,
tool: ctx.tool,
action: ctx.action,
session_id: ctx.session_id,
provider_id: ctx.provider_id,
reply_scope: ctx.reply_scope,
retry_config: ctx.retry_config,
attempt: ctx.attempt,
observer: ctx.observer,
mocks: ctx.mocks,
caller: ctx.caller,
};
let node = flow_ir
.nodes
.get(¤t)
.with_context(|| format!("node {} not found", current.as_str()))?;
let payload_template = node.payload_expr.clone();
let prev = state
.last_output
.as_ref()
.cloned()
.unwrap_or_else(|| Value::Object(JsonMap::new()));
let ctx_value = template_context(&state, prev);
#[cfg(feature = "fault-injection")]
{
let fault_ctx = FaultContext {
pack_id: ctx.pack_id,
flow_id: ctx.flow_id,
node_id: Some(current.as_str()),
attempt: ctx.attempt,
};
maybe_fail(FaultPoint::TemplateRender, fault_ctx)
.map_err(|err| anyhow!(err.to_string()))?;
}
let mut payload =
render_template_value(&payload_template, &ctx_value, TemplateOptions::default())
.context("failed to render node input template")?;
let node_id = current.clone();
if let NodeKind::Exec { target_component } = &node.kind
&& target_component == SLOT_EXTRACTOR_COMPONENT_ID
&& let Some(schema) = flow_ir.slot_schema.as_ref()
&& let Some(map) = payload.as_object_mut()
{
let input = map.entry("input").or_insert(Value::Null);
inject_slot_definitions(input, schema, step_ctx.flow_id, node_id.as_str());
}
let observed_payload = payload.clone();
let event = NodeEvent {
context: &step_ctx,
node_id: node_id.as_str(),
node,
payload: &observed_payload,
};
if let Some(observer) = step_ctx.observer {
observer.on_node_start(&event);
}
let dispatch = self
.dispatch_node(
&step_ctx,
node_id.as_str(),
node,
&mut state,
payload,
&event,
)
.await;
let DispatchOutcome {
mut output,
control,
} = match dispatch {
Ok(outcome) => outcome,
Err(err) => {
if let Some(observer) = step_ctx.observer {
observer.on_node_error(&event, err.as_ref());
}
return Err(FlowFailure {
error: err,
node_outputs: state.outputs_map(),
});
}
};
let owned_the_submit =
attach_pending_card_answers(&mut state, node_id.as_str(), node, &mut output);
state.nodes.insert(node_id.clone().into(), output.clone());
state.last_output = Some(output.payload.clone());
if let Some(bindings) = node.vars_out.as_ref() {
let ctx = template_context(&state, output.payload.clone());
for (var_name, template) in bindings.iter() {
let rendered = render_template_value(
template,
&ctx,
TemplateOptions {
allow_pointer: true,
},
)
.with_context(|| format!("failed to render vars_out binding `{var_name}`"))?;
state.vars.insert(var_name.clone(), rendered);
}
}
if let Some(observer) = step_ctx.observer {
observer.on_node_end(&event, &output.payload);
}
match control {
NodeControl::Continue => {
enum NextDecision {
Next(NodeId),
End,
Wait,
}
let decision = match &node.routing {
Routing::Next { node_id } => NextDecision::Next(node_id.clone()),
Routing::End | Routing::Reply => NextDecision::End,
Routing::Branch { default, .. } => match default {
Some(target) => NextDecision::Next(target.clone()),
None => NextDecision::End,
},
Routing::Custom(raw) => {
match evaluate_custom_routing(raw, &output, &state, &flow_ir, &node_id)
{
CustomRoutingDecision::Next(nid) => NextDecision::Next(nid),
CustomRoutingDecision::End => NextDecision::End,
CustomRoutingDecision::Wait => NextDecision::Wait,
}
}
};
if owned_the_submit {
consume_routing_action(&mut state.entry);
}
state.resumed_at = None;
match decision {
NextDecision::Next(n) => current = n,
NextDecision::End => {
let node_outputs = state.outputs_map();
let nodes_snapshot = state.nodes.clone();
let final_output = state.finalize_with(Some(output.payload.clone()));
return Ok(FlowExecution::completed(
lift_first_node_error_from_nodes(final_output, &nodes_snapshot),
node_outputs,
));
}
NextDecision::Wait => {
let mut snapshot_state = state.clone();
snapshot_state.clear_egress();
let snapshot = FlowSnapshot {
pack_id: step_ctx.pack_id.to_string(),
flow_id: step_ctx.flow_id.to_string(),
next_flow: (current_flow_id != step_ctx.flow_id)
.then_some(current_flow_id.clone()),
next_node: node_id.as_str().to_string(),
awaiting_submit: true,
state: snapshot_state,
};
let node_outputs = state.outputs_map();
let output_value = state.finalize_with(Some(output.payload.clone()));
return Ok(FlowExecution::waiting(
output_value,
FlowWait {
reason: Some(format!(
"awaiting user submit at node `{}`",
node_id.as_str()
)),
snapshot,
},
node_outputs,
));
}
}
}
NodeControl::Wait { reason } => {
let next: Option<NodeId> = match &node.routing {
Routing::Next { node_id } => Some(node_id.clone()),
Routing::End | Routing::Reply => None,
Routing::Branch { default, .. } => default.clone(),
Routing::Custom(raw) => {
match evaluate_custom_routing(raw, &output, &state, &flow_ir, &node_id)
{
CustomRoutingDecision::Next(nid) => Some(nid),
CustomRoutingDecision::End | CustomRoutingDecision::Wait => None,
}
}
};
let resume_target = next.ok_or_else(|| {
anyhow!(
"session.wait node {} requires a non-empty route",
current.as_str()
)
})?;
let mut snapshot_state = state.clone();
snapshot_state.clear_egress();
let snapshot = FlowSnapshot {
pack_id: step_ctx.pack_id.to_string(),
flow_id: step_ctx.flow_id.to_string(),
next_flow: (current_flow_id != step_ctx.flow_id)
.then_some(current_flow_id.clone()),
next_node: resume_target.as_str().to_string(),
awaiting_submit: false,
state: snapshot_state,
};
let node_outputs = state.outputs_map();
let output_value = state.clone().finalize_with(None);
return Ok(FlowExecution::waiting(
output_value,
FlowWait { reason, snapshot },
node_outputs,
));
}
NodeControl::LoopHere { reason } => {
let mut snapshot_state = state.clone();
snapshot_state.clear_egress();
let snapshot = FlowSnapshot {
pack_id: step_ctx.pack_id.to_string(),
flow_id: step_ctx.flow_id.to_string(),
next_flow: (current_flow_id != step_ctx.flow_id)
.then_some(current_flow_id.clone()),
next_node: node_id.as_str().to_string(),
awaiting_submit: false,
state: snapshot_state,
};
let node_outputs = state.outputs_map();
let rendered = rendered_park(&output.payload);
let output_value = state.finalize_with(Some(rendered));
return Ok(FlowExecution::waiting(
output_value,
FlowWait { reason, snapshot },
node_outputs,
));
}
NodeControl::AwaitHere {
reason,
correlation_id: _,
} => {
let mut snapshot_state = state.clone();
snapshot_state.clear_egress();
let snapshot = FlowSnapshot {
pack_id: step_ctx.pack_id.to_string(),
flow_id: step_ctx.flow_id.to_string(),
next_flow: (current_flow_id != step_ctx.flow_id)
.then_some(current_flow_id.clone()),
next_node: node_id.as_str().to_string(), awaiting_submit: false,
state: snapshot_state,
};
let node_outputs = state.outputs_map();
let output_value = state.clone().finalize_with(None);
return Ok(FlowExecution::waiting(
output_value,
FlowWait { reason, snapshot },
node_outputs,
));
}
NodeControl::Jump(jump) => {
let jump_target = self.apply_jump(&step_ctx, &mut state, jump).await?;
flow_ir = jump_target.flow;
current_flow_id = jump_target.flow_id;
current = jump_target.node_id;
}
NodeControl::Respond {
text,
card_cbor,
needs_user,
} => {
let response = json!({
"text": text,
"card_cbor": card_cbor,
"needs_user": needs_user,
});
state.push_egress(response);
let node_outputs = state.outputs_map();
let nodes_snapshot = state.nodes.clone();
let final_output = state.finalize_with(None);
return Ok(FlowExecution::completed(
lift_first_node_error_from_nodes(final_output, &nodes_snapshot),
node_outputs,
));
}
}
}
}
async fn dispatch_node(
&self,
ctx: &FlowContext<'_>,
node_id: &str,
node: &HostNode,
state: &mut ExecutionState,
mut payload: Value,
event: &NodeEvent<'_>,
) -> Result<DispatchOutcome> {
inject_card_locale(&mut payload, &state.entry);
inject_card_route(&mut payload, &state.entry, node);
match &node.kind {
NodeKind::Exec { target_component } => self
.execute_component_exec(
ctx,
node_id,
node,
payload,
event,
ComponentOverrides {
component: Some(target_component.as_str()),
operation: node.operation_name.as_deref(),
},
)
.await
.and_then(component_dispatch_outcome),
NodeKind::PackComponent { component_ref } => self
.execute_component_call(ctx, node_id, node, payload, component_ref.as_str(), event)
.await
.and_then(component_dispatch_outcome),
NodeKind::FlowCall => self
.execute_flow_call(ctx, payload)
.await
.map(DispatchOutcome::complete),
NodeKind::FlowGoto => execute_flow_goto(payload),
NodeKind::ProviderInvoke => self
.execute_provider_invoke(ctx, node_id, state, payload, event)
.await
.map(DispatchOutcome::complete),
NodeKind::BuiltinEmit { kind } => {
match kind {
EmitKind::Log | EmitKind::Response => {}
EmitKind::Other(component) => {
tracing::debug!(%component, "handling emit.* as builtin");
}
}
state.push_egress(payload.clone());
Ok(DispatchOutcome::complete(NodeOutput::new(payload)))
}
NodeKind::BuiltinStateGet => self
.execute_state_get(ctx, payload)
.await
.map(DispatchOutcome::complete),
NodeKind::BuiltinStateSet => self
.execute_state_set(ctx, payload)
.await
.map(DispatchOutcome::complete),
NodeKind::VarSet { name, value } => {
if name.trim().is_empty() {
tracing::warn!(
node_id = %node_id,
"var_set node has an empty variable name; skipping write"
);
return Ok(DispatchOutcome::complete(NodeOutput::new(
serde_json::json!({ "ok": true }),
)));
}
let prev = state.last_output.clone().unwrap_or(Value::Null);
let ctx_val = template_context(state, prev);
let rendered = render_template_value(
value,
&ctx_val,
TemplateOptions {
allow_pointer: true,
},
)
.context("failed to render var_set value")?;
state.vars.insert(name.clone(), rendered);
Ok(DispatchOutcome::complete(NodeOutput::new(
serde_json::json!({ "ok": true }),
)))
}
NodeKind::Wait => {
let reason = extract_wait_reason(&payload);
Ok(DispatchOutcome::wait(NodeOutput::new(payload), reason))
}
NodeKind::DwAgent {
agent_id,
conversational,
} => {
#[cfg(feature = "agentic-worker")]
match self.dw_agent_dispatch {
crate::runner::agent_node::DwAgentDispatch::Nats => {
if *conversational {
let is_agent_response = state.entry.get("ok").is_some();
if is_agent_response && state.take_agent_await(node_id) {
let ok = state
.entry
.get("ok")
.and_then(Value::as_bool)
.unwrap_or(false);
if !ok {
let message = state
.entry
.get("error")
.and_then(|e| e.get("message"))
.and_then(Value::as_str)
.unwrap_or("the agent could not respond");
tracing::warn!(
agent_id = %agent_id,
error = %message,
"conversational dw.agent (nats) response was an error/timeout envelope; surfacing and re-parking without bumping the park-loop cap"
);
let output =
NodeOutput::new(serde_json::json!({ "reply": message }));
Ok(DispatchOutcome::with_control(
output,
NodeControl::LoopHere {
reason: Some(format!(
"conversational dw.agent `{agent_id}` (nats) awaiting next user message after error response"
)),
},
))
} else {
let agent_out =
state.entry.get("output").cloned().unwrap_or(Value::Null);
let output = NodeOutput::new(agent_out.clone());
let ended = agent_out
.get("terminated_by")
.and_then(serde_json::Value::as_str)
== Some("conversation_ended");
if ended {
state.reset_park_turns(node_id);
Ok(DispatchOutcome::complete(output))
} else {
let turns = state.bump_park_turns(node_id);
if turns >= MAX_PARK_TURNS {
tracing::warn!(
agent_id = %agent_id,
turns,
"conversational dw.agent (nats) hit park-loop cap ({MAX_PARK_TURNS}); force-advancing to successor"
);
state.reset_park_turns(node_id);
Ok(DispatchOutcome::complete(output))
} else {
Ok(DispatchOutcome::with_control(
output,
NodeControl::LoopHere {
reason: Some(format!(
"conversational dw.agent `{agent_id}` (nats) awaiting next user message"
)),
},
))
}
}
}
} else {
state.mark_agent_await(node_id);
let remote_payload =
serde_json::json!({ "await": true, "input": payload });
self.execute_remote_dispatch(
ctx,
"agentic",
agent_id,
remote_payload,
true,
)
.await
}
} else {
let remote_payload =
serde_json::json!({ "await": true, "input": payload });
self.execute_remote_dispatch(
ctx,
"agentic",
agent_id,
remote_payload,
false,
)
.await
}
}
crate::runner::agent_node::DwAgentDispatch::InProcess => {
let resume_payload = (state.take_tool_await(node_id)
&& is_card_submit(&state.entry))
.then(|| state.entry.clone());
let output = self
.execute_dw_agent(
ctx,
agent_id,
payload,
*conversational,
resume_payload.as_ref(),
)
.await?;
if awaiting_tool_input(&output.payload) {
state.mark_tool_await(node_id);
Ok(DispatchOutcome::with_control(
output,
NodeControl::LoopHere {
reason: Some(format!(
"dw.agent `{agent_id}` awaiting the user on a flow tool"
)),
},
))
} else if *conversational {
let ended = output
.payload
.get("terminated_by")
.and_then(serde_json::Value::as_str)
== Some("conversation_ended");
if ended {
state.reset_park_turns(node_id);
Ok(DispatchOutcome::complete(output))
} else {
let turns = state.bump_park_turns(node_id);
if turns >= MAX_PARK_TURNS {
tracing::warn!(
agent_id = %agent_id,
turns,
"conversational dw.agent hit park-loop cap ({MAX_PARK_TURNS}); force-advancing to successor"
);
state.reset_park_turns(node_id);
Ok(DispatchOutcome::complete(output))
} else {
Ok(DispatchOutcome::with_control(
output,
NodeControl::LoopHere {
reason: Some(format!(
"conversational dw.agent `{agent_id}` awaiting next user message"
)),
},
))
}
}
} else {
Ok(DispatchOutcome::complete(output))
}
}
}
#[cfg(not(feature = "agentic-worker"))]
{
self.execute_dw_agent(ctx, agent_id, payload, *conversational, None)
.await
.map(DispatchOutcome::complete)
}
}
NodeKind::DwAgentGraph { graph_id } => self
.execute_dw_agent_graph(ctx, graph_id, payload)
.await
.map(DispatchOutcome::complete),
NodeKind::SorlaCall { target } => {
self.execute_sorla_call(
ctx,
node_id,
target,
payload,
node_has_error_route(&node.routing),
)
.await
}
NodeKind::OperalaCall { target } => {
self.execute_operala_call(ctx, target, payload).await
}
NodeKind::AgenticCall { target } => {
self.execute_agentic_call(ctx, target, payload).await
}
NodeKind::TelcoXCall { target } => {
self.execute_telco_x_call(ctx, target, payload).await
}
NodeKind::ApprovalCall { target } => {
self.execute_approval_call(ctx, node_id, target, payload, state)
.await
}
NodeKind::Mcp { server_id, tool } => self
.execute_mcp(
ctx,
server_id,
tool,
payload,
node_has_error_route(&node.routing),
)
.await
.map(DispatchOutcome::complete),
NodeKind::A2a { agent_id } => self
.execute_a2a(ctx, agent_id, payload, node_has_error_route(&node.routing))
.await
.map(DispatchOutcome::complete),
}
}
#[cfg(feature = "agentic-worker")]
async fn execute_dw_agent(
&self,
ctx: &FlowContext<'_>,
agent_id: &str,
payload: Value,
conversational: bool,
resume_payload: Option<&Value>,
) -> Result<NodeOutput> {
let handler = self
.agent_node_handler
.as_ref()
.context("DwAgent node dispatched but no AgentNodeHandler configured on FlowEngine")?;
let session_owned = crate::runner::nested_flow::agent_session_for(ctx.session_id)
.map_err(anyhow::Error::msg)?;
let session_id = session_owned.as_str();
let started = std::time::Instant::now();
let mut result = handler
.execute_with_resume(
ctx.tenant,
&self.default_env,
agent_id,
session_id,
&payload,
conversational,
ctx.caller,
resume_payload,
)
.await?;
if let Value::Object(map) = &mut result {
map.insert(
"duration_ms".into(),
Value::from(started.elapsed().as_millis() as u64),
);
}
Ok(NodeOutput::new(result))
}
#[cfg(not(feature = "agentic-worker"))]
async fn execute_dw_agent(
&self,
_ctx: &FlowContext<'_>,
agent_id: &str,
_payload: Value,
_conversational: bool,
_resume_payload: Option<&Value>,
) -> Result<NodeOutput> {
anyhow::bail!(
"DwAgent node '{agent_id}' cannot run: this build was compiled without the \
`agentic-worker` feature. Rebuild with --features agentic-worker."
)
}
#[cfg(feature = "agentic-worker")]
async fn execute_sorla_call(
&self,
ctx: &FlowContext<'_>,
node_id: &str,
target: &str,
payload: Value,
has_error_route: bool,
) -> Result<DispatchOutcome> {
let caller = format!("flow:{}/{node_id}", ctx.flow_id);
let http_result = match self.mcp_secrets_for_dispatch() {
Some(secrets) => {
crate::runner::sorla_node::execute_sorla_http(
&*secrets,
ctx.tenant,
self.mcp_credential_unit(),
target,
&payload,
&caller,
)
.await
}
None => Ok(None),
};
match http_result {
Ok(Some(result)) => {
let bound = match payload.get("output").and_then(Value::as_str) {
Some(key) if !key.is_empty() => json!({ key: result.clone() }),
_ => result.clone(),
};
Ok(DispatchOutcome::complete(mcp_node_output(
bound,
&result,
has_error_route,
)))
}
Ok(None) if self.remote_dispatch_configured() => {
self.execute_remote_dispatch(ctx, "sorla", target, payload, false)
.await
}
Ok(None) => sorla_failure(
format!(
"sorla_route_missing: no route document for SoR `{target}` and no NATS configured"
),
has_error_route,
),
Err(e) => sorla_failure(e, has_error_route),
}
}
#[cfg(not(feature = "agentic-worker"))]
async fn execute_sorla_call(
&self,
ctx: &FlowContext<'_>,
_node_id: &str,
target: &str,
payload: Value,
_has_error_route: bool,
) -> Result<DispatchOutcome> {
self.execute_remote_dispatch(ctx, "sorla", target, payload, false)
.await
}
async fn execute_operala_call(
&self,
ctx: &FlowContext<'_>,
target: &str,
payload: Value,
) -> Result<DispatchOutcome> {
if let Some(handler) = self.operala_node_handler.as_ref() {
let raw_operation = payload
.get("operation")
.and_then(Value::as_str)
.unwrap_or_default();
let operation = if raw_operation.eq_ignore_ascii_case("invoke") {
"run"
} else {
raw_operation
};
let inner_input = payload.get("input").cloned().unwrap_or(Value::Null);
let session_id = ctx.session_id.unwrap_or("");
let result = handler
.execute(
ctx.tenant,
&self.default_env,
target,
operation,
session_id,
&inner_input,
)
.await?;
return Ok(DispatchOutcome::complete(NodeOutput::new(result)));
}
self.execute_remote_dispatch(ctx, "operala", target, payload, false)
.await
}
async fn execute_agentic_call(
&self,
ctx: &FlowContext<'_>,
target: &str,
payload: Value,
) -> Result<DispatchOutcome> {
self.execute_remote_dispatch(ctx, "agentic", target, payload, false)
.await
}
async fn execute_telco_x_call(
&self,
ctx: &FlowContext<'_>,
target: &str,
payload: Value,
) -> Result<DispatchOutcome> {
self.execute_remote_dispatch(ctx, "telco-x", target, payload, false)
.await
}
async fn execute_approval_call(
&self,
ctx: &FlowContext<'_>,
node_id: &str,
target: &str,
payload: Value,
state: &mut ExecutionState,
) -> Result<DispatchOutcome> {
if let Some(parked) = state.take_approval_await(node_id) {
if entry_is_approval_response(&state.entry) {
if response_authenticates(&state.entry, &parked) {
let mut response = state.entry.clone();
approval_token::strip_from_response(&mut response);
let outcome = approval_outcome_from_entry(&response);
let output =
NodeOutput::with_meta(response, serde_json::json!({ "outcome": outcome }));
return Ok(DispatchOutcome::complete(output));
}
tracing::warn!(
node_id,
"refusing approval response: its decision_token is missing or does not match the one this gate was issued; the gate stays parked"
);
}
state.mark_approval_await(node_id, parked);
return Ok(DispatchOutcome::await_here(
NodeOutput::new(serde_json::json!({ "pending": true })),
Some("awaiting approval decision".to_string()),
String::new(),
));
}
let input = payload.get("input").cloned().unwrap_or(Value::Null);
if !approval_requires_human(&input) {
let output = NodeOutput::with_meta(
serde_json::json!({
"ok": true,
"output": { "decision": "approved", "auto": true },
"error": serde_json::Value::Null,
}),
serde_json::json!({ "outcome": "approved" }),
);
return Ok(DispatchOutcome::complete(output));
}
let issued = approval_token::issue();
let outcome = self
.execute_remote_dispatch_with_token(
ctx,
APPROVAL_RUNTIME,
target,
payload,
true,
Some(issued.token),
)
.await?;
if let NodeControl::AwaitHere { correlation_id, .. } = &outcome.control {
state.mark_approval_await(
node_id,
ParkedApproval {
correlation_id: Some(correlation_id.clone()).filter(|id| !id.is_empty()),
token_fingerprint: Some(issued.fingerprint),
},
);
}
Ok(outcome)
}
#[cfg(feature = "agentic-worker")]
async fn execute_mcp(
&self,
ctx: &FlowContext<'_>,
server_id: &str,
tool: &str,
payload: Value,
has_error_route: bool,
) -> Result<NodeOutput> {
let payload_server = crate::runner::mcp_node::str_field(&payload, "server");
let payload_tool = crate::runner::mcp_node::str_field(&payload, "tool");
let server_id = payload_server.as_deref().unwrap_or(server_id);
let tool = payload_tool.as_deref().unwrap_or(tool);
let arguments = payload
.get("arguments")
.cloned()
.unwrap_or_else(|| Value::Object(JsonMap::new()));
let pack_routes = self
.packs
.iter()
.find(|pack| pack.metadata().pack_id == ctx.pack_id)
.and_then(|pack| pack.mcp_routes());
let auth_team = pack_routes
.and_then(|routes| routes.get(server_id))
.and_then(|route| route.auth_team.as_deref());
let secrets = self.mcp_secrets_for_dispatch();
let result = crate::runner::mcp_node::aw::invoke_with_secrets(
self.mcp_tool_source.as_ref(),
pack_routes,
secrets.as_ref(),
ctx.tenant,
&self.default_env,
auth_team,
self.mcp_credential_unit(),
server_id,
tool,
&arguments,
)
.await;
Ok(mcp_node_output(
bind_node_result(&payload, result.clone()),
&result,
has_error_route,
))
}
#[cfg(not(feature = "agentic-worker"))]
async fn execute_mcp(
&self,
_ctx: &FlowContext<'_>,
server_id: &str,
tool: &str,
_payload: Value,
_has_error_route: bool,
) -> Result<NodeOutput> {
Ok(NodeOutput::new(json!({
"error": format!(
"mcp node '{server_id}/{tool}' requires the agentic-worker feature (MCP runtime not compiled in)"
)
})))
}
#[cfg(feature = "agentic-worker")]
fn a2a_source_for(
&self,
tenant: &str,
pack: &Arc<PackRuntime>,
) -> Option<Arc<greentic_aw_runtime::A2aToolSource>> {
let key = (tenant.to_string(), pack.metadata().pack_id.to_string());
if let Some(cached) = self.a2a_sources.read().get(&key) {
return Some(Arc::clone(cached));
}
let secrets = self.mcp_secrets_for_dispatch();
let source = crate::runner::a2a_node::aw::source_for_pack(
pack,
tenant,
secrets,
self.mcp_credential_unit(),
)?;
let mut sources = self.a2a_sources.write();
let entry = sources.entry(key).or_insert(source);
Some(Arc::clone(entry))
}
#[cfg(feature = "agentic-worker")]
async fn execute_a2a(
&self,
ctx: &FlowContext<'_>,
agent_id: &str,
payload: Value,
has_error_route: bool,
) -> Result<NodeOutput> {
let payload_agent = crate::runner::a2a_node::agent_from_payload(&payload);
let agent_id = payload_agent.as_deref().unwrap_or(agent_id);
let pack = self.pack_for_flow(ctx)?;
let pack_id = pack.metadata().pack_id.to_string();
let Some(message) = payload.get("message").filter(|value| !is_blank(value)) else {
let result = greentic_aw_runtime::a2a_source::call_error_value(
agent_id,
"a2a node has no `message` to send (expected a non-empty `message` field \
in the node's config)",
);
tracing::warn!(agent = agent_id, "a2a node has no message configured");
return Ok(a2a_node_output(
bind_node_result(&payload, result.clone()),
&result,
has_error_route,
));
};
let source = self.a2a_source_for(ctx.tenant, pack);
let store = pack.state_store_handle();
let state_ctx = self.state_tenant_ctx(ctx).ok();
let result = crate::runner::a2a_node::aw::invoke(
crate::runner::a2a_node::aw::A2aCall {
source: source.as_ref(),
store: store.as_ref(),
state_ctx: state_ctx.as_ref(),
flow_id: ctx.flow_id,
session_id: ctx.session_id.filter(|hint| !hint.is_empty()),
tenant: ctx.tenant,
env: &self.default_env,
pack_id: &pack_id,
},
agent_id,
message,
)
.await;
Ok(a2a_node_output(
bind_node_result(&payload, result.clone()),
&result,
has_error_route,
))
}
#[cfg(not(feature = "agentic-worker"))]
async fn execute_a2a(
&self,
_ctx: &FlowContext<'_>,
agent_id: &str,
_payload: Value,
_has_error_route: bool,
) -> Result<NodeOutput> {
Ok(NodeOutput::new(json!({
"status": "error",
"agent": agent_id,
"error": format!(
"a2a node '{agent_id}' requires the agentic-worker feature (the A2A client is \
not compiled in)"
)
})))
}
async fn execute_remote_dispatch(
&self,
ctx: &FlowContext<'_>,
runtime: &str,
target: &str,
payload: Value,
resume_at_self: bool,
) -> Result<DispatchOutcome> {
self.execute_remote_dispatch_with_token(ctx, runtime, target, payload, resume_at_self, None)
.await
}
async fn execute_remote_dispatch_with_token(
&self,
ctx: &FlowContext<'_>,
runtime: &str,
target: &str,
payload: Value,
resume_at_self: bool,
decision_token: Option<String>,
) -> Result<DispatchOutcome> {
let handler = self.dispatch_handler_for(runtime).with_context(|| {
format!("{runtime}.call node dispatched but no RemoteDispatchHandler configured")
})?;
let await_mode = payload
.get("await")
.and_then(Value::as_bool)
.unwrap_or(true);
let operation = payload
.get("operation")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let deadline_ms = payload.get("deadline_ms").and_then(Value::as_u64);
let inner_input = payload.get("input").cloned().unwrap_or(Value::Null);
let raw_hint = ctx.session_id.unwrap_or_default();
let bare_hint = raw_hint.split("::").next().unwrap_or_default();
let mut correlation_id =
format!("{}::pack={}::flow={}", bare_hint, ctx.pack_id, ctx.flow_id);
if let Some(scope) = ctx.reply_scope {
if let Some(thread) = scope.thread.as_deref().filter(|value| !value.is_empty()) {
correlation_id.push_str("::thread=");
correlation_id.push_str(thread);
}
if let Some(reply_to) = scope.reply_to.as_deref().filter(|value| !value.is_empty()) {
correlation_id.push_str("::reply=");
correlation_id.push_str(reply_to);
}
}
if runtime == APPROVAL_RUNTIME {
correlation_id.push_str(crate::runner::runtime_session_resumer::NONCE_HINT_MARKER);
correlation_id.push_str(&crate::runner::runtime_session_resumer::new_dispatch_nonce());
}
let mode = if await_mode {
greentic_types::DispatchMode::Await
} else {
greentic_types::DispatchMode::FireAndForget
};
let action = handler
.dispatch(crate::runner::remote_dispatch::RemoteDispatch {
tenant: ctx.tenant.to_string(),
env: self.default_env.clone(),
runtime: runtime.to_string(),
target: target.to_string(),
operation,
mode,
correlation_id: correlation_id.clone(),
input: inner_input,
deadline_ms,
decision_token,
})
.await?;
match action {
crate::runner::remote_dispatch::RemoteDispatchAction::AwaitingResponse {
correlation_id,
} => {
let reason = format!("await-runtime:{correlation_id}");
let output = NodeOutput::new(serde_json::json!({
"pending": true,
"correlation_id": correlation_id.clone(),
}));
if resume_at_self {
Ok(DispatchOutcome::await_here(
output,
Some(reason),
correlation_id,
))
} else {
Ok(DispatchOutcome::wait(output, Some(reason)))
}
}
crate::runner::remote_dispatch::RemoteDispatchAction::Dispatched => {
let output = NodeOutput::new(serde_json::json!({
"dispatched": true,
"correlation_id": correlation_id,
}));
Ok(DispatchOutcome::complete(output))
}
}
}
#[cfg(feature = "agentic-worker")]
async fn execute_dw_agent_graph(
&self,
ctx: &FlowContext<'_>,
graph_id: &str,
payload: Value,
) -> Result<NodeOutput> {
let handler = self.graph_node_handler.as_ref().context(
"DwAgentGraph node dispatched but no GraphNodeHandler configured on FlowEngine",
)?;
let session_id = ctx.session_id.unwrap_or("");
let result = handler
.execute(
ctx.tenant,
&self.default_env,
graph_id,
session_id,
&payload,
)
.await?;
Ok(NodeOutput::new(result))
}
#[cfg(not(feature = "agentic-worker"))]
async fn execute_dw_agent_graph(
&self,
_ctx: &FlowContext<'_>,
graph_id: &str,
_payload: Value,
) -> Result<NodeOutput> {
anyhow::bail!(
"DwAgentGraph node '{graph_id}' cannot run: this build was compiled without the \
`agentic-worker` feature. Rebuild with --features agentic-worker."
)
}
async fn execute_state_get(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
let key = Self::extract_state_key_helper(&payload)?;
let pack = self.pack_for_flow(ctx)?;
let store = pack
.state_store_handle()
.context("state store is not configured for this runtime")?;
let tenant_ctx = self.state_tenant_ctx(ctx)?;
let state_key = greentic_state::StateKey::new(&key);
let value = store
.get_json(
&tenant_ctx,
crate::storage::state::STATE_PREFIX,
&state_key,
None,
)
.with_context(|| format!("state.get failed for key `{key}`"))?;
let payload = serde_json::json!({
"key": key,
"value": value,
"found": value.is_some(),
});
Ok(NodeOutput::new(payload))
}
async fn execute_state_set(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
let key = Self::extract_state_key_helper(&payload)?;
let value = payload.get("value").cloned().unwrap_or(Value::Null);
let pack = self.pack_for_flow(ctx)?;
let store = pack
.state_store_handle()
.context("state store is not configured for this runtime")?;
let tenant_ctx = self.state_tenant_ctx(ctx)?;
let state_key = greentic_state::StateKey::new(&key);
store
.set_json(
&tenant_ctx,
crate::storage::state::STATE_PREFIX,
&state_key,
None,
&value,
None,
)
.with_context(|| format!("state.set failed for key `{key}`"))?;
let payload = serde_json::json!({ "key": key, "value": value });
Ok(NodeOutput::new(payload))
}
fn pack_for_flow(&self, ctx: &FlowContext<'_>) -> Result<&Arc<PackRuntime>> {
let key = FlowKey {
pack_id: ctx.pack_id.to_string(),
flow_id: ctx.flow_id.to_string(),
};
let idx = self.flow_sources.get(&key).with_context(|| {
format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
})?;
Ok(&self.packs[*idx])
}
fn extract_state_key_helper(payload: &Value) -> Result<String> {
payload
.get("key")
.and_then(Value::as_str)
.map(String::from)
.filter(|k| !k.is_empty())
.context("state node payload missing required `key` (non-empty string)")
}
fn state_tenant_ctx(&self, ctx: &FlowContext<'_>) -> Result<greentic_types::TenantCtx> {
let env = greentic_types::EnvId::from_str(&self.default_env)
.with_context(|| format!("invalid env id `{}`", self.default_env))?;
let tenant = greentic_types::TenantId::from_str(ctx.tenant)
.with_context(|| format!("invalid tenant id `{}`", ctx.tenant))?;
Ok(greentic_types::TenantCtx::new(env, tenant))
}
async fn apply_jump(
&self,
ctx: &FlowContext<'_>,
state: &mut ExecutionState,
jump: JumpControl,
) -> Result<JumpTarget> {
let target_flow = jump.flow.trim();
if target_flow.is_empty() {
bail!("missing_flow");
}
let flow = self
.get_or_load_flow(ctx.pack_id, target_flow)
.await
.with_context(|| format!("unknown_flow:{target_flow}"))?;
let target_node = if let Some(node) = jump.node.as_deref() {
let parsed = NodeId::from_str(node).with_context(|| format!("unknown_node:{node}"))?;
if !flow.nodes.contains_key(&parsed) {
bail!("unknown_node:{node}");
}
parsed
} else {
flow.start
.clone()
.or_else(|| flow.nodes.keys().next().cloned())
.ok_or_else(|| anyhow!("jump_failed: flow {target_flow} has no start node"))?
};
let max_redirects = jump.max_redirects.unwrap_or(3);
if state.redirect_count() >= max_redirects {
bail!("redirect_limit");
}
state.increment_redirect_count();
state.replace_input(jump.payload.clone());
state.last_output = Some(jump.payload);
tracing::info!(
flow_id = %ctx.flow_id,
target_flow = %target_flow,
target_node = %target_node.as_str(),
reason = ?jump.reason,
redirects = state.redirect_count(),
"flow.jump.applied"
);
Ok(JumpTarget {
flow_id: target_flow.to_string(),
flow,
node_id: target_node,
})
}
async fn execute_flow_call(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
#[derive(Deserialize)]
struct FlowCallPayload {
#[serde(alias = "flow")]
flow_id: String,
#[serde(default)]
input: Value,
}
let call: FlowCallPayload =
serde_json::from_value(payload).context("invalid payload for flow.call node")?;
if call.flow_id.trim().is_empty() {
bail!("flow.call requires a non-empty flow_id");
}
let sub_input = if call.input.is_null() {
Value::Null
} else {
call.input
};
let flow_id_owned = call.flow_id;
let action = "flow.call";
let sub_ctx = FlowContext {
tenant: ctx.tenant,
pack_id: ctx.pack_id,
flow_id: flow_id_owned.as_str(),
node_id: None,
tool: ctx.tool,
action: Some(action),
session_id: ctx.session_id,
provider_id: ctx.provider_id,
reply_scope: ctx.reply_scope,
retry_config: ctx.retry_config,
attempt: ctx.attempt,
observer: ctx.observer,
mocks: ctx.mocks,
caller: ctx.caller,
};
let execution = Box::pin(self.execute(sub_ctx, sub_input))
.await
.with_context(|| format!("flow.call failed for {}", flow_id_owned))?;
match execution.status {
FlowStatus::Completed => Ok(NodeOutput::new(execution.output)),
FlowStatus::Waiting(wait) => bail!(
"flow.call cannot pause (flow {} waiting {:?})",
flow_id_owned,
wait.reason
),
}
}
}
fn execute_flow_goto(payload: Value) -> Result<DispatchOutcome> {
#[derive(Deserialize)]
struct FlowGotoPayload {
#[serde(alias = "flow")]
flow_id: String,
#[serde(default)]
node: Option<String>,
#[serde(default)]
input: Value,
#[serde(default)]
max_redirects: Option<u32>,
#[serde(default)]
reason: Option<String>,
}
let goto: FlowGotoPayload =
serde_json::from_value(payload).context("invalid payload for flow.goto node")?;
let flow = goto.flow_id.trim().to_string();
if flow.is_empty() {
bail!("flow.goto requires a non-empty flow_id");
}
let node = goto
.node
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty());
let jump = JumpControl {
flow,
node,
payload: goto.input,
hints: Value::Null,
max_redirects: goto.max_redirects,
reason: goto.reason.or_else(|| Some("flow.goto node".to_string())),
};
let output = NodeOutput::with_meta(jump.payload.clone(), jump.hints.clone());
Ok(DispatchOutcome::with_control(
output,
NodeControl::Jump(jump),
))
}
impl FlowEngine {
async fn execute_component_exec(
&self,
ctx: &FlowContext<'_>,
node_id: &str,
node: &HostNode,
payload: Value,
event: &NodeEvent<'_>,
overrides: ComponentOverrides<'_>,
) -> Result<NodeOutput> {
#[derive(Deserialize)]
struct ComponentPayload {
#[serde(default, alias = "component_ref", alias = "component")]
component: Option<String>,
#[serde(alias = "op")]
operation: Option<String>,
#[serde(default)]
input: Value,
#[serde(default)]
config: Value,
}
let payload: ComponentPayload =
serde_json::from_value(payload).context("invalid payload for component.exec")?;
let component_ref = overrides
.component
.map(str::to_string)
.or_else(|| payload.component.filter(|v| !v.trim().is_empty()))
.with_context(|| "component.exec requires a component_ref")?;
let operation = resolve_component_operation(
node_id,
node.component_id.as_str(),
payload.operation,
overrides.operation,
node.operation_in_mapping.as_deref(),
)?;
let call = ComponentCall {
component_ref,
operation,
input: payload.input,
config: payload.config,
has_error_route: node_has_error_route(&node.routing),
};
self.invoke_component_call(ctx, node_id, call, event).await
}
async fn execute_component_call(
&self,
ctx: &FlowContext<'_>,
node_id: &str,
node: &HostNode,
payload: Value,
component_ref: &str,
event: &NodeEvent<'_>,
) -> Result<NodeOutput> {
let payload_operation = extract_operation_from_mapping(&payload);
let (input, config) = split_operation_payload(payload);
let operation = resolve_component_operation(
node_id,
node.component_id.as_str(),
payload_operation,
node.operation_name.as_deref(),
node.operation_in_mapping.as_deref(),
)?;
let call = ComponentCall {
component_ref: component_ref.to_string(),
operation,
input,
config,
has_error_route: node_has_error_route(&node.routing),
};
self.invoke_component_call(ctx, node_id, call, event).await
}
async fn invoke_component_call(
&self,
ctx: &FlowContext<'_>,
node_id: &str,
mut call: ComponentCall,
event: &NodeEvent<'_>,
) -> Result<NodeOutput> {
self.validate_component(ctx, event, &call)?;
let key = FlowKey {
pack_id: ctx.pack_id.to_string(),
flow_id: ctx.flow_id.to_string(),
};
let pack_idx = *self.flow_sources.get(&key).with_context(|| {
format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
})?;
let pack = Arc::clone(&self.packs[pack_idx]);
promote_card_config_to_invocation(&mut call.input, &call.config);
resolve_card_assets(&mut call.input, &pack);
let is_card = is_card_invocation(&call.input);
let exec_ctx = component_exec_ctx(ctx, node_id);
let caller = component_caller(ctx);
let input_json = if is_card {
serde_json::to_string(&call.input)?
} else {
let meta = InvocationMeta {
env: &self.default_env,
tenant: ctx.tenant,
flow_id: ctx.flow_id,
node_id: Some(node_id),
provider_id: ctx.provider_id,
session_id: ctx.session_id,
attempt: ctx.attempt,
};
let invocation_envelope = build_invocation_envelope_as(
meta,
caller.as_ref(),
call.operation.as_str(),
call.input,
)
.context("build invocation envelope for component call")?;
serde_json::to_string(&invocation_envelope)?
};
let config_json = if call.config.is_null() {
None
} else {
Some(serde_json::to_string(&call.config)?)
};
#[cfg(feature = "fault-injection")]
{
let fault_ctx = FaultContext {
pack_id: ctx.pack_id,
flow_id: ctx.flow_id,
node_id: Some(node_id),
attempt: ctx.attempt,
};
maybe_fail(FaultPoint::BeforeComponentCall, fault_ctx)
.map_err(|err| anyhow!(err.to_string()))?;
}
let value = pack
.invoke_component_for(
call.component_ref.as_str(),
exec_ctx,
caller,
ctx.provider_id,
call.operation.as_str(),
config_json,
input_json,
)
.await?;
#[cfg(feature = "fault-injection")]
{
let fault_ctx = FaultContext {
pack_id: ctx.pack_id,
flow_id: ctx.flow_id,
node_id: Some(node_id),
attempt: ctx.attempt,
};
maybe_fail(FaultPoint::AfterComponentCall, fault_ctx)
.map_err(|err| anyhow!(err.to_string()))?;
}
if let Some((code, message)) = component_error(&value) {
if call.has_error_route {
return Ok(NodeOutput::errored(value));
}
bail!(
"component {} failed: {}: {}",
call.component_ref,
code,
message
);
}
if let Some((code, message)) = mcp_tool_error(&value) {
if call.has_error_route {
return Ok(NodeOutput::errored(normalize_mcp_tool_error(
&value, &code, &message,
)));
}
bail!(
"component {} returned tool error: {}: {}",
call.component_ref,
code,
message
);
}
let meta = outcome_meta(&value);
Ok(NodeOutput::with_meta(value, meta))
}
async fn execute_provider_invoke(
&self,
ctx: &FlowContext<'_>,
node_id: &str,
state: &ExecutionState,
payload: Value,
event: &NodeEvent<'_>,
) -> Result<NodeOutput> {
#[derive(Deserialize)]
struct ProviderPayload {
#[serde(default)]
provider_id: Option<String>,
#[serde(default)]
provider_type: Option<String>,
#[serde(default, alias = "operation")]
op: Option<String>,
#[serde(default)]
input: Value,
#[serde(default)]
in_map: Value,
#[serde(default)]
out_map: Value,
#[serde(default)]
err_map: Value,
}
let payload: ProviderPayload =
serde_json::from_value(payload).context("invalid payload for provider.invoke")?;
let op = payload
.op
.as_deref()
.filter(|v| !v.trim().is_empty())
.with_context(|| "provider.invoke requires an op")?
.to_string();
let prev = state
.last_output
.as_ref()
.cloned()
.unwrap_or_else(|| Value::Object(JsonMap::new()));
let base_ctx = template_context(state, prev);
let input_value = if !payload.in_map.is_null() {
let mut ctx_value = base_ctx.clone();
if let Value::Object(ref mut map) = ctx_value {
map.insert("input".into(), payload.input.clone());
map.insert("result".into(), payload.input.clone());
}
render_template_value(
&payload.in_map,
&ctx_value,
TemplateOptions {
allow_pointer: true,
},
)
.context("failed to render provider.invoke in_map")?
} else if !payload.input.is_null() {
payload.input
} else {
Value::Null
};
let input_json = serde_json::to_vec(&input_value)?;
self.validate_tool(
ctx,
event,
payload.provider_id.as_deref(),
payload.provider_type.as_deref(),
&op,
&input_value,
)?;
let key = FlowKey {
pack_id: ctx.pack_id.to_string(),
flow_id: ctx.flow_id.to_string(),
};
let pack_idx = *self.flow_sources.get(&key).with_context(|| {
format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
})?;
let pack = Arc::clone(&self.packs[pack_idx]);
let binding = pack.resolve_provider(
payload.provider_id.as_deref(),
payload.provider_type.as_deref(),
);
if binding.is_err()
&& let Some(output) = self.try_invoke_cross_pack_resolver(
payload.provider_id.as_deref(),
payload.provider_type.as_deref(),
&op,
&input_json,
ctx.tenant,
)?
{
return Ok(output);
}
let binding = binding?;
let exec_ctx = component_exec_ctx(ctx, node_id);
#[cfg(feature = "fault-injection")]
{
let fault_ctx = FaultContext {
pack_id: ctx.pack_id,
flow_id: ctx.flow_id,
node_id: Some(node_id),
attempt: ctx.attempt,
};
maybe_fail(FaultPoint::BeforeToolCall, fault_ctx)
.map_err(|err| anyhow!(err.to_string()))?;
}
let provider_metric_id = payload
.provider_id
.as_deref()
.or(payload.provider_type.as_deref())
.unwrap_or("unknown");
let invoke_started = std::time::Instant::now();
let invoke_result = pack
.invoke_provider(&binding, exec_ctx, &op, input_json)
.await;
let invoke_duration_ms = invoke_started.elapsed().as_secs_f64() * 1000.0;
crate::metrics::record_provider_invocation(
ctx.tenant,
provider_metric_id,
&op,
if invoke_result.is_ok() { "ok" } else { "err" },
invoke_duration_ms,
);
let result = invoke_result?;
#[cfg(feature = "fault-injection")]
{
let fault_ctx = FaultContext {
pack_id: ctx.pack_id,
flow_id: ctx.flow_id,
node_id: Some(node_id),
attempt: ctx.attempt,
};
maybe_fail(FaultPoint::AfterToolCall, fault_ctx)
.map_err(|err| anyhow!(err.to_string()))?;
}
let output = if payload.out_map.is_null() {
result
} else {
let mut ctx_value = base_ctx;
if let Value::Object(ref mut map) = ctx_value {
map.insert("input".into(), result.clone());
map.insert("result".into(), result.clone());
}
render_template_value(
&payload.out_map,
&ctx_value,
TemplateOptions {
allow_pointer: true,
},
)
.context("failed to render provider.invoke out_map")?
};
let _ = payload.err_map;
Ok(NodeOutput::new(output))
}
fn try_invoke_cross_pack_resolver(
&self,
provider_id: Option<&str>,
provider_type: Option<&str>,
op: &str,
input_json: &[u8],
tenant: &str,
) -> Result<Option<NodeOutput>> {
eprintln!(
"[DEBUG] provider.invoke: pack-local failed, has_resolver={}",
self.cross_pack_resolver.is_some()
);
let Some(resolver) = self.cross_pack_resolver.as_ref() else {
return Ok(None);
};
let provider_id = provider_id.unwrap_or("unknown");
tracing::info!(
provider_id,
op = %op,
"provider.invoke: pack-local resolution failed, trying cross-pack resolver"
);
let result_value =
resolver.invoke(provider_id, provider_type, op, input_json, tenant, None)?;
Ok(Some(NodeOutput::new(result_value)))
}
fn validate_component(
&self,
ctx: &FlowContext<'_>,
event: &NodeEvent<'_>,
call: &ComponentCall,
) -> Result<()> {
if self.validation.mode == ValidationMode::Off {
return Ok(());
}
let mut metadata = JsonMap::new();
metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
if let Some(id) = ctx.session_id {
metadata.insert("session".to_string(), json!({ "id": id }));
}
let envelope = json!({
"component_id": call.component_ref,
"operation": call.operation,
"input": call.input,
"config": call.config,
"metadata": Value::Object(metadata),
});
let issues = validate_component_envelope(&envelope);
self.report_validation(ctx, event, "component", issues)
}
fn validate_tool(
&self,
ctx: &FlowContext<'_>,
event: &NodeEvent<'_>,
provider_id: Option<&str>,
provider_type: Option<&str>,
operation: &str,
input: &Value,
) -> Result<()> {
if self.validation.mode == ValidationMode::Off {
return Ok(());
}
let tool_id = provider_id.or(provider_type).unwrap_or("provider.invoke");
let mut metadata = JsonMap::new();
metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
if let Some(id) = ctx.session_id {
metadata.insert("session".to_string(), json!({ "id": id }));
}
let envelope = json!({
"tool_id": tool_id,
"operation": operation,
"input": input,
"metadata": Value::Object(metadata),
});
let issues = validate_tool_envelope(&envelope);
self.report_validation(ctx, event, "tool", issues)
}
fn report_validation(
&self,
ctx: &FlowContext<'_>,
event: &NodeEvent<'_>,
kind: &str,
issues: Vec<ValidationIssue>,
) -> Result<()> {
if issues.is_empty() {
return Ok(());
}
if let Some(observer) = ctx.observer {
observer.on_validation(event, &issues);
}
match self.validation.mode {
ValidationMode::Warn => {
tracing::warn!(
tenant = ctx.tenant,
flow_id = ctx.flow_id,
node_id = event.node_id,
kind,
issues = ?issues,
"invocation envelope validation issues"
);
Ok(())
}
ValidationMode::Error => {
tracing::error!(
tenant = ctx.tenant,
flow_id = ctx.flow_id,
node_id = event.node_id,
kind,
issues = ?issues,
"invocation envelope validation failed"
);
bail!("invocation_validation_failed");
}
ValidationMode::Off => Ok(()),
}
}
pub fn flows(&self) -> &[FlowDescriptor] {
&self.flows
}
pub async fn flow_node_ids(&self, pack_id: &str, flow_id: &str) -> Vec<String> {
match self.get_or_load_flow(pack_id, flow_id).await {
Ok(flow) => flow
.nodes
.keys()
.map(|id| id.as_str().to_string())
.collect(),
Err(error) => {
tracing::debug!(
pack_id,
flow_id,
error = %error,
"flow not loadable while listing node ids; treating as no nodes"
);
Vec::new()
}
}
}
pub fn flow_by_key(&self, pack_id: &str, flow_id: &str) -> Option<&FlowDescriptor> {
self.flows
.iter()
.find(|descriptor| descriptor.pack_id == pack_id && descriptor.id == flow_id)
}
pub fn flow_by_type(&self, flow_type: &str) -> Option<&FlowDescriptor> {
let mut matches = self
.flows
.iter()
.filter(|descriptor| descriptor.flow_type == flow_type);
let first = matches.next()?;
if matches.next().is_some() {
return None;
}
Some(first)
}
pub fn entry_flow_by_type(&self, flow_type: &str) -> Option<&FlowDescriptor> {
let mut matches = self.flows.iter().filter(|descriptor| {
descriptor.flow_type == flow_type
&& descriptor.entry
&& !self
.messaging_provider_pack_ids
.contains(&descriptor.pack_id)
});
let first = matches.next()?;
if matches.next().is_some() {
return None;
}
Some(first)
}
pub(crate) fn pack_identity(&self, pack_id: &str) -> Option<(String, Option<String>, String)> {
self.packs
.iter()
.find(|pack| pack.metadata().pack_id == pack_id)
.map(|pack| {
let meta = pack.metadata();
(
meta.pack_id.clone(),
pack.manifest_name().map(str::to_string),
meta.version.clone(),
)
})
}
pub fn flow_by_id(&self, flow_id: &str) -> Option<&FlowDescriptor> {
let mut matches = self
.flows
.iter()
.filter(|descriptor| descriptor.id == flow_id);
let first = matches.next()?;
if matches.next().is_some() {
return None;
}
Some(first)
}
}
pub trait ExecutionObserver: Send + Sync {
fn on_node_start(&self, event: &NodeEvent<'_>);
fn on_node_end(&self, event: &NodeEvent<'_>, output: &Value);
fn on_node_error(&self, event: &NodeEvent<'_>, error: &dyn StdError);
fn on_validation(&self, _event: &NodeEvent<'_>, _issues: &[ValidationIssue]) {}
fn on_flow_attempt(&self, _flow_id: &str, _attempt: u32) {}
fn on_flow_exit(&self, _flow_id: &str) {}
}
pub struct NodeEvent<'a> {
pub context: &'a FlowContext<'a>,
pub node_id: &'a str,
pub node: &'a HostNode,
pub payload: &'a Value,
}
#[cfg(feature = "agentic-worker")]
const MAX_PARK_TURNS: u32 = 100;
#[derive(Clone, Debug, Serialize, Deserialize)]
struct PendingCardAnswers {
node_id: String,
answers: JsonMap<String, Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExecutionState {
#[serde(default)]
entry: Value,
#[serde(default)]
input: Value,
#[serde(default)]
nodes: HashMap<String, NodeOutput>,
#[serde(default)]
egress: Vec<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
last_output: Option<Value>,
#[serde(default)]
redirect_count: u32,
#[serde(default)]
vars: JsonMap<String, Value>,
#[serde(default)]
park_turns: HashMap<String, u32>,
#[serde(default)]
pending_agent_await: HashMap<String, ()>,
#[serde(default)]
pending_approval_await: HashMap<String, Option<String>>,
#[serde(default)]
pending_approval_token: HashMap<String, String>,
#[serde(default)]
pending_tool_await: HashMap<String, ()>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pending_card_answers: Option<PendingCardAnswers>,
#[serde(default, skip_serializing_if = "Option::is_none")]
resumed_at: Option<String>,
}
impl ExecutionState {
fn new(input: Value) -> Self {
Self {
entry: input.clone(),
input,
nodes: HashMap::new(),
egress: Vec::new(),
last_output: None,
redirect_count: 0,
vars: JsonMap::new(),
park_turns: HashMap::new(),
pending_agent_await: HashMap::new(),
pending_approval_await: HashMap::new(),
pending_approval_token: HashMap::new(),
pending_tool_await: HashMap::new(),
pending_card_answers: None,
resumed_at: None,
}
}
#[allow(dead_code)]
fn ensure_entry(&mut self) {
if self.entry.is_null() {
self.entry = self.input.clone();
}
}
fn context(&self) -> Value {
let mut nodes = JsonMap::new();
for (id, output) in &self.nodes {
nodes.insert(
id.clone(),
json!({
"ok": output.ok,
"payload": output.payload.clone(),
"meta": output.meta.clone(),
}),
);
}
json!({
"entry": self.entry.clone(),
"input": self.input.clone(),
"nodes": nodes,
"redirect_count": self.redirect_count,
"park_turns": self.park_turns.clone(),
"pending_agent_await": self.pending_agent_await.keys().cloned().collect::<Vec<_>>(),
})
}
fn outputs_map(&self) -> JsonMap<String, Value> {
let mut outputs = JsonMap::new();
for (id, output) in &self.nodes {
outputs.insert(id.clone(), node_output_view(&output.payload));
}
outputs
}
fn push_egress(&mut self, payload: Value) {
self.egress.push(payload);
}
fn replace_input(&mut self, input: Value) {
self.input = input;
}
fn clear_egress(&mut self) {
self.egress.clear();
}
fn redirect_count(&self) -> u32 {
self.redirect_count
}
fn increment_redirect_count(&mut self) {
self.redirect_count = self.redirect_count.saturating_add(1);
}
#[cfg(any(feature = "agentic-worker", test))]
fn bump_park_turns(&mut self, node_id: &str) -> u32 {
let entry = self.park_turns.entry(node_id.to_string()).or_insert(0);
*entry = entry.saturating_add(1);
*entry
}
#[cfg(any(feature = "agentic-worker", test))]
fn reset_park_turns(&mut self, node_id: &str) {
self.park_turns.remove(node_id);
}
#[cfg(any(feature = "agentic-worker", test))]
fn mark_agent_await(&mut self, node_id: &str) {
self.pending_agent_await.insert(node_id.to_string(), ());
}
#[cfg(any(feature = "agentic-worker", test))]
fn take_agent_await(&mut self, node_id: &str) -> bool {
self.pending_agent_await.remove(node_id).is_some()
}
#[cfg(any(feature = "agentic-worker", test))]
fn mark_tool_await(&mut self, node_id: &str) {
self.pending_tool_await.insert(node_id.to_string(), ());
}
#[cfg(any(feature = "agentic-worker", test))]
fn take_tool_await(&mut self, node_id: &str) -> bool {
self.pending_tool_await.remove(node_id).is_some()
}
fn mark_approval_await(&mut self, node_id: &str, parked: ParkedApproval) {
self.pending_approval_await
.insert(node_id.to_string(), parked.correlation_id);
match parked.token_fingerprint {
Some(fingerprint) => {
self.pending_approval_token
.insert(node_id.to_string(), fingerprint);
}
None => {
self.pending_approval_token.remove(node_id);
}
}
}
fn take_approval_await(&mut self, node_id: &str) -> Option<ParkedApproval> {
let correlation_id = self.pending_approval_await.remove(node_id)?;
Some(ParkedApproval {
correlation_id,
token_fingerprint: self.pending_approval_token.remove(node_id),
})
}
pub(crate) fn pending_approvals(&self) -> Vec<ParkedApproval> {
self.pending_approval_await
.iter()
.map(|(node_id, correlation_id)| ParkedApproval {
correlation_id: correlation_id.clone(),
token_fingerprint: self.pending_approval_token.get(node_id).cloned(),
})
.collect()
}
fn finalize_with(mut self, final_payload: Option<Value>) -> Value {
if self.egress.is_empty() {
return final_payload.unwrap_or(Value::Null);
}
let mut emitted = std::mem::take(&mut self.egress);
if let Some(value) = final_payload {
match value {
Value::Null => {}
Value::Array(items) => emitted.extend(items),
other if emitted.last() == Some(&other) => {}
other => emitted.push(other),
}
}
Value::Array(emitted)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct NodeOutput {
ok: bool,
payload: Value,
meta: Value,
}
impl NodeOutput {
fn new(payload: Value) -> Self {
Self {
ok: true,
payload,
meta: Value::Null,
}
}
#[allow(dead_code)]
fn with_error(node_id: &str, err: &(dyn std::error::Error + 'static)) -> Self {
Self {
ok: false,
payload: Value::Null,
meta: json!({
"error": {
"kind": "flow_node_failed",
"message": err.to_string(),
"node_id": node_id,
}
}),
}
}
}
struct DispatchOutcome {
output: NodeOutput,
control: NodeControl,
}
impl DispatchOutcome {
fn complete(output: NodeOutput) -> Self {
Self {
output,
control: NodeControl::Continue,
}
}
fn wait(output: NodeOutput, reason: Option<String>) -> Self {
Self {
output,
control: NodeControl::Wait { reason },
}
}
fn await_here(output: NodeOutput, reason: Option<String>, correlation_id: String) -> Self {
Self {
output,
control: NodeControl::AwaitHere {
reason,
correlation_id,
},
}
}
fn with_control(output: NodeOutput, control: NodeControl) -> Self {
Self { output, control }
}
}
#[derive(Clone, Debug)]
enum NodeControl {
Continue,
Wait {
reason: Option<String>,
},
#[allow(dead_code)]
LoopHere {
reason: Option<String>,
},
AwaitHere {
reason: Option<String>,
#[allow(dead_code)]
correlation_id: String,
},
Jump(JumpControl),
Respond {
text: Option<String>,
card_cbor: Option<Vec<u8>>,
needs_user: Option<bool>,
},
}
#[derive(Clone, Debug)]
struct JumpControl {
flow: String,
node: Option<String>,
payload: Value,
hints: Value,
max_redirects: Option<u32>,
reason: Option<String>,
}
#[derive(Clone, Debug)]
struct JumpTarget {
flow_id: String,
flow: HostFlow,
node_id: NodeId,
}
impl NodeOutput {
fn with_meta(payload: Value, meta: Value) -> Self {
Self {
ok: true,
payload,
meta,
}
}
fn errored(payload: Value) -> Self {
let mut meta = JsonMap::new();
if let Some(outcome) = payload.get("outcome").and_then(Value::as_str) {
meta.insert("outcome".to_string(), Value::String(outcome.to_string()));
}
if let Some(error) = payload.get("error") {
meta.insert("error".to_string(), error.clone());
}
let meta = if meta.is_empty() {
Value::Null
} else {
Value::Object(meta)
};
Self {
ok: false,
payload,
meta,
}
}
}
fn component_exec_ctx(ctx: &FlowContext<'_>, node_id: &str) -> ComponentExecCtx {
ComponentExecCtx {
tenant: ComponentTenantCtx {
tenant: ctx.tenant.to_string(),
team: None,
user: ctx.provider_id.map(str::to_string),
trace_id: None,
i18n_id: None,
correlation_id: ctx.session_id.map(str::to_string),
deadline_unix_ms: None,
attempt: ctx.attempt,
idempotency_key: ctx.session_id.map(str::to_string),
},
i18n_id: None,
flow_id: ctx.flow_id.to_string(),
node_id: Some(node_id.to_string()),
}
}
fn component_caller(ctx: &FlowContext<'_>) -> Option<crate::caller_identity::ComponentCaller> {
ctx.caller
.and_then(crate::caller_identity::ComponentCaller::from_block)
}
fn to_node_output(value: &Value) -> greentic_types::node_io::NodeOutput {
use greentic_types::node_io::{ErrorKind, NodeError, NodeOutput as NioOutput};
if let Value::Object(map) = value {
let native_errors = map.contains_key("errors") && !map.contains_key("ok");
let native_data = map.contains_key("data") && !map.contains_key("ok") && map.len() == 1;
if (native_errors || native_data)
&& let Ok(parsed) = serde_json::from_value::<NioOutput>(value.clone())
{
return parsed;
}
if let Some((code, message)) = component_error(value) {
return NioOutput::failed(vec![NodeError {
code,
message,
kind: ErrorKind::Internal,
retryable: false,
source: None,
details: Value::Null,
}]);
}
}
NioOutput::ok(value.clone())
}
fn node_output_view(payload: &Value) -> Value {
let nio = to_node_output(payload);
let data = nio.data().cloned().unwrap_or(Value::Null);
let errors = serde_json::to_value(nio.errors()).unwrap_or_else(|_| Value::Array(Vec::new()));
match payload {
Value::Object(map) => {
let mut view = map.clone();
view.insert("data".to_string(), data);
view.insert("errors".to_string(), errors);
Value::Object(view)
}
other => other.clone(),
}
}
enum DeclaredAnswerFields {
Absent,
Malformed,
Declared(Vec<String>),
}
fn declared_answer_fields(payload_expr: &Value) -> DeclaredAnswerFields {
let Some(raw) = payload_expr.get("answer_fields") else {
return DeclaredAnswerFields::Absent;
};
let Some(arr) = raw.as_array() else {
return DeclaredAnswerFields::Malformed;
};
match arr
.iter()
.map(|entry| entry.as_str().map(str::to_string))
.collect::<Option<Vec<String>>>()
{
Some(list) => DeclaredAnswerFields::Declared(list),
None => DeclaredAnswerFields::Malformed,
}
}
fn consume_routing_action(entry: &mut Value) {
for pointer in ["/input/metadata", "/metadata"] {
if let Some(Value::Object(meta)) = entry.pointer_mut(pointer) {
meta.remove("action");
}
}
}
fn attach_pending_card_answers(
state: &mut ExecutionState,
node_id: &str,
node: &HostNode,
output: &mut NodeOutput,
) -> bool {
let is_target = state
.pending_card_answers
.as_ref()
.is_some_and(|pending| pending.node_id == node_id);
if !is_target {
return false;
}
let Some(pending) = state.pending_card_answers.take() else {
return false;
};
let Some(map) = output.payload.as_object_mut() else {
tracing::warn!(
node_id = %node_id,
"node output payload is not an object; submitted answers not attached"
);
return true;
};
if map.contains_key("answers") {
tracing::warn!(
node_id = %node_id,
"node output already carries `answers`; overwriting with the submitted fields"
);
}
let answers = match declared_answer_fields(&node.payload_expr) {
DeclaredAnswerFields::Declared(allow_list) => {
let allowed: std::collections::HashSet<&str> =
allow_list.iter().map(String::as_str).collect();
pending
.answers
.into_iter()
.filter(|(key, _)| allowed.contains(key.as_str()))
.collect()
}
DeclaredAnswerFields::Malformed => {
tracing::warn!(
node_id = %node_id,
"answer_fields present but malformed; falling back to unfiltered answers"
);
pending.answers
}
DeclaredAnswerFields::Absent => pending.answers,
};
map.insert("answers".to_string(), Value::Object(answers));
true
}
fn resumed_card_node(snapshot: &FlowSnapshot) -> Option<String> {
snapshot.awaiting_submit.then(|| snapshot.next_node.clone())
}
fn awaiting_tool_input(payload: &Value) -> bool {
payload.get("terminated_by").and_then(Value::as_str) == Some("awaiting_tool_input")
}
pub(crate) fn tool_presentation(payload: &Value) -> Option<&Value> {
if !awaiting_tool_input(payload) {
return None;
}
payload
.get("pending_presentation")
.filter(|value| !value.is_null())
}
const SUBMIT_MARKER_KEY: &str = "greentic_submit";
pub(crate) fn rendered_park(payload: &Value) -> Value {
let Some(card) = tool_presentation(payload) else {
return payload.clone();
};
let side_reply = payload
.get("side_turn")
.and_then(Value::as_bool)
.unwrap_or(false)
&& payload
.get("reply")
.and_then(Value::as_str)
.is_some_and(|reply| !reply.trim().is_empty());
if !side_reply {
return card.clone();
}
let mut reply = payload.clone();
if let Some(map) = reply.as_object_mut() {
map.remove("pending_presentation");
map.remove("side_turn");
}
let mut items = vec![reply];
match card {
Value::Array(cards) => items.extend(cards.iter().cloned()),
single => items.push(single.clone()),
}
Value::Array(items)
}
#[cfg(any(feature = "agentic-worker", test))]
const ENVELOPE_TRANSPORT_KEYS: &[&str] = &[
"id",
"tenant",
"channel",
"session_id",
"reply_scope",
"from",
"to",
"correlation_id",
"attachments",
"extensions",
];
#[cfg(any(feature = "agentic-worker", test))]
const CHANNEL_CONTEXT_METADATA_KEYS: &[&str] = &[
"locale",
"team",
"env",
"autoStart",
"universal",
"user_id",
"user_verified",
"flow_hint",
"extensions",
];
#[cfg(any(feature = "agentic-worker", test))]
const CHANNEL_CONTEXT_METADATA_PREFIX: &str = "channel.";
#[cfg(any(feature = "agentic-worker", test))]
fn is_channel_context_key(key: &str) -> bool {
CHANNEL_CONTEXT_METADATA_KEYS.contains(&key) || key.starts_with(CHANNEL_CONTEXT_METADATA_PREFIX)
}
#[cfg(any(feature = "agentic-worker", test))]
fn stamped_identity_matches(key: &str, value: &Value, envelope: &Value) -> bool {
let Some(value) = value.as_str() else {
return false;
};
match key {
"route" => envelope.get("session_id").and_then(Value::as_str) == Some(value),
"tenant" => envelope.pointer("/tenant/tenant").and_then(Value::as_str) == Some(value),
_ => false,
}
}
#[cfg(any(feature = "agentic-worker", test))]
fn is_channel_envelope(map: &JsonMap<String, Value>) -> bool {
map.contains_key("session_id") && map.contains_key("channel") && map.contains_key("tenant")
}
#[cfg(any(feature = "agentic-worker", test))]
fn is_card_submit(entry: &Value) -> bool {
let metadata = resolve_entry_metadata(entry).and_then(Value::as_object);
let has_action = metadata
.and_then(|meta| meta.get("action"))
.and_then(Value::as_str)
.is_some_and(|action| !action.trim().is_empty());
if has_action {
return true;
}
let marked = metadata
.and_then(|meta| meta.get(SUBMIT_MARKER_KEY))
.is_some_and(|value| value.as_str() == Some("true") || value.as_bool() == Some(true));
if marked {
return true;
}
let envelope = entry
.get("input")
.filter(|v| v.is_object())
.unwrap_or(entry);
let root_input = envelope.as_object().is_some_and(|map| {
let channel_envelope = is_channel_envelope(map);
map.keys().any(|key| {
key != "metadata"
&& key != "text"
&& !(channel_envelope && ENVELOPE_TRANSPORT_KEYS.contains(&key.as_str()))
})
});
let metadata_input = metadata.is_some_and(|meta| {
meta.iter().any(|(key, value)| {
key != "action"
&& key != SUBMIT_MARKER_KEY
&& !is_channel_context_key(key)
&& !stamped_identity_matches(key, value, envelope)
})
});
root_input || metadata_input
}
fn pending_from_snapshot(snapshot: &FlowSnapshot, input: &Value) -> Option<PendingCardAnswers> {
if !snapshot.awaiting_submit {
return None;
}
Some(PendingCardAnswers {
node_id: snapshot.next_node.clone(),
answers: submitted_fields(input),
})
}
fn outcome_meta(output: &Value) -> Value {
match output.get("outcome").and_then(Value::as_str) {
Some(outcome) => json!({ "outcome": outcome }),
None => Value::Null,
}
}
fn component_error(value: &Value) -> Option<(String, String)> {
let obj = value.as_object()?;
let ok = obj.get("ok").and_then(Value::as_bool)?;
if ok {
return None;
}
let err = obj.get("error")?.as_object()?;
let code = err
.get("code")
.and_then(Value::as_str)
.unwrap_or("component_error");
let message = err
.get("message")
.and_then(Value::as_str)
.unwrap_or("component reported error");
Some((code.to_string(), message.to_string()))
}
fn mcp_tool_error(value: &Value) -> Option<(String, String)> {
let obj = value.as_object()?;
if obj.contains_key("result") {
return None;
}
let err = obj.get("error")?.as_object()?;
let code = err
.get("code")
.and_then(Value::as_str)
.unwrap_or("tool_error");
let raw_message = err
.get("message")
.and_then(Value::as_str)
.unwrap_or("tool returned an error");
let status = err.get("status").and_then(Value::as_u64);
let message = match status {
Some(s) => format!("{raw_message} (status {s})"),
None => raw_message.to_string(),
};
Some((code.to_string(), message))
}
fn normalize_mcp_tool_error(value: &Value, code: &str, message: &str) -> Value {
let mut obj = value.as_object().cloned().unwrap_or_default();
obj.insert("ok".to_string(), Value::Bool(false));
let mut error = obj
.get("error")
.and_then(Value::as_object)
.cloned()
.unwrap_or_default();
error.insert("code".to_string(), Value::String(code.to_string()));
error.insert("message".to_string(), Value::String(message.to_string()));
obj.insert("error".to_string(), Value::Object(error));
Value::Object(obj)
}
#[cfg(feature = "agentic-worker")]
fn mcp_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
if !has_error_route {
return NodeOutput::new(bound);
}
let Some(error) = result.get("error") else {
return NodeOutput::new(bound);
};
if let Some((code, message)) = mcp_tool_error(result) {
return NodeOutput::errored(normalize_mcp_tool_error(&bound, &code, &message));
}
let message = error
.as_str()
.map(str::to_string)
.unwrap_or_else(|| error.to_string());
NodeOutput::errored(normalize_mcp_tool_error(
&bound,
"mcp_call_failed",
&message,
))
}
#[cfg(feature = "agentic-worker")]
fn bind_node_result(payload: &Value, result: Value) -> Value {
match payload.get("output").and_then(Value::as_str) {
Some(key) if !key.is_empty() => json!({ key: result }),
_ => result,
}
}
#[cfg(feature = "agentic-worker")]
fn is_blank(value: &Value) -> bool {
match value {
Value::Null => true,
Value::String(text) => text.trim().is_empty(),
_ => false,
}
}
#[cfg(feature = "agentic-worker")]
fn a2a_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
if !has_error_route {
return NodeOutput::new(bound);
}
let Some(error) = result.get("error").and_then(Value::as_str) else {
return NodeOutput::new(bound);
};
let code = match result.get("status").and_then(Value::as_str) {
Some("failed") => "a2a_agent_failed",
_ => "a2a_call_failed",
};
NodeOutput::errored(normalize_mcp_tool_error(&bound, code, error))
}
#[cfg(feature = "agentic-worker")]
fn sorla_failure(msg: impl Into<String>, has_error_route: bool) -> Result<DispatchOutcome> {
let msg = msg.into();
if has_error_route {
Ok(DispatchOutcome::complete(NodeOutput::errored(json!({
"error": msg
}))))
} else {
Err(anyhow!(msg))
}
}
fn extract_wait_reason(payload: &Value) -> Option<String> {
match payload {
Value::String(s) => Some(s.clone()),
Value::Object(map) => map
.get("reason")
.and_then(Value::as_str)
.map(|value| value.to_string()),
_ => None,
}
}
fn component_dispatch_outcome(output: NodeOutput) -> Result<DispatchOutcome> {
if let Some(control) = parse_component_control(&output.payload)? {
return Ok(match control {
NodeControl::Jump(jump) => {
let adjusted = NodeOutput::with_meta(jump.payload.clone(), jump.hints.clone());
DispatchOutcome::with_control(adjusted, NodeControl::Jump(jump))
}
NodeControl::Respond {
text,
card_cbor,
needs_user,
} => DispatchOutcome::with_control(
output,
NodeControl::Respond {
text,
card_cbor,
needs_user,
},
),
other => DispatchOutcome::with_control(output, other),
});
}
Ok(DispatchOutcome::complete(output))
}
fn parse_component_control(payload: &Value) -> Result<Option<NodeControl>> {
let Value::Object(map) = payload else {
return Ok(None);
};
let Some(control_value) = map.get("greentic_control") else {
return Ok(None);
};
let control = control_value
.as_object()
.ok_or_else(|| anyhow!("jump_failed: greentic_control must be an object"))?;
let action = control
.get("action")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("jump_failed: greentic_control.action is required"))?;
let version = control
.get("v")
.and_then(Value::as_u64)
.ok_or_else(|| anyhow!("jump_failed: greentic_control.v is required"))?;
if version != 1 {
bail!("jump_failed: unsupported greentic_control.v={version}");
}
match action {
"jump" => {
let flow = control
.get("flow")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow!("jump_failed: jump flow is required"))?
.to_string();
let node = control
.get("node")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string);
let payload = control.get("payload").cloned().unwrap_or(Value::Null);
let hints = control.get("hints").cloned().unwrap_or(Value::Null);
let max_redirects = control
.get("max_redirects")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok());
let reason = control
.get("reason")
.and_then(Value::as_str)
.map(str::to_string);
Ok(Some(NodeControl::Jump(JumpControl {
flow,
node,
payload,
hints,
max_redirects,
reason,
})))
}
"respond" => {
let text = control
.get("text")
.and_then(Value::as_str)
.map(str::to_string);
let card_cbor = control
.get("card_cbor")
.and_then(Value::as_array)
.map(|bytes| {
bytes
.iter()
.filter_map(Value::as_u64)
.filter_map(|value| u8::try_from(value).ok())
.collect::<Vec<_>>()
});
let needs_user = control.get("needs_user").and_then(Value::as_bool);
Ok(Some(NodeControl::Respond {
text,
card_cbor,
needs_user,
}))
}
_ => Ok(None),
}
}
fn alias_input_to_entry(mut entry: Value) -> Value {
if let Value::Object(map) = &mut entry
&& !map.contains_key("input")
{
let base = Value::Object(map.clone());
map.insert("input".into(), base);
}
entry
}
fn merge_submitted_fields_into_entry(mut entry: Value, fields: JsonMap<String, Value>) -> Value {
if let Value::Object(map) = &mut entry {
for (key, value) in fields {
map.entry(key).or_insert(value);
}
}
entry
}
fn now_namespace(at: DateTime<Utc>) -> Value {
json!({
"iso": at.to_rfc3339_opts(SecondsFormat::Millis, true),
"epoch_ms": at.timestamp_millis(),
"date": at.format("%Y-%m-%d").to_string(),
})
}
fn template_context(state: &ExecutionState, prev: Value) -> Value {
let entry = if state.entry.is_null() {
Value::Object(JsonMap::new())
} else {
let fields = submitted_fields(&state.entry);
merge_submitted_fields_into_entry(alias_input_to_entry(state.entry.clone()), fields)
};
let mut ctx = JsonMap::new();
ctx.insert("entry".into(), entry.clone());
ctx.insert("in".into(), entry); ctx.insert("prev".into(), prev);
ctx.insert("node".into(), Value::Object(state.outputs_map()));
ctx.insert("state".into(), state.context());
ctx.insert("vars".into(), Value::Object(state.vars.clone()));
ctx.insert("now".into(), now_namespace(Utc::now()));
Value::Object(ctx)
}
fn seed_vars_and_collect_missing_required(
vars_init: &JsonMap<String, Value>,
required: &[String],
target: &mut JsonMap<String, Value>,
) -> Vec<String> {
for (name, default) in vars_init.iter() {
target
.entry(name.clone())
.or_insert_with(|| default.clone());
}
required
.iter()
.filter(|name| !target.contains_key(name.as_str()))
.cloned()
.collect()
}
impl From<Flow> for HostFlow {
fn from(value: Flow) -> Self {
let mut nodes = IndexMap::new();
for (id, node) in value.nodes {
nodes.insert(id.clone(), HostNode::from(node));
}
let start = value
.entrypoints
.get("default")
.and_then(Value::as_str)
.and_then(|id| NodeId::from_str(id).ok())
.or_else(|| nodes.keys().next().cloned());
let vars_init = value
.metadata
.extra
.get("vars_init")
.and_then(|v| v.as_object())
.map(|decls| {
decls
.iter()
.filter_map(|(name, decl)| {
decl.get("default").map(|d| (name.clone(), d.clone()))
})
.collect::<JsonMap<String, Value>>()
})
.unwrap_or_default();
let required_vars = value
.metadata
.extra
.get("vars_init")
.and_then(|v| v.as_object())
.map(|decls| {
decls
.iter()
.filter(|(_, decl)| decl.get("required") == Some(&Value::Bool(true)))
.map(|(name, _)| name.clone())
.collect::<Vec<String>>()
})
.unwrap_or_default();
let slot_schema = value
.metadata
.extra
.get(SLOT_SCHEMA_METADATA_KEY)
.filter(|v| !v.is_null())
.cloned();
Self {
id: value.id.as_str().to_string(),
start,
nodes,
vars_init,
required_vars,
slot_schema,
}
}
}
impl From<Node> for HostNode {
fn from(node: Node) -> Self {
let full_ref = node.component.id.as_str().to_string();
let operation_in_mapping = extract_operation_from_mapping(&node.input.mapping);
let is_builtin = full_ref.starts_with("component.exec")
|| full_ref.starts_with("flow.")
|| full_ref.starts_with("emit.")
|| full_ref.starts_with("session.")
|| full_ref.starts_with("provider.")
|| full_ref.starts_with("dw.")
|| full_ref.starts_with("sorla.")
|| full_ref.starts_with("operala.")
|| full_ref.starts_with("agentic.")
|| full_ref.starts_with("approval.")
|| full_ref.starts_with("var.")
|| full_ref.starts_with("mcp:")
|| full_ref.starts_with("a2a:");
let (component_ref, raw_operation) =
if node.component.operation.is_some() || is_builtin || operation_in_mapping.is_some() {
(full_ref, node.component.operation.clone())
} else if let Some(dot) = full_ref.rfind('.') {
let comp = full_ref[..dot].to_string();
let op = full_ref[dot + 1..].to_string();
(comp, Some(op))
} else {
(full_ref, None)
};
let operation_is_component_exec = raw_operation.as_deref() == Some("component.exec");
let operation_is_emit = raw_operation
.as_deref()
.map(|op| op.starts_with("emit."))
.unwrap_or(false);
let is_component_exec = component_ref == "component.exec" || operation_is_component_exec;
let kind = if is_component_exec {
let target = if component_ref == "component.exec" {
if let Some(op) = raw_operation
.as_deref()
.filter(|op| op.starts_with("emit."))
{
op.to_string()
} else {
extract_target_component(&node.input.mapping)
.unwrap_or_else(|| "component.exec".to_string())
}
} else {
extract_target_component(&node.input.mapping)
.unwrap_or_else(|| component_ref.clone())
};
if target.starts_with("emit.") {
NodeKind::BuiltinEmit {
kind: emit_kind_from_ref(&target),
}
} else {
NodeKind::Exec {
target_component: target,
}
}
} else if operation_is_emit {
NodeKind::BuiltinEmit {
kind: emit_kind_from_ref(raw_operation.as_deref().unwrap_or("emit.log")),
}
} else {
match component_ref.as_str() {
"flow.call" => NodeKind::FlowCall,
"flow.goto" => NodeKind::FlowGoto,
"provider.invoke" => NodeKind::ProviderInvoke,
"session.wait" => NodeKind::Wait,
"state.get" => NodeKind::BuiltinStateGet,
"state.set" => NodeKind::BuiltinStateSet,
"var.set" => {
let name = node
.input
.mapping
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let value = node
.input
.mapping
.get("value")
.cloned()
.unwrap_or(Value::Null);
NodeKind::VarSet { name, value }
}
"dw.agent" => NodeKind::DwAgent {
agent_id: raw_operation.clone().unwrap_or_default(),
conversational: node.conversational,
},
"dw.agent_graph" => NodeKind::DwAgentGraph {
graph_id: raw_operation.clone().unwrap_or_default(),
},
"sorla.call" => NodeKind::SorlaCall {
target: raw_operation.clone().unwrap_or_default(),
},
"operala.call" => NodeKind::OperalaCall {
target: raw_operation.clone().unwrap_or_default(),
},
"agentic.call" => NodeKind::AgenticCall {
target: raw_operation.clone().unwrap_or_default(),
},
"telco-x.call" => NodeKind::TelcoXCall {
target: raw_operation.clone().unwrap_or_default(),
},
"approval.call" => NodeKind::ApprovalCall {
target: raw_operation.clone().unwrap_or_default(),
},
comp if comp.starts_with("emit.") => NodeKind::BuiltinEmit {
kind: emit_kind_from_ref(comp),
},
"mcp" => mcp_node_kind(&node.input.mapping, raw_operation.as_deref()),
comp if comp.starts_with("mcp:") => mcp_node_kind(&node.input.mapping, Some(comp)),
"a2a" => a2a_node_kind(&node.input.mapping, raw_operation.as_deref()),
comp if comp.starts_with("a2a:") => a2a_node_kind(&node.input.mapping, Some(comp)),
other => NodeKind::PackComponent {
component_ref: other.to_string(),
},
}
};
let component_label = match &kind {
NodeKind::Exec { .. } => "component.exec".to_string(),
NodeKind::PackComponent { component_ref } => component_ref.clone(),
NodeKind::ProviderInvoke => "provider.invoke".to_string(),
NodeKind::FlowCall => "flow.call".to_string(),
NodeKind::FlowGoto => "flow.goto".to_string(),
NodeKind::BuiltinEmit { kind } => emit_ref_from_kind(kind),
NodeKind::BuiltinStateGet => "state.get".to_string(),
NodeKind::BuiltinStateSet => "state.set".to_string(),
NodeKind::VarSet { .. } => "var.set".to_string(),
NodeKind::Wait => "session.wait".to_string(),
NodeKind::DwAgent { .. } => "dw.agent".to_string(),
NodeKind::DwAgentGraph { .. } => "dw.agent_graph".to_string(),
NodeKind::SorlaCall { .. } => "sorla.call".to_string(),
NodeKind::OperalaCall { .. } => "operala.call".to_string(),
NodeKind::AgenticCall { .. } => "agentic.call".to_string(),
NodeKind::TelcoXCall { .. } => "telco-x.call".to_string(),
NodeKind::ApprovalCall { .. } => "approval.call".to_string(),
NodeKind::Mcp { server_id, tool } => format!("mcp:{server_id}/{tool}"),
NodeKind::A2a { agent_id } => format!("a2a:{agent_id}"),
};
let operation_name = if is_component_exec && operation_is_component_exec {
None
} else {
raw_operation.clone()
};
let vars_out = node
.input
.mapping
.get("vars_out")
.and_then(Value::as_object)
.cloned();
let response_timeout_secs = response_timeout_from_mapping(&node.input.mapping);
let payload_expr = match kind {
NodeKind::BuiltinEmit { .. } => extract_emit_payload(&node.input.mapping),
NodeKind::VarSet { .. } => Value::Null,
_ => {
let mut mapping = node.input.mapping.clone();
if let Some(obj) = mapping.as_object_mut() {
obj.remove("vars_out");
obj.remove(RESPONSE_TIMEOUT_KEY);
}
mapping
}
};
Self {
kind,
component: component_label,
component_id: if is_component_exec {
"component.exec".to_string()
} else {
component_ref
},
operation_name,
operation_in_mapping,
payload_expr,
routing: node.routing,
vars_out,
response_timeout_secs,
}
}
}
pub(crate) const RESPONSE_TIMEOUT_KEY: &str = "response_timeout_secs";
fn response_timeout_from_mapping(mapping: &Value) -> Option<u64> {
mapping
.get(RESPONSE_TIMEOUT_KEY)
.and_then(Value::as_u64)
.filter(|secs| *secs > 0)
}
fn mcp_node_kind(payload: &Value, legacy_ref: Option<&str>) -> NodeKind {
if let Some((server_id, tool)) = crate::runner::mcp_node::server_tool_from_payload(payload) {
return NodeKind::Mcp { server_id, tool };
}
if let Some((server_id, tool)) = legacy_ref.and_then(parse_legacy_mcp_ref) {
return NodeKind::Mcp { server_id, tool };
}
NodeKind::PackComponent {
component_ref: "mcp".to_string(),
}
}
fn a2a_node_kind(payload: &Value, legacy_ref: Option<&str>) -> NodeKind {
if let Some(agent_id) = crate::runner::a2a_node::agent_from_payload(payload) {
return NodeKind::A2a { agent_id };
}
if let Some(agent_id) = legacy_ref.and_then(crate::runner::a2a_node::agent_from_ref) {
return NodeKind::A2a { agent_id };
}
NodeKind::PackComponent {
component_ref: "a2a".to_string(),
}
}
fn parse_legacy_mcp_ref(reference: &str) -> Option<(String, String)> {
let rest = reference.strip_prefix("mcp:").unwrap_or(reference);
let (server, tool) = rest.split_once('/')?;
if server.is_empty() || tool.is_empty() {
return None;
}
Some((server.to_string(), tool.to_string()))
}
fn extract_target_component(payload: &Value) -> Option<String> {
match payload {
Value::Object(map) => map
.get("component")
.or_else(|| map.get("component_ref"))
.and_then(Value::as_str)
.map(|s| s.to_string()),
_ => None,
}
}
fn extract_operation_from_mapping(payload: &Value) -> Option<String> {
match payload {
Value::Object(map) => map
.get("operation")
.or_else(|| map.get("op"))
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(|value| value.to_string()),
_ => None,
}
}
fn extract_emit_payload(payload: &Value) -> Value {
if let Value::Object(map) = payload {
if let Some(input) = map.get("input") {
return input.clone();
}
if let Some(inner) = map.get("payload") {
return inner.clone();
}
}
payload.clone()
}
fn split_operation_payload(payload: Value) -> (Value, Value) {
if let Value::Object(mut map) = payload.clone()
&& map.contains_key("input")
{
let input = map.remove("input").unwrap_or(Value::Null);
let config = map.remove("config").unwrap_or(Value::Null);
let legacy_only = map.keys().all(|key| {
matches!(
key.as_str(),
"operation" | "op" | "component" | "component_ref"
)
});
if legacy_only {
return (input, config);
}
}
(payload, Value::Null)
}
fn resolve_component_operation(
node_id: &str,
component_label: &str,
payload_operation: Option<String>,
operation_override: Option<&str>,
operation_in_mapping: Option<&str>,
) -> Result<String> {
if let Some(op) = operation_override
.map(str::trim)
.filter(|value| !value.is_empty())
{
return Ok(op.to_string());
}
if let Some(op) = payload_operation
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
{
return Ok(op.to_string());
}
let mut message = format!(
"missing operation for node `{}` (component `{}`); expected node.component.operation to be set",
node_id, component_label,
);
if let Some(found) = operation_in_mapping {
message.push_str(&format!(
". Found operation in input.mapping (`{}`) but this is not used; pack compiler must preserve node.component.operation.",
found
));
}
bail!(message);
}
fn emit_kind_from_ref(component_ref: &str) -> EmitKind {
match component_ref {
"emit.log" => EmitKind::Log,
"emit.response" => EmitKind::Response,
other => EmitKind::Other(other.to_string()),
}
}
fn emit_ref_from_kind(kind: &EmitKind) -> String {
match kind {
EmitKind::Log => "emit.log".to_string(),
EmitKind::Response => "emit.response".to_string(),
EmitKind::Other(other) => other.clone(),
}
}
fn is_card_invocation(input: &Value) -> bool {
if let Value::Object(map) = input {
return map.contains_key("card_source") || map.contains_key("card_spec");
}
false
}
fn promote_card_config_to_invocation(input: &mut Value, config: &Value) {
if is_card_invocation(input) {
return;
}
let cfg_map = card_defaults_source(input, config);
let Some(cfg) = cfg_map else { return };
let default_asset = cfg
.get("default_card_asset")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string);
let default_inline = cfg
.get("default_card_inline")
.filter(|value| value.is_object() || value.is_array())
.cloned();
let default_source = cfg
.get("default_source")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_lowercase);
if default_asset.is_none() && default_inline.is_none() && default_source.is_none() {
return;
}
let card_source = default_source.unwrap_or_else(|| {
if default_inline.is_some() {
"inline".to_string()
} else {
"asset".to_string()
}
});
let mut card_spec = serde_json::Map::new();
match card_source.as_str() {
"asset" => {
if let Some(path) = default_asset {
card_spec.insert("asset_path".into(), Value::String(path));
}
}
"inline" => {
if let Some(inline) = default_inline {
card_spec.insert("inline_json".into(), inline);
}
}
_ => {}
}
if !matches!(input, Value::Object(_)) {
*input = Value::Object(serde_json::Map::new());
}
if let Value::Object(map) = input {
map.insert("card_source".into(), Value::String(card_source));
map.insert("card_spec".into(), Value::Object(card_spec));
}
}
fn card_defaults_source<'a>(
input: &'a Value,
config: &'a Value,
) -> Option<&'a serde_json::Map<String, Value>> {
if let Value::Object(map) = config {
return Some(map);
}
if let Value::Object(map) = input
&& let Some(Value::Object(nested)) = map.get("config")
{
return Some(nested);
}
None
}
fn activity_locale(entry: &Value) -> Option<&str> {
entry
.pointer("/input/metadata/locale")
.or_else(|| entry.pointer("/metadata/locale"))
.and_then(Value::as_str)
.filter(|locale| !locale.trim().is_empty())
}
fn inject_card_locale(payload: &mut Value, entry: &Value) {
if !is_card_invocation(payload) {
return;
}
let Value::Object(map) = payload else { return };
if map.contains_key("locale") {
return;
}
if let Some(locale) = activity_locale(entry) {
map.insert("locale".into(), Value::String(locale.to_string()));
}
}
fn inject_card_route(payload: &mut Value, entry: &Value, node: &HostNode) {
let is_adaptive_card =
node.component_id().contains("adaptive-card") || node.component.contains("adaptive-card");
if !is_adaptive_card || is_card_invocation(payload) {
return;
}
let route = entry
.pointer("/input/metadata/routeToCardId")
.or_else(|| entry.pointer("/metadata/routeToCardId"))
.or_else(|| entry.pointer("/input/metadata/toCardId"))
.or_else(|| entry.pointer("/metadata/toCardId"))
.or_else(|| entry.pointer("/input/metadata/nextCardId"))
.or_else(|| entry.pointer("/metadata/nextCardId"))
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty());
let Some(route) = route else {
return;
};
if !matches!(payload, Value::Object(_)) {
*payload = Value::Object(serde_json::Map::new());
}
if let Value::Object(map) = payload {
let mut card_spec = serde_json::Map::new();
card_spec.insert(
"asset_path".into(),
Value::String(format!("assets/cards/{route}.json")),
);
map.insert("card_source".into(), Value::String("asset".into()));
map.insert("card_spec".into(), Value::Object(card_spec));
tracing::debug!(route_to_card = %route, "inject_card_route: routed card asset selected");
}
}
fn inject_slot_definitions(input: &mut Value, slot_schema: &Value, flow_id: &str, node_id: &str) {
if input.is_null() {
*input = Value::Object(serde_json::Map::new());
}
let Some(map) = input.as_object_mut() else {
tracing::warn!(
flow_id,
node_id,
"slot-extractor input is not an object; cannot inject slot_definitions"
);
return;
};
if map.contains_key("slot_definitions") {
return;
}
let slot_count = slot_schema.as_array().map_or(0, Vec::len);
tracing::debug!(
flow_id,
slot_count,
"injecting flow-level slot_schema as slot_definitions into slot-extractor input"
);
map.insert("slot_definitions".to_string(), slot_schema.clone());
}
fn resolve_card_assets(input: &mut Value, pack: &crate::pack::PackRuntime) {
resolve_card_spec_asset(input, pack);
if let Value::Object(map) = input
&& let Some(Value::Object(call)) = map.get_mut("call")
&& let Some(payload) = call.get_mut("payload")
{
resolve_card_spec_asset(payload, pack);
}
}
fn resolve_card_spec_asset(value: &mut Value, pack: &crate::pack::PackRuntime) {
let Value::Object(map) = value else { return };
let is_asset = map
.get("card_source")
.and_then(Value::as_str)
.map(|s| s.eq_ignore_ascii_case("asset"))
.unwrap_or(false);
if !is_asset {
return;
}
let asset_path = map
.get("card_spec")
.and_then(|spec| spec.get("asset_path"))
.and_then(Value::as_str)
.map(str::to_string);
let Some(asset_path) = asset_path else { return };
match pack.read_asset(&asset_path) {
Ok(bytes) => {
let card_json: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(err) => {
tracing::warn!(
asset_path,
%err,
"failed to parse card asset as JSON; leaving as asset reference"
);
return;
}
};
tracing::debug!(asset_path, "pre-resolved card asset to inline_json");
map.insert("card_source".into(), Value::String("inline".into()));
if let Some(Value::Object(spec)) = map.get_mut("card_spec") {
spec.insert("inline_json".into(), card_json);
spec.remove("asset_path");
}
}
Err(err) => {
tracing::warn!(
asset_path,
%err,
"card asset not found in pack; leaving as asset reference"
);
}
}
let configured_bundle_path = map
.get("card_spec")
.and_then(|spec| spec.get("i18n_bundle_path"))
.and_then(Value::as_str)
.map(|s| s.trim().trim_end_matches('/').to_string())
.filter(|s| !s.is_empty());
let bundle_path = configured_bundle_path
.clone()
.unwrap_or_else(|| "assets/i18n".to_string());
let i18n_entries = load_i18n_bundle_entries(&bundle_path, |path| pack.read_asset(path));
if !i18n_entries.is_empty() {
let locale_keys: Vec<_> = i18n_entries.keys().cloned().collect();
if let Some(Value::Object(spec)) = map.get_mut("card_spec") {
spec.insert("i18n_inline".into(), Value::Object(i18n_entries));
if configured_bundle_path.is_some() {
tracing::info!(%bundle_path, ?locale_keys, "pre-resolved i18n bundle into card_spec.i18n_inline");
} else {
tracing::info!(%bundle_path, ?locale_keys, "auto-discovered i18n bundle and inlined into card_spec.i18n_inline");
}
}
}
}
fn load_i18n_bundle_entries<F>(bundle_path: &str, mut read_asset: F) -> JsonMap<String, Value>
where
F: FnMut(&str) -> Result<Vec<u8>>,
{
let mut i18n_entries = JsonMap::new();
if bundle_path.ends_with(".json") {
if let Ok(bytes) = read_asset(bundle_path)
&& let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
{
i18n_entries.insert("en".to_string(), Value::Object(entries));
}
return i18n_entries;
}
let manifest_path = format!("{bundle_path}/_manifest.json");
let locale_codes: Vec<String> = read_asset(&manifest_path)
.ok()
.and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
.and_then(|value| {
let locales = value
.get("locales")
.and_then(Value::as_array)
.cloned()
.or_else(|| value.as_array().cloned());
locales.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.map(String::from)
.collect()
})
})
.unwrap_or_default();
tracing::info!(%bundle_path, ?locale_codes, "i18n manifest discovered locales");
for locale in &locale_codes {
let candidate = format!("{bundle_path}/{locale}.json");
if let Ok(bytes) = read_asset(&candidate)
&& let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
{
i18n_entries.insert(locale.clone(), Value::Object(entries));
}
}
if !i18n_entries.contains_key("en") {
let en_path = format!("{bundle_path}/en.json");
if let Ok(bytes) = read_asset(&en_path)
&& let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
{
i18n_entries.insert("en".to_string(), Value::Object(entries));
}
}
i18n_entries
}
#[derive(Debug)]
pub(crate) enum CustomRoutingDecision {
Next(NodeId),
End,
Wait,
}
fn evaluate_custom_routing(
raw: &Value,
output: &NodeOutput,
state: &ExecutionState,
flow_ir: &HostFlow,
node_id: &NodeId,
) -> CustomRoutingDecision {
let routes = match raw.as_array() {
Some(arr) => arr,
None => {
tracing::warn!(
flow_id = %flow_ir.id,
node_id = %node_id,
"custom routing is not an array; terminating"
);
return CustomRoutingDecision::End;
}
};
let ctx = build_routing_context(
output,
state,
default_success_event(routes),
default_error_event(routes),
);
let mut has_condition = false;
let mut unmatched_conditions: Vec<&str> = Vec::new();
for route in routes {
let condition = route.get("condition").and_then(|v| v.as_str());
let to = route.get("to").and_then(|v| v.as_str());
if route.get("on_message").and_then(Value::as_bool) == Some(true) {
has_condition = true;
unmatched_conditions.push("on_message");
let resumed_here = state.resumed_at.as_deref() == Some(node_id.as_str());
let no_action = resolve_dotted_path(&ctx, "response.action")
.is_none_or(|action| action.trim().is_empty());
if resumed_here
&& no_action
&& let Some(target) = to
&& let Ok(nid) = NodeId::new(target)
{
tracing::debug!(
flow_id = %flow_ir.id,
node_id = %node_id,
target = target,
"on_message route taken"
);
return CustomRoutingDecision::Next(nid);
}
continue;
}
if let Some(cond) = condition {
has_condition = true;
unmatched_conditions.push(cond);
if evaluate_simple_condition(cond, &ctx)
&& let Some(target) = to
&& let Ok(nid) = NodeId::new(target)
{
tracing::debug!(
flow_id = %flow_ir.id,
node_id = %node_id,
condition = cond,
target = target,
"conditional route matched"
);
return CustomRoutingDecision::Next(nid);
}
} else if let Some(target) = to
&& let Ok(nid) = NodeId::new(target)
{
tracing::debug!(
flow_id = %flow_ir.id,
node_id = %node_id,
target = target,
"default route taken"
);
return CustomRoutingDecision::Next(nid);
}
}
if has_condition {
tracing::warn!(
flow_id = %flow_ir.id,
node_id = %node_id,
conditions = ?unmatched_conditions,
"no conditional route matched; pausing run at current node for resume"
);
CustomRoutingDecision::Wait
} else {
tracing::warn!(
flow_id = %flow_ir.id,
node_id = %node_id,
"no route matched and no conditions present; terminating"
);
CustomRoutingDecision::End
}
}
fn evaluate_simple_condition(condition: &str, ctx: &Value) -> bool {
if let Some((path, expected)) = split_condition(condition, "==") {
return string_eq(ctx, path, expected, false);
}
if let Some((path, expected)) = split_condition(condition, "!=") {
return string_eq(ctx, path, expected, true);
}
if let Some((path, expected)) = split_condition(condition, ">=") {
return numeric_cmp(ctx, path, expected, |a, b| a >= b);
}
if let Some((path, expected)) = split_condition(condition, "<=") {
return numeric_cmp(ctx, path, expected, |a, b| a <= b);
}
if let Some((path, expected)) = split_condition(condition, ">") {
return numeric_cmp(ctx, path, expected, |a, b| a > b);
}
if let Some((path, expected)) = split_condition(condition, "<") {
return numeric_cmp(ctx, path, expected, |a, b| a < b);
}
if let Some((path, expected)) = split_condition(condition, " contains ") {
let needle = expected.to_lowercase();
return resolve_dotted_path(ctx, path)
.is_some_and(|actual| actual.to_lowercase().contains(&needle));
}
false
}
fn split_condition<'a>(condition: &'a str, op: &str) -> Option<(&'a str, &'a str)> {
let idx = condition.find(op)?;
let path = condition[..idx].trim();
let value = condition[idx + op.len()..].trim().trim_matches('"');
Some((path, value))
}
fn string_eq(ctx: &Value, path: &str, expected: &str, negate: bool) -> bool {
let matches = resolve_dotted_path(ctx, path)
.as_deref()
.is_some_and(|a| a.eq_ignore_ascii_case(expected));
if negate { !matches } else { matches }
}
fn numeric_cmp(ctx: &Value, path: &str, expected: &str, cmp: impl Fn(f64, f64) -> bool) -> bool {
let Some(actual) = resolve_dotted_path(ctx, path).and_then(|a| a.trim().parse::<f64>().ok())
else {
return false;
};
let Ok(rhs) = expected.parse::<f64>() else {
return false;
};
cmp(actual, rhs)
}
fn resolve_dotted_path(value: &Value, path: &str) -> Option<String> {
let parts: Vec<&str> = path.split('.').collect();
let mut current = value;
for part in &parts {
current = current.get(part)?;
}
match current {
Value::String(s) => Some(s.clone()),
Value::Bool(b) => Some(b.to_string()),
Value::Number(n) => Some(n.to_string()),
_ => Some(current.to_string()),
}
}
const SUCCESS_EVENT_PORTS: [&str; 3] = ["on_success", "on_complete", "on_submit"];
const ERROR_EVENT_PORTS: [&str; 3] = ["on_error", "on_cancel", "on_timeout"];
fn node_has_error_route(routing: &Routing) -> bool {
let Routing::Custom(raw) = routing else {
return false;
};
let Some(routes) = raw.as_array() else {
return false;
};
routes.iter().any(|route| {
let by_event = route
.get("event")
.and_then(Value::as_str)
.is_some_and(|e| ERROR_EVENT_PORTS.contains(&e));
let by_condition = route
.get("condition")
.and_then(Value::as_str)
.is_some_and(|c| ERROR_EVENT_PORTS.iter().any(|port| c.contains(port)));
by_event || by_condition
})
}
fn default_success_event(routes: &[Value]) -> &'static str {
default_event(routes, &SUCCESS_EVENT_PORTS, "on_success")
}
fn default_error_event(routes: &[Value]) -> &'static str {
default_event(routes, &ERROR_EVENT_PORTS, "on_error")
}
fn default_event(routes: &[Value], ports: &[&'static str], fallback: &'static str) -> &'static str {
let referenced: Vec<&str> = routes
.iter()
.filter_map(|route| route.get("condition").and_then(Value::as_str))
.filter_map(condition_event_eq)
.collect();
ports
.iter()
.copied()
.find(|port| referenced.contains(port))
.unwrap_or(fallback)
}
fn condition_event_eq(condition: &str) -> Option<&str> {
let idx = condition.find("==")?;
if condition[..idx].trim() != "event" {
return None;
}
Some(condition[idx + 2..].trim().trim_matches('"'))
}
fn resolve_entry_metadata(entry: &Value) -> Option<&Value> {
entry
.pointer("/input/metadata")
.or_else(|| entry.pointer("/metadata"))
}
fn submitted_fields(entry: &Value) -> JsonMap<String, Value> {
let mut fields = JsonMap::new();
if let Some(Value::Object(meta)) = resolve_entry_metadata(entry) {
for (key, value) in meta {
if key == "action" || key == SUBMIT_MARKER_KEY {
continue;
}
fields.insert(key.clone(), value.clone());
}
}
let envelope = entry
.get("input")
.filter(|v| v.is_object())
.unwrap_or(entry);
if let Some(map) = envelope.as_object() {
for (key, value) in map {
if key == "metadata" || key == "text" {
continue;
}
fields.insert(key.clone(), value.clone());
}
}
fields
}
fn build_routing_context(
output: &NodeOutput,
state: &ExecutionState,
success_event: &str,
error_event: &str,
) -> Value {
let mut ctx = match &output.payload {
Value::Object(map) => map.clone(),
_ => JsonMap::new(),
};
let entry = alias_input_to_entry(state.entry.clone());
ctx.insert("entry".into(), entry.clone());
ctx.insert("in".into(), entry.clone());
ctx.insert("node".into(), Value::Object(state.outputs_map()));
let metadata = resolve_entry_metadata(&entry);
let mut response = JsonMap::new();
if let Some(Value::Object(meta)) = metadata {
for (k, v) in meta {
match v {
Value::String(s) => {
response.insert(k.clone(), Value::String(s.clone()));
}
other => {
response.insert(k.clone(), other.clone());
}
}
}
}
if let Some(text) = entry
.pointer("/input/text")
.or_else(|| entry.pointer("/text"))
.filter(|t| !t.is_null())
{
response.insert("text".into(), text.clone());
}
ctx.insert("response".into(), Value::Object(response));
let event = output
.meta
.get("outcome")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| {
if output.ok {
success_event
} else {
error_event
}
.to_string()
});
ctx.insert("event".into(), Value::String(event));
Value::Object(ctx)
}
fn approval_requires_human(input: &Value) -> bool {
let mode = input
.get("mode")
.and_then(Value::as_str)
.unwrap_or("always");
match mode {
"above_risk" => {
let risk = input.get("risk").and_then(Value::as_f64).unwrap_or(0.0);
let threshold = input
.get("risk_threshold")
.and_then(Value::as_f64)
.unwrap_or(1.0);
risk >= threshold
}
"above_confidence" => {
let confidence = input
.get("confidence")
.and_then(Value::as_f64)
.unwrap_or(0.0);
let threshold = input
.get("confidence_threshold")
.and_then(Value::as_f64)
.unwrap_or(1.0);
confidence < threshold
}
_ => true,
}
}
fn entry_is_approval_response(entry: &Value) -> bool {
entry.get("ok").is_some()
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ParkedApproval {
pub(crate) correlation_id: Option<String>,
pub(crate) token_fingerprint: Option<String>,
}
pub(crate) fn response_authenticates(response: &Value, parked: &ParkedApproval) -> bool {
match parked.token_fingerprint.as_deref() {
None => true,
Some(fingerprint) => {
approval_token::verify(approval_token::from_response(response), fingerprint)
}
}
}
fn approval_outcome_from_entry(entry: &Value) -> &'static str {
let timed_out = entry
.pointer("/error/code")
.and_then(Value::as_str)
.is_some_and(|code| code.eq_ignore_ascii_case("timeout"));
if timed_out {
return "timeout";
}
if entry.get("ok").and_then(Value::as_bool) == Some(false) {
return "denied";
}
match entry.pointer("/output/decision").and_then(Value::as_str) {
Some(decision) if decision.eq_ignore_ascii_case("approved") => "approved",
_ => "denied",
}
}
#[cfg(test)]
mod approval_gate_tests {
use super::{approval_outcome_from_entry, approval_requires_human, entry_is_approval_response};
use serde_json::json;
#[test]
fn above_risk_auto_approves_below_threshold() {
let input = json!({ "risk": 0.5, "mode": "above_risk", "risk_threshold": 0.7 });
assert!(!approval_requires_human(&input));
}
#[test]
fn above_risk_requires_human_at_or_above_threshold() {
let input = json!({ "risk": 0.9, "mode": "above_risk", "risk_threshold": 0.7 });
assert!(approval_requires_human(&input));
}
#[test]
fn above_confidence_requires_human_when_low_confidence() {
let input =
json!({ "confidence": 0.4, "mode": "above_confidence", "confidence_threshold": 0.8 });
assert!(approval_requires_human(&input));
}
#[test]
fn always_and_missing_gate_require_human() {
assert!(approval_requires_human(&json!({ "mode": "always" })));
assert!(approval_requires_human(&json!({})));
}
#[test]
fn entry_is_a_response_only_when_the_envelope_has_ok() {
assert!(entry_is_approval_response(
&json!({ "ok": true, "output": { "decision": "approved" } })
));
assert!(entry_is_approval_response(
&json!({ "ok": false, "error": { "code": "timeout" } })
));
assert!(!entry_is_approval_response(
&json!({ "text": "hi", "metadata": { "action": "go" } })
));
assert!(!entry_is_approval_response(&json!({})));
}
#[test]
fn outcome_reads_the_decision() {
assert_eq!(
approval_outcome_from_entry(
&json!({ "ok": true, "output": { "decision": "approved" } })
),
"approved"
);
assert_eq!(
approval_outcome_from_entry(&json!({ "ok": true, "output": { "decision": "denied" } })),
"denied"
);
}
#[test]
fn timeout_wins_over_the_decision() {
assert_eq!(
approval_outcome_from_entry(
&json!({ "ok": false, "output": null, "error": { "code": "timeout" } })
),
"timeout"
);
}
#[test]
fn unknown_or_missing_decision_fails_closed_to_denied() {
assert_eq!(
approval_outcome_from_entry(&json!({ "ok": true, "output": { "decision": "maybe" } })),
"denied"
);
assert_eq!(
approval_outcome_from_entry(&json!({ "ok": true, "output": {} })),
"denied"
);
assert_eq!(
approval_outcome_from_entry(&json!({ "ok": true })),
"denied"
);
assert_eq!(
approval_outcome_from_entry(&json!({ "ok": false, "error": { "code": "nats_down" } })),
"denied"
);
}
#[test]
fn a_failed_envelope_is_denied_even_if_it_carries_an_approval() {
assert_eq!(
approval_outcome_from_entry(&json!({
"ok": false,
"error": { "code": "nats_down" },
"output": { "decision": "approved" }
})),
"denied"
);
}
#[test]
fn decision_match_is_case_insensitive() {
assert_eq!(
approval_outcome_from_entry(
&json!({ "ok": true, "output": { "decision": "Approved" } })
),
"approved"
);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn native_op_key_for(kind: &NodeKind) -> Option<&'static str> {
match kind {
NodeKind::Exec { .. } | NodeKind::PackComponent { .. } => None,
NodeKind::BuiltinEmit { .. } | NodeKind::Mcp { .. } | NodeKind::A2a { .. } => None,
NodeKind::ProviderInvoke => Some("provider.invoke"),
NodeKind::FlowCall => Some("flow.call"),
NodeKind::FlowGoto => Some("flow.goto"),
NodeKind::BuiltinStateGet => Some("state.get"),
NodeKind::BuiltinStateSet => Some("state.set"),
NodeKind::VarSet { .. } => Some("var.set"),
NodeKind::Wait => Some("session.wait"),
NodeKind::DwAgent { .. } => Some("dw.agent"),
NodeKind::DwAgentGraph { .. } => Some("dw.agent_graph"),
NodeKind::SorlaCall { .. } => Some("sorla.call"),
NodeKind::OperalaCall { .. } => Some("operala.call"),
NodeKind::AgenticCall { .. } => Some("agentic.call"),
NodeKind::TelcoXCall { .. } => Some("telco-x.call"),
NodeKind::ApprovalCall { .. } => Some("approval.call"),
}
}
#[test]
fn every_engine_dispatched_op_key_is_native_to_the_loader() {
for key in [
"provider.invoke",
"flow.call",
"flow.goto",
"state.get",
"state.set",
"var.set",
"session.wait",
"dw.agent",
"dw.agent_graph",
"sorla.call",
"operala.call",
"agentic.call",
"telco-x.call",
"approval.call",
] {
assert!(
crate::runner::flow_adapter::is_native_op_key(key),
"the engine dispatches `{key}`, but the loader does not treat it \
as native — it will be wrapped as a generic component and the \
engine arm becomes unreachable"
);
}
assert!(crate::runner::flow_adapter::is_native_op_key(
"emit.response"
));
assert!(crate::runner::flow_adapter::is_native_op_key(
"mcp:srv/tool"
));
for key in ["mcp", "mcp:srv/tool", "a2a", "a2a:8d2f0c1e-recipe"] {
assert!(
crate::runner::flow_adapter::is_native_op_key(key),
"the engine dispatches `{key}`, but the loader does not treat it as native"
);
}
assert!(!crate::runner::flow_adapter::is_native_op_key("mcp.exec"));
assert!(!crate::runner::flow_adapter::is_native_op_key("a2a.exec"));
assert_eq!(native_op_key_for(&NodeKind::FlowGoto), Some("flow.goto"));
}
#[test]
fn the_a2a_component_ref_is_a_valid_component_id() {
assert!(greentic_types::ComponentId::from_str("a2a").is_ok());
}
#[test]
fn a2a_node_kind_prefers_the_payload_over_the_ref() {
let payload = json!({ "agent": "from-payload", "message": "hi" });
assert!(matches!(
a2a_node_kind(&payload, Some("a2a:from-ref")),
NodeKind::A2a { agent_id } if agent_id == "from-payload"
));
}
#[test]
fn a2a_node_kind_falls_back_to_both_ref_spellings() {
for reference in ["a2a:8d2f0c1e-recipe", "8d2f0c1e-recipe"] {
assert!(
matches!(
a2a_node_kind(&json!({ "message": "hi" }), Some(reference)),
NodeKind::A2a { agent_id } if agent_id == "8d2f0c1e-recipe"
),
"{reference} must resolve the agent id"
);
}
}
#[test]
fn an_a2a_node_naming_no_agent_loads_as_a_generic_component() {
for legacy in [None, Some("a2a:"), Some("")] {
assert!(
matches!(
a2a_node_kind(&json!({ "message": "hi" }), legacy),
NodeKind::PackComponent { .. }
),
"legacy={legacy:?} must not classify as an a2a node"
);
}
}
#[cfg(feature = "agentic-worker")]
fn a2a_result(status: &str, extra: (&str, &str)) -> Value {
json!({ "status": status, "agent": "recipe", extra.0: extra.1 })
}
#[cfg(feature = "agentic-worker")]
#[test]
fn without_an_error_route_an_a2a_node_reports_ok_and_keeps_the_value() {
let result = a2a_result("error", ("error", "card unreachable"));
let output = a2a_node_output(bind_node_result(&json!({}), result.clone()), &result, false);
assert!(output.ok);
assert_eq!(output.payload["error"], "card unreachable");
}
#[cfg(feature = "agentic-worker")]
#[test]
fn only_a_failure_marks_an_a2a_node_errored_and_the_two_failures_keep_their_codes() {
let cases = [
("completed", "reply", true, None),
("input_required", "question", true, None),
("working", "detail", true, None),
("failed", "error", false, Some("a2a_agent_failed")),
("error", "error", false, Some("a2a_call_failed")),
];
for (status, key, ok, code) in cases {
let result = a2a_result(status, (key, "some text"));
let output =
a2a_node_output(bind_node_result(&json!({}), result.clone()), &result, true);
assert_eq!(
output.ok, ok,
"status {status} produced {:?}",
output.payload
);
assert_eq!(
output.payload["status"], status,
"the status must survive so a flow can still route on it"
);
match code {
Some(code) => {
assert_eq!(output.payload["error"]["code"], code, "status {status}");
assert_eq!(output.payload["error"]["message"], "some text");
}
None => assert!(
output.payload["error"].is_null() || output.payload["error"].is_string(),
"status {status} must not be reshaped into an error envelope: {:?}",
output.payload
),
}
}
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_failed_a2a_node_keeps_its_output_binding_key() {
let result = a2a_result("failed", ("error", "the agent rejected the request"));
let payload = json!({ "agent": "recipe", "message": "hi", "output": "answer" });
let output = a2a_node_output(bind_node_result(&payload, result.clone()), &result, true);
assert!(!output.ok);
assert_eq!(output.payload["answer"]["status"], "failed");
assert_eq!(output.payload["error"]["code"], "a2a_agent_failed");
}
#[cfg(feature = "agentic-worker")]
#[test]
fn the_output_binding_rule_is_one_rule_for_both_remote_tool_nodes() {
let result = json!({ "status": "completed", "reply": "an omelette" });
assert_eq!(
bind_node_result(&json!({ "output": "answer" }), result.clone()),
json!({ "answer": result })
);
for payload in [json!({}), json!({ "output": "" }), json!("not an object")] {
assert_eq!(bind_node_result(&payload, result.clone()), result);
}
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_blank_message_is_recognised_as_nothing_to_send() {
for blank in [json!(null), json!(""), json!(" ")] {
assert!(is_blank(&blank), "{blank} must read as blank");
}
for present in [json!("hi"), json!(0), json!(false), json!({ "a": 1 })] {
assert!(!is_blank(&present), "{present} must read as content");
}
}
#[cfg(feature = "agentic-worker")]
struct PanicIfDispatchedHandler;
#[cfg(feature = "agentic-worker")]
#[async_trait::async_trait]
impl crate::runner::remote_dispatch::RemoteDispatchHandler for PanicIfDispatchedHandler {
async fn dispatch(
&self,
_request: crate::runner::remote_dispatch::RemoteDispatch,
) -> anyhow::Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
panic!(
"a route document resolved for this SoR; NATS must never be reached \
(amendment A1: a route document always wins over NATS)"
);
}
}
#[cfg(feature = "agentic-worker")]
fn sorla_call_node(routing: Routing) -> HostNode {
HostNode {
kind: NodeKind::SorlaCall {
target: "landlord".to_string(),
},
component: "sorla.call".into(),
component_id: "sorla.call".into(),
operation_name: None,
operation_in_mapping: None,
payload_expr: Value::Null,
routing,
vars_out: None,
response_timeout_secs: None,
}
}
#[cfg(feature = "agentic-worker")]
fn sorla_call_ctx() -> FlowContext<'static> {
FlowContext {
tenant: "acme",
pack_id: "test-pack",
flow_id: "f",
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
}
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn a_route_document_wins_over_nats() {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/admin/v1/capabilities"))
.respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
crate::runner::sorx_invoker::fixtures::caps_response_one_business_action(),
))
.mount(&server)
.await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::path("/admin/v1/capabilities/invoke"))
.respond_with(
wiremock::ResponseTemplate::new(200)
.set_body_json(json!({"ok": true, "result": {"id": "pay-1"}})),
)
.mount(&server)
.await;
let secrets = crate::runner::sorla_route::test_secrets::Handle::with(&[(
"secrets://default/acme/_/sorla/landlord",
&format!(r#"{{"url":"{}","tenant":"acme"}}"#, server.uri()),
)])
.manager();
let mut engine = minimal_engine();
engine.mcp_secrets = Some(secrets);
engine.remote_dispatch_handler = Some(Arc::new(PanicIfDispatchedHandler));
let ctx = sorla_call_ctx();
let node = sorla_call_node(Routing::End);
let mut state = ExecutionState::new(Value::Null);
let payload = json!({
"await": true,
"operation": "record_rent_payment",
"input": {"amount": 5},
});
let event = NodeEvent {
context: &ctx,
node_id: "call",
node: &node,
payload: &payload,
};
let outcome = engine
.dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
.await
.expect("a resolved route document must dispatch over HTTP, never NATS");
assert!(outcome.output.ok);
assert_eq!(
outcome.output.payload,
json!({"id": "pay-1"}),
"the node output must be the HTTP result"
);
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn a_backend_failure_never_falls_back_to_nats() {
let secrets = crate::runner::sorla_route::test_secrets::Handle::with(&[]);
secrets.fail(
"secrets://default/acme/_/sorla/landlord",
"connection refused",
);
let mut engine = minimal_engine();
engine.mcp_secrets = Some(secrets.manager());
engine.remote_dispatch_handler = Some(Arc::new(PanicIfDispatchedHandler));
let ctx = sorla_call_ctx();
let node = sorla_call_node(Routing::End);
let mut state = ExecutionState::new(Value::Null);
let payload = json!({
"await": true,
"operation": "record_rent_payment",
"input": {},
});
let event = NodeEvent {
context: &ctx,
node_id: "call",
node: &node,
payload: &payload,
};
let result = engine
.dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
.await;
let err = match result {
Err(err) => err,
Ok(_) => panic!("a backend failure must fail the node, not silently succeed"),
};
assert!(err.to_string().contains("could not be read"), "got: {err}");
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn no_route_and_no_nats_fails_with_sorla_route_missing() {
let engine = minimal_engine();
let ctx = sorla_call_ctx();
let payload = json!({
"await": true,
"operation": "record_rent_payment",
"input": {},
});
let node = sorla_call_node(Routing::End);
let mut state = ExecutionState::new(Value::Null);
let event = NodeEvent {
context: &ctx,
node_id: "call",
node: &node,
payload: &payload,
};
let result = engine
.dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
.await;
let err = match result {
Err(err) => err,
Ok(_) => panic!("no route document and no NATS handler must fail the node"),
};
assert!(
err.to_string().contains("sorla_route_missing"),
"got: {err}"
);
let node = sorla_call_node(Routing::Custom(json!([
{ "condition": "event == \"on_success\"", "to": "n" },
{ "condition": "event == \"on_error\"", "to": "e" },
])));
let mut state = ExecutionState::new(Value::Null);
let event = NodeEvent {
context: &ctx,
node_id: "call",
node: &node,
payload: &payload,
};
let outcome = engine
.dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
.await
.expect("an error-routed node must complete, not hard-fail");
assert!(!outcome.output.ok);
let message = outcome
.output
.payload
.get("error")
.and_then(Value::as_str)
.unwrap_or_default();
assert!(message.contains("sorla_route_missing"), "got: {message}");
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn an_approval_inbox_leaves_sorla_route_missing_intact() {
let mut engine = minimal_engine();
engine.set_approval_dispatch_handler(Arc::new(PanicIfDispatchedHandler));
let ctx = sorla_call_ctx();
let payload = json!({
"await": true,
"operation": "record_rent_payment",
"input": {},
});
let node = sorla_call_node(Routing::End);
let mut state = ExecutionState::new(Value::Null);
let event = NodeEvent {
context: &ctx,
node_id: "call",
node: &node,
payload: &payload,
};
let err = match engine
.dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
.await
{
Err(err) => err,
Ok(_) => panic!("a missing route with only the approval inbox must fail the node"),
};
assert!(
err.to_string().contains("sorla_route_missing"),
"got: {err}"
);
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn only_approval_dispatches_use_the_approval_slot() {
let inbox = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let mut engine = minimal_engine();
engine.set_approval_dispatch_handler(inbox.clone());
let ctx = sorla_call_ctx();
let node = HostNode::for_test_approval("hitl");
let mut state = ExecutionState::new(Value::Null);
let payload = json!({ "await": true, "input": { "mode": "always" } });
let event = NodeEvent {
context: &ctx,
node_id: "gate",
node: &node,
payload: &payload,
};
let outcome = engine
.dispatch_node(&ctx, "gate", &node, &mut state, payload.clone(), &event)
.await
.expect("approval.call must dispatch through the approval slot");
assert!(matches!(outcome.control, NodeControl::AwaitHere { .. }));
{
let calls = inbox.calls.lock().unwrap();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].runtime, APPROVAL_RUNTIME);
assert!(calls[0].decision_token.is_some());
assert!(
crate::runner::runtime_session_resumer::split_dispatch_nonce(
&calls[0].correlation_id
)
.1
.is_some(),
"the id carries its per-dispatch nonce"
);
}
let parked = state.pending_approvals();
assert_eq!(parked.len(), 1);
assert!(parked[0].token_fingerprint.is_some());
let err = engine
.execute_remote_dispatch(&ctx, "telco-x", "t", json!({"await": true}), true)
.await
.err()
.expect("a non-approval runtime must not use the approval slot");
assert!(
err.to_string()
.contains("no RemoteDispatchHandler configured"),
"got: {err}"
);
assert_eq!(inbox.calls.lock().unwrap().len(), 1);
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn approval_falls_back_to_the_shared_slot() {
let shared = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let mut engine = minimal_engine();
engine.set_remote_dispatch_handler(shared.clone());
let ctx = sorla_call_ctx();
let node = HostNode::for_test_approval("hitl");
let mut state = ExecutionState::new(Value::Null);
let payload = json!({ "await": true, "input": { "mode": "always" } });
let event = NodeEvent {
context: &ctx,
node_id: "gate",
node: &node,
payload: &payload,
};
engine
.dispatch_node(&ctx, "gate", &node, &mut state, payload.clone(), &event)
.await
.expect("approval.call must fall back to the shared slot");
assert_eq!(shared.calls.lock().unwrap().len(), 1);
}
use crate::validate::{ValidationConfig, ValidationMode};
use greentic_types::{
Flow, FlowComponentRef, FlowId, FlowKind, FlowMetadata, InputMapping, Node, NodeId,
OutputMapping, Routing, TelemetryHints,
};
use serde_json::json;
use std::collections::{BTreeMap, HashMap as StdHashMap};
use std::str::FromStr;
use std::sync::Mutex;
use tokio::runtime::Runtime;
fn minimal_engine() -> FlowEngine {
FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::new()),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
}
}
#[cfg(feature = "agentic-worker")]
struct StubSecrets;
#[cfg(feature = "agentic-worker")]
#[async_trait::async_trait]
impl greentic_secrets_lib::SecretsManager for StubSecrets {
async fn read(&self, _path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
Ok(Vec::new())
}
async fn write(&self, _path: &str, _bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
Ok(())
}
async fn delete(&self, _path: &str) -> greentic_secrets_lib::Result<()> {
Ok(())
}
}
#[cfg(feature = "agentic-worker")]
#[test]
#[serial_test::serial]
fn an_injected_manager_is_what_an_mcp_node_dispatches_with() {
let injected: crate::secrets::DynSecretsManager = std::sync::Arc::new(StubSecrets);
let engine = minimal_engine().with_mcp_secrets(Some(injected.clone()));
let chosen = engine
.mcp_secrets_for_dispatch()
.expect("an injected manager is always a choice");
assert!(std::sync::Arc::ptr_eq(&chosen, &injected));
}
#[cfg(feature = "agentic-worker")]
#[test]
fn no_injection_leaves_the_env_derived_behaviour_alone() {
let engine = minimal_engine();
assert!(engine.mcp_secrets.is_none());
}
#[cfg(feature = "agentic-worker")]
#[test]
#[serial_test::serial]
fn binding_no_manager_does_not_clear_one_already_bound() {
let injected: crate::secrets::DynSecretsManager = std::sync::Arc::new(StubSecrets);
let engine = minimal_engine()
.with_mcp_secrets(Some(injected.clone()))
.with_mcp_secrets(None);
let chosen = engine
.mcp_secrets_for_dispatch()
.expect("the bound manager must survive");
assert!(std::sync::Arc::ptr_eq(&chosen, &injected));
}
fn flow_desc(id: &str, pack_id: &str, flow_type: &str, entry: bool) -> FlowDescriptor {
FlowDescriptor {
id: id.into(),
flow_type: flow_type.into(),
pack_id: pack_id.into(),
profile: pack_id.into(),
version: "0.0.0".into(),
description: None,
entry,
}
}
#[test]
fn entry_flow_by_type_disambiguates_entrypoint_from_internal_helpers() {
let mut engine = minimal_engine();
engine.flows = vec![
flow_desc("default", "weatherapi-pack", "messaging", true),
flow_desc("flow_", "weatherapi-pack", "messaging", false),
flow_desc("flow_error", "weatherapi-pack", "messaging", false),
flow_desc("flow_get_weather", "weatherapi-pack", "messaging", false),
];
assert!(
engine.flow_by_type("messaging").is_none(),
"multiple messaging flows must be ambiguous for the plain lookup"
);
let resolved = engine
.entry_flow_by_type("messaging")
.expect("single entry flow must resolve");
assert_eq!(resolved.id, "default");
assert_eq!(resolved.pack_id, "weatherapi-pack");
}
#[test]
fn entry_flow_by_type_still_ambiguous_across_two_entrypoints() {
let mut engine = minimal_engine();
engine.flows = vec![
flow_desc("default", "pack.a", "messaging", true),
flow_desc("default", "pack.b", "messaging", true),
flow_desc("helper", "pack.a", "messaging", false),
];
assert!(engine.entry_flow_by_type("messaging").is_none());
}
#[test]
fn entry_flow_by_type_excludes_messaging_provider_pack_flows() {
let mut engine = minimal_engine();
engine.flows = vec![
flow_desc("main", "hr-onboarding-pack", "messaging", true),
flow_desc("main", "messaging-teams", "messaging", true),
];
engine
.messaging_provider_pack_ids
.insert("messaging-teams".to_string());
assert!(engine.flow_by_type("messaging").is_none());
let resolved = engine
.entry_flow_by_type("messaging")
.expect("app entry flow must resolve past the provider flow");
assert_eq!(resolved.id, "main");
assert_eq!(resolved.pack_id, "hr-onboarding-pack");
}
#[test]
fn entry_flow_by_type_matches_plain_lookup_for_single_flow() {
let mut engine = minimal_engine();
engine.flows = vec![flow_desc("only", "pack.a", "messaging", true)];
assert_eq!(
engine.flow_by_type("messaging").map(|f| f.id.as_str()),
Some("only")
);
assert_eq!(
engine
.entry_flow_by_type("messaging")
.map(|f| f.id.as_str()),
Some("only")
);
}
#[test]
fn to_node_output_legacy_success_becomes_data() {
let out = to_node_output(&json!({ "ok": true, "temp": "20C" }));
assert!(out.is_ok(), "legacy ok:true must classify as Data");
let data = out.data().expect("data present");
assert_eq!(data.get("temp").and_then(Value::as_str), Some("20C"));
}
#[test]
fn to_node_output_legacy_error_becomes_errors() {
let out = to_node_output(
&json!({ "ok": false, "error": { "code": "E_BAD", "message": "boom" } }),
);
assert!(!out.is_ok(), "legacy ok:false must classify as Errors");
let errs = out.errors();
assert_eq!(errs.len(), 1);
assert_eq!(errs[0].code, "E_BAD");
assert_eq!(errs[0].message, "boom");
}
#[test]
fn to_node_output_native_data_envelope_roundtrips() {
let out = to_node_output(&json!({ "data": { "x": 1 } }));
assert!(out.is_ok());
assert_eq!(
out.data().and_then(|d| d.get("x")).and_then(Value::as_i64),
Some(1)
);
}
#[test]
fn to_node_output_native_errors_envelope_roundtrips() {
let out = to_node_output(&json!({
"errors": [ { "code": "C", "message": "m", "kind": "validation",
"retryable": false, "details": {} } ]
}));
assert!(!out.is_ok());
assert_eq!(out.errors()[0].code, "C");
assert_eq!(
out.errors()[0].kind,
greentic_types::node_io::ErrorKind::Validation
);
}
#[test]
fn to_node_output_bare_object_becomes_data() {
let out = to_node_output(&json!({ "foo": 1 }));
assert!(out.is_ok());
assert_eq!(
out.data()
.and_then(|d| d.get("foo"))
.and_then(Value::as_i64),
Some(1)
);
}
#[test]
fn templating_renders_with_partials_and_data() {
let mut state = ExecutionState::new(json!({ "city": "London" }));
state.nodes.insert(
"forecast".to_string(),
NodeOutput::new(json!({ "temp": "20C" })),
);
let ctx = state.context();
assert_eq!(ctx["nodes"]["forecast"]["payload"]["temp"], json!("20C"));
}
#[test]
fn outputs_map_exposes_node_io_data_and_errors_alongside_flat() {
let mut state = ExecutionState::new(json!({}));
state.nodes.insert(
"forecast".to_string(),
NodeOutput::new(json!({ "temp": "20C" })),
);
let outs = state.outputs_map();
assert_eq!(outs["forecast"]["temp"], json!("20C"));
assert_eq!(outs["forecast"]["data"]["temp"], json!("20C"));
assert_eq!(outs["forecast"]["errors"], json!([]));
}
#[test]
fn finalize_wraps_emitted_payloads() {
let mut state = ExecutionState::new(json!({}));
state.push_egress(json!({ "text": "first" }));
state.push_egress(json!({ "text": "second" }));
let result = state.finalize_with(Some(json!({ "text": "final" })));
assert_eq!(
result,
json!([
{ "text": "first" },
{ "text": "second" },
{ "text": "final" }
])
);
}
#[test]
fn finalize_does_not_double_terminal_emit_response() {
let card = json!({ "renderedCard": { "type": "AdaptiveCard" } });
let mut state = ExecutionState::new(json!({}));
state.push_egress(card.clone());
let result = state.finalize_with(Some(card.clone()));
assert_eq!(result, json!([card]));
}
#[test]
fn finalize_still_appends_distinct_terminal_output() {
let mut state = ExecutionState::new(json!({}));
state.push_egress(json!({ "text": "emitted" }));
let result = state.finalize_with(Some(json!({ "text": "final" })));
assert_eq!(result, json!([{ "text": "emitted" }, { "text": "final" }]));
}
#[test]
fn alias_input_to_entry_exposes_input_for_bare_message() {
let msg = json!({ "text": "hi", "metadata": { "operation": "get_weather" } });
let aliased = alias_input_to_entry(msg);
assert_eq!(
aliased.pointer("/metadata/operation"),
Some(&json!("get_weather"))
);
assert_eq!(
aliased.pointer("/input/metadata/operation"),
Some(&json!("get_weather"))
);
}
#[test]
fn alias_input_to_entry_preserves_explicit_input_wrapper() {
let wrapped = json!({ "input": { "metadata": { "operation": "x" } } });
assert_eq!(alias_input_to_entry(wrapped.clone()), wrapped);
}
#[test]
fn alias_input_to_entry_ignores_non_objects() {
assert_eq!(alias_input_to_entry(json!("hi")), json!("hi"));
assert_eq!(alias_input_to_entry(json!(null)), json!(null));
}
fn render_entry(entry: Value, expr: &str) -> Value {
let st = ExecutionState::new(entry);
let ctx = template_context(&st, Value::Null);
render_template_value(&json!(expr), &ctx, TemplateOptions::default())
.expect("template renders")
}
#[test]
fn entry_root_exposes_submitted_fields_on_the_wrapped_path() {
let entry = json!({
"input": {
"metadata": { "action": "submit", "company_size": "11-50" },
"text": "hi"
},
"tenant": "acme",
"correlation_id": "c-1"
});
assert_eq!(
render_entry(entry.clone(), "{{entry.company_size}}"),
json!("11-50")
);
assert_eq!(
render_entry(entry.clone(), "{{in.company_size}}"),
json!("11-50")
);
assert_eq!(
render_entry(entry.clone(), "{{entry.input.metadata.company_size}}"),
json!("11-50")
);
assert_eq!(
render_entry(entry.clone(), "{{in.input.metadata.company_size}}"),
json!("11-50")
);
assert_eq!(
render_entry(entry.clone(), "{{entry.tenant}}"),
json!("acme")
);
assert_eq!(
render_entry(entry.clone(), "{{entry.correlation_id}}"),
json!("c-1")
);
assert_eq!(
render_entry(entry.clone(), "{{entry.input.text}}"),
json!("hi")
);
assert_eq!(
render_entry(entry, "{{entry.input.metadata.action}}"),
json!("submit")
);
}
#[test]
fn entry_root_exposes_submitted_fields_on_the_demo_path() {
let entry = json!({
"company_size": "11-50",
"metadata": { "action": "submit", "email": "a@b.c" },
"text": "hi"
});
assert_eq!(
render_entry(entry.clone(), "{{entry.company_size}}"),
json!("11-50")
);
assert_eq!(
render_entry(entry.clone(), "{{entry.email}}"),
json!("a@b.c")
);
assert_eq!(
render_entry(entry.clone(), "{{entry.metadata.email}}"),
json!("a@b.c")
);
assert_eq!(render_entry(entry, "{{entry.text}}"), json!("hi"));
}
#[test]
fn entry_merge_never_clobbers_an_existing_root_key() {
let entry = json!({
"input": {
"metadata": { "tenant": "evil", "company_size": "11-50" }
},
"tenant": "acme"
});
assert_eq!(
render_entry(entry.clone(), "{{entry.tenant}}"),
json!("acme")
);
assert_eq!(
render_entry(entry.clone(), "{{entry.company_size}}"),
json!("11-50")
);
assert_eq!(
render_entry(entry, "{{entry.input.metadata.company_size}}"),
json!("11-50")
);
}
#[test]
fn entry_and_in_stay_identical_after_the_merge() {
let entry = json!({
"input": { "metadata": { "action": "submit", "email": "a@b.c" } },
"tenant": "acme"
});
let st = ExecutionState::new(entry);
let ctx = template_context(&st, Value::Null);
assert_eq!(
ctx.pointer("/entry"),
ctx.pointer("/in"),
"`in` is an alias of `entry` and must not drift from it"
);
}
#[test]
fn entry_merge_leaves_a_non_object_entry_untouched() {
assert_eq!(
merge_submitted_fields_into_entry(json!("hi"), JsonMap::new()),
json!("hi")
);
let mut fields = JsonMap::new();
fields.insert("x".into(), json!(1));
assert_eq!(
merge_submitted_fields_into_entry(json!(null), fields),
json!(null)
);
}
#[test]
fn finalize_flattens_final_array() {
let mut state = ExecutionState::new(json!({}));
state.push_egress(json!({ "text": "only" }));
let result = state.finalize_with(Some(json!([
{ "text": "extra-1" },
{ "text": "extra-2" }
])));
assert_eq!(
result,
json!([
{ "text": "only" },
{ "text": "extra-1" },
{ "text": "extra-2" }
])
);
}
#[test]
fn inject_card_locale_uses_entry_metadata_without_overwriting_payload() {
let mut payload = json!({
"card_source": "inline",
"card_spec": { "title": "Hello" }
});
inject_card_locale(
&mut payload,
&json!({"input": {"metadata": {"locale": "nl-NL"}}}),
);
assert_eq!(payload["locale"], json!("nl-NL"));
let mut existing = json!({
"card_source": "inline",
"card_spec": { "title": "Hello" },
"locale": "en-GB"
});
inject_card_locale(&mut existing, &json!({"metadata": {"locale": "nl-NL"}}));
assert_eq!(existing["locale"], json!("en-GB"));
}
#[test]
fn load_i18n_bundle_entries_reads_manifest_and_falls_back_to_en() {
let assets = StdHashMap::from([
(
"cards/i18n/_manifest.json".to_string(),
br#"{"locales":["de"]}"#.to_vec(),
),
(
"cards/i18n/de.json".to_string(),
br#"{"title":"Hallo"}"#.to_vec(),
),
(
"cards/i18n/en.json".to_string(),
br#"{"title":"Hello"}"#.to_vec(),
),
]);
let entries = load_i18n_bundle_entries("cards/i18n", |path| {
assets
.get(path)
.cloned()
.with_context(|| format!("missing asset {path}"))
});
assert_eq!(entries["de"]["title"], json!("Hallo"));
assert_eq!(entries["en"]["title"], json!("Hello"));
}
#[test]
fn load_i18n_bundle_entries_reads_single_file_bundle() {
let entries = load_i18n_bundle_entries("cards/i18n.json", |path| {
if path == "cards/i18n.json" {
Ok(br#"{"title":"Hello"}"#.to_vec())
} else {
bail!("unexpected asset {path}");
}
});
assert_eq!(entries["en"]["title"], json!("Hello"));
}
struct TestCrossPackResolver;
impl CrossPackResolver for TestCrossPackResolver {
fn invoke(
&self,
provider_id: &str,
provider_type: Option<&str>,
op: &str,
input: &[u8],
tenant: &str,
team: Option<&str>,
) -> Result<Value> {
Ok(json!({
"provider_id": provider_id,
"provider_type": provider_type,
"op": op,
"tenant": tenant,
"team": team,
"input": serde_json::from_slice::<Value>(input)?,
}))
}
}
#[test]
fn cross_pack_resolver_returns_node_output_when_present() {
let mut engine = minimal_engine();
engine.set_cross_pack_resolver(Arc::new(TestCrossPackResolver));
let output = engine
.try_invoke_cross_pack_resolver(
Some("mail"),
Some("messaging"),
"send",
br#"{"subject":"hello"}"#,
"demo",
)
.expect("resolver invocation")
.expect("resolver output");
assert_eq!(
output.payload,
json!({
"provider_id": "mail",
"provider_type": "messaging",
"op": "send",
"tenant": "demo",
"team": null,
"input": { "subject": "hello" },
})
);
}
#[test]
fn flow_goto_builds_a_jump_to_the_named_flow() {
let outcome = execute_flow_goto(json!({
"flow_id": "support",
"node": "ask_order",
"input": { "order": "A-1" },
}))
.expect("goto builds");
let NodeControl::Jump(jump) = outcome.control else {
panic!("flow.goto must produce a Jump, got {:?}", outcome.control);
};
assert_eq!(jump.flow, "support");
assert_eq!(jump.node.as_deref(), Some("ask_order"));
assert_eq!(jump.payload, json!({ "order": "A-1" }));
assert_eq!(outcome.output.payload, json!({ "order": "A-1" }));
}
#[test]
fn flow_goto_accepts_the_flow_alias_and_defaults_the_entry_node() {
let outcome = execute_flow_goto(json!({ "flow": "support" })).expect("goto builds");
let NodeControl::Jump(jump) = outcome.control else {
panic!("expected a Jump");
};
assert_eq!(jump.flow, "support");
assert!(
jump.node.is_none(),
"no node means `apply_jump` uses the target flow's start"
);
assert_eq!(jump.payload, Value::Null);
}
#[test]
fn flow_goto_refuses_an_empty_flow_id() {
for payload in [json!({ "flow_id": "" }), json!({ "flow_id": " " })] {
let err = execute_flow_goto(payload)
.err()
.expect("empty target must not build");
assert!(
err.to_string().contains("flow_id"),
"error must name the field: {err}"
);
}
let err = execute_flow_goto(json!({ "input": {} }))
.err()
.expect("missing target");
assert!(err.to_string().contains("flow.goto"), "got: {err}");
}
#[test]
fn flow_goto_treats_a_blank_entry_node_as_absent() {
let outcome =
execute_flow_goto(json!({ "flow_id": "support", "node": " " })).expect("goto builds");
let NodeControl::Jump(jump) = outcome.control else {
panic!("expected a Jump");
};
assert!(jump.node.is_none());
}
#[test]
fn flow_goto_forwards_the_redirect_ceiling_and_reason() {
let outcome = execute_flow_goto(json!({
"flow_id": "support",
"max_redirects": 1,
"reason": "menu choice",
}))
.expect("goto builds");
let NodeControl::Jump(jump) = outcome.control else {
panic!("expected a Jump");
};
assert_eq!(jump.max_redirects, Some(1));
assert_eq!(jump.reason.as_deref(), Some("menu choice"));
}
#[test]
fn flow_goto_names_itself_as_the_reason_by_default() {
let outcome = execute_flow_goto(json!({ "flow_id": "support" })).expect("goto builds");
let NodeControl::Jump(jump) = outcome.control else {
panic!("expected a Jump");
};
assert_eq!(jump.reason.as_deref(), Some("flow.goto node"));
}
#[test]
fn parse_component_control_ignores_plain_payload() {
let payload = json!({
"flow": "not-a-control-field",
"node": "n1"
});
let control = parse_component_control(&payload).expect("parse control");
assert!(control.is_none());
}
#[test]
fn parse_component_control_parses_jump_marker() {
let payload = json!({
"greentic_control": {
"action": "jump",
"v": 1,
"flow": "flow.b",
"node": "node-2",
"payload": { "message": "hi" },
"hints": { "k": "v" },
"max_redirects": 2,
"reason": "handoff"
}
});
let control = parse_component_control(&payload)
.expect("parse control")
.expect("missing control");
match control {
NodeControl::Jump(jump) => {
assert_eq!(jump.flow, "flow.b");
assert_eq!(jump.node.as_deref(), Some("node-2"));
assert_eq!(jump.payload, json!({ "message": "hi" }));
assert_eq!(jump.hints, json!({ "k": "v" }));
assert_eq!(jump.max_redirects, Some(2));
assert_eq!(jump.reason.as_deref(), Some("handoff"));
}
other => panic!("expected jump control, got {other:?}"),
}
}
#[test]
fn parse_component_control_rejects_invalid_marker() {
let payload = json!({
"greentic_control": "bad-shape"
});
let err = parse_component_control(&payload).expect_err("expected invalid marker error");
assert!(err.to_string().contains("greentic_control"));
}
#[test]
fn missing_operation_reports_node_and_component() {
let engine = minimal_engine();
let rt = Runtime::new().unwrap();
let retry_config = RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
};
let ctx = FlowContext {
tenant: "tenant",
pack_id: "test-pack",
flow_id: "flow",
node_id: Some("missing-op"),
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config,
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let node = HostNode {
kind: NodeKind::Exec {
target_component: "qa.process".into(),
},
component: "component.exec".into(),
component_id: "component.exec".into(),
operation_name: None,
operation_in_mapping: None,
payload_expr: Value::Null,
routing: Routing::End,
vars_out: None,
response_timeout_secs: None,
};
let _state = ExecutionState::new(Value::Null);
let payload = json!({ "component": "qa.process" });
let event = NodeEvent {
context: &ctx,
node_id: "missing-op",
node: &node,
payload: &payload,
};
let err = rt
.block_on(engine.execute_component_exec(
&ctx,
"missing-op",
&node,
payload.clone(),
&event,
ComponentOverrides {
component: None,
operation: None,
},
))
.unwrap_err();
let message = err.to_string();
assert!(
message.contains("missing operation for node `missing-op`"),
"unexpected message: {message}"
);
assert!(
message.contains("(component `component.exec`)"),
"unexpected message: {message}"
);
}
#[test]
fn missing_operation_mentions_mapping_hint() {
let engine = minimal_engine();
let rt = Runtime::new().unwrap();
let retry_config = RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
};
let ctx = FlowContext {
tenant: "tenant",
pack_id: "test-pack",
flow_id: "flow",
node_id: Some("missing-op-hint"),
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config,
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let node = HostNode {
kind: NodeKind::Exec {
target_component: "qa.process".into(),
},
component: "component.exec".into(),
component_id: "component.exec".into(),
operation_name: None,
operation_in_mapping: Some("render".into()),
payload_expr: Value::Null,
routing: Routing::End,
vars_out: None,
response_timeout_secs: None,
};
let _state = ExecutionState::new(Value::Null);
let payload = json!({ "component": "qa.process" });
let event = NodeEvent {
context: &ctx,
node_id: "missing-op-hint",
node: &node,
payload: &payload,
};
let err = rt
.block_on(engine.execute_component_exec(
&ctx,
"missing-op-hint",
&node,
payload.clone(),
&event,
ComponentOverrides {
component: None,
operation: None,
},
))
.unwrap_err();
let message = err.to_string();
assert!(
message.contains("missing operation for node `missing-op-hint`"),
"unexpected message: {message}"
);
assert!(
message.contains("Found operation in input.mapping (`render`)"),
"unexpected message: {message}"
);
}
struct CountingObserver {
starts: Mutex<Vec<String>>,
ends: Mutex<Vec<Value>>,
}
impl CountingObserver {
fn new() -> Self {
Self {
starts: Mutex::new(Vec::new()),
ends: Mutex::new(Vec::new()),
}
}
}
impl ExecutionObserver for CountingObserver {
fn on_node_start(&self, event: &NodeEvent<'_>) {
self.starts.lock().unwrap().push(event.node_id.to_string());
}
fn on_node_end(&self, _event: &NodeEvent<'_>, output: &Value) {
self.ends.lock().unwrap().push(output.clone());
}
fn on_node_error(&self, _event: &NodeEvent<'_>, _error: &dyn StdError) {}
}
#[test]
fn approval_call_component_id_is_not_dot_split() {
let node = Node {
id: NodeId::from_str("gate").unwrap(),
component: FlowComponentRef {
id: "approval.call".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "await": true, "input": { "mode": "always" } }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let host_node = HostNode::from(node);
assert_eq!(
host_node.component_id(),
"approval.call",
"approval.call must stay intact; splitting it yields 'approval', which \
is never a key in the pack's component map"
);
assert_eq!(
host_node.operation_name(),
None,
"the id is already complete — lowering must not invent an operation"
);
}
#[test]
fn approval_call_with_no_operation_dispatches_as_approval_call() {
let node = Node {
id: NodeId::from_str("gate").unwrap(),
component: FlowComponentRef {
id: "approval.call".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "await": true, "input": { "mode": "always" } }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let host_node = HostNode::from(node);
assert!(
matches!(&host_node.kind, NodeKind::ApprovalCall { target } if target.is_empty()),
"expected NodeKind::ApprovalCall with an empty target, got {:?}",
host_node.kind
);
}
#[test]
fn emits_end_event_for_successful_node() {
let node_id = NodeId::from_str("emit").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "message": "logged" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(node_id.clone(), node);
let flow = Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("emit.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(node_id.to_string()),
)]),
nodes,
metadata: Default::default(),
};
let host_flow = HostFlow::from(flow);
let engine = FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "emit.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let observer = CountingObserver::new();
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "emit.flow",
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: Some(&observer),
mocks: None,
caller: None,
};
let rt = Runtime::new().unwrap();
let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
assert!(matches!(result.status, FlowStatus::Completed));
assert!(
!result.node_outputs.is_empty(),
"completed flow must expose its per-node outputs"
);
assert!(
result
.node_outputs
.values()
.any(|v| v.to_string().contains("logged")),
"node_outputs must carry the executed node's payload: {:?}",
result.node_outputs
);
let starts = observer.starts.lock().unwrap();
let ends = observer.ends.lock().unwrap();
assert_eq!(starts.len(), 1);
assert_eq!(ends.len(), 1);
assert_eq!(ends[0], json!({ "message": "logged" }));
}
#[test]
fn dotted_component_id_with_mapping_operation_is_not_split() {
let node = Node {
conversational: false,
id: NodeId::from_str("render").unwrap(),
component: FlowComponentRef {
id: "ai.greentic.component-templates".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "operation": "handle_message", "input": "hi" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
};
let host = HostNode::from(node);
assert!(
matches!(&host.kind, NodeKind::PackComponent { component_ref } if component_ref == "ai.greentic.component-templates"),
"dotted component id must stay intact, got kind {:?}",
host.kind
);
assert_eq!(host.component, "ai.greentic.component-templates");
assert_eq!(host.operation_in_mapping(), Some("handle_message"));
}
#[test]
fn packed_component_operation_id_still_splits_without_mapping_operation() {
let node = Node {
conversational: false,
id: NodeId::from_str("render").unwrap(),
component: FlowComponentRef {
id: "templating.handlebars".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "text": "hello" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
};
let host = HostNode::from(node);
assert!(
matches!(&host.kind, NodeKind::PackComponent { component_ref } if component_ref == "templating"),
"packed <component>.<operation> id must split, got kind {:?}",
host.kind
);
assert_eq!(host.operation_name(), Some("handlebars"));
}
#[cfg(feature = "agentic-worker")]
#[test]
fn the_agent_node_receives_the_context_caller_not_a_payload_one() {
use crate::runner::agent_node::AgentNodeHandler;
use std::sync::Mutex;
struct Recorder(Arc<Mutex<Option<Value>>>);
#[async_trait::async_trait]
impl AgentNodeHandler for Recorder {
async fn execute(
&self,
_tenant_id: &str,
_env_id: &str,
_agent_id: &str,
_session_id: &str,
_flow_input: &Value,
_conversational: bool,
caller: Option<&Value>,
) -> anyhow::Result<Value> {
*self.0.lock().unwrap() = caller.cloned();
Ok(json!({ "reply": "ok", "trail": [], "terminated_by": "done" }))
}
}
let seen = Arc::new(Mutex::new(None));
let handler: Arc<dyn AgentNodeHandler> = Arc::new(Recorder(Arc::clone(&seen)));
let node_id = NodeId::from_str("agent").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "dw.agent".parse().unwrap(),
pack_alias: None,
operation: Some("greeter".to_string()),
},
input: InputMapping {
mapping: json!({
"user_text": "ping",
"caller": { "user_verified": true, "sub": "forged@evil" }
}),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(node_id.clone(), node);
let flow = Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("dw.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(node_id.to_string()),
)]),
nodes,
metadata: Default::default(),
};
let engine = FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "dw.flow".to_string(),
},
HostFlow::from(flow),
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: Some(handler),
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let trusted = json!({ "user_verified": true, "sub": "u-1@acme" });
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "dw.flow",
node_id: None,
tool: None,
action: None,
session_id: Some("sess-1"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: Some(&trusted),
};
let rt = Runtime::new().unwrap();
rt.block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
.unwrap();
let got = seen.lock().unwrap().clone().expect("handler saw a caller");
assert_eq!(
got["sub"], "u-1@acme",
"the context caller must win over the payload one"
);
assert_ne!(got["sub"], "forged@evil");
}
#[test]
fn dw_agent_node_routes_to_handler_and_returns_reply() {
use crate::runner::agent_node::{AgentNodeHandler, RuntimeAgentNodeHandler};
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::llm::LlmResponse;
use greentic_aw_runtime::mock::{
MockAgentStateStore, MockConfigProvider, MockLlmBackend, MockTelemetry, NoopToolLedger,
};
use greentic_aw_runtime::{
AgentConfig, AgentLimits, AgentRuntime, LlmProviderRef, TenantContext,
};
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("pong".into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let config_provider = MockConfigProvider::new();
let tenant = TenantContext::new("demo", "local");
config_provider.insert(
&tenant,
"greeter",
AgentConfig {
agent_id: "greeter".into(),
system_prompt: "sys".into(),
tools: vec![],
guardrails: vec![],
llm: LlmProviderRef {
provider: "mock".into(),
model: "m".into(),
credential_ref: None,
},
limits: AgentLimits::default(),
memory: None,
knowledge: None,
conversational: false,
opening_message: None,
on_text_while_parked: Default::default(),
},
);
let config_provider = Arc::new(config_provider);
let token_meter = Arc::new(MockTokenMeter::new(0));
let ledger = Arc::new(NoopToolLedger);
let ext_runtime = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let runtime = Arc::new(AgentRuntime::new(
config_provider,
store,
ext_runtime,
llm,
telemetry,
token_meter,
ledger,
None,
));
let handler: Arc<dyn AgentNodeHandler> =
Arc::new(RuntimeAgentNodeHandler::new(runtime, None, None, None));
let node_id = NodeId::from_str("agent").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "dw.agent".parse().unwrap(),
pack_alias: None,
operation: Some("greeter".to_string()),
},
input: InputMapping {
mapping: json!({ "user_text": "ping" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(node_id.clone(), node);
let flow = Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("dw.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(node_id.to_string()),
)]),
nodes,
metadata: Default::default(),
};
let host_flow = HostFlow::from(flow);
let engine = FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "dw.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: Some(handler),
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "dw.flow",
node_id: None,
tool: None,
action: None,
session_id: Some("sess-1"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
.unwrap();
assert!(matches!(result.status, FlowStatus::Completed));
let output_str = serde_json::to_string(&result.output).unwrap();
assert!(
output_str.contains("pong"),
"expected agent reply in flow output, got: {output_str}"
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn dw_agent_graph_node_routes_to_handler_and_returns_reply() {
use std::sync::Mutex;
use crate::runner::graph_node::GraphNodeHandler;
struct RecordingGraphHandler {
seen: Mutex<Option<(String, String, String, String)>>,
}
#[async_trait::async_trait]
impl GraphNodeHandler for RecordingGraphHandler {
async fn execute(
&self,
tenant_id: &str,
env_id: &str,
graph_id: &str,
session_id: &str,
_flow_input: &Value,
) -> Result<Value> {
*self.seen.lock().unwrap() = Some((
tenant_id.to_string(),
env_id.to_string(),
graph_id.to_string(),
session_id.to_string(),
));
Ok(json!({
"reply": "graph-pong",
"trail": [],
"terminated_by": "respond",
}))
}
}
let handler = Arc::new(RecordingGraphHandler {
seen: Mutex::new(None),
});
let handler_dyn: Arc<dyn GraphNodeHandler> = handler.clone();
let node_id = NodeId::from_str("graph").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "dw.agent_graph".parse().unwrap(),
pack_alias: None,
operation: Some("triage".to_string()),
},
input: InputMapping {
mapping: json!({ "user_text": "ping" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(node_id.clone(), node);
let flow = Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("dwg.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(node_id.to_string()),
)]),
nodes,
metadata: Default::default(),
};
let host_flow = HostFlow::from(flow);
let engine = FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "dwg.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: Some(handler_dyn),
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "dwg.flow",
node_id: None,
tool: None,
action: None,
session_id: Some("sess-1"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
.unwrap();
assert!(matches!(result.status, FlowStatus::Completed));
let seen = handler.seen.lock().unwrap().clone();
assert_eq!(
seen,
Some((
"demo".to_string(),
"local".to_string(),
"triage".to_string(),
"sess-1".to_string(),
)),
"dw.agent_graph dispatch must mirror dw.agent's tenant/env/graph_id/session derivation"
);
let output_str = serde_json::to_string(&result.output).unwrap();
assert!(
output_str.contains("graph-pong"),
"expected graph reply in flow output, got: {output_str}"
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn dw_agent_nats_mode_dispatches_remote() {
use std::sync::Mutex;
use crate::runner::agent_node::DwAgentDispatch;
use crate::runner::remote_dispatch::{
RemoteDispatch, RemoteDispatchAction, RemoteDispatchHandler,
};
struct RecordingDispatcher {
seen: Mutex<Option<RemoteDispatch>>,
}
#[async_trait::async_trait]
impl RemoteDispatchHandler for RecordingDispatcher {
async fn dispatch(
&self,
request: RemoteDispatch,
) -> anyhow::Result<RemoteDispatchAction> {
let corr = request.correlation_id.clone();
*self.seen.lock().unwrap() = Some(request);
Ok(RemoteDispatchAction::AwaitingResponse {
correlation_id: corr,
})
}
}
let dispatcher = Arc::new(RecordingDispatcher {
seen: Mutex::new(None),
});
let resume_id = NodeId::from_str("after-agent").unwrap();
let node_id = NodeId::from_str("agent-nats").unwrap();
let agent_node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "dw.agent".parse().unwrap(),
pack_alias: None,
operation: Some("greeter".to_string()),
},
input: InputMapping {
mapping: json!({ "user_text": "hi" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::Next {
node_id: resume_id.clone(),
},
telemetry: TelemetryHints::default(),
conversational: false,
};
let resume_node = Node {
id: resume_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "message": "done" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(node_id.clone(), agent_node);
nodes.insert(resume_id.clone(), resume_node);
let flow = Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("nats-agent.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(node_id.to_string()),
)]),
nodes,
metadata: Default::default(),
};
let host_flow = HostFlow::from(flow);
let engine = FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "nats-agent.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: Some(dispatcher.clone() as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>),
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: DwAgentDispatch::Nats,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "nats-agent.flow",
node_id: None,
tool: None,
action: None,
session_id: Some("sess-nats"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(ctx, json!({ "user_text": "hi" })))
.unwrap();
assert!(
matches!(result.status, FlowStatus::Waiting(_)),
"expected Waiting outcome from dw.agent Nats mode, got: {:?}",
result.status
);
let seen = dispatcher.seen.lock().unwrap();
let dispatch = seen.as_ref().expect("dispatcher was not called");
assert_eq!(
dispatch.runtime, "agentic",
"runtime name must be 'agentic'"
);
assert_eq!(dispatch.target, "greeter", "target must be the agent_id");
assert_eq!(
dispatch.input,
json!({ "user_text": "hi" }),
"node payload must be forwarded as dispatch input"
);
}
fn host_flow_for_test(
flow_id: &str,
node_ids: &[&str],
default_start: Option<&str>,
) -> HostFlow {
let mut nodes = indexmap::IndexMap::default();
for node_id in node_ids {
let id = NodeId::from_str(node_id).unwrap();
let node = Node {
id: id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "message": node_id }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
nodes.insert(id, node);
}
let mut entrypoints = BTreeMap::new();
if let Some(start) = default_start {
entrypoints.insert("default".to_string(), Value::String(start.to_string()));
}
HostFlow::from(Flow {
schema_version: "1.0".into(),
id: FlowId::from_str(flow_id).unwrap(),
kind: FlowKind::Messaging,
entrypoints,
nodes,
metadata: Default::default(),
})
}
fn jump_test_engine() -> FlowEngine {
let target_flow = host_flow_for_test("flow.target", &["node-a", "node-b"], None);
FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "flow.target".to_string(),
},
target_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
}
}
fn jump_ctx<'a>(flow_id: &'a str) -> FlowContext<'a> {
FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id,
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
}
}
#[test]
fn component_exec_ctx_presents_the_verified_caller() {
let block = json!({
"user_verified": true,
"sub": "u-1@acme",
"team": "sales",
"groups": ["employee"]
});
let mut ctx = jump_ctx("caller.flow");
ctx.provider_id = Some("messaging-webchat");
ctx.caller = Some(&block);
let exec = component_exec_ctx(&ctx, "lookup");
let caller = component_caller(&ctx);
let v05 = crate::component_api::exec_ctx_v0_5_as(&exec, caller.as_ref());
assert_eq!(v05.tenant.user_id.as_deref(), Some("u-1@acme"));
assert_eq!(v05.tenant.team_id.as_deref(), Some("sales"));
let v06 =
crate::component_api::envelope_v0_6_as(&exec, caller.as_ref(), "c", "{}").unwrap();
assert_eq!(v06.ctx.user_id.as_deref(), Some("u-1@acme"));
assert_eq!(v06.ctx.team_id.as_deref(), Some("sales"));
assert_eq!(exec.tenant.user.as_deref(), Some("messaging-webchat"));
assert_eq!(exec.tenant.team, None);
}
#[test]
fn component_exec_ctx_without_a_verified_caller_presents_no_user() {
let unverified = json!({ "user_verified": false, "sub": "u-1", "team": "sales" });
for provider in ["messaging-webchat", "greentic-run-demo"] {
for caller in [None, Some(&unverified)] {
let mut ctx = jump_ctx("caller.flow");
ctx.provider_id = Some(provider);
ctx.caller = caller;
let exec = component_exec_ctx(&ctx, "lookup");
let caller = component_caller(&ctx);
assert!(caller.is_none());
let v05 = crate::component_api::exec_ctx_v0_5_for(
&exec,
caller.as_ref(),
ctx.provider_id,
);
assert_eq!(v05.tenant.user_id, None);
assert_eq!(v05.tenant.user, None);
assert_eq!(v05.tenant.provider_id.as_deref(), Some(provider));
assert_eq!(v05.tenant.team_id, None);
assert!(v05.tenant.attributes.is_empty());
let v04 = crate::component_api::exec_ctx_v0_4_for(
&exec,
caller.as_ref(),
ctx.provider_id,
);
assert_eq!(v04.tenant.user, None);
let v06 = crate::component_api::envelope_v0_6_for(
&exec,
caller.as_ref(),
ctx.provider_id,
"c",
"{}",
)
.unwrap();
assert_eq!(v06.ctx.user_id, None);
assert_eq!(exec.tenant.user.as_deref(), Some(provider));
assert_eq!(exec.tenant.team, None);
}
}
}
#[test]
fn component_exec_ctx_with_a_verified_caller_also_names_the_provider() {
let block = json!({ "user_verified": true, "sub": "u-1@acme" });
let mut ctx = jump_ctx("caller.flow");
ctx.provider_id = Some("messaging-webchat");
ctx.caller = Some(&block);
let exec = component_exec_ctx(&ctx, "lookup");
let caller = component_caller(&ctx);
let v05 = crate::component_api::exec_ctx_v0_5_for(&exec, caller.as_ref(), ctx.provider_id);
assert_eq!(v05.tenant.user_id.as_deref(), Some("u-1@acme"));
assert_eq!(v05.tenant.provider_id.as_deref(), Some("messaging-webchat"));
assert_eq!(exec.tenant.user.as_deref(), Some("messaging-webchat"));
}
#[test]
fn with_rollout_ids_binds_revision_identity() {
let engine = minimal_engine().with_rollout_ids(RolloutIds {
customer_id: Some("cust-acme".into()),
deployment_id: Some("01JTKS".into()),
bundle_id: Some("customer.support".into()),
revision_id: Some("01JTKR".into()),
});
assert_eq!(engine.rollout_ids.revision_id.as_deref(), Some("01JTKR"));
assert_eq!(engine.rollout_ids.deployment_id.as_deref(), Some("01JTKS"));
assert!(minimal_engine().rollout_ids.is_empty());
}
#[cfg(feature = "agentic-worker")]
#[test]
fn mcp_credential_unit_is_the_revisions_bundle_id() {
let engine = minimal_engine().with_rollout_ids(RolloutIds {
customer_id: None,
deployment_id: Some("01JTKS".into()),
bundle_id: Some("customer.support".into()),
revision_id: Some("01JTKR".into()),
});
assert_eq!(engine.mcp_credential_unit(), Some("customer.support"));
assert_eq!(minimal_engine().mcp_credential_unit(), None);
}
#[test]
fn a_flow_goto_node_produces_a_jump_the_engine_applies() {
let outcome = execute_flow_goto(json!({
"flow_id": "flow.target",
"input": { "order": "A-1" },
}))
.expect("goto builds");
let NodeControl::Jump(jump) = outcome.control else {
panic!("expected a Jump");
};
let engine = jump_test_engine();
let mut state = ExecutionState::new(Value::Null);
let rt = Runtime::new().unwrap();
let target = rt
.block_on(engine.apply_jump(&jump_ctx("flow.source"), &mut state, jump))
.expect("the engine must accept the jump a flow.goto node builds");
assert_eq!(target.flow_id, "flow.target");
assert_eq!(
target.node_id.as_str(),
"node-a",
"no explicit node means the target flow's first node"
);
assert_eq!(
state.redirect_count(),
1,
"the loop guard must have counted"
);
}
#[test]
fn a_flow_goto_node_can_name_the_entry_node() {
let outcome = execute_flow_goto(json!({ "flow_id": "flow.target", "node": "node-b" }))
.expect("goto builds");
let NodeControl::Jump(jump) = outcome.control else {
panic!("expected a Jump");
};
let engine = jump_test_engine();
let mut state = ExecutionState::new(Value::Null);
let rt = Runtime::new().unwrap();
let target = rt
.block_on(engine.apply_jump(&jump_ctx("flow.source"), &mut state, jump))
.expect("jump applies");
assert_eq!(target.node_id.as_str(), "node-b");
}
#[test]
fn apply_jump_unknown_flow_errors() {
let engine = minimal_engine();
let mut state = ExecutionState::new(Value::Null);
let rt = Runtime::new().unwrap();
let err = rt
.block_on(engine.apply_jump(
&jump_ctx("flow.source"),
&mut state,
JumpControl {
flow: "flow.missing".into(),
node: None,
payload: json!({ "ok": true }),
hints: Value::Null,
max_redirects: None,
reason: None,
},
))
.unwrap_err();
assert!(
err.to_string().contains("unknown_flow"),
"unexpected error: {err}"
);
}
#[test]
fn apply_jump_unknown_node_errors() {
let engine = jump_test_engine();
let mut state = ExecutionState::new(Value::Null);
let rt = Runtime::new().unwrap();
let err = rt
.block_on(engine.apply_jump(
&jump_ctx("flow.source"),
&mut state,
JumpControl {
flow: "flow.target".into(),
node: Some("node-missing".into()),
payload: json!({ "ok": true }),
hints: Value::Null,
max_redirects: None,
reason: None,
},
))
.unwrap_err();
assert!(
err.to_string().contains("unknown_node"),
"unexpected error: {err}"
);
}
#[test]
fn apply_jump_uses_default_start_fallback() {
let engine = jump_test_engine();
let mut state = ExecutionState::new(Value::Null);
let rt = Runtime::new().unwrap();
let target = rt
.block_on(engine.apply_jump(
&jump_ctx("flow.source"),
&mut state,
JumpControl {
flow: "flow.target".into(),
node: None,
payload: json!({ "k": "v" }),
hints: Value::Null,
max_redirects: None,
reason: None,
},
))
.expect("jump target");
assert_eq!(target.flow_id, "flow.target");
assert_eq!(target.node_id.as_str(), "node-a");
}
#[test]
fn apply_jump_redirect_limit_enforced() {
let engine = jump_test_engine();
let mut state = ExecutionState::new(Value::Null);
state.redirect_count = 3;
let rt = Runtime::new().unwrap();
let err = rt
.block_on(engine.apply_jump(
&jump_ctx("flow.source"),
&mut state,
JumpControl {
flow: "flow.target".into(),
node: None,
payload: json!({ "k": "v" }),
hints: Value::Null,
max_redirects: Some(3),
reason: None,
},
))
.unwrap_err();
assert_eq!(err.to_string(), "redirect_limit");
}
#[test]
fn park_turns_bump_and_reset() {
let mut state = ExecutionState::new(Value::Null);
assert_eq!(state.bump_park_turns("a"), 1);
assert_eq!(state.bump_park_turns("a"), 2);
assert_eq!(state.bump_park_turns("b"), 1);
assert_eq!(state.bump_park_turns("a"), 3);
state.reset_park_turns("a");
assert_eq!(
state.bump_park_turns("a"),
1,
"reset must restart from zero"
);
assert_eq!(
state.bump_park_turns("b"),
2,
"resetting `a` must not disturb `b`'s counter"
);
}
#[test]
fn park_turns_survives_snapshot_roundtrip() {
let mut state = ExecutionState::new(json!({}));
state.bump_park_turns("agent-1");
state.bump_park_turns("agent-1");
let encoded = serde_json::to_string(&state).expect("serialize");
let decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded.park_turns.get("agent-1"), Some(&2));
let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
let decoded_legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
assert!(decoded_legacy.park_turns.is_empty());
}
#[test]
fn pending_agent_await_mark_and_take() {
let mut st = ExecutionState::new(serde_json::json!({}));
assert!(!st.take_agent_await("agent"), "unmarked node takes false");
st.mark_agent_await("agent");
assert!(st.take_agent_await("agent"), "marked node takes true");
assert!(!st.take_agent_await("agent"), "take clears the marker");
st.mark_agent_await("a");
st.mark_agent_await("b");
assert!(st.take_agent_await("a"));
assert!(st.take_agent_await("b"));
}
#[test]
fn pending_agent_await_survives_snapshot_roundtrip() {
let mut st = ExecutionState::new(serde_json::json!({}));
st.mark_agent_await("agent");
let json = serde_json::to_string(&st).expect("serialize");
let back: ExecutionState = serde_json::from_str(&json).expect("deserialize");
let mut back = back;
assert!(
back.take_agent_await("agent"),
"marker survives serde round-trip"
);
let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0,"vars":{},"park_turns":{}}"#;
let mut legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy decode");
assert!(!legacy.take_agent_await("agent"), "absent key → empty");
}
#[test]
fn approval_await_mark_and_take() {
let mut st = ExecutionState::new(json!({}));
assert!(
st.take_approval_await("gate").is_none(),
"unmarked node takes None"
);
st.mark_approval_await("gate", parked("corr::n=abc", Some("fp")));
assert_eq!(
st.take_approval_await("gate"),
Some(parked("corr::n=abc", Some("fp"))),
"marked node takes its recorded correlation and fingerprint"
);
assert!(
st.take_approval_await("gate").is_none(),
"take clears the mark"
);
}
#[test]
fn approval_await_survives_snapshot_roundtrip() {
let mut st = ExecutionState::new(json!({}));
st.mark_approval_await("gate", parked("corr::n=abc", Some("fp")));
let encoded = serde_json::to_string(&st).expect("serialize");
assert!(
!encoded.contains("decision_token"),
"only the fingerprint is persisted"
);
let mut decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(
decoded.pending_approvals(),
vec![parked("corr::n=abc", Some("fp"))]
);
assert_eq!(
decoded.take_approval_await("gate"),
Some(parked("corr::n=abc", Some("fp"))),
"the marker, correlation and fingerprint must survive a park/resume snapshot"
);
}
#[test]
fn approval_await_defaults_empty_for_old_snapshots() {
let mut decoded: ExecutionState =
serde_json::from_str(r#"{"entry":{},"input":{}}"#).expect("old snapshot decodes");
assert!(decoded.take_approval_await("gate").is_none());
}
#[test]
fn approval_await_decodes_the_pre_correlation_unit_marker() {
let mut decoded: ExecutionState = serde_json::from_str(
r#"{"entry":{},"input":{},"pending_approval_await":{"gate":null}}"#,
)
.expect("pre-correlation snapshot decodes");
assert_eq!(decoded.pending_approvals(), vec![ParkedApproval::default()]);
assert_eq!(
decoded.take_approval_await("gate"),
Some(ParkedApproval::default())
);
}
fn parked(correlation: &str, fingerprint: Option<&str>) -> ParkedApproval {
ParkedApproval {
correlation_id: Some(correlation.to_string()),
token_fingerprint: fingerprint.map(str::to_string),
}
}
#[test]
fn a_snapshot_parked_before_tokens_has_no_fingerprint_and_is_not_verified() {
let decoded: ExecutionState = serde_json::from_str(
r#"{"entry":{},"input":{},"pending_approval_await":{"gate":"corr::n=abc"}}"#,
)
.expect("pre-token snapshot decodes");
let parks = decoded.pending_approvals();
assert_eq!(parks, vec![parked("corr::n=abc", None)]);
assert!(response_authenticates(
&json!({"ok": true, "output": {"decision": "approved"}}),
&parks[0]
));
}
#[test]
fn a_tokened_gate_resumes_only_on_its_own_token_and_only_once() {
let issued = approval_token::issue();
let mut st = ExecutionState::new(json!({}));
st.mark_approval_await("gate", parked("corr", Some(&issued.fingerprint)));
let right =
json!({"ok": true, "output": {"decision": "approved", "decision_token": issued.token}});
let wrong = json!({"ok": true, "output": {"decision": "approved", "decision_token": approval_token::issue().token}});
let missing = json!({"ok": true, "output": {"decision": "approved"}});
let park = st.take_approval_await("gate").expect("parked");
assert!(!response_authenticates(&missing, &park));
assert!(!response_authenticates(&wrong, &park));
assert!(response_authenticates(&right, &park));
assert!(st.take_approval_await("gate").is_none());
assert!(st.pending_approvals().is_empty());
}
#[test]
fn dispatch_outcome_await_here_stores_variant() {
let output = NodeOutput::new(json!({"ok": true}));
let outcome = DispatchOutcome::await_here(
output,
Some("awaiting agent response".to_string()),
"corr-123".to_string(),
);
match outcome.control {
NodeControl::AwaitHere {
reason,
correlation_id,
} => {
assert_eq!(reason.as_deref(), Some("awaiting agent response"));
assert_eq!(correlation_id, "corr-123");
}
other => panic!("expected NodeControl::AwaitHere, got {other:?}"),
}
}
fn on_message_routing() -> Value {
json!([
{ "condition": "response.action == \"go_a\"", "to": "page_a" },
{ "to": "fallback", "on_message": true },
{ "out": true }
])
}
fn empty_flow() -> HostFlow {
HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
}
}
fn route_with(resumed_at: Option<&str>, entry: Value) -> CustomRoutingDecision {
let mut state = ExecutionState::new(entry.clone());
state.entry = entry;
state.resumed_at = resumed_at.map(str::to_string);
evaluate_custom_routing(
&on_message_routing(),
&NodeOutput::new(Value::Null),
&state,
&empty_flow(),
&NodeId::from_str("menu").unwrap(),
)
}
#[test]
fn an_on_message_route_does_not_fire_when_the_card_was_just_rendered() {
let decision = route_with(None, json!({ "text": "hello" }));
assert!(
matches!(decision, CustomRoutingDecision::Wait),
"a freshly rendered card must park, got {decision:?}"
);
}
#[test]
fn an_on_message_route_is_taken_when_the_person_types_at_the_parked_card() {
let decision = route_with(Some("menu"), json!({ "text": "2+2 berapa?" }));
match decision {
CustomRoutingDecision::Next(n) => assert_eq!(n.as_str(), "fallback"),
other => panic!("expected fallback, got {other:?}"),
}
}
#[test]
fn a_button_still_wins_over_the_on_message_route() {
let entry = json!({ "text": "", "metadata": { "action": "go_a" } });
match route_with(Some("menu"), entry) {
CustomRoutingDecision::Next(n) => assert_eq!(n.as_str(), "page_a"),
other => panic!("expected page_a, got {other:?}"),
}
}
#[test]
fn an_unknown_action_reparks_instead_of_taking_the_on_message_route() {
let entry = json!({ "text": "", "metadata": { "action": "stale_button" } });
let decision = route_with(Some("menu"), entry);
assert!(
matches!(decision, CustomRoutingDecision::Wait),
"a click that matches nothing is not a typed message, got {decision:?}"
);
}
#[test]
fn a_resume_at_another_node_does_not_take_the_route() {
let decision = route_with(Some("some_other_card"), json!({ "text": "hi" }));
assert!(matches!(decision, CustomRoutingDecision::Wait));
}
#[test]
fn only_a_card_awaiting_its_submit_counts_as_a_resumed_card() {
let mut snapshot = FlowSnapshot {
pack_id: "p".into(),
flow_id: "f".into(),
next_flow: None,
next_node: "menu".into(),
awaiting_submit: true,
state: ExecutionState::new(Value::Null),
};
assert_eq!(resumed_card_node(&snapshot).as_deref(), Some("menu"));
snapshot.awaiting_submit = false;
assert_eq!(resumed_card_node(&snapshot), None);
}
#[test]
fn evaluate_custom_routing_waits_when_conditional_falls_through() {
let raw_routing = json!([
{ "condition": "response.action == \"go\"", "to": "next" },
{ "out": true }
]);
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current_node = NodeId::from_str("current").unwrap();
let output = NodeOutput::new(Value::Null);
let mut state_empty = ExecutionState::new(json!({ "metadata": { "action": "" } }));
state_empty.entry = json!({ "metadata": { "action": "" } });
let decision_empty =
evaluate_custom_routing(&raw_routing, &output, &state_empty, &flow_ir, ¤t_node);
assert!(
matches!(decision_empty, CustomRoutingDecision::Wait),
"expected Wait on conditional fall-through, got {decision_empty:?}"
);
let mut state_go = ExecutionState::new(json!({ "metadata": { "action": "go" } }));
state_go.entry = json!({ "metadata": { "action": "go" } });
let decision_go =
evaluate_custom_routing(&raw_routing, &output, &state_go, &flow_ir, ¤t_node);
match decision_go {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
other => panic!("expected Next(\"next\"), got {other:?}"),
}
}
#[test]
fn node_output_with_error_marks_ok_false_and_stashes_in_meta() {
let err: Box<dyn std::error::Error + 'static> =
Box::<dyn std::error::Error + 'static>::from("weatherapi returned 401 Unauthorized");
let out = NodeOutput::with_error("call_weather", err.as_ref());
assert!(!out.ok);
assert_eq!(out.payload, Value::Null);
assert_eq!(out.meta["error"]["kind"], "flow_node_failed");
assert_eq!(out.meta["error"]["node_id"], "call_weather");
assert_eq!(
out.meta["error"]["message"],
"weatherapi returned 401 Unauthorized"
);
}
#[test]
fn lift_first_node_error_promotes_node_meta_to_output_metadata() {
let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
let err: Box<dyn std::error::Error + 'static> =
Box::<dyn std::error::Error + 'static>::from("weatherapi returned 401 Unauthorized");
nodes.insert(
"call_weather".to_string(),
NodeOutput::with_error("call_weather", err.as_ref()),
);
nodes.insert(
"render_current_card".to_string(),
NodeOutput::new(json!({ "text": "message" })),
);
let final_output = json!({ "text": "message" });
let enriched = lift_first_node_error_from_nodes(final_output, &nodes);
assert_eq!(
enriched["metadata"]["error_kind"], "flow_node_failed",
"first failing node's kind must be lifted"
);
assert_eq!(
enriched["metadata"]["error_message"],
"weatherapi returned 401 Unauthorized"
);
assert_eq!(enriched["metadata"]["node_id"], "call_weather");
assert_eq!(enriched["text"], "message");
}
#[test]
fn lift_first_node_error_is_noop_when_all_nodes_ok() {
let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
nodes.insert(
"ok_node".to_string(),
NodeOutput::new(json!({ "text": "all good" })),
);
let output = json!({ "text": "all good" });
let lifted = lift_first_node_error_from_nodes(output.clone(), &nodes);
assert_eq!(lifted, output);
}
fn broken_flow_engine(pack_id_str: &str, flow_id_str: &str) -> FlowEngine {
let host_flow = host_flow_for_test(flow_id_str, &["only-node"], Some("does-not-exist"));
FlowEngine {
operala_node_handler: None,
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: pack_id_str.to_string(),
flow_id: flow_id_str.to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
}
}
fn terminal_failure_ctx<'a>(pack_id_str: &'a str, flow_id_str: &'a str) -> FlowContext<'a> {
FlowContext {
tenant: "demo",
pack_id: pack_id_str,
flow_id: flow_id_str,
node_id: None,
tool: None,
action: None,
session_id: Some("conv-1"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
}
}
#[tokio::test]
async fn a_terminal_failure_keeps_the_outputs_of_the_nodes_that_ran() {
let (pack_id_str, flow_id_str) = ("test-pack", "partial.flow");
let node = |id: &str, component: &str, routing: Routing| {
let id = NodeId::from_str(id).unwrap();
(
id.clone(),
Node {
id,
component: FlowComponentRef {
id: component.parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "message": "hello" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing,
telemetry: TelemetryHints::default(),
conversational: false,
},
)
};
let mut nodes = indexmap::IndexMap::default();
let (first_id, first) = node(
"first",
"emit.log",
Routing::Next {
node_id: NodeId::from_str("second").unwrap(),
},
);
nodes.insert(first_id, first);
let (second_id, second) = node("second", "no.such.component", Routing::End);
nodes.insert(second_id, second);
let flow = HostFlow::from(Flow {
schema_version: "1.0".into(),
id: FlowId::from_str(flow_id_str).unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([("default".to_string(), Value::String("first".into()))]),
nodes,
metadata: Default::default(),
});
let engine = broken_flow_engine(pack_id_str, flow_id_str);
engine.flow_cache.write().insert(
FlowKey {
pack_id: pack_id_str.to_string(),
flow_id: flow_id_str.to_string(),
},
flow,
);
let ctx = terminal_failure_ctx(pack_id_str, flow_id_str);
let result = engine
.execute(ctx, Value::Null)
.await
.expect("a session flow surfaces the failure as an envelope");
assert_eq!(
result.output["metadata"]["error_kind"],
"flow_execution_failed"
);
assert!(
result.node_outputs.contains_key("first"),
"the node that ran before the failure must keep its output, got {:?}",
result.node_outputs
);
}
#[tokio::test]
async fn execute_user_facing_flow_failure_returns_completed_with_error_envelope() {
let flow_id_str = "broken.flow";
let pack_id_str = "test-pack";
let engine = broken_flow_engine(pack_id_str, flow_id_str);
let ctx = terminal_failure_ctx(pack_id_str, flow_id_str);
let result = engine
.execute(ctx, Value::Null)
.await
.expect("must not propagate Err");
assert!(matches!(result.status, FlowStatus::Completed));
assert_eq!(
result.output["metadata"]["error_kind"],
"flow_execution_failed"
);
let msg = result.output["metadata"]["error_message"]
.as_str()
.unwrap_or("");
assert!(!msg.is_empty(), "error_message must be populated");
assert_eq!(result.output["metadata"]["flow_id"], "broken.flow");
assert_eq!(
result.output["text"],
user_facing_flow_failure_text(&Value::Null),
"a terminal session-flow failure must carry the resolved user-facing message"
);
let shown = result.output["text"].as_str().unwrap_or_default();
assert!(
!shown.trim().is_empty(),
"an empty `text` is silent on every channel"
);
assert!(
!shown.contains("does-not-exist"),
"raw engine text must stay in metadata.error_message"
);
}
#[tokio::test]
async fn execute_user_facing_flow_failure_answers_in_the_conversation_locale() {
let flow_id_str = "broken.flow";
let pack_id_str = "test-pack";
let engine = broken_flow_engine(pack_id_str, flow_id_str);
let result = engine
.execute(
terminal_failure_ctx(pack_id_str, flow_id_str),
json!({ "metadata": { "locale": "id-ID" } }),
)
.await
.expect("must not propagate Err");
let shown = result.output["text"].as_str().unwrap_or_default();
assert_eq!(
shown,
user_facing_flow_failure_text_for("id"),
"an Indonesian conversation must be answered in Indonesian"
);
assert_ne!(
shown,
crate::runner::i18n::FLOW_EXECUTION_FAILED_EN,
"the conversation locale was ignored"
);
let nested = engine
.execute(
terminal_failure_ctx(pack_id_str, flow_id_str),
json!({ "input": { "metadata": { "locale": "ja" } } }),
)
.await
.expect("must not propagate Err");
let nested_text = nested.output["text"].as_str().unwrap_or_default();
assert_eq!(nested_text, user_facing_flow_failure_text_for("ja"));
assert!(!nested_text.trim().is_empty());
assert!(
!nested_text.contains("does-not-exist"),
"raw engine text must stay in metadata.error_message in every locale"
);
let unknown = engine
.execute(
terminal_failure_ctx(pack_id_str, flow_id_str),
json!({ "metadata": { "locale": "kl-GL" } }),
)
.await
.expect("must not propagate Err");
assert_eq!(
unknown.output["text"],
crate::runner::i18n::FLOW_EXECUTION_FAILED_EN
);
}
#[test]
fn activity_locale_reads_both_shapes_and_treats_blank_as_absent() {
assert_eq!(
activity_locale(&json!({ "metadata": { "locale": "nl-NL" } })),
Some("nl-NL")
);
assert_eq!(
activity_locale(&json!({ "input": { "metadata": { "locale": "en-GB" } } })),
Some("en-GB")
);
assert_eq!(
activity_locale(&json!({
"input": { "metadata": { "locale": "ja" } },
"metadata": { "locale": "id" },
})),
Some("ja")
);
assert_eq!(
activity_locale(&json!({ "metadata": { "locale": " " } })),
None
);
assert_eq!(
activity_locale(&json!({ "metadata": { "locale": "" } })),
None
);
assert_eq!(
activity_locale(&json!({ "metadata": { "locale": 7 } })),
None
);
assert_eq!(activity_locale(&Value::Null), None);
assert_eq!(activity_locale(&json!({})), None);
}
#[test]
fn user_facing_flow_failure_text_is_localized_and_never_empty() {
let english = user_facing_flow_failure_text_for("en");
assert_eq!(english, crate::runner::i18n::FLOW_EXECUTION_FAILED_EN);
for locale in ["id", "es", "ja", "zh"] {
let translated = user_facing_flow_failure_text_for(locale);
assert_ne!(
translated, english,
"`{locale}` must resolve to its own wording, not English"
);
}
assert_eq!(user_facing_flow_failure_text_for("id-ID"), {
user_facing_flow_failure_text_for("id")
});
assert_eq!(user_facing_flow_failure_text_for("zh_TW"), {
user_facing_flow_failure_text_for("zh")
});
for locale in ["", "xx", "klingon", "C", "C.UTF-8", "POSIX"] {
assert_eq!(
user_facing_flow_failure_text_for(locale),
english,
"`{locale}` must fall back to English"
);
}
for locale in ["en", "id", "es", "ja", "zh", "", "xx", "C.UTF-8"] {
let text = user_facing_flow_failure_text_for(locale);
assert!(
!text.trim().is_empty(),
"`{locale}` resolved to empty text, which is silent on every channel"
);
}
}
#[test]
fn mcp_tool_error_recognises_generator_error_shape() {
let value = json!({
"error": {
"code": "tool_error",
"message": "API request returned status 401",
"status": 401
}
});
let (code, message) = mcp_tool_error(&value).expect("must detect MCP error shape");
assert_eq!(code, "tool_error");
assert!(message.contains("API request returned status 401"));
assert!(message.contains("(status 401)"));
}
#[test]
fn mcp_tool_error_skips_success_responses() {
let value = json!({ "result": { "current": { "temp_c": 19.0 } } });
assert!(mcp_tool_error(&value).is_none());
}
#[test]
fn mcp_tool_error_skips_non_object_and_unrelated_shapes() {
assert!(mcp_tool_error(&Value::Null).is_none());
assert!(mcp_tool_error(&json!({"unrelated": true})).is_none());
assert!(mcp_tool_error(&json!({"error": "oops"})).is_none());
}
#[test]
fn normalize_mcp_tool_error_matches_component_error_shape() {
let value = json!({
"error": { "code": "tool_error", "message": "boom", "status": 502 }
});
let normalized = normalize_mcp_tool_error(&value, "tool_error", "boom (status 502)");
assert_eq!(
component_error(&normalized),
Some(("tool_error".to_string(), "boom (status 502)".to_string())),
"the normalized payload must be recognised by component_error verbatim"
);
assert_eq!(normalized["error"]["status"], json!(502));
}
#[test]
fn mcp_node_output_reports_failure_when_the_node_has_an_error_route() {
let result = json!({ "error": "MCP is not configured on this runner" });
let bound = result.clone();
let out = mcp_node_output(bound, &result, true);
assert!(
!out.ok,
"a failed MCP call with an error route must not report ok"
);
assert_eq!(
component_error(&out.payload),
Some((
"mcp_call_failed".to_string(),
"MCP is not configured on this runner".to_string()
)),
"the payload must be recognised by component_error verbatim, got {:?}",
out.payload
);
assert_eq!(
out.meta.pointer("/error/message").and_then(Value::as_str),
Some("MCP is not configured on this runner"),
"the message must reach meta.error where lift_first_node_error_from_nodes reads it"
);
let view = node_output_view(&out.payload);
let errors = view["errors"].as_array().expect("errors must be an array");
assert_eq!(errors.len(), 1, "errors must be populated, got {view:?}");
assert_eq!(
errors[0]["message"], "MCP is not configured on this runner",
"{{{{node.<id>.errors[0].message}}}} must surface the real message"
);
}
#[test]
fn mcp_node_output_uses_mcp_tool_error_for_the_object_shaped_error() {
let result = json!({
"error": {
"code": "tool_error",
"message": "API request returned status 401",
"status": 401
}
});
let bound = result.clone();
let (expected_code, expected_message) =
mcp_tool_error(&result).expect("the detector must recognise this shape");
let out = mcp_node_output(bound, &result, true);
assert!(
!out.ok,
"an object-shaped MCP tool error with an error route must not report ok"
);
assert_eq!(
component_error(&out.payload),
Some((expected_code.clone(), expected_message.clone())),
"the code/message must be exactly what mcp_tool_error derives, got {:?}",
out.payload
);
assert_eq!(expected_code, "tool_error");
assert!(expected_message.contains("API request returned status 401"));
assert!(expected_message.contains("(status 401)"));
let view = node_output_view(&out.payload);
let errors = view["errors"].as_array().expect("errors must be an array");
assert_eq!(errors.len(), 1, "errors must be populated, got {view:?}");
assert_eq!(errors[0]["message"], expected_message);
}
#[test]
fn mcp_node_output_preserves_the_output_binding_key_alongside_the_error_envelope() {
let result = json!({ "error": "connection refused" });
let bound = json!({ "quote_result_data": result.clone() });
let out = mcp_node_output(bound.clone(), &result, true);
assert!(!out.ok);
assert_eq!(
out.payload["quote_result_data"], result,
"the output-key binding must survive untouched, got {:?}",
out.payload
);
assert_eq!(out.payload["ok"], json!(false));
assert_eq!(out.payload["error"]["code"], "mcp_call_failed");
assert_eq!(out.payload["error"]["message"], "connection refused");
let view = node_output_view(&out.payload);
assert_eq!(
view["quote_result_data"], result,
"{{{{node.<id>.quote_result_data}}}} must still resolve, got {view:?}"
);
let errors = view["errors"].as_array().expect("errors must be an array");
assert_eq!(errors[0]["message"], "connection refused");
}
#[test]
fn mcp_node_output_ignores_failure_when_the_node_has_no_error_route() {
let result = json!({ "error": "MCP is not configured on this runner" });
let bound = json!({ "quote_result_data": result.clone() });
let out = mcp_node_output(bound.clone(), &result, false);
assert!(
out.ok,
"a node with no error route must keep reporting ok, unchanged from pre-R3"
);
assert_eq!(
out.payload, bound,
"the payload must be exactly the bound value, no envelope reshaping"
);
assert_eq!(out.meta, Value::Null);
}
#[test]
fn mcp_node_output_stays_ok_on_success_regardless_of_error_route() {
let result = json!({ "annual_premium": 1234 });
let bound = json!({ "quote_result_data": result.clone() });
for has_error_route in [true, false] {
let out = mcp_node_output(bound.clone(), &result, has_error_route);
assert!(out.ok, "a successful MCP call must report ok");
assert_eq!(out.payload, bound);
assert_eq!(out.meta, Value::Null);
}
}
#[test]
fn mcp_failure_with_on_error_route_routes_to_the_error_branch() {
let raw_routing = json!([
{ "condition": "event == \"on_success\"", "to": "ok_node" },
{ "condition": "event == \"on_error\"", "to": "err_node" }
]);
let routing = Routing::Custom(raw_routing.clone());
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current = NodeId::from_str("current").unwrap();
let state = ExecutionState::new(json!({}));
let result = json!({ "error": "MCP is not configured on this runner" });
let has_error_route = node_has_error_route(&routing);
assert!(has_error_route);
let out = mcp_node_output(result.clone(), &result, has_error_route);
match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err_node"),
other => panic!("expected the on_error route, got {other:?}"),
}
}
#[test]
fn mcp_failure_with_success_only_routing_never_parks() {
let raw_routing = json!([
{ "condition": "event == \"on_success\"", "to": "ok_node" }
]);
let routing = Routing::Custom(raw_routing.clone());
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current = NodeId::from_str("current").unwrap();
let state = ExecutionState::new(json!({}));
let result = json!({ "error": "MCP is not configured on this runner" });
let has_error_route = node_has_error_route(&routing);
assert!(
!has_error_route,
"a success-only Custom routing has no error branch"
);
let out = mcp_node_output(result.clone(), &result, has_error_route);
assert!(out.ok, "no error route means the failure is not surfaced");
match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(
nid.as_str(),
"ok_node",
"the flow must continue on the success path, not park"
),
other => panic!(
"a node with no error route must never park on an MCP failure, got {other:?}"
),
}
}
#[tokio::test]
async fn execute_non_user_facing_flow_failure_still_propagates() {
let flow_id_str = "broken.flow";
let pack_id_str = "test-pack";
let host_flow = host_flow_for_test(flow_id_str, &["only-node"], Some("does-not-exist"));
let engine = FlowEngine {
operala_node_handler: None,
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: pack_id_str.to_string(),
flow_id: flow_id_str.to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
};
let ctx = FlowContext {
tenant: "demo",
pack_id: pack_id_str,
flow_id: flow_id_str,
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let result = engine.execute(ctx, Value::Null).await;
assert!(result.is_err(), "non-user-facing flow must propagate Err");
}
#[test]
fn host_flow_extracts_slot_schema_from_metadata_extra() {
use greentic_types::FlowMetadata;
use std::collections::BTreeSet;
let schema = json!([
{"name": "counterparty", "slot_type": "string", "required": true},
{"name": "due_date", "slot_type": "date", "required": true}
]);
let flow = Flow {
schema_version: "flow-v1".into(),
id: FlowId::from_str("test.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::new(),
nodes: IndexMap::default(),
metadata: FlowMetadata {
title: None,
description: None,
tags: BTreeSet::new(),
extra: json!({(SLOT_SCHEMA_METADATA_KEY): schema}),
},
};
let host = HostFlow::from(flow);
assert_eq!(
host.slot_schema.as_ref(),
Some(&schema),
"HostFlow must extract slot_schema from metadata.extra"
);
}
#[test]
fn host_flow_slot_schema_is_none_when_absent() {
let flow = Flow {
schema_version: "flow-v1".into(),
id: FlowId::from_str("test.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::new(),
nodes: IndexMap::default(),
metadata: Default::default(),
};
let host = HostFlow::from(flow);
assert!(
host.slot_schema.is_none(),
"HostFlow.slot_schema must be None when metadata.extra has no greentic.slot_schema"
);
}
#[test]
fn inject_slot_definitions_adds_to_object_input() {
let schema = json!([
{"name": "city", "slot_type": "string"}
]);
let mut input = json!({"utterance": "hello"});
inject_slot_definitions(&mut input, &schema, "f", "n");
assert_eq!(
input,
json!({"utterance": "hello", "slot_definitions": schema}),
"slot_definitions must be injected into existing object"
);
}
#[test]
fn inject_slot_definitions_wraps_null_input() {
let schema = json!([{"name": "x", "slot_type": "string"}]);
let mut input = Value::Null;
inject_slot_definitions(&mut input, &schema, "f", "n");
assert_eq!(
input,
json!({"slot_definitions": schema}),
"null input must become an object with slot_definitions"
);
}
#[test]
fn inject_slot_definitions_preserves_explicit_inline() {
let flow_schema = json!([{"name": "city", "slot_type": "string"}]);
let inline_defs = json!([{"name": "country", "slot_type": "string"}]);
let mut input = json!({
"utterance": "hello",
"slot_definitions": inline_defs
});
inject_slot_definitions(&mut input, &flow_schema, "f", "n");
assert_eq!(
input["slot_definitions"], inline_defs,
"explicit inline slot_definitions must not be overwritten"
);
}
#[test]
fn inject_slot_definitions_skips_non_object_input() {
let schema = json!([{"name": "x", "slot_type": "string"}]);
let mut input = json!("a string");
inject_slot_definitions(&mut input, &schema, "f", "n");
assert_eq!(
input,
json!("a string"),
"non-object input must be left unchanged"
);
}
fn make_flow_doc_for_test(
id: &str,
node_name: &str,
component: &str,
slot_schema: Option<Value>,
) -> greentic_flow::model::FlowDoc {
use greentic_flow::model::{FlowDoc, NodeDoc};
let mut nodes = IndexMap::new();
nodes.insert(
node_name.to_string(),
NodeDoc {
raw: {
let mut m = IndexMap::new();
m.insert(
"component.exec".to_string(),
json!({ "component": component }),
);
m
},
routing: json!([{ "out": true }]),
..Default::default()
},
);
FlowDoc {
id: id.into(),
title: None,
description: None,
flow_type: "messaging".into(),
start: Some(node_name.into()),
parameters: json!({}),
tags: Vec::new(),
schema_version: None,
entrypoints: IndexMap::new(),
meta: None,
slot_schema,
nodes,
}
}
#[test]
fn compile_flow_round_trips_slot_schema_into_host_flow() {
let slot_defs = json!([
{ "name": "counterparty", "slot_type": "string", "required": true,
"pattern": ".+" },
{ "name": "due_date", "slot_type": "date", "required": true,
"pattern": "\\d{4}-\\d{2}-\\d{2}" }
]);
let doc = make_flow_doc_for_test(
"slot-test",
"extractor",
"slot-extractor",
Some(slot_defs.clone()),
);
let flow = greentic_flow::compile_flow(doc).expect("compile_flow must succeed");
assert_eq!(
flow.metadata.extra.get(SLOT_SCHEMA_METADATA_KEY),
Some(&slot_defs),
"compile_flow must forward slot_schema into metadata.extra"
);
let host = HostFlow::from(flow);
assert_eq!(
host.slot_schema.as_ref(),
Some(&slot_defs),
"HostFlow.slot_schema must survive the compile_flow -> HostFlow round-trip"
);
}
#[test]
fn compile_flow_without_slot_schema_leaves_host_flow_none() {
let doc = make_flow_doc_for_test("no-slots", "echo", "echo", None);
let flow = greentic_flow::compile_flow(doc).expect("compile_flow must succeed");
assert!(
flow.metadata.extra.get(SLOT_SCHEMA_METADATA_KEY).is_none(),
"metadata.extra must not contain greentic.slot_schema when FlowDoc.slot_schema is None"
);
let host = HostFlow::from(flow);
assert!(
host.slot_schema.is_none(),
"HostFlow.slot_schema must be None when FlowDoc has no slot_schema"
);
}
#[test]
fn multi_edge_node_routes_on_injected_event() {
let raw_routing = json!([
{ "condition": "event == \"on_success\"", "to": "next" },
{ "condition": "event == \"on_error\"", "to": "err" }
]);
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current = NodeId::from_str("current").unwrap();
let state = ExecutionState::new(json!({}));
let ok_out = NodeOutput::new(json!({ "x": 1 }));
match evaluate_custom_routing(&raw_routing, &ok_out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
other => panic!("expected Next(\"next\"), got {other:?}"),
}
let routed = NodeOutput::with_meta(json!({}), json!({ "outcome": "on_error" }));
match evaluate_custom_routing(&raw_routing, &routed, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err"),
other => panic!("expected Next(\"err\"), got {other:?}"),
}
}
#[test]
fn approval_outcomes_route_three_ways() {
let raw_routing = json!([
{ "condition": "event == \"approved\"", "to": "do_it" },
{ "condition": "event == \"denied\"", "to": "reject" },
{ "condition": "event == \"timeout\"", "to": "escalate" }
]);
let flow_ir = HostFlow {
slot_schema: None,
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
};
let current = NodeId::from_str("gate").unwrap();
let state = ExecutionState::new(json!({}));
for (outcome, expected) in [
("approved", "do_it"),
("denied", "reject"),
("timeout", "escalate"),
] {
let out = NodeOutput::with_meta(json!({}), json!({ "outcome": outcome }));
match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(
nid.as_str(),
expected,
"outcome {outcome} must route to {expected}"
),
other => panic!("outcome {outcome}: expected Next({expected}), got {other:?}"),
}
}
}
#[test]
fn errored_output_routes_to_on_error_branch() {
let raw_routing = json!([
{ "condition": "event == \"on_success\"", "to": "ok_node" },
{ "condition": "event == \"on_error\"", "to": "err_node" }
]);
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current = NodeId::from_str("current").unwrap();
let state = ExecutionState::new(json!({}));
let errored =
NodeOutput::errored(json!({ "ok": false, "error": { "code": "E", "message": "m" } }));
match evaluate_custom_routing(&raw_routing, &errored, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err_node"),
other => panic!("expected on_error route, got {other:?}"),
}
}
#[test]
fn errored_output_with_outcome_routes_to_that_branch() {
let raw_routing = json!([
{ "condition": "event == \"on_success\"", "to": "ok_node" },
{ "condition": "event == \"on_timeout\"", "to": "timeout_node" },
{ "condition": "event == \"on_error\"", "to": "err_node" }
]);
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current = NodeId::from_str("current").unwrap();
let state = ExecutionState::new(json!({}));
let errored = NodeOutput::errored(json!({
"ok": false,
"outcome": "on_timeout",
"error": { "code": "E", "message": "m" }
}));
match evaluate_custom_routing(&raw_routing, &errored, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "timeout_node"),
other => panic!("expected on_timeout route, got {other:?}"),
}
}
#[test]
fn errored_output_preserves_meta_error_alongside_outcome() {
let errored = NodeOutput::errored(json!({
"ok": false,
"outcome": "on_timeout",
"error": { "code": "E1", "message": "boom" }
}));
assert_eq!(
errored.meta.get("outcome").and_then(Value::as_str),
Some("on_timeout"),
"outcome must survive so routing can pick the on_timeout branch"
);
assert_eq!(
errored.meta["error"]["message"], "boom",
"error must survive alongside outcome, not be clobbered by it"
);
let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
nodes.insert("run".to_string(), errored);
let lifted = lift_first_node_error_from_nodes(json!({}), &nodes);
assert_eq!(
lifted["metadata"]["error_message"], "boom",
"lift_first_node_error_from_nodes must read the real message, not the generic fallback"
);
assert_eq!(lifted["metadata"]["node_id"], "run");
}
#[test]
fn component_error_routed_failure_surfaces_real_message_via_lift() {
let errored = NodeOutput::errored(json!({
"ok": false,
"error": { "code": "E1", "message": "disk full" }
}));
let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
nodes.insert("run".to_string(), errored);
let lifted = lift_first_node_error_from_nodes(json!({}), &nodes);
assert_eq!(
lifted["metadata"]["error_message"], "disk full",
"a component_error-routed failure must surface its real message, \
not the generic \"flow node failed\" default"
);
assert_eq!(lifted["metadata"]["node_id"], "run");
}
#[test]
fn node_has_error_route_detects_error_family_ports() {
let with_err = Routing::Custom(json!([
{ "condition": "event == \"on_success\"", "to": "n" },
{ "condition": "event == \"on_error\"", "to": "e" }
]));
assert!(
node_has_error_route(&with_err),
"on_error route must be detected"
);
let only_success = Routing::Custom(json!([
{ "condition": "event == \"on_success\"", "to": "n" }
]));
assert!(
!node_has_error_route(&only_success),
"a success-only Custom routing has no error branch"
);
let plain = Routing::Next {
node_id: NodeId::from_str("n").unwrap(),
};
assert!(
!node_has_error_route(&plain),
"Routing::Next has no error branch"
);
}
#[test]
fn success_default_matches_available_outcome_port() {
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current = NodeId::from_str("current").unwrap();
let state = ExecutionState::new(json!({}));
let ok_out = NodeOutput::new(json!({ "answer": "hi" }));
let on_complete_routing = json!([
{ "condition": "event == \"on_complete\"", "to": "next" },
{ "condition": "event == \"on_cancel\"", "to": "cancelled" }
]);
match evaluate_custom_routing(&on_complete_routing, &ok_out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
other => panic!("expected Next(\"next\") via on_complete default, got {other:?}"),
}
let on_submit_routing = json!([
{ "condition": "event == \"on_submit\"", "to": "saved" },
{ "condition": "event == \"on_cancel\"", "to": "cancelled" }
]);
match evaluate_custom_routing(&on_submit_routing, &ok_out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "saved"),
other => panic!("expected Next(\"saved\") via on_submit default, got {other:?}"),
}
let on_success_routing = json!([
{ "condition": "event == \"on_success\"", "to": "ok" },
{ "condition": "event == \"on_error\"", "to": "err" }
]);
match evaluate_custom_routing(&on_success_routing, &ok_out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "ok"),
other => panic!("expected Next(\"ok\") via on_success default, got {other:?}"),
}
}
#[test]
fn condition_evaluator_supports_comparisons_and_contains() {
let ctx = json!({
"a": { "age": 18 },
"b": { "status": "ok" },
"c": { "text": "Hello World" }
});
assert!(evaluate_simple_condition("a.age >= 18", &ctx));
assert!(!evaluate_simple_condition("a.age > 18", &ctx));
assert!(evaluate_simple_condition("a.age <= 18", &ctx));
assert!(!evaluate_simple_condition("a.age < 18", &ctx));
assert!(evaluate_simple_condition("c.text contains \"world\"", &ctx));
assert!(!evaluate_simple_condition("c.text contains \"bye\"", &ctx));
assert!(evaluate_simple_condition("b.status == \"ok\"", &ctx));
assert!(!evaluate_simple_condition("b.status != \"ok\"", &ctx));
assert!(!evaluate_simple_condition("b.status >= 1", &ctx));
}
#[test]
fn routing_context_exposes_prior_node_outputs_under_node() {
let mut state = ExecutionState::new(json!({}));
state
.nodes
.insert("register".into(), NodeOutput::new(json!({ "q_age": 21 })));
let current = NodeOutput::new(json!({ "status": "ok" }));
let ctx = build_routing_context(¤t, &state, "on_success", "on_error");
assert!(
evaluate_simple_condition("node.register.q_age >= 18", &ctx),
"a prior node's output must be readable via node.<id>.<field>: {ctx:?}"
);
assert!(
evaluate_simple_condition("node.register.data.q_age >= 18", &ctx),
"the data envelope must resolve like it does in params: {ctx:?}"
);
}
#[test]
fn routing_context_keeps_the_predecessor_shorthand() {
let mut state = ExecutionState::new(json!({}));
state
.nodes
.insert("register".into(), NodeOutput::new(json!({ "q_age": 21 })));
let current = NodeOutput::new(json!({ "q_age": 30 }));
let ctx = build_routing_context(¤t, &state, "on_success", "on_error");
assert!(
evaluate_simple_condition("q_age >= 30", &ctx),
"the bare form must still resolve against the current payload: {ctx:?}"
);
}
#[test]
fn routing_context_does_not_resolve_a_missing_node() {
let state = ExecutionState::new(json!({}));
let current = NodeOutput::new(json!({ "status": "ok" }));
let ctx = build_routing_context(¤t, &state, "on_success", "on_error");
assert!(
!evaluate_simple_condition("node.ghost.x == \"y\"", &ctx),
"a missing node must not resolve: {ctx:?}"
);
}
#[test]
fn failure_default_matches_available_outcome_port() {
let flow_ir = HostFlow {
id: "flow.test".to_string(),
start: None,
nodes: IndexMap::new(),
vars_init: JsonMap::new(),
required_vars: Vec::new(),
slot_schema: None,
};
let current = NodeId::from_str("current").unwrap();
let state = ExecutionState::new(json!({}));
let err_out = NodeOutput {
ok: false,
payload: json!({}),
meta: Value::Null,
};
let on_cancel_routing = json!([
{ "condition": "event == \"on_complete\"", "to": "next" },
{ "condition": "event == \"on_cancel\"", "to": "cancelled" }
]);
match evaluate_custom_routing(&on_cancel_routing, &err_out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "cancelled"),
other => panic!("expected Next(\"cancelled\") via on_cancel default, got {other:?}"),
}
let on_error_routing = json!([
{ "condition": "event == \"on_success\"", "to": "ok" },
{ "condition": "event == \"on_error\"", "to": "err" }
]);
match evaluate_custom_routing(&on_error_routing, &err_out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err"),
other => panic!("expected Next(\"err\") via on_error default, got {other:?}"),
}
let on_timeout_routing = json!([
{ "condition": "event == \"on_success\"", "to": "ok" },
{ "condition": "event == \"on_timeout\"", "to": "timed_out" }
]);
match evaluate_custom_routing(&on_timeout_routing, &err_out, &state, &flow_ir, ¤t) {
CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "timed_out"),
other => panic!("expected Next(\"timed_out\") via on_timeout default, got {other:?}"),
}
}
#[test]
fn outcome_meta_surfaces_component_emitted_outcome() {
assert_eq!(
outcome_meta(&json!({ "ok": true, "outcome": "on_complete" })),
json!({ "outcome": "on_complete" })
);
assert_eq!(
outcome_meta(&json!({ "ok": true, "body": {} })),
Value::Null
);
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
#[ignore = "requires live NATS; run with --ignored after `nats-server -js`"]
async fn dw_agent_scale_to_zero_nats_e2e() {
use crate::runner::agent_node::DwAgentDispatch;
use crate::runner::dispatch_listener::{SessionResumer, run_response_listener};
use crate::runner::remote_dispatch::NatsDispatcher;
use futures::StreamExt as _;
use greentic_types::{
RuntimeDispatchResponse, TenantCtx as DispatchTenantCtx, request_topic, response_topic,
};
use tokio::sync::Notify;
let nats_url = match std::env::var("GREENTIC_EVENTS_NATS_URL") {
Ok(url) => url,
Err(_) => {
eprintln!(
"skipping dw_agent_scale_to_zero_nats_e2e: GREENTIC_EVENTS_NATS_URL not set"
);
return;
}
};
let resume_id = NodeId::from_str("after-agent").unwrap();
let agent_node_id = NodeId::from_str("agent-e2e").unwrap();
let agent_node = Node {
id: agent_node_id.clone(),
component: FlowComponentRef {
id: "dw.agent".parse().unwrap(),
pack_alias: None,
operation: Some("greeter".to_string()),
},
input: InputMapping {
mapping: json!({ "user_text": "ping" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::Next {
node_id: resume_id.clone(),
},
telemetry: TelemetryHints::default(),
conversational: false,
};
let resume_node = Node {
id: resume_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "message": "resumed" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(agent_node_id.clone(), agent_node);
nodes.insert(resume_id.clone(), resume_node);
let flow = greentic_types::Flow {
schema_version: "1.0".into(),
id: greentic_types::FlowId::from_str("e2e-agent.flow").unwrap(),
kind: greentic_types::FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(agent_node_id.to_string()),
)]),
nodes,
metadata: Default::default(),
};
let host_flow = HostFlow::from(flow);
let dispatcher_client = async_nats::connect(&nats_url)
.await
.expect("NATS: dispatcher client");
let bridge_client = async_nats::connect(&nats_url)
.await
.expect("NATS: fake bridge client");
let listener_client = async_nats::connect(&nats_url)
.await
.expect("NATS: response listener client");
let agentic_request_subject = request_topic("agentic");
let agentic_response_subject = response_topic("agentic");
let mut req_sub = bridge_client
.subscribe(agentic_request_subject.clone())
.await
.expect("fake bridge: subscribe to agentic request subject");
let bridge_reply_client = bridge_client.clone();
let reply_subject = agentic_response_subject.clone();
tokio::spawn(async move {
while let Some(msg) = req_sub.next().await {
let headers = msg.headers.as_ref();
let get_hdr = |name: &str| {
headers
.and_then(|h| h.get(name))
.map(|v| v.as_str().to_owned())
.unwrap_or_default()
};
let correlation_id = get_hdr("Greentic-Correlation-Id");
let tenant = get_hdr("Greentic-Tenant");
let env = get_hdr("Greentic-Env");
let response_payload = RuntimeDispatchResponse {
ok: true,
output: json!({
"reply": "pong",
"trail": [],
"terminated_by": "final_reply"
}),
events: vec![],
error: None,
};
let body =
serde_json::to_vec(&response_payload).expect("serialize fake bridge response");
let mut resp_headers = async_nats::HeaderMap::new();
resp_headers.insert("Greentic-Correlation-Id", correlation_id.as_str());
resp_headers.insert("Greentic-Tenant", tenant.as_str());
resp_headers.insert("Greentic-Env", env.as_str());
bridge_reply_client
.publish_with_headers(reply_subject.clone(), resp_headers, body.into())
.await
.expect("fake bridge: publish response");
}
});
struct RecordingResumer {
calls: std::sync::Mutex<Vec<(String, Value)>>,
notify: Notify,
}
impl RecordingResumer {
fn new() -> Self {
Self {
calls: std::sync::Mutex::new(vec![]),
notify: Notify::new(),
}
}
}
#[async_trait::async_trait]
impl SessionResumer for RecordingResumer {
async fn resume(
&self,
_tenant: DispatchTenantCtx,
correlation_id: &str,
output: Value,
) -> anyhow::Result<()> {
self.calls
.lock()
.unwrap()
.push((correlation_id.to_string(), output));
self.notify.notify_one();
Ok(())
}
}
let resumer = Arc::new(RecordingResumer::new());
let resumer_for_listener = resumer.clone();
tokio::spawn(async move {
run_response_listener(listener_client, "agentic".to_owned(), resumer_for_listener)
.await
.expect("response listener exited unexpectedly");
});
tokio::time::sleep(tokio::time::Duration::from_millis(150)).await;
let nats_engine_dispatcher = Arc::new(NatsDispatcher::new(dispatcher_client));
let engine = FlowEngine {
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
messaging_provider_pack_ids: std::collections::HashSet::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: "e2e-pack".to_string(),
flow_id: "e2e-agent.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: crate::validate::ValidationConfig {
mode: crate::validate::ValidationMode::Off,
},
cross_pack_resolver: None,
rollout_ids: RolloutIds::default(),
approval_dispatch_handler: None,
remote_dispatch_handler: Some(
nats_engine_dispatcher
as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
),
dw_agent_dispatch: DwAgentDispatch::Nats,
agent_node_handler: None,
graph_node_handler: None,
mcp_tool_source: None,
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let ctx = FlowContext {
tenant: "demo",
pack_id: "e2e-pack",
flow_id: "e2e-agent.flow",
node_id: None,
tool: None,
action: None,
session_id: Some("e2e-sess-1"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let result = engine
.execute(ctx, json!({ "user_text": "ping" }))
.await
.expect("engine.execute succeeded");
assert!(
matches!(result.status, FlowStatus::Waiting(_)),
"expected FlowStatus::Waiting from dw.agent Nats path, got: {:?}",
result.status
);
eprintln!("dw.agent: flow paused (Waiting) — dispatch published to NATS");
let wait = tokio::time::timeout(
tokio::time::Duration::from_secs(5),
resumer.notify.notified(),
)
.await;
assert!(
wait.is_ok(),
"timed out waiting for fake bridge reply — is NATS running? ({nats_url})"
);
let calls = resumer.calls.lock().unwrap();
assert_eq!(
calls.len(),
1,
"resumer should have been called exactly once"
);
let (ref _corr, ref output) = calls[0];
assert_eq!(
output["output"]["reply"],
json!("pong"),
"resumed reply must match the aw-serve canned reply"
);
eprintln!(
"PASSED: dw.agent scale-to-zero NATS e2e — reply={:?}",
output["output"]["reply"]
);
}
#[test]
fn execution_state_vars_survive_serde_round_trip() {
let mut st = ExecutionState::new(json!({}));
st.vars.insert("counter".into(), json!(3));
st.vars.insert("region".into(), json!("us-east-1"));
let encoded = serde_json::to_string(&st).expect("serialize");
let decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded.vars.get("counter"), Some(&json!(3)));
assert_eq!(decoded.vars.get("region"), Some(&json!("us-east-1")));
}
#[test]
fn execution_state_vars_default_empty_for_old_snapshots() {
let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
let decoded: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
assert!(decoded.vars.is_empty());
}
#[test]
fn template_context_exposes_vars_namespace_typed() {
let mut st = ExecutionState::new(serde_json::json!({}));
st.vars.insert("count".into(), serde_json::json!(5));
st.vars.insert("name".into(), serde_json::json!("aws"));
let ctx = template_context(&st, serde_json::Value::Null);
let rendered_num = render_template_value(
&serde_json::json!("{{vars.count}}"),
&ctx,
TemplateOptions::default(),
)
.expect("render num");
assert_eq!(rendered_num, serde_json::json!(5));
let rendered_str = render_template_value(
&serde_json::json!("prefix-{{vars.name}}"),
&ctx,
TemplateOptions::default(),
)
.expect("render str");
assert_eq!(rendered_str, serde_json::json!("prefix-aws"));
}
#[test]
fn vars_namespace_does_not_shadow_existing_namespaces() {
let st = ExecutionState::new(serde_json::json!({"user": {"id": 7}}));
let ctx = template_context(&st, serde_json::Value::Null);
let obj = ctx.as_object().expect("ctx object");
for key in ["entry", "in", "prev", "node", "state", "vars", "now"] {
assert!(obj.contains_key(key), "context must expose `{key}`");
}
}
fn fixed_instant() -> DateTime<Utc> {
DateTime::parse_from_rfc3339("2026-09-09T10:53:04.250Z")
.expect("a literal RFC3339 instant")
.with_timezone(&Utc)
}
#[test]
fn now_namespace_carries_iso_epoch_ms_and_date() {
let now = now_namespace(fixed_instant());
assert_eq!(now["iso"], serde_json::json!("2026-09-09T10:53:04.250Z"));
assert_eq!(now["epoch_ms"], serde_json::json!(1_788_951_184_250i64));
assert_eq!(now["date"], serde_json::json!("2026-09-09"));
}
#[test]
fn a_node_config_can_render_a_timestamp_it_was_never_given() {
let st = ExecutionState::new(serde_json::json!({}));
let ctx = template_context(&st, serde_json::Value::Null);
let rendered = render_template_value(
&serde_json::json!({ "hs_timestamp": "{{now.iso}}" }),
&ctx,
TemplateOptions::default(),
)
.expect("render");
let stamp = rendered["hs_timestamp"]
.as_str()
.expect("an ISO string, not an object");
assert!(
DateTime::parse_from_rfc3339(stamp).is_ok(),
"`{stamp}` must parse as RFC3339 — an API rejecting it is the \
failure this field exists to prevent"
);
}
#[test]
fn epoch_ms_resolves_as_a_number_not_a_string() {
let st = ExecutionState::new(serde_json::json!({}));
let ctx = template_context(&st, serde_json::Value::Null);
let rendered = render_template_value(
&serde_json::json!("{{now.epoch_ms}}"),
&ctx,
TemplateOptions::default(),
)
.expect("render");
assert!(
rendered.is_i64(),
"expected a JSON number, got {rendered:?}"
);
}
#[test]
fn a_now_reference_no_longer_renders_as_the_empty_string() {
let st = ExecutionState::new(serde_json::json!({}));
let ctx = template_context(&st, serde_json::Value::Null);
for expression in ["{{now.iso}}", "{{now.date}}"] {
let rendered = render_template_value(
&serde_json::json!(expression),
&ctx,
TemplateOptions::default(),
)
.expect("render");
assert_ne!(
rendered,
serde_json::json!(""),
"`{expression}` must resolve to something"
);
}
}
#[test]
fn one_context_sees_a_single_instant() {
let st = ExecutionState::new(serde_json::json!({}));
let ctx = template_context(&st, serde_json::Value::Null);
let rendered = render_template_value(
&serde_json::json!({ "a": "{{now.iso}}", "b": "{{now.iso}}" }),
&ctx,
TemplateOptions::default(),
)
.expect("render");
assert_eq!(rendered["a"], rendered["b"]);
}
fn flow_with_extra(extra: serde_json::Value) -> Flow {
Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("test.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::new(),
nodes: indexmap::IndexMap::default(),
metadata: FlowMetadata {
title: None,
description: None,
tags: Default::default(),
extra,
},
}
}
#[test]
fn seed_vars_seeds_defaults_and_reports_missing_required() {
use serde_json::json;
let mut vars_init = JsonMap::new();
vars_init.insert("region".into(), json!("us-east-1"));
let required = vec!["name".to_string(), "region".to_string()];
let mut target = JsonMap::new();
let missing = seed_vars_and_collect_missing_required(&vars_init, &required, &mut target);
assert_eq!(
target.get("region"),
Some(&json!("us-east-1")),
"default seeded"
);
assert_eq!(
missing,
vec!["name".to_string()],
"only the defaultless required var is missing"
);
}
#[test]
fn seed_vars_respects_preexisting_value_for_required() {
use serde_json::json;
let vars_init = JsonMap::new(); let required = vec!["name".to_string()];
let mut target = JsonMap::new();
target.insert("name".into(), json!("Budi"));
let missing = seed_vars_and_collect_missing_required(&vars_init, &required, &mut target);
assert!(
missing.is_empty(),
"a required var with a provided value is not missing"
);
assert_eq!(
target.get("name"),
Some(&json!("Budi")),
"provided value not overwritten"
);
}
#[test]
fn from_flow_extracts_vars_init() {
let flow = flow_with_extra(serde_json::json!({
"vars_init": {
"region": { "type": "string", "default": "us-east-1" },
"counter": { "type": "number", "default": 0 }
}
}));
let host: HostFlow = HostFlow::from(flow);
assert_eq!(
host.vars_init.get("region"),
Some(&serde_json::json!("us-east-1"))
);
assert_eq!(host.vars_init.get("counter"), Some(&serde_json::json!(0)));
}
#[test]
fn from_flow_vars_init_absent() {
let flow = flow_with_extra(serde_json::json!({}));
let host: HostFlow = HostFlow::from(flow);
assert!(host.vars_init.is_empty());
}
#[test]
fn from_flow_collects_required_vars() {
let flow = flow_with_extra(serde_json::json!({
"vars_init": {
"name": { "type": "string", "required": true },
"region": { "type": "string", "default": "us-east-1" },
"note": { "type": "string", "required": false }
}
}));
let host: HostFlow = HostFlow::from(flow);
assert_eq!(host.required_vars, vec!["name".to_string()]);
}
#[test]
fn execute_once_fails_on_missing_required_var() {
let node_id = NodeId::from_str("n1").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "message": "{{vars.region}}" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(node_id.clone(), node);
let flow = Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("vars.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(node_id.to_string()),
)]),
nodes,
metadata: FlowMetadata {
title: None,
description: None,
tags: Default::default(),
extra: json!({
"vars_init": {
"region": { "type": "string", "required": true }
}
}),
},
};
let host_flow = HostFlow::from(flow);
let engine = FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "vars.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let observer = CountingObserver::new();
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "vars.flow",
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: Some(&observer),
mocks: None,
caller: None,
};
let rt = Runtime::new().unwrap();
let err = rt
.block_on(engine.execute(ctx, Value::Null))
.expect_err("a required var with no default and no value must fail the run");
let msg = err.to_string();
assert!(msg.contains("region"), "error names the missing var: {msg}");
assert!(
!should_retry(&err),
"missing-required-var is deterministic and must not be retried"
);
assert!(
observer.ends.lock().unwrap().is_empty(),
"flow aborted before the node ran"
);
}
#[test]
fn execute_once_seeds_declared_vars() {
let node_id = NodeId::from_str("n1").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "message": "{{vars.region}}" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(node_id.clone(), node);
let flow = Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("vars.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(node_id.to_string()),
)]),
nodes,
metadata: FlowMetadata {
title: None,
description: None,
tags: Default::default(),
extra: json!({
"vars_init": {
"region": { "type": "string", "default": "us-east-1" }
}
}),
},
};
let host_flow = HostFlow::from(flow);
let engine = FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: HashMap::new(),
flow_cache: RwLock::new(HashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "vars.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let observer = CountingObserver::new();
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "vars.flow",
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: Some(&observer),
mocks: None,
caller: None,
};
let rt = Runtime::new().unwrap();
let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
assert!(matches!(result.status, FlowStatus::Completed));
let ends = observer.ends.lock().unwrap();
assert_eq!(ends.len(), 1);
assert_eq!(
ends[0].get("message").and_then(Value::as_str),
Some("us-east-1"),
"vars.region must be seeded to its default and rendered in the node payload"
);
}
fn var_set_flow(
var_set_input: Value,
emit_input: Value,
vars_init_extra: Option<Value>,
) -> Flow {
let set_id = NodeId::from_str("set1").unwrap();
let emit_id = NodeId::from_str("emit1").unwrap();
let set_node = Node {
id: set_id.clone(),
component: FlowComponentRef {
id: "var.set".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: var_set_input,
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::Next {
node_id: emit_id.clone(),
},
telemetry: TelemetryHints::default(),
conversational: false,
};
let emit_node = Node {
id: emit_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: emit_input,
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(set_id.clone(), set_node);
nodes.insert(emit_id.clone(), emit_node);
let extra = vars_init_extra.unwrap_or(serde_json::json!({}));
Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("var.set.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(set_id.to_string()),
)]),
nodes,
metadata: FlowMetadata {
title: None,
description: None,
tags: Default::default(),
extra,
},
}
}
fn run_var_set_flow(flow: Flow) -> (FlowStatus, Vec<Value>) {
let host_flow = HostFlow::from(flow);
let engine = FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "var.set.flow".to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let observer = CountingObserver::new();
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "var.set.flow",
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: Some(&observer),
mocks: None,
caller: None,
};
let rt = Runtime::new().unwrap();
let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
let ends = observer.ends.lock().unwrap().clone();
(result.status, ends)
}
#[test]
fn var_set_node_writes_literal_value_into_vars() {
let flow = var_set_flow(
json!({ "name": "greeting", "value": "hi" }),
json!({ "message": "{{vars.greeting}}" }),
None,
);
let (status, ends) = run_var_set_flow(flow);
assert!(
matches!(status, FlowStatus::Completed),
"flow must complete"
);
assert_eq!(ends.len(), 2, "both nodes must fire");
assert_eq!(ends[0].get("ok"), Some(&json!(true)), "var_set output ok");
assert_eq!(
ends[1].get("message").and_then(Value::as_str),
Some("hi"),
"vars.greeting must be written and renderable in the next node"
);
}
#[test]
fn var_set_node_writes_templated_value_with_type_preserved() {
let flow = var_set_flow(
json!({ "name": "copy", "value": "{{vars.counter}}" }),
json!({ "message": "{{vars.copy}}" }),
Some(json!({
"vars_init": {
"counter": { "type": "number", "default": 1 }
}
})),
);
let (status, ends) = run_var_set_flow(flow);
assert!(
matches!(status, FlowStatus::Completed),
"flow must complete"
);
assert_eq!(ends.len(), 2, "both nodes must fire");
assert_eq!(
ends[1].get("message"),
Some(&json!(1)),
"vars.copy must preserve the JSON number type from vars.counter"
);
}
#[test]
fn var_set_empty_name_is_skipped_not_written() {
let engine = minimal_engine();
let rt = Runtime::new().unwrap();
let retry_config = RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
};
let ctx = FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "var.set.flow",
node_id: Some("set1"),
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config,
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let node = HostNode {
kind: NodeKind::VarSet {
name: "".to_string(),
value: json!("garbage"),
},
component: "var.set".into(),
component_id: "var.set".into(),
operation_name: None,
operation_in_mapping: None,
payload_expr: Value::Null,
routing: Routing::End,
vars_out: None,
response_timeout_secs: None,
};
let mut state = ExecutionState::new(Value::Null);
let payload = Value::Null;
let event = NodeEvent {
context: &ctx,
node_id: "set1",
node: &node,
payload: &payload,
};
let outcome = rt
.block_on(engine.dispatch_node(
&ctx,
"set1",
&node,
&mut state,
payload.clone(),
&event,
))
.expect("dispatch_node must not error on empty var name");
assert_eq!(
outcome.output.payload,
json!({ "ok": true }),
"dispatch must return ok:true even when name is empty"
);
assert!(
state.vars.get("").is_none(),
"empty var name must not create a \"\" key in state.vars"
);
}
#[test]
fn var_set_node_has_empty_payload_expr() {
let node_id = NodeId::from_str("set1").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "var.set".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "name": "greeting", "value": "hi" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let host_node = HostNode::from(node);
assert_eq!(
host_node.payload_expr,
Value::Null,
"var.set node must have Null payload_expr after lowering"
);
match &host_node.kind {
NodeKind::VarSet { name, value } => {
assert_eq!(name.as_str(), "greeting", "name must be preserved in kind");
assert_eq!(value, &json!("hi"), "value must be preserved in kind");
}
other => panic!("expected NodeKind::VarSet, got {other:?}"),
}
}
fn vars_out_flow(emit1_input: Value, emit2_input: Value) -> Flow {
let emit1_id = NodeId::from_str("emit1").unwrap();
let emit2_id = NodeId::from_str("emit2").unwrap();
let emit1_node = Node {
id: emit1_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: emit1_input,
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::Next {
node_id: emit2_id.clone(),
},
telemetry: TelemetryHints::default(),
conversational: false,
};
let emit2_node = Node {
id: emit2_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: emit2_input,
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(emit1_id.clone(), emit1_node);
nodes.insert(emit2_id.clone(), emit2_node);
Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("var.set.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(emit1_id.to_string()),
)]),
nodes,
metadata: FlowMetadata {
title: None,
description: None,
tags: Default::default(),
extra: serde_json::json!({}),
},
}
}
#[test]
fn vars_out_binds_node_output_into_vars() {
let flow = vars_out_flow(
json!({
"message": "hello",
"vars_out": { "lastReply": "{{prev.message}}" }
}),
json!({ "message": "{{vars.lastReply}}" }),
);
let (status, ends) = run_var_set_flow(flow);
assert!(
matches!(status, FlowStatus::Completed),
"flow must complete"
);
assert_eq!(ends.len(), 2, "both nodes must fire");
assert_eq!(
ends[1].get("message").and_then(Value::as_str),
Some("hello"),
"vars_out binding from node 1 must be readable in node 2"
);
}
#[test]
fn vars_out_is_stripped_from_component_node_payload() {
let node_id = NodeId::from_str("comp1").unwrap();
let node = Node {
id: node_id.clone(),
component: FlowComponentRef {
id: "my.component".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({
"message": "hello",
"vars_out": { "lastReply": "{{prev.message}}" }
}),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let host_node = HostNode::from(node);
assert!(
host_node.vars_out.is_some(),
"vars_out binding must be carried on the HostNode"
);
assert!(
host_node
.vars_out
.as_ref()
.unwrap()
.contains_key("lastReply"),
"vars_out must contain the declared binding"
);
assert!(
host_node.payload_expr.get("vars_out").is_none(),
"vars_out must not appear in payload_expr (would leak to wasm component input)"
);
assert_eq!(
host_node
.payload_expr
.get("message")
.and_then(Value::as_str),
Some("hello"),
"real input fields must remain in payload_expr"
);
}
#[test]
fn dotted_component_id_is_not_split_when_mapping_carries_operation() {
let node_id = NodeId::from_str("present_koncar").unwrap();
let node = Node {
id: node_id,
component: FlowComponentRef {
id: "ai.greentic.koncar.component-present".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({
"component": "ai.greentic.koncar.component-present",
"operation": "present",
"query": "hello"
}),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let host_node = HostNode::from(node);
assert_eq!(
host_node.component_id(),
"ai.greentic.koncar.component-present",
"dotted component id must survive lowering intact"
);
match &host_node.kind {
NodeKind::PackComponent { component_ref } => assert_eq!(
component_ref, "ai.greentic.koncar.component-present",
"PackComponent must look up the full id, not a dot-split prefix"
),
other => panic!("expected NodeKind::PackComponent, got {other:?}"),
}
assert_eq!(
host_node.operation_in_mapping(),
Some("present"),
"the operation must still be readable from the mapping"
);
}
fn vars_survive_flow() -> Flow {
let set_id = NodeId::from_str("set1").unwrap();
let wait_id = NodeId::from_str("wait1").unwrap();
let emit_id = NodeId::from_str("emit1").unwrap();
let set_node = Node {
id: set_id.clone(),
component: FlowComponentRef {
id: "var.set".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "name": "greeting", "value": "hello" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::Next {
node_id: wait_id.clone(),
},
telemetry: TelemetryHints::default(),
conversational: false,
};
let wait_node = Node {
id: wait_id.clone(),
component: FlowComponentRef {
id: "session.wait".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: Value::Null,
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::Next {
node_id: emit_id.clone(),
},
telemetry: TelemetryHints::default(),
conversational: false,
};
let emit_node = Node {
id: emit_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({
"greeting": "{{vars.greeting}}",
"counter": "{{vars.counter}}"
}),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(set_id.clone(), set_node);
nodes.insert(wait_id.clone(), wait_node);
nodes.insert(emit_id.clone(), emit_node);
Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("vars.survive.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(set_id.to_string()),
)]),
nodes,
metadata: FlowMetadata {
title: None,
description: None,
tags: Default::default(),
extra: json!({
"vars_init": {
"counter": { "type": "number", "default": 1 }
}
}),
},
}
}
#[test]
fn vars_survive_park_and_resume_end_to_end() {
let flow = vars_survive_flow();
let host_flow = HostFlow::from(flow);
let flow_id = "vars.survive.flow";
let pack_id = "test-pack";
let engine = FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: pack_id.to_string(),
flow_id: flow_id.to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let rt = Runtime::new().unwrap();
let ctx1 = FlowContext {
tenant: "demo",
pack_id,
flow_id,
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let result1 = rt.block_on(engine.execute(ctx1, Value::Null)).unwrap();
let snapshot = match result1.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting after session.wait, got {other:?}"),
};
assert_eq!(
snapshot.state.vars.get("greeting"),
Some(&json!("hello")),
"greeting var must be in snapshot"
);
assert_eq!(
snapshot.state.vars.get("counter"),
Some(&json!(1)),
"counter var (from vars_init) must be in snapshot"
);
let observer2 = CountingObserver::new();
let ctx2 = FlowContext {
tenant: "demo",
pack_id,
flow_id,
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: Some(&observer2),
mocks: None,
caller: None,
};
let result2 = rt
.block_on(engine.resume(ctx2, snapshot, Value::Null))
.unwrap();
assert!(
matches!(result2.status, FlowStatus::Completed),
"flow must complete after resume"
);
let ends2 = observer2.ends.lock().unwrap().clone();
assert_eq!(ends2.len(), 1, "only emit.log fires after resume");
assert_eq!(
ends2[0].get("greeting").and_then(Value::as_str),
Some("hello"),
"vars.greeting must survive the park/resume"
);
assert_eq!(
ends2[0].get("counter"),
Some(&json!(1)),
"vars.counter (vars_init) must survive the park/resume"
);
}
#[cfg(feature = "agentic-worker")]
struct StubAgentHandler {
payload: serde_json::Value,
}
#[cfg(feature = "agentic-worker")]
#[async_trait::async_trait]
impl crate::runner::agent_node::AgentNodeHandler for StubAgentHandler {
async fn execute(
&self,
_tenant_id: &str,
_env_id: &str,
_agent_id: &str,
_session_id: &str,
_flow_input: &serde_json::Value,
_conversational: bool,
_caller: Option<&serde_json::Value>,
) -> anyhow::Result<serde_json::Value> {
Ok(self.payload.clone())
}
}
#[cfg(feature = "agentic-worker")]
fn conversational_dw_flow(conversational: bool) -> HostFlow {
let mut nodes = IndexMap::new();
let agent_id = NodeId::from_str("agent").unwrap();
let thanks_id = NodeId::from_str("thanks").unwrap();
nodes.insert(
agent_id.clone(),
HostNode {
kind: NodeKind::DwAgent {
agent_id: "a".to_string(),
conversational,
},
component: "dw.agent".to_string(),
component_id: "dw.agent".to_string(),
operation_name: Some("a".to_string()),
operation_in_mapping: None,
payload_expr: json!({ "user_text": "hi" }),
routing: Routing::Next {
node_id: thanks_id.clone(),
},
vars_out: None,
response_timeout_secs: None,
},
);
nodes.insert(
thanks_id.clone(),
HostNode {
kind: NodeKind::BuiltinEmit {
kind: EmitKind::Response,
},
component: "emit.response".to_string(),
component_id: "emit.response".to_string(),
operation_name: None,
operation_in_mapping: None,
payload_expr: json!({ "text": "thanks" }),
routing: Routing::End,
vars_out: None,
response_timeout_secs: None,
},
);
HostFlow {
slot_schema: None,
id: "conv.flow".to_string(),
start: Some(agent_id),
nodes,
vars_init: JsonMap::new(),
required_vars: Vec::new(),
}
}
#[cfg(feature = "agentic-worker")]
fn conv_engine(flow: HostFlow, payload: serde_json::Value) -> FlowEngine {
conv_engine_with(flow, std::sync::Arc::new(StubAgentHandler { payload }))
}
#[cfg(feature = "agentic-worker")]
fn conv_engine_with(
flow: HostFlow,
handler: std::sync::Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
) -> FlowEngine {
FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "conv.flow".to_string(),
},
flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
agent_node_handler: Some(handler),
graph_node_handler: None,
mcp_tool_source: None,
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
}
}
#[cfg(feature = "agentic-worker")]
fn conv_ctx<'a>() -> FlowContext<'a> {
FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "conv.flow",
node_id: None,
tool: None,
action: None,
session_id: Some("sess-conv"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
}
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_parks_and_loops_on_normal_reply() {
let engine = conv_engine(
conversational_dw_flow(true),
json!({ "reply": "hello there", "trail": [], "terminated_by": "final_reply" }),
);
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting (park-loop), got {other:?}"),
};
assert_eq!(
snapshot.next_node, "agent",
"must re-enter the dw.agent node itself"
);
assert!(
serde_json::to_string(&result.output)
.unwrap()
.contains("hello there"),
"the agent reply must be rendered before parking: {:?}",
result.output
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_advances_on_conversation_ended() {
let engine = conv_engine(
conversational_dw_flow(true),
json!({ "reply": "bye", "trail": [], "terminated_by": "conversation_ended" }),
);
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
assert!(
matches!(result.status, FlowStatus::Completed),
"conversation_ended must advance to the successor and complete, got {:?}",
result.status
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn non_conversational_dw_agent_never_loops() {
for tb in ["final_reply", "conversation_ended"] {
let engine = conv_engine(
conversational_dw_flow(false),
json!({ "reply": "x", "trail": [], "terminated_by": tb }),
);
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
assert!(
matches!(result.status, FlowStatus::Completed),
"non-conversational must complete (route onward) for terminated_by={tb}, got {:?}",
result.status
);
}
}
#[cfg(feature = "agentic-worker")]
struct ToolParkAgentHandler {
outputs: std::sync::Mutex<Vec<serde_json::Value>>,
resumes: std::sync::Mutex<Vec<Option<serde_json::Value>>>,
}
#[cfg(feature = "agentic-worker")]
impl ToolParkAgentHandler {
fn new(outputs: Vec<serde_json::Value>) -> Self {
Self {
outputs: std::sync::Mutex::new(outputs),
resumes: std::sync::Mutex::new(Vec::new()),
}
}
}
#[cfg(feature = "agentic-worker")]
#[async_trait::async_trait]
impl crate::runner::agent_node::AgentNodeHandler for ToolParkAgentHandler {
async fn execute(
&self,
_tenant_id: &str,
_env_id: &str,
_agent_id: &str,
_session_id: &str,
_flow_input: &serde_json::Value,
_conversational: bool,
_caller: Option<&serde_json::Value>,
) -> anyhow::Result<serde_json::Value> {
anyhow::bail!("the engine must call execute_with_resume")
}
async fn execute_with_resume(
&self,
_tenant_id: &str,
_env_id: &str,
_agent_id: &str,
_session_id: &str,
_flow_input: &serde_json::Value,
_conversational: bool,
_caller: Option<&serde_json::Value>,
resume_payload: Option<&serde_json::Value>,
) -> anyhow::Result<serde_json::Value> {
self.resumes.lock().unwrap().push(resume_payload.cloned());
let mut outputs = self.outputs.lock().unwrap();
anyhow::ensure!(!outputs.is_empty(), "no scripted agent output");
Ok(outputs.remove(0))
}
}
#[cfg(feature = "agentic-worker")]
fn awaiting_tool_output() -> serde_json::Value {
json!({
"reply": "please pick a room",
"trail": [],
"terminated_by": "awaiting_tool_input",
"pending_presentation": { "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }
})
}
#[cfg(feature = "agentic-worker")]
#[test]
fn dw_agent_awaiting_tool_input_parks_renders_the_card_and_resumes_with_the_submit() {
let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
awaiting_tool_output(),
json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
]));
let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
let rt = Runtime::new().unwrap();
let first = rt
.block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
.unwrap();
let snapshot = match first.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected the flow to park on the tool, got {other:?}"),
};
assert_eq!(snapshot.next_node, "agent", "re-enter the agent node");
assert_eq!(
first.output,
json!({ "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }),
"the card, not the agent envelope, is the turn output"
);
assert_eq!(
first.node_outputs["agent"]["pending_presentation"]["type"], "AdaptiveCard",
"the node output keeps the full envelope: {:?}",
first.node_outputs
);
assert!(snapshot.state.pending_tool_await.contains_key("agent"));
assert!(
snapshot.state.park_turns.is_empty(),
"a tool park is not a conversational turn"
);
let submit = json!({ "metadata": { "action": "submit" }, "room": "101" });
let second = rt
.block_on(engine.resume(conv_ctx(), snapshot, submit.clone()))
.unwrap();
assert!(
matches!(second.status, FlowStatus::Completed),
"the resumed non-conversational agent routes onward, got {:?}",
second.status
);
assert_eq!(*handler.resumes.lock().unwrap(), vec![None, Some(submit)]);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn an_agent_chat_resume_payload_reaches_the_parked_agent() {
let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
awaiting_tool_output(),
json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
]));
let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
let rt = Runtime::new().unwrap();
let first = rt
.block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
.unwrap();
let FlowStatus::Waiting(wait) = first.status else {
panic!("expected a park");
};
let submit = json!({ "metadata": { "action": "submit" }, "room": "101" });
let payload =
crate::http::agent_chat::turn_payload(String::new(), submit.as_object().cloned());
rt.block_on(engine.resume(conv_ctx(), wait.snapshot, payload))
.unwrap();
assert_eq!(*handler.resumes.lock().unwrap(), vec![None, Some(submit)]);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_typed_message_during_a_tool_park_is_not_a_resume_payload() {
let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
awaiting_tool_output(),
json!({ "reply": "ok, cancelled", "trail": [], "terminated_by": "final_reply" }),
]));
let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
let rt = Runtime::new().unwrap();
let first = rt
.block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
.unwrap();
let FlowStatus::Waiting(wait) = first.status else {
panic!("expected a park");
};
rt.block_on(engine.resume(conv_ctx(), wait.snapshot, json!({ "text": "never mind" })))
.unwrap();
assert_eq!(*handler.resumes.lock().unwrap(), vec![None, None]);
}
#[cfg(feature = "agentic-worker")]
fn side_turn_output() -> serde_json::Value {
json!({
"reply": "the signature is in Settings",
"trail": [],
"terminated_by": "awaiting_tool_input",
"side_turn": true,
"pending_presentation": { "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }
})
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_plain_park_still_renders_only_the_card() {
let out = awaiting_tool_output();
assert_eq!(rendered_park(&out), out["pending_presentation"]);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_side_turn_park_renders_the_reply_then_the_card() {
let out = side_turn_output();
let rendered = rendered_park(&out);
let items = rendered.as_array().expect("reply + card");
assert_eq!(items.len(), 2);
assert_eq!(items[0]["reply"], "the signature is in Settings");
assert!(items[0].get("pending_presentation").is_none());
assert_eq!(items[1], out["pending_presentation"]);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_side_turn_with_a_list_card_renders_one_flat_list() {
let mut out = side_turn_output();
out["pending_presentation"] = json!([{ "text": "pick a room" }, { "text": "or cancel" }]);
let rendered = rendered_park(&out);
let items = rendered.as_array().expect("flat list");
assert_eq!(items.len(), 3, "reply + both card messages: {rendered}");
assert_eq!(items[0]["reply"], "the signature is in Settings");
assert_eq!(items[1], json!({ "text": "pick a room" }));
assert_eq!(items[2], json!({ "text": "or cancel" }));
assert!(items.iter().all(|item| !item.is_array()), "no nested list");
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_side_turn_keeps_the_await_armed_so_a_submit_still_resumes() {
let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
awaiting_tool_output(),
side_turn_output(),
json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
]));
let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
let rt = Runtime::new().unwrap();
let first = rt
.block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
.unwrap();
let FlowStatus::Waiting(wait) = first.status else {
panic!("expected a park");
};
let second = rt
.block_on(engine.resume(
conv_ctx(),
wait.snapshot,
json!({ "text": "how do I get a signature?" }),
))
.unwrap();
assert!(
second.output.is_array(),
"reply and card: {}",
second.output
);
let FlowStatus::Waiting(wait) = second.status else {
panic!("the side turn must keep the flow parked");
};
rt.block_on(engine.resume(
conv_ctx(),
wait.snapshot,
json!({ "metadata": { "action": "submit" } }),
))
.unwrap();
let resumes = handler.resumes.lock().unwrap();
assert_eq!(resumes.len(), 3);
assert!(resumes[0].is_none() && resumes[1].is_none());
assert!(resumes[2].is_some(), "the submit must resume the tool");
}
#[cfg(any(feature = "agentic-worker", test))]
fn wrapped_typed_message(text: &str) -> serde_json::Value {
json!({
"input": {
"id": "msg-2",
"tenant": { "env": "local", "tenant": "acme", "tenant_id": "acme" },
"channel": "webchat",
"session_id": "sess-1",
"from": { "id": "user-1", "kind": "user" },
"to": [],
"correlation_id": "corr-1",
"attachments": [],
"metadata": {},
"extensions": { "caller": { "sub": "user-1", "user_verified": true } },
"text": text
}
})
}
#[test]
fn a_typed_message_in_a_channel_envelope_is_not_a_card_submit() {
assert!(!is_card_submit(&wrapped_typed_message("2+2 berapa?")));
let mut with_context = wrapped_typed_message("hi");
with_context["input"]["metadata"] =
json!({ "locale": "en-US", "team": "support", "env": "prod", "autoStart": false });
assert!(!is_card_submit(&with_context));
let mut by_action = wrapped_typed_message("");
by_action["input"]["metadata"] = json!({ "action": "start_request" });
assert!(is_card_submit(&by_action));
let mut by_values = wrapped_typed_message("");
by_values["input"]["metadata"] = json!({ "room": "101" });
assert!(is_card_submit(&by_values));
let flat_typed = wrapped_typed_message("2+2 berapa?")["input"].clone();
assert!(!is_card_submit(&flat_typed));
let mut flat_submit = flat_typed.clone();
flat_submit["metadata"] = json!({ "action": "start_request" });
assert!(is_card_submit(&flat_submit));
assert!(is_card_submit(
&json!({ "channel": "email", "metadata": {} })
));
}
#[cfg(any(feature = "agentic-worker", test))]
fn provider_stamped_metadata() -> serde_json::Value {
json!({
"universal": "true",
"env": "prod",
"tenant": "acme",
"route": "sess-1",
"user_id": "user-1",
"user_verified": "true",
"flow_hint": "main",
"locale": "en-US",
"extensions": "{\"caller\":{\"sub\":\"user-1\"}}",
"channel.channel_data": "{}"
})
}
#[test]
fn a_typed_message_with_provider_stamped_metadata_is_not_a_card_submit() {
let mut typed = wrapped_typed_message("how do I get a mail signature?");
typed["input"]["metadata"] = provider_stamped_metadata();
assert!(!is_card_submit(&typed));
let flat = typed["input"].clone();
assert!(!is_card_submit(&flat));
}
#[test]
fn a_click_is_still_a_card_submit_beside_provider_stamped_metadata() {
let mut by_action = wrapped_typed_message("");
let mut meta = provider_stamped_metadata();
meta["action"] = json!("start_request");
by_action["input"]["metadata"] = meta;
assert!(is_card_submit(&by_action));
let mut by_values = wrapped_typed_message("");
let mut meta = provider_stamped_metadata();
meta["room"] = json!("101");
by_values["input"]["metadata"] = meta;
assert!(is_card_submit(&by_values));
}
#[test]
fn channel_context_prefix_matches_only_the_channel_namespace() {
let mut typed = wrapped_typed_message("hi");
typed["input"]["metadata"] = json!({ "mychannel.x": "1" });
assert!(is_card_submit(&typed));
typed["input"]["metadata"] = json!({ "channel.x": "1" });
assert!(!is_card_submit(&typed));
}
#[test]
fn the_provider_submit_marker_makes_an_empty_submit_a_submit() {
let mut click = wrapped_typed_message("message");
let mut meta = provider_stamped_metadata();
meta["greentic_submit"] = json!("true");
click["input"]["metadata"] = meta;
assert!(is_card_submit(&click));
let flat = click["input"].clone();
assert!(is_card_submit(&flat));
let mut typed = wrapped_typed_message("message");
typed["input"]["metadata"] = provider_stamped_metadata();
assert!(!is_card_submit(&typed));
let mut other = wrapped_typed_message("message");
let mut meta = provider_stamped_metadata();
meta["greentic_submit"] = json!("false");
other["input"]["metadata"] = meta;
assert!(!is_card_submit(&other));
}
#[test]
fn the_submit_marker_is_not_a_submitted_answer() {
let entry = json!({ "metadata": { "room": "101", "greentic_submit": "true" } });
let fields = submitted_fields(&entry);
assert!(fields.contains_key("room"));
assert!(!fields.contains_key("greentic_submit"));
}
#[test]
fn a_card_input_named_like_a_stamped_key_with_its_own_value_is_a_submit() {
for (key, value) in [("route", "billing"), ("tenant", "other-corp")] {
let mut click = wrapped_typed_message("");
click["input"]["metadata"] = json!({ key: value });
assert!(is_card_submit(&click), "{key}={value} must count as input");
let flat = click["input"].clone();
assert!(
is_card_submit(&flat),
"flat {key}={value} must count as input"
);
}
let mut typed = wrapped_typed_message("hi");
typed["input"]["metadata"] = json!({ "route": "sess-1", "tenant": "acme" });
assert!(!is_card_submit(&typed));
}
#[test]
fn keys_the_activities_path_never_stamps_are_input() {
for key in ["tenant_id", "conversation_id", "tenant_channel_id"] {
let mut click = wrapped_typed_message("");
click["input"]["metadata"] = json!({ key: "x" });
assert!(is_card_submit(&click), "{key} must count as input");
}
}
#[cfg(feature = "agentic-worker")]
#[test]
fn a_typed_envelope_message_during_a_tool_park_is_not_a_resume_payload() {
let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
awaiting_tool_output(),
json!({ "reply": "that is outside my scope", "trail": [], "terminated_by": "final_reply" }),
]));
let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
let rt = Runtime::new().unwrap();
let first = rt
.block_on(engine.execute(conv_ctx(), wrapped_typed_message("book a room")))
.unwrap();
let FlowStatus::Waiting(wait) = first.status else {
panic!("expected a park");
};
rt.block_on(engine.resume(
conv_ctx(),
wait.snapshot,
wrapped_typed_message("2+2 berapa?"),
))
.unwrap();
assert_eq!(*handler.resumes.lock().unwrap(), vec![None, None]);
}
#[test]
fn is_card_submit_tells_a_submit_from_a_typed_message() {
assert!(is_card_submit(
&json!({ "metadata": { "action": "submit" } })
));
assert!(is_card_submit(
&json!({ "input": { "metadata": { "action": "go" } } })
));
assert!(is_card_submit(&json!({ "room": "101", "metadata": {} })));
assert!(!is_card_submit(&json!({ "text": "never mind" })));
assert!(!is_card_submit(
&json!({ "text": "hi", "metadata": { "action": " " } })
));
}
#[test]
fn pending_tool_await_mark_take_and_legacy_snapshot() {
let mut st = ExecutionState::new(json!({}));
assert!(!st.take_tool_await("agent"));
st.mark_tool_await("agent");
let back: ExecutionState =
serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap();
let mut back = back;
assert!(back.take_tool_await("agent"), "survives the snapshot");
assert!(!back.take_tool_await("agent"), "take clears it");
let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
let legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
assert!(legacy.pending_tool_await.is_empty());
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_force_advances_after_park_loop_cap() {
let engine = conv_engine(
conversational_dw_flow(true),
json!({ "reply": "still thinking", "trail": [], "terminated_by": "final_reply" }),
);
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
let mut snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting after turn 1, got {other:?}"),
};
for turn in 2..MAX_PARK_TURNS {
let result = rt
.block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
.unwrap();
snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting at turn {turn}, got {other:?}"),
};
}
let result = rt
.block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
.unwrap();
assert!(
matches!(result.status, FlowStatus::Completed),
"park-loop cap must force-advance to the successor at turn {MAX_PARK_TURNS}, got {:?}",
result.status
);
}
#[cfg(feature = "agentic-worker")]
struct ScriptedNatsDispatcher {
calls: Mutex<Vec<crate::runner::remote_dispatch::RemoteDispatch>>,
}
#[cfg(feature = "agentic-worker")]
#[async_trait::async_trait]
impl crate::runner::remote_dispatch::RemoteDispatchHandler for ScriptedNatsDispatcher {
async fn dispatch(
&self,
request: crate::runner::remote_dispatch::RemoteDispatch,
) -> anyhow::Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
let correlation_id = request.correlation_id.clone();
self.calls.lock().unwrap().push(request);
Ok(
crate::runner::remote_dispatch::RemoteDispatchAction::AwaitingResponse {
correlation_id,
},
)
}
}
#[cfg(feature = "agentic-worker")]
fn nats_conv_engine(
flow: HostFlow,
dispatcher: std::sync::Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
) -> FlowEngine {
FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "conv.flow".to_string(),
},
flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: Some(dispatcher),
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::Nats,
agent_node_handler: None,
graph_node_handler: None,
mcp_tool_source: None,
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
}
}
#[cfg(feature = "agentic-worker")]
fn agent_response_envelope(reply: &str, terminated_by: &str) -> Value {
json!({
"ok": true,
"output": { "reply": reply, "trail": [], "terminated_by": terminated_by },
"events": [],
"error": Value::Null,
})
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_nats_turn1_parks_via_await_here() {
let dispatcher = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting after fresh dispatch, got {other:?}"),
};
assert_eq!(
snapshot.next_node, "agent",
"AwaitHere must resume at self, not the routing successor"
);
assert_eq!(
dispatcher.calls.lock().unwrap().len(),
1,
"a fresh user turn must dispatch to NATS exactly once"
);
assert_eq!(
result.output,
Value::Null,
"no reply is known yet on the initial dispatch — the async response hasn't arrived"
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_nats_park_loop_full_turn_cycle() {
let dispatcher = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting (AwaitHere) after turn 1 dispatch, got {other:?}"),
};
assert_eq!(snapshot.next_node, "agent");
assert_eq!(dispatcher.calls.lock().unwrap().len(), 1);
let result = rt
.block_on(engine.resume(
conv_ctx(),
snapshot,
agent_response_envelope("hello there", "final_reply"),
))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting (LoopHere) after not-ended response, got {other:?}"),
};
assert_eq!(
snapshot.next_node, "agent",
"LoopHere also re-enters the node itself"
);
assert!(
serde_json::to_string(&result.output)
.unwrap()
.contains("hello there"),
"the agent's reply must be surfaced once the response resume lands: {:?}",
result.output
);
assert_eq!(
dispatcher.calls.lock().unwrap().len(),
1,
"the response landing must not itself trigger another NATS dispatch"
);
let result = rt
.block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "user says more" })))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting (AwaitHere) after turn 2 dispatch, got {other:?}"),
};
assert_eq!(snapshot.next_node, "agent");
assert_eq!(
dispatcher.calls.lock().unwrap().len(),
2,
"a second fresh user turn must dispatch to NATS again"
);
let result = rt
.block_on(engine.resume(
conv_ctx(),
snapshot,
agent_response_envelope("bye", "conversation_ended"),
))
.unwrap();
assert!(
matches!(result.status, FlowStatus::Completed),
"conversation_ended response must advance to the successor and complete, got {:?}",
result.status
);
assert_eq!(
dispatcher.calls.lock().unwrap().len(),
2,
"conversation end must not trigger another NATS dispatch"
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_nats_force_advances_after_park_loop_cap() {
let dispatcher = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
let mut snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
};
for turn in 1..MAX_PARK_TURNS {
let result = rt
.block_on(engine.resume(
conv_ctx(),
snapshot,
agent_response_envelope("still thinking", "final_reply"),
))
.unwrap();
snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting (LoopHere) at response #{turn}, got {other:?}"),
};
let result = rt
.block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
.unwrap();
snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => {
panic!("expected Waiting (AwaitHere) after user turn #{turn}, got {other:?}")
}
};
}
let result = rt
.block_on(engine.resume(
conv_ctx(),
snapshot,
agent_response_envelope("still thinking", "final_reply"),
))
.unwrap();
assert!(
matches!(result.status, FlowStatus::Completed),
"park-loop cap must force-advance to the successor at response {MAX_PARK_TURNS}, got {:?}",
result.status
);
assert_eq!(
dispatcher.calls.lock().unwrap().len(),
1 + (MAX_PARK_TURNS as usize - 1),
"exactly one NATS dispatch per user turn across the whole park-loop"
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_nats_and_inprocess_transcripts_match_for_same_script() {
let rt = Runtime::new().unwrap();
let inproc_handler = Arc::new(ScriptedAgentHandler {
script: Mutex::new(std::collections::VecDeque::from(vec![
json!({ "reply": "hello there", "trail": [], "terminated_by": "final_reply" }),
json!({ "reply": "bye", "trail": [], "terminated_by": "conversation_ended" }),
])),
});
let inproc_engine = conv_engine_scripted(conversational_dw_flow(true), inproc_handler);
let r1 = rt
.block_on(inproc_engine.execute(conv_ctx(), Value::Null))
.unwrap();
let inproc_snapshot = match r1.status {
FlowStatus::Waiting(ref w) => w.snapshot.clone(),
ref other => panic!("in-process turn 1: expected Waiting, got {other:?}"),
};
let r2 = rt
.block_on(inproc_engine.resume(conv_ctx(), inproc_snapshot, json!({ "text": "more" })))
.unwrap();
let dispatcher = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let nats_engine = nats_conv_engine(conversational_dw_flow(true), dispatcher);
let n1 = rt
.block_on(nats_engine.execute(conv_ctx(), Value::Null))
.unwrap();
let n1_snapshot = match n1.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("nats turn 1 dispatch: expected Waiting, got {other:?}"),
};
let n1r = rt
.block_on(nats_engine.resume(
conv_ctx(),
n1_snapshot,
agent_response_envelope("hello there", "final_reply"),
))
.unwrap();
let n1r_snapshot = match n1r.status {
FlowStatus::Waiting(ref w) => w.snapshot.clone(),
ref other => panic!("nats turn 1 response resume: expected Waiting, got {other:?}"),
};
let n2 = rt
.block_on(nats_engine.resume(conv_ctx(), n1r_snapshot, json!({ "text": "more" })))
.unwrap();
let n2_snapshot = match n2.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("nats turn 2 dispatch: expected Waiting, got {other:?}"),
};
let n2r = rt
.block_on(nats_engine.resume(
conv_ctx(),
n2_snapshot,
agent_response_envelope("bye", "conversation_ended"),
))
.unwrap();
assert!(matches!(r1.status, FlowStatus::Waiting(_)));
assert!(
matches!(n1r.status, FlowStatus::Waiting(_)),
"nats turn 1's user-visible status must also be Waiting"
);
assert!(matches!(r2.status, FlowStatus::Completed));
assert!(
matches!(n2r.status, FlowStatus::Completed),
"nats turn 2 must also complete, matching the in-process transcript"
);
assert!(
serde_json::to_string(&r1.output)
.unwrap()
.contains("hello there"),
"in-process turn 1 must surface the reply: {:?}",
r1.output
);
assert!(
serde_json::to_string(&n1r.output)
.unwrap()
.contains("hello there"),
"nats turn 1 must surface the identical reply once the response resume lands: {:?}",
n1r.output
);
}
#[cfg(feature = "agentic-worker")]
fn agent_error_envelope(message: &str, code: Option<&str>) -> Value {
json!({
"ok": false,
"output": Value::Null,
"events": [],
"error": { "code": code, "message": message },
})
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_nats_interleaved_user_message_is_not_misread_as_response() {
let dispatcher = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
};
assert!(
snapshot.state.pending_agent_await.contains_key("agent"),
"turn 1 dispatch must mark the pending await"
);
assert_eq!(dispatcher.calls.lock().unwrap().len(), 1);
let result = rt
.block_on(engine.resume(
conv_ctx(),
snapshot,
json!({ "text": "are you still there?" }),
))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!(
"a stray user message must re-dispatch as a fresh turn (Waiting/AwaitHere), got {other:?}"
),
};
assert_eq!(
snapshot.next_node, "agent",
"the fresh re-dispatch still awaits at self"
);
assert_eq!(
dispatcher.calls.lock().unwrap().len(),
2,
"the stray user message must trigger its OWN fresh NATS dispatch, not be swallowed"
);
assert!(
snapshot.state.pending_agent_await.contains_key("agent"),
"the marker must still be set for the real response to land against"
);
assert_eq!(
result.output,
Value::Null,
"no reply is surfaced — this was not a misread null agent turn"
);
assert!(
!snapshot.state.park_turns.contains_key("agent"),
"a stray user message must not touch the park-loop cap"
);
}
#[cfg(feature = "agentic-worker")]
#[test]
fn conversational_dw_agent_nats_error_envelope_surfaces_and_reparks_without_cap_bump() {
let dispatcher = Arc::new(ScriptedNatsDispatcher {
calls: Mutex::new(vec![]),
});
let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
let rt = Runtime::new().unwrap();
let result = rt
.block_on(engine.execute(conv_ctx(), Value::Null))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
};
let result = rt
.block_on(engine.resume(conv_ctx(), snapshot, agent_error_envelope("boom", None)))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("an error envelope must re-park (Waiting/LoopHere), got {other:?}"),
};
assert_eq!(
snapshot.next_node, "agent",
"LoopHere re-enters the node itself"
);
assert!(
serde_json::to_string(&result.output)
.unwrap()
.contains("boom"),
"the error message must be surfaced as the reply: {:?}",
result.output
);
assert!(
!snapshot.state.park_turns.contains_key("agent"),
"an error response must NOT bump the park-loop cap counter"
);
let result = rt
.block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "hello?" })))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting (AwaitHere) after user turn, got {other:?}"),
};
assert_eq!(dispatcher.calls.lock().unwrap().len(), 2);
let result = rt
.block_on(engine.resume(
conv_ctx(),
snapshot,
agent_error_envelope("timeout waiting for agent response", Some("timeout")),
))
.unwrap();
let snapshot = match result.status {
FlowStatus::Waiting(w) => w.snapshot,
other => {
panic!("a timeout envelope must also re-park (Waiting/LoopHere), got {other:?}")
}
};
assert!(
serde_json::to_string(&result.output)
.unwrap()
.contains("timeout waiting for agent response"),
"the timeout message must be surfaced as the reply: {:?}",
result.output
);
assert!(
!snapshot.state.park_turns.contains_key("agent"),
"two error/timeout responses in a row (with an intervening user turn) must still \
not have bumped the park-loop cap counter"
);
}
#[cfg(feature = "agentic-worker")]
struct ScriptedAgentHandler {
script: Mutex<std::collections::VecDeque<serde_json::Value>>,
}
#[cfg(feature = "agentic-worker")]
#[async_trait::async_trait]
impl crate::runner::agent_node::AgentNodeHandler for ScriptedAgentHandler {
async fn execute(
&self,
_tenant_id: &str,
_env_id: &str,
_agent_id: &str,
_session_id: &str,
_flow_input: &serde_json::Value,
_conversational: bool,
_caller: Option<&serde_json::Value>,
) -> anyhow::Result<serde_json::Value> {
Ok(self
.script
.lock()
.unwrap()
.pop_front()
.expect("ScriptedAgentHandler: script exhausted"))
}
}
#[cfg(feature = "agentic-worker")]
fn conv_engine_scripted(
flow: HostFlow,
handler: std::sync::Arc<ScriptedAgentHandler>,
) -> FlowEngine {
FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "conv.flow".to_string(),
},
flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
agent_node_handler: Some(handler),
graph_node_handler: None,
mcp_tool_source: None,
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
}
}
struct StubOperalaHandler {
payload: serde_json::Value,
}
#[async_trait::async_trait]
impl crate::runner::operala_node::OperalaNodeHandler for StubOperalaHandler {
async fn execute(
&self,
_tenant: &str,
_env: &str,
_target: &str,
_operation: &str,
_session_id: &str,
_input: &serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
Ok(self.payload.clone())
}
}
#[derive(Clone, Debug)]
struct OperalaCallRecord {
tenant: String,
env: String,
target: String,
operation: String,
session_id: String,
input: serde_json::Value,
}
#[derive(Default)]
struct RecordingOperalaHandler {
calls: std::sync::Mutex<Vec<OperalaCallRecord>>,
}
#[async_trait::async_trait]
impl crate::runner::operala_node::OperalaNodeHandler for RecordingOperalaHandler {
async fn execute(
&self,
tenant: &str,
env: &str,
target: &str,
operation: &str,
session_id: &str,
input: &serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
self.calls
.lock()
.map_err(|_| anyhow::anyhow!("recording handler lock poisoned"))?
.push(OperalaCallRecord {
tenant: tenant.to_string(),
env: env.to_string(),
target: target.to_string(),
operation: operation.to_string(),
session_id: session_id.to_string(),
input: input.clone(),
});
Ok(json!({ "ok": true, "reply": "recorded" }))
}
}
fn operala_flow(target: &str) -> HostFlow {
operala_flow_with_payload(
target,
json!({ "operation": "", "input": { "goal": "hi" } }),
)
}
fn operala_flow_with_payload(target: &str, payload_expr: Value) -> HostFlow {
let mut nodes = IndexMap::new();
let node_id = NodeId::from_str("op").unwrap();
nodes.insert(
node_id.clone(),
HostNode {
kind: NodeKind::OperalaCall {
target: target.to_string(),
},
component: "operala.call".to_string(),
component_id: "operala.call".to_string(),
operation_name: Some(target.to_string()),
operation_in_mapping: None,
payload_expr,
routing: Routing::End,
vars_out: None,
response_timeout_secs: None,
},
);
HostFlow {
slot_schema: None,
id: "operala.flow".to_string(),
start: Some(node_id),
nodes,
vars_init: JsonMap::new(),
required_vars: Vec::new(),
}
}
fn operala_engine(
flow: HostFlow,
handler: Option<std::sync::Arc<dyn crate::runner::operala_node::OperalaNodeHandler>>,
) -> FlowEngine {
FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: "test-pack".to_string(),
flow_id: "operala.flow".to_string(),
},
flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: handler,
}
}
fn operala_ctx<'a>() -> FlowContext<'a> {
FlowContext {
tenant: "demo",
pack_id: "test-pack",
flow_id: "operala.flow",
node_id: None,
tool: None,
action: None,
session_id: Some("sess-op"),
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
}
}
#[test]
fn operala_call_with_in_process_handler_completes_inline() {
let handler = std::sync::Arc::new(StubOperalaHandler {
payload: json!({ "reply": "stub" }),
});
let engine = operala_engine(operala_flow("deep_worker"), Some(handler));
let execution = tokio::runtime::Runtime::new()
.unwrap()
.block_on(engine.execute(operala_ctx(), Value::Null))
.expect("operala.call with an in-process handler must complete");
assert!(matches!(execution.status, FlowStatus::Completed));
assert_eq!(execution.output, json!({ "reply": "stub" }));
}
#[test]
fn operala_call_hands_the_handler_run_and_the_nodes_input() {
let deep_worker = json!({ "iterationBudget": 3, "reflection": false, "delegation": false });
let recorder = std::sync::Arc::new(RecordingOperalaHandler::default());
let engine = operala_engine(
operala_flow_with_payload(
"w1",
json!({
"operation": "invoke",
"input": { "goal": "summarise the quarter", "deep_worker": deep_worker.clone() }
}),
),
Some(recorder.clone()),
);
let execution = tokio::runtime::Runtime::new()
.unwrap()
.block_on(engine.execute(operala_ctx(), Value::Null))
.expect("operala.call with an in-process handler must complete");
assert!(matches!(execution.status, FlowStatus::Completed));
let calls = recorder.calls.lock().unwrap().clone();
assert_eq!(calls.len(), 1, "exactly one dispatch: {calls:?}");
let call = &calls[0];
assert_eq!(call.operation, "run", "invoke must be normalised to run");
assert_eq!(call.target, "w1");
assert_eq!(call.tenant, "demo");
assert_eq!(call.env, "local");
assert_eq!(call.session_id, "sess-op");
assert_eq!(call.input["goal"], json!("summarise the quarter"));
assert_eq!(
call.input["deep_worker"], deep_worker,
"settings must reach the invoker verbatim"
);
assert!(
call.input.get("operation").is_none(),
"the handler gets payload.input, not the envelope"
);
}
#[test]
fn operala_call_without_handler_or_nats_fails() {
let engine = operala_engine(operala_flow("deep_worker"), None);
let execution = tokio::runtime::Runtime::new()
.unwrap()
.block_on(engine.execute(operala_ctx(), Value::Null))
.expect("session flow returns a completed error envelope, not an Err");
assert!(matches!(execution.status, FlowStatus::Completed));
let msg = execution.output["metadata"]["error_message"]
.as_str()
.unwrap_or_default();
assert!(
msg.contains("operala.call node dispatched but no RemoteDispatchHandler configured"),
"unexpected output: {:?}",
execution.output
);
}
#[test]
fn submitted_fields_reads_root_inputs_on_the_demo_path() {
let entry = json!({
"amount": "500",
"reason": "looks good",
"metadata": { "action": "approve" }
});
let fields = submitted_fields(&entry);
assert_eq!(fields.get("amount"), Some(&json!("500")));
assert_eq!(fields.get("reason"), Some(&json!("looks good")));
assert!(
!fields.contains_key("metadata"),
"the envelope key is not a field"
);
assert!(
!fields.contains_key("action"),
"the route discriminator is not a field"
);
}
#[test]
fn submitted_fields_reads_metadata_on_the_wrapped_path() {
let entry = json!({
"input": {
"metadata": { "action": "approve", "email": "a@b.c" },
"text": "hi"
}
});
let fields = submitted_fields(&entry);
assert_eq!(fields.get("email"), Some(&json!("a@b.c")));
assert!(!fields.contains_key("action"));
assert!(!fields.contains_key("text"), "envelope text is not a field");
assert!(
!fields.contains_key("input"),
"the envelope root must be resolved, or `input` becomes one giant field"
);
}
#[test]
fn submitted_fields_lets_the_envelope_root_win_a_collision() {
let entry = json!({
"email": "root@x",
"metadata": { "action": "go", "email": "meta@x" }
});
assert_eq!(
submitted_fields(&entry).get("email"),
Some(&json!("root@x"))
);
}
#[test]
fn submitted_fields_counts_a_root_input_named_action() {
let entry = json!({ "action": "typed", "metadata": { "action": "approve" } });
assert_eq!(
submitted_fields(&entry).get("action"),
Some(&json!("typed"))
);
}
#[test]
fn submitted_fields_is_empty_for_a_button_with_no_inputs() {
let entry = json!({ "metadata": { "action": "approve" } });
assert!(submitted_fields(&entry).is_empty());
}
fn plain_card_node() -> HostNode {
HostNode {
kind: NodeKind::Exec {
target_component: "card".to_string(),
},
component: "component.exec".to_string(),
component_id: "component.exec".to_string(),
operation_name: None,
operation_in_mapping: None,
payload_expr: Value::Null,
routing: Routing::End,
vars_out: None,
response_timeout_secs: None,
}
}
#[test]
fn an_old_snapshot_without_the_flag_deserializes_as_not_awaiting_submit() {
let raw = json!({
"pack_id": "p",
"flow_id": "f",
"next_node": "card",
"state": {}
});
let snap: FlowSnapshot = serde_json::from_value(raw).expect("legacy snapshot decodes");
assert!(!snap.awaiting_submit);
}
#[test]
fn submitted_answers_survive_the_resume_redispatch_and_reach_a_later_node() {
let mut state = ExecutionState::new(json!({}));
state.nodes.insert(
"card".to_string(),
NodeOutput::new(json!({ "event": "rendered" })),
);
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&json!({
"email": "a@b.c",
"metadata": { "action": "submit" }
})),
});
let mut fresh = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut fresh);
state.nodes.insert("card".to_string(), fresh);
let ctx = template_context(&state, Value::Null);
let rendered = render_template_value(
&json!("{{node.card.answers.email}}"),
&ctx,
TemplateOptions::default(),
)
.expect("render");
assert_eq!(rendered, json!("a@b.c"));
}
#[test]
fn the_card_render_context_carries_the_answers_too() {
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&json!({ "email": "a@b.c" })),
});
let mut output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
state.nodes.insert("card".to_string(), output);
let ctx = state.context();
assert_eq!(
ctx["nodes"]["card"]["payload"]["answers"]["email"],
json!("a@b.c")
);
}
#[test]
fn answers_are_absent_before_any_submit() {
let mut state = ExecutionState::new(json!({}));
let mut output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
assert!(output.payload.get("answers").is_none());
}
#[test]
fn a_button_with_no_inputs_yields_an_empty_answers_object() {
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&json!({ "metadata": { "action": "approve" } })),
});
let mut output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
assert_eq!(output.payload["answers"], json!({}));
}
#[test]
fn the_pending_answers_are_consumed_exactly_once() {
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&json!({ "email": "a@b.c" })),
});
let mut first = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut first);
assert!(first.payload.get("answers").is_some());
let mut second = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut second);
assert!(
second.payload.get("answers").is_none(),
"consumed, not read"
);
}
#[test]
fn answers_attach_even_when_the_redispatch_failed() {
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&json!({ "email": "a@b.c" })),
});
let mut output = NodeOutput::new(json!({ "ok": false, "error": { "code": "boom" } }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
assert_eq!(output.payload["answers"]["email"], json!("a@b.c"));
}
#[test]
fn answers_are_not_attached_to_a_different_node() {
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&json!({ "email": "a@b.c" })),
});
let mut other = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "next_step", &plain_card_node(), &mut other);
assert!(other.payload.get("answers").is_none());
assert!(
state.pending_card_answers.is_some(),
"still pending for its own node"
);
}
#[test]
fn answers_intersect_the_declared_allow_list_on_a_wrapped_start_envelope() {
let entry = json!({
"input": {
"id": "msg-1",
"tenant": "acme",
"channel": "webchat",
"session_id": "sess-1",
"from": "user-1",
"to": "bot-1",
"correlation_id": "corr-1",
"attachments": [],
"metadata": {
"action": "submit",
"nextCardId": "confirm",
"route": "default",
"env": "prod",
"team": "support",
"locale": "en-US",
"autoStart": true,
"url": "https://api.example.com",
"model": "gpt-4",
"provider": "openai",
"api_key_secret": "secrets://tenant/acme/openai_key",
"full_name": "Ada Lovelace",
"email": "ada@example.com"
},
"text": "submitted"
}
});
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&entry),
});
let node = HostNode {
payload_expr: json!({ "answer_fields": ["full_name", "email"] }),
..plain_card_node()
};
let mut output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &node, &mut output);
let answers = output.payload["answers"]
.as_object()
.expect("answers must be an object");
assert_eq!(
answers,
&serde_json::Map::from_iter([
("full_name".to_string(), json!("Ada Lovelace")),
("email".to_string(), json!("ada@example.com")),
]),
"answers must contain exactly the two declared card inputs, and \
nothing from transport identity, routing, or pack config: {answers:?}"
);
}
#[test]
fn answer_fields_absent_keeps_todays_permissive_behaviour() {
let entry = json!({
"input": {
"tenant": "acme",
"metadata": { "action": "submit", "email": "a@b.c" },
"text": "hi"
}
});
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&entry),
});
let mut output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
assert_eq!(output.payload["answers"]["tenant"], json!("acme"));
assert_eq!(output.payload["answers"]["email"], json!("a@b.c"));
}
#[test]
fn answer_fields_declared_empty_yields_no_answers() {
let mut state = ExecutionState::new(json!({}));
state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&json!({
"email": "a@b.c",
"metadata": { "action": "approve" }
})),
});
let node = HostNode {
payload_expr: json!({ "answer_fields": [] }),
..plain_card_node()
};
let mut output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(&mut state, "card", &node, &mut output);
assert_eq!(output.payload["answers"], json!({}));
}
#[test]
fn absent_and_malformed_answer_fields_both_stay_permissive_but_declared_filters() {
let entry = json!({ "email": "a@b.c", "phone": "555-1234" });
let mut absent_state = ExecutionState::new(json!({}));
absent_state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&entry),
});
let mut absent_output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(
&mut absent_state,
"card",
&plain_card_node(),
&mut absent_output,
);
assert_eq!(
absent_output.payload["answers"],
json!({ "email": "a@b.c", "phone": "555-1234" }),
"absent must stay fully permissive"
);
let mut malformed_state = ExecutionState::new(json!({}));
malformed_state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&entry),
});
let malformed_node = HostNode {
payload_expr: json!({ "answer_fields": "{{unresolved.template}}" }),
..plain_card_node()
};
let mut malformed_output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(
&mut malformed_state,
"card",
&malformed_node,
&mut malformed_output,
);
assert_eq!(
malformed_output.payload["answers"],
json!({ "email": "a@b.c", "phone": "555-1234" }),
"malformed must ALSO stay fully permissive, same as absent"
);
let mut declared_state = ExecutionState::new(json!({}));
declared_state.pending_card_answers = Some(PendingCardAnswers {
node_id: "card".to_string(),
answers: submitted_fields(&entry),
});
let declared_node = HostNode {
payload_expr: json!({ "answer_fields": ["email"] }),
..plain_card_node()
};
let mut declared_output = NodeOutput::new(json!({ "event": "rendered" }));
attach_pending_card_answers(
&mut declared_state,
"card",
&declared_node,
&mut declared_output,
);
assert_eq!(
declared_output.payload["answers"],
json!({ "email": "a@b.c" }),
"declared must filter down to exactly the allow-listed keys"
);
}
#[test]
fn pending_from_snapshot_names_next_node_when_awaiting_submit() {
let snapshot = FlowSnapshot {
pack_id: "p".to_string(),
flow_id: "f".to_string(),
next_flow: None,
next_node: "card".to_string(),
awaiting_submit: true,
state: ExecutionState::new(json!({})),
};
let input = json!({ "email": "a@b.c", "metadata": { "action": "submit" } });
let pending = pending_from_snapshot(&snapshot, &input).expect("should park answers");
assert_eq!(pending.node_id, "card");
assert_eq!(pending.answers.get("email"), Some(&json!("a@b.c")));
}
#[test]
fn pending_from_snapshot_is_none_when_not_awaiting_submit() {
let snapshot = FlowSnapshot {
pack_id: "p".to_string(),
flow_id: "f".to_string(),
next_flow: None,
next_node: "successor".to_string(),
awaiting_submit: false,
state: ExecutionState::new(json!({})),
};
let input = json!({ "email": "a@b.c" });
assert!(pending_from_snapshot(&snapshot, &input).is_none());
}
fn card_answers_flow() -> Flow {
let card_id = NodeId::from_str("card").unwrap();
let next_id = NodeId::from_str("next").unwrap();
let card_node = Node {
id: card_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "event": "rendered" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::Custom(json!([
{ "condition": "response.action == \"submit\"", "to": next_id.to_string() }
])),
telemetry: TelemetryHints::default(),
conversational: false,
};
let next_node = Node {
id: next_id.clone(),
component: FlowComponentRef {
id: "emit.log".parse().unwrap(),
pack_alias: None,
operation: None,
},
input: InputMapping {
mapping: json!({ "got_email": "{{node.card.answers.email}}" }),
},
output: OutputMapping {
mapping: Value::Null,
},
err_map: None,
routing: Routing::End,
telemetry: TelemetryHints::default(),
conversational: false,
};
let mut nodes = indexmap::IndexMap::default();
nodes.insert(card_id.clone(), card_node);
nodes.insert(next_id.clone(), next_node);
Flow {
schema_version: "1.0".into(),
id: FlowId::from_str("card.answers.flow").unwrap(),
kind: FlowKind::Messaging,
entrypoints: BTreeMap::from([(
"default".to_string(),
Value::String(card_id.to_string()),
)]),
nodes,
metadata: FlowMetadata {
title: None,
description: None,
tags: Default::default(),
extra: json!({}),
},
}
}
#[test]
fn card_answers_survive_a_real_park_and_resume_and_reach_a_later_node() {
let flow = card_answers_flow();
let host_flow = HostFlow::from(flow);
let flow_id = "card.answers.flow";
let pack_id = "test-pack";
let engine = FlowEngine {
messaging_provider_pack_ids: Default::default(),
rollout_ids: RolloutIds::default(),
packs: Vec::new(),
flows: Vec::new(),
flow_sources: StdHashMap::new(),
flow_cache: RwLock::new(StdHashMap::from([(
FlowKey {
pack_id: pack_id.to_string(),
flow_id: flow_id.to_string(),
},
host_flow,
)])),
default_env: "local".to_string(),
validation: ValidationConfig {
mode: ValidationMode::Off,
},
cross_pack_resolver: None,
approval_dispatch_handler: None,
remote_dispatch_handler: None,
#[cfg(feature = "agentic-worker")]
dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
#[cfg(feature = "agentic-worker")]
agent_node_handler: None,
#[cfg(feature = "agentic-worker")]
graph_node_handler: None,
#[cfg(feature = "agentic-worker")]
mcp_tool_source: None,
#[cfg(feature = "agentic-worker")]
mcp_secrets: None,
#[cfg(feature = "agentic-worker")]
a2a_sources: RwLock::new(HashMap::new()),
operala_node_handler: None,
};
let rt = Runtime::new().unwrap();
let ctx1 = FlowContext {
tenant: "demo",
pack_id,
flow_id,
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let result1 = rt.block_on(engine.execute(ctx1, Value::Null)).unwrap();
let snapshot = match result1.status {
FlowStatus::Waiting(w) => w.snapshot,
other => panic!("expected Waiting at the card node, got {other:?}"),
};
assert!(
snapshot.awaiting_submit,
"the card's conditional fall-through must set awaiting_submit"
);
assert_eq!(snapshot.next_node, "card");
let ctx2 = FlowContext {
tenant: "demo",
pack_id,
flow_id,
node_id: None,
tool: None,
action: None,
session_id: None,
provider_id: None,
reply_scope: None,
retry_config: RetryConfig {
max_attempts: 1,
base_delay_ms: 1,
},
attempt: 1,
observer: None,
mocks: None,
caller: None,
};
let input = json!({ "email": "a@b.c", "metadata": { "action": "submit" } });
let result2 = rt.block_on(engine.resume(ctx2, snapshot, input)).unwrap();
assert!(
matches!(result2.status, FlowStatus::Completed),
"the submit must route past the card to `next`"
);
assert_eq!(
result2.node_outputs["card"]["answers"]["email"],
json!("a@b.c"),
"the card's own re-dispatched output must carry the merged answers"
);
assert_eq!(
result2.node_outputs["next"]["got_email"],
json!("a@b.c"),
"`next`, a LATER node, must read the answers through {{node.card.answers.email}}"
);
}
}
use tracing::Instrument;
pub struct FlowContext<'a> {
pub tenant: &'a str,
pub pack_id: &'a str,
pub flow_id: &'a str,
pub node_id: Option<&'a str>,
pub tool: Option<&'a str>,
pub action: Option<&'a str>,
pub session_id: Option<&'a str>,
pub provider_id: Option<&'a str>,
pub reply_scope: Option<&'a greentic_types::ReplyScope>,
pub retry_config: RetryConfig,
pub attempt: u32,
pub observer: Option<&'a dyn ExecutionObserver>,
pub mocks: Option<&'a MockLayer>,
pub caller: Option<&'a serde_json::Value>,
}
#[derive(Copy, Clone)]
pub struct RetryConfig {
pub max_attempts: u32,
pub base_delay_ms: u64,
}
fn lift_first_node_error_from_nodes(output: Value, nodes: &HashMap<String, NodeOutput>) -> Value {
let Some((node_id, failed)) = nodes.iter().find(|(_, out)| !out.ok) else {
return output;
};
let err_meta = failed.meta.get("error");
let message = err_meta
.and_then(|e| e.get("message"))
.and_then(|v| v.as_str())
.unwrap_or("flow node failed");
let kind = err_meta
.and_then(|e| e.get("kind"))
.and_then(|v| v.as_str())
.unwrap_or("flow_node_failed");
let mut output = match output {
Value::Object(map) => map,
Value::Null => JsonMap::new(),
other => {
let mut wrap = JsonMap::new();
wrap.insert("payload".to_string(), other);
wrap
}
};
let metadata_entry = output
.entry("metadata".to_string())
.or_insert_with(|| Value::Object(JsonMap::new()));
let metadata_map = match metadata_entry {
Value::Object(map) => map,
_ => {
*metadata_entry = Value::Object(JsonMap::new());
metadata_entry.as_object_mut().unwrap()
}
};
metadata_map
.entry("error_kind".to_string())
.or_insert(Value::String(kind.to_string()));
metadata_map
.entry("error_message".to_string())
.or_insert(Value::String(message.to_string()));
metadata_map
.entry("node_id".to_string())
.or_insert(Value::String(node_id.clone()));
Value::Object(output)
}
fn should_retry(err: &anyhow::Error) -> bool {
let lower = err.to_string().to_lowercase();
lower.contains("transient")
|| lower.contains("unavailable")
|| lower.contains("internal")
|| lower.contains("timeout")
}
impl From<FlowRetryConfig> for RetryConfig {
fn from(value: FlowRetryConfig) -> Self {
Self {
max_attempts: value.max_attempts.max(1),
base_delay_ms: value.base_delay_ms.max(50),
}
}
}