graphrt-core 0.6.3

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! `human-input`: pauses the run until a person submits a form or picks an action.
//!
//! First run: returns a pause request of kind `human_input` whose data holds
//! the rendered prompt, the form fields, the available actions and the
//! optional timeout. The host persists the run snapshot and shows the form.
//!
//! Resume: the host passes `{ "action": "<id>", "values": { ... } }` as the
//! node's resume input. The node validates the action and required fields,
//! outputs each field value plus `action`, and selects the branch whose handle
//! equals the action id. Resuming without input pauses again.
//!
//! `card` (optional) adds a UI block (see [`crate::ui`]) to the pause data, e.g. an
//! Adaptive Card the host renders in place of the plain form: either the block itself or a
//! `{{#node.output#}}` reference to one. The host answers with the card action's id as
//! `action` and the card's inputs as `values`, so a card's submit actions must use the
//! node's action ids. Leave `form` empty with a card: every value is then an output.

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

use crate::dsl::NodeDoc;
use crate::node::{
    ConfigError, Node, NodeContext, NodeError, NodeOutcome, NodeOutput, NodeResult, NodeRole, PauseRequest,
};
use crate::pool::Selector;
use crate::template::Template;
use crate::value::Value;

/// Action used when none are configured.
pub const DEFAULT_ACTION: &str = "submit";

/// `human-input` configuration.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct HumanInputConfig {
    /// Message shown to the person; may contain `{{#..#}}` placeholders.
    #[serde(default, alias = "content")]
    pub prompt: Option<Template>,
    #[serde(default)]
    pub form: Option<Form>,
    /// Alternative to `form.fields`.
    #[serde(default)]
    pub inputs: Vec<Field>,
    #[serde(default)]
    pub actions: Vec<Action>,
    /// How long the host should wait before expiring the request; reported to
    /// the host as `timeout_ms` in the pause data. (A node-level `timeout_ms` is
    /// the per-attempt timeout every node has, so it cannot be used for this.)
    #[serde(default)]
    pub expire_after_ms: Option<u64>,
    /// What the host should do when the request expires: `stop` (the default)
    /// or answer with one of `actions`. The engine does not act on it; it is
    /// reported in the pause data as `on_expire` for the host to carry out
    /// (`graphrt serve --expire-approvals` does).
    #[serde(default)]
    pub on_expire: OnExpire,
    /// A UI block shown with the question, or a `{{#..#}}` reference to one.
    #[serde(default)]
    pub card: Option<serde_json::Value>,
}

/// What happens when a `human-input` request expires (see `expire_after_ms`).
///
/// Written `on_expire: stop` or `on_expire: { action: <id> }`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum OnExpire {
    /// `on_expire: stop`, or no setting: the host stops the run.
    #[default]
    Stop,
    /// The host answers with this action id and the fields' defaults, as a
    /// person picking that action would.
    Answer {
        /// One of the node's `actions` ids (or `submit` when it sets none).
        action: String,
    },
}

impl<'de> Deserialize<'de> for OnExpire {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct AnswerForm {
            action: String,
        }
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Form {
            Keyword(String),
            Answer(AnswerForm),
        }
        match Form::deserialize(deserializer)? {
            Form::Keyword(keyword) if keyword == "stop" => Ok(Self::Stop),
            Form::Answer(AnswerForm { action }) if !action.is_empty() => Ok(Self::Answer { action }),
            _ => Err(serde::de::Error::custom("`on_expire` must be `stop` or `{ action: <id> }`")),
        }
    }
}

impl OnExpire {
    /// The pause data form: `{"kind": "stop"}` or `{"kind": "answer", "action": "<id>"}`.
    fn to_value(&self) -> Value {
        match self {
            Self::Stop => Value::object([("kind", Value::from("stop"))]),
            Self::Answer { action } => {
                Value::object([("kind", Value::from("answer")), ("action", Value::from(action.as_str()))])
            }
        }
    }
}

/// Form definition.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct Form {
    #[serde(default)]
    pub fields: Vec<Field>,
}

/// A form field.
#[derive(Clone, Debug, Deserialize)]
pub struct Field {
    #[serde(alias = "variable")]
    pub name: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(rename = "type", default = "text_kind")]
    pub kind: String,
    #[serde(default)]
    pub required: bool,
    /// Default value; strings may contain `{{#..#}}` placeholders.
    #[serde(default)]
    pub default: Option<serde_json::Value>,
}

