graphrt-core 0.8.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
//! `workflow`: runs another workflow as one step (cargo feature `subagents`).
//!
//! ```yaml
//! - id: report
//!   type: workflow
//!   workflow: store-report          # a linked workflow, by name
//!   inputs:
//!     store: "{{#each_store.item#}}"
//!     month: "{{#start.month#}}"
//! ```
//!
//! Unlike `subagents` of an `agent`, nothing is left to a model: the node always
//! starts the named workflow with the given inputs, as a child run of the same
//! run ([`crate::node::ChildRuns`]). The child gets its inputs, the parent's
//! `sys` values and its own environment, nothing else of the parent. It shares
//! the step and token budgets, the deadline, the depth limit (so a workflow that
//! calls itself stops there) and the control signals, and a child that pauses
//! pauses the parent: resuming the run resumes the child where it stopped.
//!
//! Outputs: the child's run outputs (what its `end` and `answer` nodes give),
//! by their own names. Inside an `iteration` every item starts its own child.

use futures::future::BoxFuture;
use indexmap::IndexMap;
use serde::Deserialize;

use crate::dsl::NodeDoc;
use crate::node::{
    CHILD_PAUSE, ChildRequest, ConfigError, Node, NodeContext, NodeError, NodeOutcome, NodeOutput, NodeResult,
    PauseRequest, SubgraphResult,
};
use crate::pool::{SYS, Selector, VariablePool};
use crate::snapshot::FrameSnapshot;
use crate::template::Template;
use crate::value::Value;

/// The node kind.
pub const KIND: &str = "workflow";

/// `workflow` configuration.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct WorkflowConfig {
    workflow: String,
    #[serde(default)]
    inputs: IndexMap<String, serde_json::Value>,
}

/// The `workflow` node.
#[derive(Debug)]
pub(crate) struct WorkflowNode {
    workflow: String,
    inputs: IndexMap<String, serde_json::Value>,
    selectors: Vec<Selector>,
}

/// What a paused node keeps until it is resumed: its waiting child.
#[derive(Debug, serde::Serialize, Deserialize)]
struct Waiting {
    snapshot: FrameSnapshot,
}

/// Whether `name` can name a linked workflow: it becomes a segment of frame ids.
pub fn is_workflow_name(name: &str) -> bool {
    !name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

impl WorkflowNode {
    pub(crate) fn new(doc: &NodeDoc) -> Result<Self, ConfigError> {
        let raw = serde_json::Value::Object(doc.config.clone());
        let config: WorkflowConfig = serde_json::from_value(raw).map_err(|e| ConfigError::new(doc, e.to_string()))?;
        if !is_workflow_name(&config.workflow) {
            return Err(ConfigError::new(
                doc,
                format!(
                    "workflow: `{}` is not a workflow name (letters, digits, `_` and `-`, the file name without \
                     its extension)",
                    config.workflow
                ),
            )
            .at_field("workflow"));
        }
        let mut selectors = Vec::new();
        for value in config.inputs.values() {
            collect_selectors(value, &mut selectors);
        }
        Ok(Self { workflow: config.workflow, inputs: config.inputs, selectors })
    }

    /// The child's inputs: every string with placeholders rendered (exactly one
    /// placeholder keeps the value's type).
    fn render_inputs(&self, pool: &VariablePool) -> IndexMap<String, Value> {
        self.inputs.iter().map(|(name, value)| (name.clone(), render(value, pool))).collect()
    }

    fn finish(&self, ctx: &NodeContext, result: SubgraphResult) -> NodeResult {
        match result {
            SubgraphResult::Completed { outputs, .. } => {
                let mut output = NodeOutput::new();
                for (name, value) in outputs {
                    output = output.with(name, value);
                }
                Ok(NodeOutcome::Completed(output))
            }
            // The run stops (aborted, or a limit of the run): the child failed for that reason.
            SubgraphResult::Failed { error, .. } if ctx.children.as_ref().is_some_and(|c| c.run_stopped()) => {
                Err(error)
            }
            SubgraphResult::Failed { error, .. } => {
                let message = format!("workflow `{}`: {}", self.workflow, error.message);
                Err(NodeError { message, ..error })
            }
            SubgraphResult::Paused { snapshot, reasons } => {
                let state = serde_json::to_value(Waiting { snapshot })
                    .map_err(|e| NodeError::fatal("workflow_state", format!("cannot save the child run: {e}")))?;
                let data = Value::from_json(serde_json::json!({
                    "workflow": self.workflow,
                    "reasons": reasons.iter().map(|r| r.kind.clone()).collect::<Vec<_>>(),
                }));
                // The nodes inside the child reported why: this node passes it on.
                Ok(NodeOutcome::Paused(PauseRequest { kind: CHILD_PAUSE.to_owned(), data, state }))
            }
        }
    }
}

impl Node for WorkflowNode {
    fn inputs(&self) -> Vec<Selector> {
        self.selectors.clone()
    }

    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
        Box::pin(async move {
            let Some(children) = ctx.children.clone() else {
                return Err(NodeError::fatal(
                    "unknown_workflow",
                    format!(
                        "workflow `{}` is not linked to this run (`graphrt run` finds `{0}.yaml` next to the \
                         workflow, `graphrt serve` serves it from the same folder)",
                        self.workflow
                    ),
                ));
            };
            let request = match ctx.resume.as_ref() {
                Some(resume) => {
                    let waiting: Waiting = serde_json::from_value(resume.state.clone()).map_err(|e| {
                        NodeError::fatal("workflow_state", format!("cannot read the paused child run: {e}"))
                    })?;
                    ChildRequest::resume(self.workflow.clone(), 0, waiting.snapshot)
                }
                None => {
                    let sys: IndexMap<String, Value> = ctx
                        .pool
                        .namespace(SYS)
                        .map(|vars| vars.iter().map(|(name, value)| (name.to_owned(), value.clone())).collect())
                        .unwrap_or_default();
                    ChildRequest::start(self.workflow.clone(), 0, self.render_inputs(&ctx.pool)).with_sys(sys)
                }
            };
            let result = children.run(request).await;
            self.finish(&ctx, result)
        })
    }
}

