Skip to main content

graphrt_ffi/
approvals.rs

1//! What a paused run asks, and the answers that resume it.
2//!
3//! A run pauses when an `agent` node holds tool calls for approval
4//! (`require_approval`) or a `human-input` node waits for a form. A
5//! [`PausedRun`] lists those requests as typed records and collects the
6//! answers; [`crate::WorkflowHandle::resume_paused`] resumes the run with them.
7//! [`PausedRun::to_json`] is what an app persists to resume later, even after
8//! a restart ([`PausedRun::from_json`]).
9
10use std::sync::{Mutex, PoisonError};
11
12use graphrt_core::Value;
13use graphrt_core::event::PauseReason;
14use graphrt_core::snapshot::Snapshot;
15
16use crate::GraphrtError;
17
18/// What a request asks for.
19#[derive(Clone, Debug, PartialEq, Eq, uniffi::Enum)]
20pub enum RequestKind {
21    /// An `agent` node holds tool calls until someone approves or rejects them.
22    ToolApproval,
23    /// A `human-input` node waits for a form: an action and field values.
24    HumanInput,
25    /// A pause of another kind (`data_json` holds the details).
26    Other { name: String },
27}
28
29/// A tool call waiting for approval.
30#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
31pub struct PendingToolCall {
32    /// The call's id, for [`PausedRun::decide_tool_call`].
33    pub id: String,
34    /// The tool as the model sees it.
35    pub name: String,
36    /// The arguments, as JSON (secret values masked).
37    pub arguments_json: String,
38}
39
40/// A field of a `human-input` form.
41#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
42pub struct FormField {
43    pub name: String,
44    pub label: String,
45    /// `text`, `paragraph`, `number`, `select`, `file`... as the node declares it.
46    pub field_type: String,
47    pub required: bool,
48    /// The default value as JSON, if any.
49    pub default_json: Option<String>,
50}
51
52/// A button of a `human-input` form.
53#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
54pub struct FormAction {
55    pub id: String,
56    pub title: String,
57}
58
59/// One node of a paused run that waits for an answer.
60#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
61pub struct ApprovalRequest {
62    /// The key to answer under: the node id, or `<frame>/<node_id>` inside containers.
63    pub key: String,
64    pub node_id: String,
65    pub kind: RequestKind,
66    /// The text shown to the person (human input).
67    pub prompt: Option<String>,
68    /// Form fields (human input).
69    pub fields: Vec<FormField>,
70    /// Form buttons (human input).
71    pub actions: Vec<FormAction>,
72    /// Calls waiting for approval (tool approval).
73    pub tool_calls: Vec<PendingToolCall>,
74    /// How long the request may wait, when the node sets a limit.
75    pub timeout_ms: Option<u64>,
76    /// A UI card to show with the request, as JSON, when the node has one.
77    pub card_json: Option<String>,
78    /// The raw pause data, for kinds this record does not model.
79    pub data_json: String,
80}
81
82fn str_at(value: &Value, path: &[&str]) -> Option<String> {
83    value.get_path(path).as_ref().and_then(Value::as_str).map(str::to_owned)
84}
85
86fn array_at(value: &Value, key: &str) -> Vec<serde_json::Value> {
87    match value.get_path(&[key]).map(|v| v.to_json()) {
88        Some(serde_json::Value::Array(items)) => items,
89        _ => Vec::new(),
90    }
91}
92
93fn json_str(value: &serde_json::Value, key: &str) -> String {
94    value.get(key).and_then(serde_json::Value::as_str).unwrap_or_default().to_owned()
95}
96
97impl ApprovalRequest {
98    /// The request of one pause reason; `None` for a pause nobody answers
99    /// (paused from outside with `RunHandle.pause`).
100    pub(crate) fn of(reason: &PauseReason) -> Option<Self> {
101        let node_id = reason.node_id.as_deref()?;
102        let key = if reason.frame.is_empty() { node_id.to_owned() } else { format!("{}/{node_id}", reason.frame) };
103        let kind = match reason.kind.as_str() {
104            "tool_approval" => RequestKind::ToolApproval,
105            "human_input" => RequestKind::HumanInput,
106            other => RequestKind::Other { name: other.to_owned() },
107        };
108        let data = &reason.data;
109        let tool_calls = array_at(data, "calls")
110            .iter()
111            .map(|call| PendingToolCall {
112                id: json_str(call, "id"),
113                name: json_str(call, "name"),
114                arguments_json: call.get("arguments").map(|a| a.to_string()).unwrap_or_else(|| "{}".to_owned()),
115            })
116            .collect();
117        let fields = array_at(data, "fields")
118            .iter()
119            .map(|field| FormField {
120                name: json_str(field, "name"),
121                label: json_str(field, "label"),
122                field_type: json_str(field, "type"),
123                required: field.get("required").and_then(serde_json::Value::as_bool).unwrap_or(false),
124                default_json: field.get("default").filter(|d| !d.is_null()).map(|d| d.to_string()),
125            })
126            .collect();
127        let actions = array_at(data, "actions")
128            .iter()
129            .map(|action| FormAction { id: json_str(action, "id"), title: json_str(action, "title") })
130            .collect();
131        let timeout_ms = data
132            .get_path(&["timeout_ms"])
133            .as_ref()
134            .and_then(Value::as_i64)
135            .and_then(|t| u64::try_from(t).ok())
136            .filter(|t| *t > 0);
137        let card_json = data.get_path(&["card"]).filter(|c| !c.is_null()).map(|c| c.to_json().to_string());
138        Some(Self {
139            key,
140            node_id: node_id.to_owned(),
141            kind,
142            prompt: str_at(data, &["prompt"]),
143            fields,
144            actions,
145            tool_calls,
146            timeout_ms,
147            card_json,
148            data_json: data.to_json().to_string(),
149        })
150    }
151}
152
153/// A paused run: its requests, the answers given so far and its snapshot.
154#[derive(Debug, uniffi::Object)]
155pub struct PausedRun {
156    snapshot: Snapshot,
157    reasons: Vec<PauseReason>,
158    requests: Vec<ApprovalRequest>,
159    answers: Mutex<serde_json::Map<String, serde_json::Value>>,
160}
161
162impl PausedRun {
163    pub(crate) fn new(snapshot: Snapshot, reasons: Vec<PauseReason>) -> Self {
164        let requests = reasons.iter().filter_map(ApprovalRequest::of).collect();
165        Self { snapshot, reasons, requests, answers: Mutex::new(serde_json::Map::new()) }
166    }
167
168    pub(crate) fn snapshot(&self) -> &Snapshot {
169        &self.snapshot
170    }
171
172    pub(crate) fn inputs(&self) -> serde_json::Map<String, serde_json::Value> {
173        self.answers.lock().unwrap_or_else(PoisonError::into_inner).clone()
174    }
175
176    fn request(&self, key: &str) -> Result<&ApprovalRequest, GraphrtError> {
177        self.requests.iter().find(|r| r.key == key).ok_or_else(|| {
178            let keys: Vec<&str> = self.requests.iter().map(|r| r.key.as_str()).collect();
179            GraphrtError::input(format!("no request `{key}` in this paused run (requests: {keys:?})"))
180        })
181    }
182
183    fn set(&self, key: &str, answer: serde_json::Value) {
184        self.answers.lock().unwrap_or_else(PoisonError::into_inner).insert(key.to_owned(), answer);
185    }
186
187    /// Answer a form with the defaults of its fields and the action `action`.
188    fn answer_form(
189        &self,
190        request: &ApprovalRequest,
191        action: &str,
192        values: serde_json::Value,
193    ) -> Result<(), GraphrtError> {
194        if !request.actions.iter().any(|a| a.id == action) {
195            let ids: Vec<&str> = request.actions.iter().map(|a| a.id.as_str()).collect();
196            return Err(GraphrtError::input(format!(
197                "request `{}` has no action `{action}` (actions: {ids:?})",
198                request.key
199            )));
200        }
201        let mut merged = serde_json::Map::new();
202        for field in &request.fields {
203            if let Some(default) = field.default_json.as_deref().and_then(|d| serde_json::from_str(d).ok()) {
204                merged.insert(field.name.clone(), default);
205            }
206        }
207        match values {
208            serde_json::Value::Object(given) => merged.extend(given),
209            serde_json::Value::Null => {}
210            _ => return Err(GraphrtError::input("values must be a JSON object")),
211        }
212        self.set(&request.key, serde_json::json!({ "action": action, "values": merged }));
213        Ok(())
214    }
215
216    fn decide(&self, key: &str, approved: bool, reason: Option<String>) -> Result<(), GraphrtError> {
217        let request = self.request(key)?;
218        match &request.kind {
219            RequestKind::ToolApproval => {
220                let mut answer = serde_json::json!({ "approved": approved });
221                if let (Some(reason), Some(fields)) = (reason, answer.as_object_mut()) {
222                    fields.insert("reason".to_owned(), serde_json::Value::from(reason));
223                }
224                self.set(key, answer);
225                Ok(())
226            }
227            RequestKind::HumanInput => {
228                let action = if approved { "approve" } else { "reject" };
229                self.answer_form(request, action, serde_json::Value::Null)
230            }
231            RequestKind::Other { name } => {
232                Err(GraphrtError::input(format!("request `{key}` is a `{name}` pause; answer it with set_input")))
233            }
234        }
235    }
236}
237
238#[uniffi::export]
239impl PausedRun {
240    /// A paused run from the result JSON of a run that ended with status
241    /// `paused` (what `RunHandle.waitJson` and `EventListener.onFinish` return),
242    /// or from what [`PausedRun::to_json`] returned.
243    #[uniffi::constructor]
244    pub fn from_json(json: String) -> Result<std::sync::Arc<Self>, GraphrtError> {
245        #[derive(serde::Deserialize)]
246        struct Paused {
247            status: String,
248            #[serde(default)]
249            reasons: Vec<PauseReason>,
250            snapshot: Option<Snapshot>,
251        }
252        let paused: Paused =
253            serde_json::from_str(&json).map_err(|e| GraphrtError::input(format!("paused run: {e}")))?;
254        if paused.status != "paused" {
255            return Err(GraphrtError::input(format!("the run is `{}`, not paused", paused.status)));
256        }
257        let snapshot = paused.snapshot.ok_or_else(|| GraphrtError::input("paused run: no snapshot"))?;
258        Ok(std::sync::Arc::new(Self::new(snapshot, paused.reasons)))
259    }
260
261    /// The paused run as JSON (requests and snapshot, not the answers), to store
262    /// and read back with [`PausedRun::from_json`]. It holds the run's variables
263    /// (never secrets): keep it in the app's private storage.
264    pub fn to_json(&self) -> String {
265        serde_json::json!({ "status": "paused", "reasons": self.reasons, "snapshot": self.snapshot }).to_string()
266    }
267
268    /// Run id of the paused run.
269    pub fn run_id(&self) -> String {
270        self.snapshot.run_id.clone()
271    }
272
273    /// The snapshot alone, for `WorkflowHandle.resume`.
274    pub fn snapshot_json(&self) -> String {
275        self.snapshot.to_json().unwrap_or_default()
276    }
277
278    /// Every request of the run, in the order the nodes paused.
279    pub fn requests(&self) -> Vec<ApprovalRequest> {
280        self.requests.clone()
281    }
282
283    /// Keys of the requests that have no answer yet. Resuming with requests
284    /// unanswered keeps those nodes paused.
285    pub fn unanswered(&self) -> Vec<String> {
286        let answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
287        self.requests.iter().filter(|r| !answers.contains_key(&r.key)).map(|r| r.key.clone()).collect()
288    }
289
290    /// Approve request `key`: every held tool call runs, or a form is answered
291    /// with its `approve` action and the fields' defaults.
292    pub fn approve(&self, key: String, reason: Option<String>) -> Result<(), GraphrtError> {
293        self.decide(&key, true, reason)
294    }
295
296    /// Reject request `key`: the model is told the calls were not approved (and
297    /// why, with `reason`), or a form is answered with its `reject` action.
298    pub fn reject(&self, key: String, reason: Option<String>) -> Result<(), GraphrtError> {
299        self.decide(&key, false, reason)
300    }
301
302    /// Approve or reject one held tool call of request `key`. Calls without a
303    /// decision keep the node paused.
304    pub fn decide_tool_call(&self, key: String, call_id: String, approved: bool) -> Result<(), GraphrtError> {
305        let request = self.request(&key)?;
306        if request.kind != RequestKind::ToolApproval {
307            return Err(GraphrtError::input(format!("request `{key}` holds no tool calls")));
308        }
309        if !request.tool_calls.iter().any(|c| c.id == call_id) {
310            return Err(GraphrtError::input(format!("request `{key}` holds no call `{call_id}`")));
311        }
312        let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
313        let entry = answers.entry(key).or_insert_with(|| serde_json::json!({}));
314        if !entry.is_object() {
315            *entry = serde_json::json!({});
316        }
317        if let Some(fields) = entry.as_object_mut() {
318            let per_call = fields.entry("approvals").or_insert_with(|| serde_json::json!({}));
319            if let Some(per_call) = per_call.as_object_mut() {
320                per_call.insert(call_id, serde_json::Value::Bool(approved));
321            }
322        }
323        Ok(())
324    }
325
326    /// Answer the form of request `key` with `action` (one of its actions) and
327    /// field values as a JSON object; fields left out get their defaults.
328    pub fn answer(&self, key: String, action: String, values_json: String) -> Result<(), GraphrtError> {
329        let request = self.request(&key)?;
330        if request.kind != RequestKind::HumanInput {
331            return Err(GraphrtError::input(format!("request `{key}` is not a form")));
332        }
333        let values = if values_json.trim().is_empty() {
334            serde_json::Value::Null
335        } else {
336            serde_json::from_str(&values_json).map_err(|e| GraphrtError::input(format!("values: {e}")))?
337        };
338        self.answer_form(request, &action, values)
339    }
340
341    /// Set the resume input of request `key` as raw JSON, for pause kinds the
342    /// helpers above do not cover.
343    pub fn set_input(&self, key: String, input_json: String) -> Result<(), GraphrtError> {
344        self.request(&key)?;
345        let input: serde_json::Value =
346            serde_json::from_str(&input_json).map_err(|e| GraphrtError::input(format!("input: {e}")))?;
347        self.set(&key, input);
348        Ok(())
349    }
350
351    /// The resume inputs collected so far, as JSON (what `WorkflowHandle.resume` takes).
352    pub fn inputs_json(&self) -> String {
353        serde_json::Value::Object(self.inputs()).to_string()
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360    use graphrt_core::event::FrameId;
361    use serde_json::json;
362
363    fn reason(node: &str, kind: &str, data: serde_json::Value) -> PauseReason {
364        PauseReason {
365            frame: FrameId::from(""),
366            node_id: Some(node.to_owned()),
367            kind: kind.to_owned(),
368            data: Value::from_json(data),
369        }
370    }
371
372    fn snapshot() -> Snapshot {
373        Snapshot {
374            format: graphrt_core::snapshot::SNAPSHOT_FORMAT,
375            run_id: "run-1".into(),
376            graph_fingerprint: String::new(),
377            elapsed_ms: 0,
378            steps: 0,
379            usage: graphrt_core::event::Usage::default(),
380            handled_errors: 0,
381            root: graphrt_core::snapshot::FrameSnapshot::default(),
382            ..Snapshot::default()
383        }
384    }
385
386    fn paused(reasons: &[PauseReason]) -> PausedRun {
387        PausedRun::new(snapshot(), reasons.to_vec())
388    }
389
390    fn external() -> PauseReason {
391        PauseReason { frame: FrameId::from(""), node_id: None, kind: "external".into(), data: Value::Null }
392    }
393
394    fn tool_pause() -> PauseReason {
395        reason(
396            "assistant",
397            "tool_approval",
398            json!({"calls": [
399                {"id": "c1", "name": "device__send", "arguments": {"to": "Ada"}},
400                {"id": "c2", "name": "device__call", "arguments": {}},
401            ]}),
402        )
403    }
404
405    fn form_pause() -> PauseReason {
406        reason(
407            "review",
408            "human_input",
409            json!({
410                "prompt": "Ship it?",
411                "fields": [{"name": "note", "label": "Note", "type": "text", "required": false, "default": "ok"}],
412                "actions": [{"id": "approve", "title": "Approve"}, {"id": "reject", "title": "Reject"}],
413                "timeout_ms": 60000,
414            }),
415        )
416    }
417
418    #[test]
419    fn requests_are_typed() {
420        let run = paused(&[tool_pause(), form_pause(), external()]);
421        let requests = run.requests();
422        assert_eq!(requests.len(), 2, "an external pause asks nobody");
423        let tools = &requests[0];
424        assert_eq!((tools.key.as_str(), &tools.kind), ("assistant", &RequestKind::ToolApproval));
425        assert_eq!(tools.tool_calls[0].id, "c1");
426        assert_eq!(tools.tool_calls[0].arguments_json, r#"{"to":"Ada"}"#);
427        let form = &requests[1];
428        assert_eq!(form.kind, RequestKind::HumanInput);
429        assert_eq!(form.prompt.as_deref(), Some("Ship it?"));
430        assert_eq!(form.fields[0].default_json.as_deref(), Some(r#""ok""#));
431        assert_eq!(form.actions[1].id, "reject");
432        assert_eq!(form.timeout_ms, Some(60_000));
433        assert_eq!(run.unanswered(), ["assistant", "review"]);
434    }
435
436    #[test]
437    fn approve_and_reject_build_the_inputs_each_node_reads() -> Result<(), GraphrtError> {
438        let run = paused(&[tool_pause(), form_pause()]);
439        run.reject("assistant".into(), Some("not now".into()))?;
440        run.approve("review".into(), None)?;
441        let inputs: serde_json::Value =
442            serde_json::from_str(&run.inputs_json()).map_err(|e| GraphrtError::input(e.to_string()))?;
443        assert_eq!(
444            inputs,
445            json!({
446                "assistant": {"approved": false, "reason": "not now"},
447                "review": {"action": "approve", "values": {"note": "ok"}},
448            })
449        );
450        assert!(run.unanswered().is_empty());
451        Ok(())
452    }
453
454    #[test]
455    fn per_call_decisions_and_form_answers() -> Result<(), GraphrtError> {
456        let run = paused(&[tool_pause(), form_pause()]);
457        run.decide_tool_call("assistant".into(), "c1".into(), true)?;
458        run.decide_tool_call("assistant".into(), "c2".into(), false)?;
459        run.answer("review".into(), "reject".into(), r#"{"note": "too risky"}"#.into())?;
460        let inputs: serde_json::Value =
461            serde_json::from_str(&run.inputs_json()).map_err(|e| GraphrtError::input(e.to_string()))?;
462        assert_eq!(inputs["assistant"], json!({"approvals": {"c1": true, "c2": false}}));
463        assert_eq!(inputs["review"], json!({"action": "reject", "values": {"note": "too risky"}}));
464        Ok(())
465    }
466
467    #[test]
468    fn wrong_answers_are_refused() {
469        let run = paused(&[tool_pause(), form_pause()]);
470        assert!(run.approve("nope".into(), None).is_err());
471        assert!(run.decide_tool_call("assistant".into(), "c9".into(), true).is_err());
472        assert!(run.decide_tool_call("review".into(), "c1".into(), true).is_err());
473        assert!(run.answer("review".into(), "publish".into(), "{}".into()).is_err());
474        assert!(run.answer("review".into(), "approve".into(), "[1]".into()).is_err());
475        assert!(run.answer("assistant".into(), "approve".into(), "{}".into()).is_err());
476        assert!(run.inputs().is_empty());
477    }
478
479    #[test]
480    fn a_paused_run_survives_a_round_trip() -> Result<(), GraphrtError> {
481        let run = paused(&[tool_pause()]);
482        let back = PausedRun::from_json(run.to_json())?;
483        assert_eq!(back.requests(), run.requests());
484        assert_eq!(back.run_id(), "run-1");
485        Ok(())
486    }
487
488    #[test]
489    fn a_result_that_is_not_paused_is_refused() {
490        assert!(PausedRun::from_json(r#"{"status":"succeeded","answer":""}"#.into()).is_err());
491        assert!(PausedRun::from_json(r#"{"status":"paused"}"#.into()).is_err());
492        assert!(PausedRun::from_json("{".into()).is_err());
493    }
494}