fn text_kind() -> String {
    "text".to_owned()
}

/// A button / decision the person can choose.
#[derive(Clone, Debug, Deserialize)]
pub struct Action {
    pub id: String,
    #[serde(default)]
    pub title: Option<String>,
}

/// The `human-input` node.
#[derive(Debug)]
pub struct HumanInputNode {
    prompt: Option<Template>,
    fields: Vec<Field>,
    actions: Vec<Action>,
    timeout_ms: Option<u64>,
    on_expire: OnExpire,
    card: Option<serde_json::Value>,
}

impl HumanInputNode {
    pub fn new(doc: &NodeDoc, config: HumanInputConfig) -> Result<Self, ConfigError> {
        let mut fields = config.form.map(|f| f.fields).unwrap_or_default();
        fields.extend(config.inputs);
        let actions = if config.actions.is_empty() {
            vec![Action { id: DEFAULT_ACTION.to_owned(), title: Some("Submit".to_owned()) }]
        } else {
            config.actions
        };
        let mut seen = std::collections::HashSet::new();
        for a in &actions {
            if a.id.is_empty() || !seen.insert(a.id.as_str()) {
                return Err(ConfigError::new(doc, format!("action ids must be unique and non-empty (`{}`)", a.id)));
            }
        }
        if let OnExpire::Answer { action } = &config.on_expire
            && !actions.iter().any(|known| known.id == *action)
        {
            return Err(ConfigError::new(
                doc,
                format!("`on_expire` names `{action}`, which is not one of the actions"),
            ));
        }
        Ok(Self {
            prompt: config.prompt,
            fields,
            actions,
            timeout_ms: config.expire_after_ms,
            on_expire: config.on_expire,
            card: config.card,
        })
    }

    fn pause(&self, ctx: &NodeContext) -> PauseRequest {
        let fields = self.fields.iter().map(|f| {
            let default = match &f.default {
                Some(serde_json::Value::String(s)) => Template::parse(s).resolve(&ctx.pool),
                Some(other) => Value::from_json(other.clone()),
                None => Value::Null,
            };
            Value::object([
                ("name", Value::from(f.name.as_str())),
                ("label", Value::from(f.label.clone().unwrap_or_else(|| f.name.clone()))),
                ("type", Value::from(f.kind.as_str())),
                ("required", Value::Bool(f.required)),
                ("default", default),
            ])
        });
        let actions = self.actions.iter().map(|a| {
            Value::object([
                ("id", Value::from(a.id.as_str())),
                ("title", Value::from(a.title.clone().unwrap_or_else(|| a.id.clone()))),
            ])
        });
        let mut data = Value::object([
            ("prompt", self.prompt.as_ref().map(|t| Value::from(t.render(&ctx.pool))).unwrap_or(Value::Null)),
            ("fields", Value::array(fields)),
            ("actions", Value::array(actions)),
            ("timeout_ms", self.timeout_ms.and_then(|t| i64::try_from(t).ok()).map(Value::Int).unwrap_or(Value::Null)),
            ("on_expire", self.on_expire.to_value()),
        ]);
        if let (Some(card), Value::Object(map)) = (&self.card, &mut data) {
            std::sync::Arc::make_mut(map).insert("card".to_owned(), self.resolve_card(card, ctx));
        }
        PauseRequest { kind: "human_input".to_owned(), data, state: serde_json::Value::Null }
    }

    /// The configured card, when it is (or refers to) a UI block; `null` otherwise.
    fn resolve_card(&self, card: &serde_json::Value, ctx: &NodeContext) -> Value {
        let resolved = match card {
            serde_json::Value::String(s) => Template::parse(s).resolve(&ctx.pool),
            other => Value::from_json(other.clone()),
        };
        if crate::ui::ui_block_kind(&resolved).is_some() { resolved } else { Value::Null }
    }

