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
//! Prompt messages read from files: a message of a node's `prompt_template`
//! may name a `file` instead of writing its `text`.
//!
//! ```yaml
//! prompt_template:
//!   - role: system
//!     file: ../prompts/report-rules.md   # relative to the workflow file
//!     required: true                     # default: a missing or empty file is an error
//!     strip_comments: true               # default: `<!-- ... -->` is taken out
//!   - { role: user, text: "Write the report for {{#start.month#}}." }
//! ```
//!
//! The file is read when the workflow is loaded ([`inline`]), and its text
//! becomes the message's `text`, placeholders included. The document then
//! holds the text, so validation sees it, the graph fingerprint covers it (a
//! paused run is not resumed against a changed file) and a bundle carries it.
//! Only a host that loads the workflow from a file can read prompt files: a
//! document given as text with a `file` is an error.

use crate::source_map::DocPath;
use crate::validate::Diagnostic;

/// Reads a prompt file named relative to the workflow, or says why it cannot.
pub type ReadFile<'a> = &'a dyn Fn(&str) -> Result<String, String>;

/// The keys of a message that reads its text from a file.
const FILE_KEYS: [&str; 3] = ["file", "required", "strip_comments"];

/// Replace every prompt message `file` of `raw` (a workflow document, as
/// decoded from YAML or JSON) by its text, read with `read`. Returns what is
/// wrong, located at the message's keys; a message that cannot be read is
/// left as it is.
pub fn inline(raw: &mut serde_json::Value, read: Option<ReadFile<'_>>) -> Vec<Diagnostic> {
    let mut found = Vec::new();
    let Some(nodes) = raw.get_mut("graph").and_then(|graph| graph.get_mut("nodes")).and_then(|n| n.as_array_mut())
    else {
        return found;
    };
    for (index, node) in nodes.iter_mut().enumerate() {
        let node_path = DocPath::root().key("graph").key("nodes").index(index);
        // A node writes its config next to `id` and `type`, or under `data`.
        let (config, path) = match node.get("data").is_some_and(serde_json::Value::is_object) {
            true => (node.get_mut("data"), node_path.key("data")),
            false => (Some(node), node_path),
        };
        let Some(template) = config.and_then(|config| config.get_mut("prompt_template")) else { continue };
        let path = path.key("prompt_template");
        match template {
            serde_json::Value::Array(messages) => {
                for (position, message) in messages.iter_mut().enumerate() {
                    inline_message(message, &path.index(position), read, &mut found);
                }
            }
            message @ serde_json::Value::Object(_) => inline_message(message, &path, read, &mut found),
            _ => {}
        }
    }
    found
}

fn inline_message(
    message: &mut serde_json::Value,
    path: &DocPath,
    read: Option<ReadFile<'_>>,
    found: &mut Vec<Diagnostic>,
) {
    let Some(fields) = message.as_object_mut() else { return };
    if !FILE_KEYS.iter().any(|key| fields.contains_key(*key)) {
        return;
    }
    let mut error = |key: &str, message: String| found.push(Diagnostic::error("prompt-file", path.key(key), message));
    let Some(file) = fields.get("file").and_then(serde_json::Value::as_str).map(str::to_owned) else {
        match fields.get("file") {
            Some(_) => error("file", "`file` is the path of a text file, relative to the workflow".to_owned()),
            None => error("required", "`required` and `strip_comments` go with a `file`".to_owned()),
        }
        return;
    };
    if fields.contains_key("text") {
        error("file", "a message has `text` or `file`, not both".to_owned());
        return;
    }
    let flag = |key: &str| match fields.get(key) {
        None | Some(serde_json::Value::Null) => Ok(true),
        Some(serde_json::Value::Bool(on)) => Ok(*on),
        Some(_) => Err(format!("`{key}` is `true` or `false`")),
    };
    let (required, strip) = match (flag("required"), flag("strip_comments")) {
        (Ok(required), Ok(strip)) => (required, strip),
        (Err(why), _) => return error("required", why),
        (_, Err(why)) => return error("strip_comments", why),
    };
    let Some(read) = read else {
        return error(
            "file",
            format!("prompt file `{file}`: prompt files are read when the workflow is loaded from a file"),
        );
    };
    let text = match read(&file) {
        Ok(text) if strip => strip_comments(&text),
        Ok(text) => text,
        Err(why) if required => return error("file", format!("cannot read prompt file `{file}`: {why}")),
        Err(_) => String::new(),
    };
    if required && text.trim().is_empty() {
        return error("file", format!("prompt file `{file}` is empty"));
    }
    for key in FILE_KEYS {
        fields.remove(key);
    }
    fields.insert("text".to_owned(), serde_json::Value::String(text));
}