fn render(value: &serde_json::Value, pool: &VariablePool) -> Value {
    match value {
        serde_json::Value::String(text) if text.contains("{{#") => Template::parse(text).resolve(pool),
        serde_json::Value::Array(items) => Value::array(items.iter().map(|item| render(item, pool))),
        serde_json::Value::Object(fields) => {
            Value::object(fields.iter().map(|(name, item)| (name.as_str(), render(item, pool))))
        }
        other => Value::from_json(other.clone()),
    }
}

fn collect_selectors(value: &serde_json::Value, out: &mut Vec<Selector>) {
    match value {
        serde_json::Value::String(text) if text.contains("{{#") => {
            out.extend(Template::parse(text).selectors().cloned());
        }
        serde_json::Value::Array(items) => items.iter().for_each(|item| collect_selectors(item, out)),
        serde_json::Value::Object(fields) => fields.values().for_each(|item| collect_selectors(item, out)),
        _ => {}
    }
}

/// Check a call of `child` with inputs named `given` (the `inputs` keys of a
/// `workflow` node) against the child's start variables: every name must be
/// one it declares, and every required one must be given.
///
/// @throws String - what is wrong, naming the variable.
pub fn check_call(child: &crate::graph::Graph, given: &[String]) -> Result<(), String> {
    let schema = crate::engine::frame::start_schema(child)?;
    let declared: Vec<&String> =
        schema.get("properties").and_then(serde_json::Value::as_object).map(|p| p.keys().collect()).unwrap_or_default();
    if let Some(unknown) = given.iter().find(|name| !declared.contains(name)) {
        let known: Vec<&str> = declared.iter().map(|name| name.as_str()).collect();
        return Err(format!(
            "it has no start variable `{unknown}` (it takes: {})",
            if known.is_empty() { "none".to_owned() } else { known.join(", ") }
        ));
    }
    let required = schema.get("required").and_then(serde_json::Value::as_array);
    for name in required.into_iter().flatten().filter_map(serde_json::Value::as_str) {
        if !given.iter().any(|given| given == name) {
            return Err(format!("its start variable `{name}` is required and not in `inputs`"));
        }
    }
    Ok(())
}

/// The `workflow` calls of `workflow`: each node's workflow name and the names of its inputs.
pub fn calls(workflow: &crate::dsl::Workflow) -> Vec<(String, String, Vec<String>)> {
    workflow
        .graph
        .nodes
        .iter()
        .filter(|node| node.kind == KIND)
        .filter_map(|node| {
            let name = node.config.get("workflow")?.as_str()?.to_owned();
            let inputs = node
                .config
                .get("inputs")
                .and_then(serde_json::Value::as_object)
                .map(|fields| fields.keys().cloned().collect())
                .unwrap_or_default();
            Some((node.id.clone(), name, inputs))
        })
        .collect()
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;
    use serde_json::json;

    fn node(config: serde_json::Value) -> Result<WorkflowNode, ConfigError> {
        WorkflowNode::new(&NodeDoc::new("call", KIND, config))
    }

    #[test]
    fn the_config_is_checked() {
        let ok = node(json!({"workflow": "store-report", "inputs": {"store": "{{#each.item#}}", "n": 3}})).unwrap();
        assert_eq!(ok.inputs().iter().map(ToString::to_string).collect::<Vec<_>>(), ["each.item"]);
        for bad in
            [json!({}), json!({"workflow": "a/b"}), json!({"workflow": "x", "input": {}}), json!({"workflow": ""})]
        {
            assert!(node(bad.clone()).is_err(), "{bad}");
        }
    }

    #[test]
    fn inputs_keep_the_type_of_a_lone_placeholder() {
        let call = node(json!({"workflow": "w", "inputs": {
            "store": "{{#each.item#}}",
            "label": "Store {{#each.index#}}",
            "nested": {"list": ["{{#each.index#}}", 2]},
            "fixed": true
        }}))
        .unwrap();
        let mut pool = VariablePool::new();
        pool.insert("each", "item", Value::object([("id", Value::from("s-1"))]));
        pool.insert("each", "index", Value::Int(4));
        let inputs = call.render_inputs(&pool);
        assert_eq!(inputs["store"], Value::object([("id", Value::from("s-1"))]));
        assert_eq!(inputs["label"], Value::from("Store 4"));
        assert_eq!(inputs["nested"], Value::object([("list", Value::array([Value::Int(4), Value::Int(2)]))]));
        assert_eq!(inputs["fixed"], Value::Bool(true));
    }

    #[tokio::test]
    async fn without_linked_workflows_the_node_fails_with_how_to_link() {
        let call = node(json!({"workflow": "store-report"})).unwrap();
        let error = call.run(NodeContext::for_test("call", VariablePool::new())).await.unwrap_err();
        assert_eq!(error.kind, "unknown_workflow");
        assert!(error.message.contains("store-report.yaml"), "{}", error.message);
    }
}