adk_graph/interrupt.rs
1//! Human-in-the-loop interrupt types
2
3use adk_core::ToolConfirmationRequest;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7/// Interrupt request from a node or configuration
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub enum Interrupt {
10 /// Interrupt before executing a node
11 Before(String),
12 /// Interrupt after executing a node
13 After(String),
14 /// Dynamic interrupt from within a node
15 Dynamic {
16 /// Message to display to the user
17 message: String,
18 /// Optional data for the interrupt
19 data: Option<Value>,
20 /// The pause's id, set by the executor when the node pauses: stable for one
21 /// pause and bound to its thread, step, node and question ([`interrupt_id`]).
22 /// Answer it with
23 /// [`ExecutionConfig::with_resume_value`](crate::node::ExecutionConfig::with_resume_value)
24 /// under this id.
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 id: Option<String>,
27 /// JSON Schema the answer must satisfy; an answer that does not is refused
28 /// when the run resumes, before any node runs.
29 #[serde(default, skip_serializing_if = "Option::is_none")]
30 response_schema: Option<Value>,
31 },
32}
33
34impl Interrupt {
35 /// The pause's id, for a dynamic interrupt the executor reported.
36 ///
37 /// # Example
38 ///
39 /// ```
40 /// use adk_graph::interrupt::interrupt;
41 ///
42 /// assert_eq!(interrupt("approve?").id(), None, "the executor assigns it");
43 /// ```
44 pub fn id(&self) -> Option<&str> {
45 match self {
46 Self::Dynamic { id, .. } => id.as_deref(),
47 Self::Before(_) | Self::After(_) => None,
48 }
49 }
50
51 /// The JSON Schema the answer must satisfy, when the interrupt declares one.
52 pub fn response_schema(&self) -> Option<&Value> {
53 match self {
54 Self::Dynamic { response_schema, .. } => response_schema.as_ref(),
55 Self::Before(_) | Self::After(_) => None,
56 }
57 }
58
59 /// Declares the JSON Schema the answer to this dynamic interrupt must satisfy; a
60 /// static gate is returned unchanged.
61 ///
62 /// # Example
63 ///
64 /// ```
65 /// use adk_graph::interrupt::interrupt;
66 /// use serde_json::json;
67 ///
68 /// let pause = interrupt("approve the refund?").with_response_schema(json!({
69 /// "type": "object",
70 /// "properties": { "approved": { "type": "boolean" } },
71 /// "required": ["approved"]
72 /// }));
73 /// assert!(pause.response_schema().is_some());
74 /// ```
75 #[must_use]
76 pub fn with_response_schema(mut self, schema: Value) -> Self {
77 if let Self::Dynamic { response_schema, .. } = &mut self {
78 *response_schema = Some(schema);
79 }
80 self
81 }
82
83 /// Gives a dynamic interrupt raised by `node` at `step` of `thread_id` its id, unless
84 /// it has one.
85 pub(crate) fn identify(&mut self, thread_id: &str, step: usize, node: &str) {
86 if let Self::Dynamic { message, data, id, response_schema } = self
87 && id.is_none()
88 {
89 *id = Some(interrupt_id(
90 thread_id,
91 step,
92 node,
93 message,
94 data.as_ref(),
95 response_schema.as_ref(),
96 ));
97 }
98 }
99}
100
101/// The id of the pause `node` raised at `step` of `thread_id` with `message`, `data` and
102/// `response_schema`: `int_` and 32 hex characters of a SHA-256 over all of them.
103///
104/// The same pause, re-raised because the run resumed without an answer, gets the same id;
105/// a later pause — the node's next pass through a loop, or the same step asking about
106/// other data — gets another, so an answer given to one pause never answers another. This
107/// is how an approval binds to its call's fingerprint.
108///
109/// # Example
110///
111/// ```
112/// use adk_graph::interrupt::interrupt_id;
113/// use serde_json::json;
114///
115/// let first = interrupt_id("t1", 3, "review", "approve?", Some(&json!({ "amount": 40 })), None);
116/// assert!(first.starts_with("int_"));
117/// assert_eq!(first, interrupt_id("t1", 3, "review", "approve?", Some(&json!({ "amount": 40 })), None));
118/// assert_ne!(first, interrupt_id("t1", 3, "review", "approve?", Some(&json!({ "amount": 900 })), None));
119/// assert_ne!(first, interrupt_id("t1", 7, "review", "approve?", Some(&json!({ "amount": 40 })), None));
120/// ```
121pub fn interrupt_id(
122 thread_id: &str,
123 step: usize,
124 node: &str,
125 message: &str,
126 data: Option<&Value>,
127 response_schema: Option<&Value>,
128) -> String {
129 use sha2::{Digest, Sha256};
130 let canonical = serde_json::json!([thread_id, step, node, message, data, response_schema]);
131 let digest = Sha256::digest(canonical.to_string().as_bytes());
132 let hex: String = digest.iter().take(16).map(|byte| format!("{byte:02x}")).collect();
133 format!("int_{hex}")
134}
135
136impl std::fmt::Display for Interrupt {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 match self {
139 Self::Before(node) => write!(f, "Interrupt before '{}'", node),
140 Self::After(node) => write!(f, "Interrupt after '{}'", node),
141 Self::Dynamic { message, .. } => write!(f, "Dynamic interrupt: {}", message),
142 }
143 }
144}
145
146/// Helper to create a dynamic interrupt from within a node
147pub fn interrupt(message: &str) -> Interrupt {
148 Interrupt::Dynamic { message: message.to_string(), data: None, id: None, response_schema: None }
149}
150
151/// Helper to create a dynamic interrupt with data
152pub fn interrupt_with_data(message: &str, data: Value) -> Interrupt {
153 Interrupt::Dynamic {
154 message: message.to_string(),
155 data: Some(data),
156 id: None,
157 response_schema: None,
158 }
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize)]
162struct PendingGraphToolConfirmation {
163 node: String,
164 request: ToolConfirmationRequest,
165}
166
167/// A persisted tool-authorization pause emitted by a graph.
168///
169/// Use [`Self::from_stream_event`] when directly streaming a graph, or
170/// [`GraphInterruptPayload::tool_confirmation`] when the graph runs as a
171/// [`crate::agent::GraphAgent`].
172#[derive(Debug, Clone, Serialize, Deserialize)]
173#[serde(rename_all = "camelCase")]
174pub struct GraphToolConfirmationPause {
175 /// Graph node whose agent requested authorization.
176 pub node: String,
177 /// The exact tool call the caller must approve or deny.
178 pub request: ToolConfirmationRequest,
179 /// Thread to resume after a decision.
180 pub thread_id: String,
181 /// Checkpoint saved before the pause was reported.
182 pub checkpoint_id: String,
183}
184
185impl GraphToolConfirmationPause {
186 /// Reserved custom-event and dynamic-interrupt marker for tool confirmation.
187 pub const KIND: &str = "tool_confirmation";
188
189 /// Read a tool-confirmation pause from a graph stream event.
190 pub fn from_stream_event(event: &crate::stream::StreamEvent) -> Option<Self> {
191 let crate::stream::StreamEvent::Custom { event_type, data, .. } = event else {
192 return None;
193 };
194 (event_type == Self::KIND).then(|| serde_json::from_value(data.clone()).ok()).flatten()
195 }
196
197 /// Read a tool-confirmation pause from an interrupted graph execution.
198 ///
199 /// Reads the first pause; [`Self::all_from_interrupted_execution`] reads every
200 /// pause of the step.
201 pub fn from_interrupted_execution(
202 interrupted: &crate::error::InterruptedExecution,
203 ) -> Option<Self> {
204 Self::from_interrupt(
205 &interrupted.interrupt,
206 &interrupted.thread_id,
207 &interrupted.checkpoint_id,
208 )
209 }
210
211 /// Read every tool-confirmation pause of an interrupted graph execution, in
212 /// node-name order.
213 pub fn all_from_interrupted_execution(
214 interrupted: &crate::error::InterruptedExecution,
215 ) -> Vec<Self> {
216 interrupted
217 .interrupts
218 .iter()
219 .filter_map(|interrupt| {
220 Self::from_interrupt(interrupt, &interrupted.thread_id, &interrupted.checkpoint_id)
221 })
222 .collect()
223 }
224
225 /// Read a tool-confirmation pause from one interrupt of the run that stopped
226 /// at `checkpoint_id` on `thread_id`.
227 pub fn from_interrupt(
228 interrupt: &Interrupt,
229 thread_id: &str,
230 checkpoint_id: &str,
231 ) -> Option<Self> {
232 let (node, request) = pending_from_interrupt(interrupt)?;
233 Some(Self {
234 node,
235 request,
236 thread_id: thread_id.to_string(),
237 checkpoint_id: checkpoint_id.to_string(),
238 })
239 }
240
241 pub(crate) fn pending_interrupt(node: String, request: ToolConfirmationRequest) -> Interrupt {
242 Interrupt::Dynamic {
243 message: Self::KIND.to_string(),
244 data: Some(Self::pending_data(node, request)),
245 id: None,
246 response_schema: None,
247 }
248 }
249
250 pub(crate) fn pending_data(node: String, request: ToolConfirmationRequest) -> Value {
251 serde_json::to_value(PendingGraphToolConfirmation { node, request }).unwrap_or(Value::Null)
252 }
253}
254
255fn pending_from_interrupt(interrupt: &Interrupt) -> Option<(String, ToolConfirmationRequest)> {
256 let Interrupt::Dynamic { message, data, .. } = interrupt else { return None };
257 if message != GraphToolConfirmationPause::KIND {
258 return None;
259 }
260 let pending: PendingGraphToolConfirmation = serde_json::from_value(data.clone()?).ok()?;
261 Some((pending.node, pending.request))
262}
263
264/// The reserved `Event::provider_metadata` key carrying a graph interrupt.
265pub const INTERRUPT_METADATA_KEY: &str = "adk.graph.interrupt";
266
267/// A graph interrupt as it crosses the [`Agent`](adk_core::Agent) boundary.
268///
269/// `GraphAgent` cannot return `GraphError::Interrupted` to a `Runner`: the trait
270/// yields events, and an error would end the invocation. It therefore emits one
271/// event carrying this payload, so a caller can read which node paused, why, and
272/// which checkpoint to resume from.
273///
274/// It travels as JSON in `Event::provider_metadata` under
275/// [`INTERRUPT_METADATA_KEY`] rather than as a field on `adk_core::EventActions`.
276/// A graph-shaped type in `adk-core` would put a Tier 3 concept in a Tier 1
277/// crate; every other consumer of the event is unaffected by an extra metadata
278/// key.
279///
280/// # Example
281///
282/// ```rust,no_run
283/// use adk_graph::interrupt::GraphInterruptPayload;
284/// # fn handle(event: &adk_core::Event) {
285/// if let Some(pause) = GraphInterruptPayload::from_event(event) {
286/// println!("paused at {:?}: {:?}", pause.node, pause.message);
287/// // Resume by invoking the same thread again, supplying any decision.
288/// }
289/// # }
290/// ```
291#[derive(Debug, Clone, Serialize, Deserialize)]
292pub struct GraphInterruptPayload {
293 /// `"before"`, `"after"`, or `"dynamic"`.
294 pub kind: String,
295 /// The gated node, for a static interrupt. `None` for a dynamic one, which
296 /// carries a message instead.
297 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub node: Option<String>,
299 /// The message a node supplied, for a dynamic interrupt.
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub message: Option<String>,
302 /// The data a node attached with `NodeOutput::interrupt_with_data`.
303 #[serde(default, skip_serializing_if = "Option::is_none")]
304 pub data: Option<Value>,
305 /// The pause's id, for a dynamic interrupt: answer it under this key.
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub interrupt_id: Option<String>,
308 /// The JSON Schema the answer must satisfy, when the node declared one.
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub response_schema: Option<Value>,
311 /// The thread to resume.
312 pub thread_id: String,
313 /// The checkpoint the run stopped at.
314 pub checkpoint_id: String,
315}
316
317impl GraphInterruptPayload {
318 /// Build a payload from an interrupt and the run it stopped.
319 pub fn new(interrupt: &Interrupt, thread_id: &str, checkpoint_id: &str) -> Self {
320 let (kind, node, message, data) = match interrupt {
321 Interrupt::Before(node) => ("before", Some(node.clone()), None, None),
322 Interrupt::After(node) => ("after", Some(node.clone()), None, None),
323 Interrupt::Dynamic { message, data, .. } => {
324 ("dynamic", None, Some(message.clone()), data.clone())
325 }
326 };
327 Self {
328 kind: kind.to_string(),
329 node,
330 message,
331 data,
332 interrupt_id: interrupt.id().map(str::to_string),
333 response_schema: interrupt.response_schema().cloned(),
334 thread_id: thread_id.to_string(),
335 checkpoint_id: checkpoint_id.to_string(),
336 }
337 }
338
339 /// Read the payload from an event, or `None` if the event is not a graph
340 /// interrupt.
341 pub fn from_event(event: &adk_core::Event) -> Option<Self> {
342 let raw = event.provider_metadata.get(INTERRUPT_METADATA_KEY)?;
343 serde_json::from_str(raw).ok()
344 }
345
346 /// Build a graph-agent interrupt payload for a tool-confirmation pause.
347 pub fn from_tool_confirmation_pause(pause: GraphToolConfirmationPause) -> Self {
348 let thread_id = pause.thread_id.clone();
349 let checkpoint_id = pause.checkpoint_id.clone();
350 Self {
351 kind: GraphToolConfirmationPause::KIND.to_string(),
352 node: Some(pause.node.clone()),
353 message: None,
354 data: serde_json::to_value(pause).ok(),
355 interrupt_id: None,
356 response_schema: None,
357 thread_id,
358 checkpoint_id,
359 }
360 }
361
362 /// Read the structured tool-confirmation pause, if this payload represents one.
363 pub fn tool_confirmation(&self) -> Option<GraphToolConfirmationPause> {
364 if self.kind != GraphToolConfirmationPause::KIND {
365 return None;
366 }
367 serde_json::from_value(self.data.clone()?).ok()
368 }
369
370 /// Serialize for transport in `Event::provider_metadata`.
371 pub fn to_metadata_value(&self) -> String {
372 serde_json::to_string(self).unwrap_or_default()
373 }
374}