/// `text` without its HTML comments (`<!-- ... -->`, an unclosed one runs to the end).
pub fn strip_comments(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(start) = rest.find("<!--") {
        out.push_str(rest.get(..start).unwrap_or_default());
        let after = rest.get(start + 4..).unwrap_or_default();
        match after.find("-->") {
            Some(end) => rest = after.get(end + 3..).unwrap_or_default(),
            None => return out,
        }
    }
    out.push_str(rest);
    out
}

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

    fn files(name: &str) -> Result<String, String> {
        match name {
            "rules.md" => {
                Ok("<!-- for the editor -->Write short sentences.\n<!-- a\nnote -->Use {{#start.month#}}.\n".into())
            }
            "blank.md" => Ok("<!-- only a note -->\n".into()),
            _ => Err("No such file or directory".into()),
        }
    }

    fn doc(message: serde_json::Value) -> serde_json::Value {
        json!({"graph": {"nodes": [{"id": "write", "type": "llm", "prompt_template": [
            message, {"role": "user", "text": "Go."}
        ]}]}})
    }

    #[test]
    fn a_file_becomes_the_message_text() {
        let mut raw = doc(json!({"role": "system", "file": "rules.md"}));
        assert!(inline(&mut raw, Some(&files)).is_empty());
        let message = &raw["graph"]["nodes"][0]["prompt_template"][0];
        assert_eq!(*message, json!({"role": "system", "text": "Write short sentences.\nUse {{#start.month#}}.\n"}));
        // As written, comments kept.
        let mut raw = doc(json!({"file": "blank.md", "strip_comments": false}));
        assert!(inline(&mut raw, Some(&files)).is_empty());
        assert_eq!(raw["graph"]["nodes"][0]["prompt_template"][0]["text"], "<!-- only a note -->\n");
    }

    #[test]
    fn a_missing_or_empty_file_is_an_error_unless_it_is_optional() {
        for (message, said) in [
            (json!({"file": "gone.md"}), "cannot read prompt file `gone.md`"),
            (json!({"file": "blank.md"}), "is empty"),
            (json!({"file": "rules.md", "text": "x"}), "not both"),
            (json!({"file": 3}), "path of a text file"),
            (json!({"file": "rules.md", "required": "yes"}), "`required`"),
        ] {
            let mut raw = doc(message.clone());
            let found = inline(&mut raw, Some(&files));
            assert_eq!(found.len(), 1, "{message}");
            assert!(found[0].message.contains(said), "{message}: {}", found[0].message);
            assert!(found[0].path.to_string().starts_with("graph.nodes[0].prompt_template[0]"), "{}", found[0].path);
        }
        let mut raw = doc(json!({"file": "gone.md", "required": false}));
        assert!(inline(&mut raw, Some(&files)).is_empty());
        assert_eq!(raw["graph"]["nodes"][0]["prompt_template"][0], json!({"text": ""}));
    }

    #[test]
    fn a_document_without_a_folder_cannot_read_files() {
        let mut raw = doc(json!({"file": "rules.md"}));
        let found = inline(&mut raw, None);
        assert!(found[0].message.contains("loaded from a file"), "{}", found[0].message);
        // A completion prompt and a node under `data` are read too.
        let mut raw = json!({"graph": {"nodes": [{"id": "w", "data": {"type": "llm", "prompt_template": {"file": "rules.md"}}}]}});
        assert!(inline(&mut raw, Some(&files)).is_empty());
        assert!(raw["graph"]["nodes"][0]["data"]["prompt_template"]["text"].as_str().unwrap().starts_with("Write"));
    }

    #[test]
    fn comments_are_taken_out() {
        assert_eq!(strip_comments("a<!-- x -->b<!--c-->d"), "abd");
        assert_eq!(strip_comments("keep <!-- open"), "keep ");
        assert_eq!(strip_comments("no comment"), "no comment");
    }
}