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