    fn complete(&self, input: &Value) -> Result<NodeOutput, NodeError> {
        let action = match input.get_path(&["action"]) {
            Some(Value::String(s)) => s.to_string(),
            None | Some(Value::Null) if self.actions.len() == 1 => {
                self.actions.first().map(|a| a.id.clone()).unwrap_or_default()
            }
            _ => return Err(NodeError::invalid_input("human input must include an `action`")),
        };
        if !self.actions.iter().any(|a| a.id == action) {
            return Err(NodeError::invalid_input(format!("unknown action `{action}`")));
        }
        let values = input.get_path(&["values"]).unwrap_or(Value::Null);
        let mut out = NodeOutput::new();
        if self.fields.is_empty() {
            if let Some(map) = values.as_object() {
                for (k, v) in map.iter() {
                    out.outputs.insert(k.clone(), v.clone());
                }
            }
        } else {
            for f in &self.fields {
                let v = values.get_path(&[f.name.as_str()]).unwrap_or(Value::Null);
                if f.required && v.is_empty() {
                    return Err(NodeError::invalid_input(format!("field `{}` is required", f.name)));
                }
                out.outputs.insert(f.name.clone(), v);
            }
        }
        out.outputs.insert("action", Value::from(action.as_str()));
        Ok(out.branch(action))
    }
}

