Skip to main content

troupekit_graph/
workflow.rs

1use crate::error::WorkflowError;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
5use troupekit_agent::dsl::{is_ident, parse_call, Call};
6use troupekit_agent::persona::{toml_error, trace_keys, valid_name};
7use troupekit_trace::TraceSpec;
8use troupekit_agent::{compile_output, validate};
9use troupekit_tools::valid_tool_name;
10
11const MAX_NODES: usize = 256;
12const MAX_STEPS_RANGE: std::ops::RangeInclusive<i64> = 1..=10_000;
13const MAX_RETRIES_RANGE: std::ops::RangeInclusive<i64> = 0..=50;
14const DEFAULT_MAX_STEPS: u32 = 200;
15const DEFAULT_MAX_RETRIES: u32 = 5;
16
17/// What a human node asks for: a yes or no approval, written as a bool,
18/// or a free answer typed by the node's `writes` key.
19/// Written `ask = "approval"` or `ask = "question"`.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum Ask {
23    Approval,
24    Question,
25}
26
27/// The work a node does. Agent nodes run a persona, tool nodes call one
28/// tool, human nodes wait for an answer, routers pick one out-edge by a
29/// condition, joins wait for every branch of a fan-out, end nodes finish.
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
32pub enum NodeKind {
33    Agent {
34        persona: String,
35        prompt: Option<String>,
36    },
37    Tool {
38        tool: String,
39    },
40    Human {
41        ask: Ask,
42        prompt: Option<String>,
43    },
44    Router {
45        condition: Call,
46    },
47    Join,
48    End,
49}
50
51/// One validated node: its id, kind, the state keys it reads and the
52/// state key it writes. Routers, joins and ends read and write nothing;
53/// a human node always writes its answer.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct Node {
57    pub id: String,
58    pub kind: NodeKind,
59    pub reads: Vec<String>,
60    pub writes: Option<String>,
61}
62
63/// One edge from node `from` to node `to`. `when` is the label a router
64/// condition returns to take it; only router edges have one.
65/// A node with several plain out-edges fans out into parallel branches.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(deny_unknown_fields)]
68pub struct Edge {
69    pub from: String,
70    pub to: String,
71    pub when: Option<String>,
72}
73
74/// A validated workflow: name, start node, step and retry caps, the
75/// compiled JSON Schema of every state key, nodes and edges. Plain data,
76/// so a graph run keeps a snapshot of the workflow it started with.
77#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
78#[serde(deny_unknown_fields)]
79pub struct Workflow {
80    pub name: String,
81    pub start: String,
82    pub max_steps: u32,
83    pub max_retries: u32,
84    pub state: BTreeMap<String, Value>,
85    pub nodes: Vec<Node>,
86    pub edges: Vec<Edge>,
87}
88
89#[derive(Deserialize)]
90#[serde(deny_unknown_fields)]
91struct WorkflowFile {
92    name: String,
93    start: String,
94    max_steps: Option<i64>,
95    max_retries: Option<i64>,
96    #[serde(default)]
97    state: toml::Table,
98    #[serde(default)]
99    nodes: Vec<NodeFile>,
100    #[serde(default)]
101    edges: Vec<Edge>,
102    trace: Option<toml::Value>,
103    trace_content: Option<bool>,
104    trace_file: Option<String>,
105}
106
107#[derive(Deserialize)]
108#[serde(deny_unknown_fields)]
109struct NodeFile {
110    id: String,
111    kind: String,
112    persona: Option<String>,
113    prompt: Option<String>,
114    tool: Option<String>,
115    ask: Option<String>,
116    condition: Option<String>,
117    reads: Option<Vec<String>>,
118    writes: Option<String>,
119}
120
121impl Workflow {
122    /// Parses and validates workflow TOML `text` read from `file`: fields,
123    /// node kinds, state keys, edges, reachability, router-free cycles and
124    /// fan-out joins. Returns the first problem found.
125    pub fn parse(file: &str, text: &str) -> Result<Workflow, WorkflowError> {
126        let raw: WorkflowFile = toml::from_str(text).map_err(|e| {
127            let p = toml_error(file, text, &e);
128            WorkflowError::new(&p.file, &p.field, p.message)
129        })?;
130        let err = |field: &str, msg: String| WorkflowError::new(file, field, msg);
131        if !valid_name(&raw.name) {
132            return Err(err(
133                "name",
134                "must be 1 to 64 of [a-z0-9-], not starting with `-`".into(),
135            ));
136        }
137        let max_steps = ranged(raw.max_steps, MAX_STEPS_RANGE, DEFAULT_MAX_STEPS)
138            .map_err(|m| err("max_steps", m))?;
139        let max_retries = ranged(raw.max_retries, MAX_RETRIES_RANGE, DEFAULT_MAX_RETRIES)
140            .map_err(|m| err("max_retries", m))?;
141        trace_keys(raw.trace.as_ref(), raw.trace_content, raw.trace_file.as_deref())
142            .map_err(|(field, m)| err(field, m))?;
143        let state = state_schemas(&raw.state).map_err(|m| err("state", m))?;
144        if raw.nodes.is_empty() || raw.nodes.len() > MAX_NODES {
145            return Err(err(
146                "nodes",
147                format!("a workflow has 1 to {MAX_NODES} nodes"),
148            ));
149        }
150        let mut nodes: Vec<Node> = Vec::with_capacity(raw.nodes.len());
151        for (i, n) in raw.nodes.into_iter().enumerate() {
152            if !is_ident(&n.id) || n.id.len() > 64 {
153                return Err(err(
154                    &format!("nodes[{i}].id"),
155                    format!("`{}` must be 1 to 64 of [a-z_][a-z0-9_]*", n.id),
156                ));
157            }
158            if nodes.iter().any(|m| m.id == n.id) {
159                return Err(err(
160                    &format!("nodes[{i}].id"),
161                    format!("duplicate node `{}`", n.id),
162                ));
163            }
164            let id = n.id.clone();
165            nodes.push(node(n, &state).map_err(|(f, m)| err(&format!("nodes.{id}.{f}"), m))?);
166        }
167        let wf = Workflow {
168            name: raw.name,
169            start: raw.start,
170            max_steps,
171            max_retries,
172            state,
173            nodes,
174            edges: raw.edges,
175        };
176        wf.check_graph().map_err(|(f, m)| err(&f, m))?;
177        Ok(wf)
178    }
179
180    /// Returns the node with id `id`.
181    /// `None` when the workflow has none.
182    /// Ids are unique, so at most one matches.
183    pub fn node(&self, id: &str) -> Option<&Node> {
184        self.nodes.iter().find(|n| n.id == id)
185    }
186
187    /// Returns the out-edges of node `id` in file order.
188    /// Fan-out branches and router choices follow this order.
189    /// Empty for end nodes and unknown ids.
190    pub fn next(&self, id: &str) -> Vec<&Edge> {
191        self.edges.iter().filter(|e| e.from == id).collect()
192    }
193
194    /// Returns how many edges lead into node `id`.
195    /// A join waits for this many branches.
196    /// Zero for unknown ids.
197    pub fn in_degree(&self, id: &str) -> usize {
198        self.edges.iter().filter(|e| e.to == id).count()
199    }
200
201    /// Checks `value` against the declared type of state key `key`.
202    /// Returns the problems as `"/<key>...: <message>"` lines, or an empty
203    /// list when it fits; an undeclared key is one problem.
204    pub fn check_value(&self, key: &str, value: &Value) -> Vec<String> {
205        let Some(schema) = self.state.get(key) else {
206            return vec![format!("`{key}` is not declared in [state]")];
207        };
208        let wrapped = serde_json::json!({
209            "type": "object",
210            "properties": {key: schema},
211            "required": [key],
212            "additionalProperties": false
213        });
214        validate(&wrapped, &serde_json::json!({key: value}))
215    }
216
217    fn check_graph(&self) -> Result<(), (String, String)> {
218        let nf = |id: &str, m: String| (format!("nodes.{id}"), m);
219        if self.node(&self.start).is_none() {
220            return Err(("start".into(), format!("unknown node `{}`", self.start)));
221        }
222        let mut seen = BTreeSet::new();
223        let mut labels: HashMap<&str, BTreeSet<&str>> = HashMap::new();
224        for (i, e) in self.edges.iter().enumerate() {
225            let field = |f: &str| format!("edges[{i}].{f}");
226            let Some(from) = self.node(&e.from) else {
227                return Err((field("from"), format!("unknown node `{}`", e.from)));
228            };
229            if self.node(&e.to).is_none() {
230                return Err((field("to"), format!("unknown node `{}`", e.to)));
231            }
232            if !seen.insert((e.from.as_str(), e.to.as_str())) {
233                return Err((
234                    format!("edges[{i}]"),
235                    format!("duplicate edge `{}` to `{}`", e.from, e.to),
236                ));
237            }
238            match (&from.kind, &e.when) {
239                (NodeKind::Router { .. }, None) => {
240                    return Err((field("when"), "a router edge needs `when`".into()))
241                }
242                (NodeKind::Router { .. }, Some(w)) => {
243                    if w.trim().is_empty() {
244                        return Err((field("when"), "must not be blank".into()));
245                    }
246                    if !labels
247                        .entry(e.from.as_str())
248                        .or_default()
249                        .insert(w.as_str())
250                    {
251                        return Err((field("when"), format!("label `{w}` repeats")));
252                    }
253                }
254                (_, Some(_)) => {
255                    return Err((field("when"), "only router edges have `when`".into()))
256                }
257                (_, None) => {}
258            }
259        }
260        for n in &self.nodes {
261            let out = self.next(&n.id).len();
262            match n.kind {
263                NodeKind::End if out > 0 => {
264                    return Err(nf(&n.id, "an end node has no out-edges".into()))
265                }
266                NodeKind::End => {}
267                _ if out == 0 => return Err(nf(&n.id, "has no out-edges".into())),
268                _ => {}
269            }
270        }
271        if !self.nodes.iter().any(|n| n.kind == NodeKind::End) {
272            return Err(("nodes".into(), "a workflow needs an end node".into()));
273        }
274        let reached = self.reachable();
275        if let Some(n) = self.nodes.iter().find(|n| !reached.contains(n.id.as_str())) {
276            return Err(nf(&n.id, format!("is unreachable from `{}`", self.start)));
277        }
278        if let Some(id) = self.router_free_cycle() {
279            return Err(nf(&id, "is on a cycle without a router".into()));
280        }
281        self.check_fan_outs()
282    }
283
284    fn reachable(&self) -> BTreeSet<&str> {
285        let mut seen = BTreeSet::from([self.start.as_str()]);
286        let mut queue = VecDeque::from([self.start.as_str()]);
287        while let Some(id) = queue.pop_front() {
288            for e in self.next(id) {
289                if seen.insert(e.to.as_str()) {
290                    queue.push_back(e.to.as_str());
291                }
292            }
293        }
294        seen
295    }
296
297    fn router_free_cycle(&self) -> Option<String> {
298        let plain = |id: &str| {
299            self.node(id)
300                .is_some_and(|n| !matches!(n.kind, NodeKind::Router { .. }))
301        };
302        let mut color: HashMap<&str, u8> = HashMap::new();
303        for n in self.nodes.iter().filter(|n| plain(&n.id)) {
304            if color.contains_key(n.id.as_str()) {
305                continue;
306            }
307            let mut stack: Vec<(&str, usize)> = vec![(n.id.as_str(), 0)];
308            color.insert(n.id.as_str(), 1);
309            while let Some((id, i)) = stack.pop() {
310                let out: Vec<&str> = self
311                    .next(id)
312                    .into_iter()
313                    .map(|e| e.to.as_str())
314                    .filter(|t| plain(t))
315                    .collect();
316                let Some(&to) = out.get(i) else {
317                    color.insert(id, 2);
318                    continue;
319                };
320                stack.push((id, i + 1));
321                match color.get(to) {
322                    Some(1) => return Some(to.to_string()),
323                    Some(_) => {}
324                    None => {
325                        color.insert(to, 1);
326                        stack.push((to, 0));
327                    }
328                }
329            }
330        }
331        None
332    }
333
334    fn check_fan_outs(&self) -> Result<(), (String, String)> {
335        let nf = |id: &str, m: String| (format!("nodes.{id}"), m);
336        let mut closes: HashMap<&str, usize> = HashMap::new();
337        for f in &self.nodes {
338            let out = self.next(&f.id);
339            if matches!(f.kind, NodeKind::Router { .. }) || out.len() < 2 {
340                continue;
341            }
342            let mut join: Option<&str> = None;
343            let mut tails: Vec<&str> = Vec::with_capacity(out.len());
344            let mut writes: BTreeMap<&str, usize> = BTreeMap::new();
345            for (b, e) in out.iter().enumerate() {
346                let (mut prev, mut cur) = (f.id.as_str(), e.to.as_str());
347                for _ in 0..=self.nodes.len() {
348                    let n = self.node(cur).expect("edge ends checked");
349                    let walkable = matches!(
350                        n.kind,
351                        NodeKind::Agent { .. } | NodeKind::Tool { .. } | NodeKind::Human { .. }
352                    );
353                    if n.kind == NodeKind::Join {
354                        break;
355                    }
356                    if !walkable || self.next(cur).len() != 1 || self.in_degree(cur) != 1 {
357                        return Err(nf(
358                            &f.id,
359                            format!(
360                                "fan-out branch reaches `{cur}` before a join; a branch is a chain of agent, tool or human nodes ending at one join"
361                            ),
362                        ));
363                    }
364                    if let Some(w) = &n.writes {
365                        if writes.insert(w.as_str(), b).is_some_and(|other| other != b) {
366                            return Err(nf(
367                                &f.id,
368                                format!("two branches of the fan-out write `{w}`"),
369                            ));
370                        }
371                    }
372                    prev = cur;
373                    cur = self.next(cur)[0].to.as_str();
374                }
375                assert_eq!(
376                    self.node(cur).map(|n| &n.kind),
377                    Some(&NodeKind::Join),
378                    "router-free cycles are rejected, so every walk ends"
379                );
380                if join.is_some_and(|j| j != cur) {
381                    return Err(nf(&f.id, "fan-out branches meet at different joins".into()));
382                }
383                join = Some(cur);
384                tails.push(prev);
385            }
386            let j = join.expect("a fan-out has branches");
387            let inputs: Vec<&str> = self
388                .edges
389                .iter()
390                .filter(|e| e.to == j)
391                .map(|e| e.from.as_str())
392                .collect();
393            if inputs.len() != tails.len() || inputs.iter().any(|i| !tails.contains(i)) {
394                return Err(nf(
395                    j,
396                    format!("join has inputs from outside the fan-out at `{}`", f.id),
397                ));
398            }
399            *closes.entry(j).or_default() += 1;
400        }
401        for n in self.nodes.iter().filter(|n| n.kind == NodeKind::Join) {
402            if closes.get(n.id.as_str()).copied().unwrap_or(0) != 1 {
403                return Err(nf(&n.id, "a join closes exactly one fan-out".into()));
404            }
405        }
406        Ok(())
407    }
408}
409
410/// Returns the trace settings of workflow TOML `text` read from `file`:
411/// `None` without `trace` or with tracing off. Only the trace keys are
412/// validated here; `Workflow::parse` checks the whole file.
413pub fn trace_spec(file: &str, text: &str) -> Result<Option<TraceSpec>, WorkflowError> {
414    let raw: WorkflowFile = toml::from_str(text).map_err(|e| {
415        let p = toml_error(file, text, &e);
416        WorkflowError::new(&p.file, &p.field, p.message)
417    })?;
418    trace_keys(raw.trace.as_ref(), raw.trace_content, raw.trace_file.as_deref())
419        .map_err(|(field, m)| WorkflowError::new(file, field, m))
420}
421
422fn ranged(
423    v: Option<i64>,
424    range: std::ops::RangeInclusive<i64>,
425    default: u32,
426) -> Result<u32, String> {
427    match v {
428        None => Ok(default),
429        Some(n) if range.contains(&n) => Ok(u32::try_from(n).expect("range fits in u32")),
430        Some(n) => Err(format!(
431            "{n} must be between {} and {}",
432            range.start(),
433            range.end()
434        )),
435    }
436}
437
438fn state_schemas(table: &toml::Table) -> Result<BTreeMap<String, Value>, String> {
439    if table.is_empty() {
440        return Ok(BTreeMap::new());
441    }
442    let schema = compile_output(table)?;
443    let props = schema["properties"]
444        .as_object()
445        .expect("compiled output is an object schema");
446    assert_eq!(props.len(), table.len(), "one schema per state key");
447    Ok(props.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
448}
449
450fn node(n: NodeFile, state: &BTreeMap<String, Value>) -> Result<Node, (String, String)> {
451    let e = |f: &str, m: String| (f.to_string(), m);
452    let set = [
453        ("persona", n.persona.is_some()),
454        ("prompt", n.prompt.is_some()),
455        ("tool", n.tool.is_some()),
456        ("ask", n.ask.is_some()),
457        ("condition", n.condition.is_some()),
458        ("reads", n.reads.is_some()),
459        ("writes", n.writes.is_some()),
460    ];
461    let allowed: &[&str] = match n.kind.as_str() {
462        "agent" => &["persona", "prompt", "reads", "writes"],
463        "tool" => &["tool", "reads", "writes"],
464        "human" => &["ask", "prompt", "reads", "writes"],
465        "router" => &["condition"],
466        "join" | "end" => &[],
467        other => {
468            return Err(e(
469                "kind",
470                format!("unknown kind `{other}`; use agent, tool, human, router, join or end"),
471            ))
472        }
473    };
474    if let Some((f, _)) = set.iter().find(|(f, s)| *s && !allowed.contains(f)) {
475        return Err(e(f, format!("is not a field of a {} node", n.kind)));
476    }
477    if n.prompt.as_ref().is_some_and(|p| p.trim().is_empty()) {
478        return Err(e("prompt", "must not be blank".into()));
479    }
480    let reads = n.reads.unwrap_or_default();
481    for (i, r) in reads.iter().enumerate() {
482        if !state.contains_key(r) {
483            return Err(e("reads", format!("`{r}` is not declared in [state]")));
484        }
485        if reads[..i].contains(r) {
486            return Err(e("reads", format!("`{r}` repeats")));
487        }
488    }
489    if let Some(w) = n.writes.as_ref().filter(|w| !state.contains_key(*w)) {
490        return Err(e("writes", format!("`{w}` is not declared in [state]")));
491    }
492    let need = |v: Option<String>, f: &str| {
493        v.ok_or_else(|| e(f, format!("a {} node needs `{f}`", n.kind)))
494    };
495    let kind = match n.kind.as_str() {
496        "agent" => {
497            let persona = need(n.persona, "persona")?;
498            if !valid_name(&persona) {
499                return Err(e(
500                    "persona",
501                    format!("`{persona}` must be 1 to 64 of [a-z0-9-], not starting with `-`"),
502                ));
503            }
504            if n.prompt.is_none() && reads.is_empty() {
505                return Err(e("prompt", "an agent node needs a prompt or reads".into()));
506            }
507            NodeKind::Agent {
508                persona,
509                prompt: n.prompt,
510            }
511        }
512        "tool" => {
513            let tool = need(n.tool, "tool")?;
514            if !valid_tool_name(&tool) {
515                return Err(e("tool", format!("`{tool}` is not a valid tool name")));
516            }
517            NodeKind::Tool { tool }
518        }
519        "human" => {
520            let ask = match need(n.ask, "ask")?.as_str() {
521                "approval" => Ask::Approval,
522                "question" => Ask::Question,
523                other => {
524                    return Err(e(
525                        "ask",
526                        format!("`{other}` must be `approval` or `question`"),
527                    ))
528                }
529            };
530            let w = n
531                .writes
532                .as_ref()
533                .ok_or_else(|| e("writes", "a human node needs `writes`".into()))?;
534            if ask == Ask::Approval && state[w] != serde_json::json!({"type": "boolean"}) {
535                return Err(e(
536                    "writes",
537                    format!("an approval writes a bool; `{w}` is not"),
538                ));
539            }
540            NodeKind::Human {
541                ask,
542                prompt: n.prompt,
543            }
544        }
545        "router" => {
546            let condition =
547                parse_call(&need(n.condition, "condition")?).map_err(|m| e("condition", m))?;
548            if condition.name == "flag" {
549                let bool_key = condition
550                    .args
551                    .first()
552                    .and_then(Value::as_str)
553                    .filter(|k| state.get(*k) == Some(&serde_json::json!({"type": "boolean"})));
554                if condition.args.len() != 1 || bool_key.is_none() {
555                    return Err(e(
556                        "condition",
557                        "flag takes one bool key declared in [state]".into(),
558                    ));
559                }
560            }
561            NodeKind::Router { condition }
562        }
563        "join" => NodeKind::Join,
564        "end" => NodeKind::End,
565        _ => unreachable!("kind checked above"),
566    };
567    Ok(Node {
568        id: n.id,
569        kind,
570        reads,
571        writes: n.writes,
572    })
573}