impl Node for HumanInputNode {
    fn role(&self) -> NodeRole {
        NodeRole::Branch
    }

    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
        Box::pin(async move {
            match ctx.resume.as_ref().and_then(|r| r.input.as_ref()) {
                Some(input) if !input.is_null() => self.complete(input).map(NodeOutcome::Completed),
                _ => Ok(NodeOutcome::Paused(self.pause(&ctx))),
            }
        })
    }

    fn inputs(&self) -> Vec<Selector> {
        let mut out: Vec<Selector> = self.prompt.iter().flat_map(|t| t.selectors().cloned()).collect();
        for field in &self.fields {
            if let Some(default) = &field.default {
                crate::condition::expected_selectors(default, &mut out);
            }
        }
        if let Some(card) = &self.card {
            crate::condition::expected_selectors(card, &mut out);
        }
        out
    }

    fn branch_handles(&self) -> Option<Vec<String>> {
        Some(self.actions.iter().map(|a| a.id.clone()).collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::node::Resume;
    use crate::pool::VariablePool;
    use serde_json::json;

    fn node(cfg: serde_json::Value) -> HumanInputNode {
        let doc = NodeDoc::new("h", "human-input", cfg);
        HumanInputNode::new(&doc, doc.parse_config().unwrap()).unwrap()
    }

    fn ctx(input: Option<serde_json::Value>) -> NodeContext {
        let mut pool = VariablePool::new();
        pool.insert("llm", "text", Value::from("draft"));
        NodeContext::for_test("h", pool)
            .with_resume(input.map(|i| Resume { state: serde_json::Value::Null, input: Some(Value::from_json(i)) }))
    }

    fn cfg() -> serde_json::Value {
        json!({
            "prompt": "Review: {{#llm.text#}}",
            "form": {"fields": [{"name": "comment", "required": true, "default": "{{#llm.text#}}"}]},
            "actions": [{"id": "approve", "title": "Approve"}, {"id": "reject"}],
            "expire_after_ms": 60000
        })
    }

    #[tokio::test]
    async fn pauses_with_rendered_form() {
        let r = node(cfg()).run(ctx(None)).await.unwrap();
        let NodeOutcome::Paused(p) = r else { panic!("{r:?}") };
        assert_eq!(p.kind, "human_input");
        assert_eq!(p.data.get_path(&["prompt"]), Some(Value::from("Review: draft")));
        assert_eq!(p.data.get_path(&["fields", "0", "default"]), Some(Value::from("draft")));
        assert_eq!(p.data.get_path(&["actions", "length"]), Some(Value::Int(2)));
    }

    async fn paused_on_expire(cfg: serde_json::Value) -> Value {
        let r = node(cfg).run(ctx(None)).await.unwrap();
        let NodeOutcome::Paused(p) = r else { panic!("{r:?}") };
        p.data.get_path(&["on_expire"]).unwrap()
    }

    #[tokio::test]
    async fn pause_reports_what_happens_on_expiry() {
        let stop = Value::object([("kind", Value::from("stop"))]);
        assert_eq!(paused_on_expire(cfg()).await, stop, "stop is the default");

        let mut stop_cfg = cfg();
        stop_cfg["on_expire"] = json!("stop");
        assert_eq!(paused_on_expire(stop_cfg).await, stop);

        let mut answer_cfg = cfg();
        answer_cfg["on_expire"] = json!({"action": "reject"});
        let answer = Value::object([("kind", Value::from("answer")), ("action", Value::from("reject"))]);
        assert_eq!(paused_on_expire(answer_cfg).await, answer);
    }

    #[test]
    fn on_expire_must_name_an_action_and_have_a_known_form() {
        let build = |on_expire: serde_json::Value| {
            let mut config = cfg();
            config["on_expire"] = on_expire;
            let doc = NodeDoc::new("h", "human-input", config);
            doc.parse_config::<HumanInputConfig>()
                .map_err(|e| e.to_string())
                .and_then(|config| HumanInputNode::new(&doc, config).map(|_| ()).map_err(|e| e.to_string()))
        };
        let unknown = build(json!({"action": "publish"})).unwrap_err();
        assert!(unknown.contains("`publish`"), "{unknown}");
        for bad in [json!("approve"), json!({"action": ""}), json!({"action": "approve", "x": 1}), json!(7)] {
            assert!(build(bad.clone()).is_err(), "{bad} should be refused");
        }
        let default_action = {
            let doc = NodeDoc::new("h", "human-input", json!({"on_expire": {"action": "submit"}}));
            HumanInputNode::new(&doc, doc.parse_config().unwrap())
        };
        assert!(default_action.is_ok(), "`submit` is the action of a node that sets none");
    }

    #[tokio::test]
    async fn pause_carries_the_referenced_card_and_card_values_pass_through() {
        let mut pool = VariablePool::new();
        pool.insert("cards", "data", Value::from_json(json!({"$ui": "adaptive_card", "version": 1, "card": {}})));
        pool.insert("llm", "text", Value::from("not a block"));
        let n = node(json!({"card": "{{#cards.data#}}", "actions": [{"id": "approve"}]}));
        assert!(n.inputs().iter().any(|s| s.to_string().contains("cards")), "{:?}", n.inputs());
        let r = n.run(NodeContext::for_test("h", pool.clone())).await.unwrap();
        let NodeOutcome::Paused(p) = r else { panic!("{r:?}") };
        assert_eq!(p.data.get_path(&["card", "$ui"]), Some(Value::from("adaptive_card")));

        let not_a_block = node(json!({"card": "{{#llm.text#}}"}));
        let NodeOutcome::Paused(p) = not_a_block.run(NodeContext::for_test("h", pool)).await.unwrap() else { panic!() };
        assert_eq!(p.data.get_path(&["card"]), Some(Value::Null));

        let without_card = node(cfg());
        let NodeOutcome::Paused(p) = without_card.run(ctx(None)).await.unwrap() else { panic!() };
        assert_eq!(p.data.get_path(&["card"]), None, "no `card` key unless configured");

        let answer = json!({"action": "approve", "values": {"amount": 120, "note": "ok"}});
        let resumed = n.run(ctx(Some(answer))).await.unwrap();
        let NodeOutcome::Completed(o) = resumed else { panic!("{resumed:?}") };
        assert_eq!(o.outputs.get("amount"), Some(&Value::Int(120)));
        assert_eq!(o.branch.as_deref(), Some("approve"));
    }

    #[tokio::test]
    async fn completes_with_action_branch() {
        let r = node(cfg()).run(ctx(Some(json!({"action": "reject", "values": {"comment": "no"}})))).await.unwrap();
        let NodeOutcome::Completed(o) = r else { panic!("{r:?}") };
        assert_eq!(o.branch.as_deref(), Some("reject"));
        assert_eq!(o.outputs.get("comment"), Some(&Value::from("no")));
        assert_eq!(o.outputs.get("action"), Some(&Value::from("reject")));
    }

    #[tokio::test]
    async fn validates_input() {
        let n = node(cfg());
        assert!(n.run(ctx(Some(json!({"action": "nope", "values": {"comment": "x"}})))).await.is_err());
        assert!(n.run(ctx(Some(json!({"action": "approve", "values": {}})))).await.is_err());
        // Single default action may be omitted.
        let n = node(json!({}));
        let r = n.run(ctx(Some(json!({"values": {"a": 1}})))).await.unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.branch.as_deref(), Some(DEFAULT_ACTION));
        assert_eq!(o.outputs.get("a"), Some(&Value::Int(1)));
    }

    #[test]
    fn duplicate_actions_rejected() {
        let doc = NodeDoc::new("h", "human-input", json!({"actions": [{"id": "a"}, {"id": "a"}]}));
        assert!(HumanInputNode::new(&doc, doc.parse_config().unwrap()).is_err());
    }
}