Skip to main content

ag_ui/
outcome.rs

1//! Run outcomes and the human-in-the-loop interrupt protocol.
2//!
3//! A run does not only end in success or error. It can also *pause*: the agent
4//! emits `RUN_FINISHED` with an [`RunOutcome::Interrupt`] outcome listing one or
5//! more [`Interrupt`]s, the client collects the answers, and the next request
6//! resumes the run by passing [`ResumeEntry`] values in
7//! [`RunAgentInput::resume`](crate::input::RunAgentInput::resume).
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::JsonObject;
13use crate::error::{Error, Result};
14use crate::ids::{SubagentRunId, ToolCallId};
15
16/// A request for human input that pauses the run.
17#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase")]
19#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
20#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
21pub struct Interrupt {
22    /// Correlation id — echoed back as
23    /// [`ResumeEntry::interrupt_id`] when the run resumes.
24    pub id: String,
25    /// Machine-readable reason, for example `"tool_approval"`.
26    pub reason: String,
27    /// Human-readable prompt to show the user.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub message: Option<String>,
30    /// The tool call awaiting approval, when the interrupt is about one.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub tool_call_id: Option<ToolCallId>,
33    /// JSON Schema the resume payload must satisfy — lets a client render a
34    /// form for the answer.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    #[cfg_attr(
37        feature = "schemars",
38        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
39    )]
40    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
41    pub response_schema: Option<JsonObject>,
42    /// When the interrupt stops being answerable, as an ISO-8601 timestamp.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub expires_at: Option<String>,
45    /// Integration-specific extras.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    #[cfg_attr(
48        feature = "schemars",
49        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
50    )]
51    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
52    pub metadata: Option<JsonObject>,
53    /// The subagent whose work raised this interrupt, when it was raised
54    /// inside one — absent for a root-raised interrupt. Attribution lives on
55    /// each interrupt rather than on `RUN_FINISHED` because one run can carry
56    /// interrupts from several subagents; a client uses it to render the
57    /// approval request inside that subagent's group. A JSON `null` is
58    /// rejected — see [`crate::event::subagent`].
59    #[serde(
60        default,
61        deserialize_with = "crate::serde_util::reject_null",
62        skip_serializing_if = "Option::is_none"
63    )]
64    pub subagent_run_id: Option<SubagentRunId>,
65}
66
67impl Interrupt {
68    /// Builds an interrupt from its two required fields.
69    pub fn new(id: impl Into<String>, reason: impl Into<String>) -> Self {
70        Self {
71            id: id.into(),
72            reason: reason.into(),
73            ..Default::default()
74        }
75    }
76
77    /// Sets the prompt to show the user.
78    ///
79    /// ```
80    /// use ag_ui::Interrupt;
81    ///
82    /// let interrupt = Interrupt::new("i-1", "tool_approval")
83    ///     .with_message("Delete the staging database?")
84    ///     .with_tool_call_id("call-7");
85    /// assert_eq!(interrupt.message.as_deref(), Some("Delete the staging database?"));
86    /// assert_eq!(interrupt.tool_call_id.as_ref().map(|id| id.as_str()), Some("call-7"));
87    /// ```
88    #[must_use]
89    pub fn with_message(mut self, message: impl Into<String>) -> Self {
90        self.message = Some(message.into());
91        self
92    }
93
94    /// Names the tool call this interrupt asks to approve.
95    #[must_use]
96    pub fn with_tool_call_id(mut self, tool_call_id: impl Into<ToolCallId>) -> Self {
97        self.tool_call_id = Some(tool_call_id.into());
98        self
99    }
100
101    /// Sets the JSON Schema the resume payload must satisfy.
102    #[must_use]
103    pub fn with_response_schema(mut self, schema: JsonObject) -> Self {
104        self.response_schema = Some(schema);
105        self
106    }
107
108    /// Attributes the interrupt to the subagent that raised it.
109    #[must_use]
110    pub fn with_subagent_run_id(mut self, subagent_run_id: impl Into<SubagentRunId>) -> Self {
111        self.subagent_run_id = Some(subagent_run_id.into());
112        self
113    }
114}
115
116/// How a run ended.
117///
118/// The field is optional on `RUN_FINISHED`: producers that predate the
119/// interrupt protocol omit it entirely, which consumers must read as success.
120#[derive(Clone, Debug, PartialEq, Serialize)]
121#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
122#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
123#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
124pub enum RunOutcome {
125    /// The run completed.
126    Success,
127    /// The run completed with frontend tool calls still awaiting answers.
128    ///
129    /// This has the same wire discriminator as [`Self::Success`]. The separate
130    /// Rust variant keeps existing `RunOutcome::Success` callers working while
131    /// preserving the list supplied by an AG-UI 1.0 producer.
132    #[serde(rename = "success")]
133    SuccessWithPendingToolCalls {
134        /// Tool calls to answer in the next run's input, in call order.
135        #[serde(rename = "pendingToolCallIds")]
136        pending_tool_call_ids: Vec<ToolCallId>,
137    },
138    /// The run is paused, waiting on the answers to `interrupts`.
139    Interrupt {
140        /// The pending requests. The protocol requires at least one; see
141        /// [`RunOutcome::validate`].
142        interrupts: Vec<Interrupt>,
143    },
144    /// The run was stopped before completion without an execution error.
145    Cancelled,
146}
147
148// A struct-shaped success variant makes serde enforce unknown-field rejection;
149// derive treats an internally tagged unit variant as an ignored payload.
150impl<'de> Deserialize<'de> for RunOutcome {
151    fn deserialize<D: serde::Deserializer<'de>>(
152        deserializer: D,
153    ) -> std::result::Result<Self, D::Error> {
154        #[derive(Deserialize)]
155        #[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
156        enum Wire {
157            Success {
158                #[serde(
159                    rename = "pendingToolCallIds",
160                    default,
161                    deserialize_with = "crate::serde_util::reject_null"
162                )]
163                pending_tool_call_ids: Option<Vec<ToolCallId>>,
164            },
165            Interrupt {
166                interrupts: Vec<Interrupt>,
167            },
168            Cancelled {},
169        }
170        Ok(match Wire::deserialize(deserializer)? {
171            Wire::Success {
172                pending_tool_call_ids: Some(pending_tool_call_ids),
173            } => Self::SuccessWithPendingToolCalls {
174                pending_tool_call_ids,
175            },
176            Wire::Success {
177                pending_tool_call_ids: None,
178            } => Self::Success,
179            Wire::Interrupt { interrupts } => Self::Interrupt { interrupts },
180            Wire::Cancelled {} => Self::Cancelled,
181        })
182    }
183}
184
185impl RunOutcome {
186    /// A successful run with frontend tool calls to answer in the next input.
187    pub fn success_with_pending_tool_calls(
188        ids: impl IntoIterator<Item = impl Into<ToolCallId>>,
189    ) -> Self {
190        Self::SuccessWithPendingToolCalls {
191            pending_tool_call_ids: ids.into_iter().map(Into::into).collect(),
192        }
193    }
194
195    /// Builds an interrupt outcome.
196    pub fn interrupt(interrupts: impl Into<Vec<Interrupt>>) -> Self {
197        Self::Interrupt {
198            interrupts: interrupts.into(),
199        }
200    }
201
202    /// Whether the run is paused rather than finished.
203    pub const fn is_interrupt(&self) -> bool {
204        matches!(self, Self::Interrupt { .. })
205    }
206
207    /// Whether execution stopped without completing or failing.
208    pub const fn is_cancelled(&self) -> bool {
209        matches!(self, Self::Cancelled)
210    }
211
212    /// Frontend tool calls still awaiting answers, in call order.
213    pub fn pending_tool_call_ids(&self) -> &[ToolCallId] {
214        match self {
215            Self::SuccessWithPendingToolCalls {
216                pending_tool_call_ids,
217            } => pending_tool_call_ids,
218            _ => &[],
219        }
220    }
221
222    /// The pending interrupts, or an empty slice for a success outcome.
223    pub fn interrupts(&self) -> &[Interrupt] {
224        match self {
225            Self::Interrupt { interrupts } => interrupts,
226            _ => &[],
227        }
228    }
229
230    /// Checks that an interrupt outcome carries at least one interrupt and each ID is unique.
231    ///
232    /// Deserializing does not enforce this, so that a stray empty array from a
233    /// buggy producer surfaces as a protocol error you can log rather than as
234    /// an unparseable event that kills the stream.
235    pub fn validate(&self) -> Result<()> {
236        match self.interrupt_error() {
237            Some(reason) => Err(Error::Protocol(reason)),
238            None => Ok(()),
239        }
240    }
241
242    pub(crate) fn interrupt_error(&self) -> Option<String> {
243        let Self::Interrupt { interrupts } = self else {
244            return None;
245        };
246        if interrupts.is_empty() {
247            return Some("RUN_FINISHED outcome `interrupt` requires at least one interrupt".into());
248        }
249        let mut seen = std::collections::HashSet::new();
250        let repeated = interrupts.iter().find(|entry| !seen.insert(&entry.id))?;
251        Some(format!(
252            "RUN_FINISHED carries interrupt id \"{}\" more than once: an interrupt's id is unique within its run",
253            crate::serde_util::excerpt(&repeated.id, false)
254        ))
255    }
256}
257
258/// How the client answered one interrupt.
259#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
260#[serde(rename_all = "lowercase")]
261#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
262#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
263pub enum ResumeStatus {
264    /// The user answered; `payload` carries the answer.
265    Resolved,
266    /// The user declined or the request timed out.
267    Cancelled,
268}
269
270impl ResumeStatus {
271    /// The status string as it appears on the wire.
272    pub const fn as_str(&self) -> &'static str {
273        match self {
274            Self::Resolved => "resolved",
275            Self::Cancelled => "cancelled",
276        }
277    }
278}
279
280/// One answer to one [`Interrupt`], sent on the resuming request.
281#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
282#[serde(rename_all = "camelCase")]
283#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
284#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
285pub struct ResumeEntry {
286    /// The [`Interrupt::id`] being answered.
287    pub interrupt_id: String,
288    /// Whether the user answered or declined.
289    pub status: ResumeStatus,
290    /// The answer. Shape is up to the agent; when the interrupt supplied a
291    /// `responseSchema`, this should satisfy it. For a tool approval that was
292    /// edited before approval, agents that advertise `approveWithEdits` expect
293    /// `{"editedArgs": …}` here. `Some(Value::Null)` is written as an
294    /// omitted field, which is how AG-UI 1.0 spells no answer.
295    #[serde(default, skip_serializing_if = "crate::serde_util::is_none_or_null")]
296    pub payload: Option<Value>,
297    /// Envelope data about the answer — signatures, routing keys — as opposed
298    /// to `payload`, which is the answer the agent asked for and will act on.
299    /// A request field, so nothing merges into it. Absent or an object — a
300    /// JSON `null` is rejected. See [`crate::metadata`].
301    #[serde(
302        default,
303        deserialize_with = "crate::serde_util::reject_null",
304        skip_serializing_if = "Option::is_none"
305    )]
306    #[cfg_attr(
307        feature = "schemars",
308        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
309    )]
310    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
311    pub metadata: Option<JsonObject>,
312}
313
314impl ResumeEntry {
315    /// Answers an interrupt with a payload.
316    pub fn resolved(interrupt_id: impl Into<String>, payload: impl Into<Value>) -> Self {
317        Self {
318            interrupt_id: interrupt_id.into(),
319            status: ResumeStatus::Resolved,
320            payload: Some(payload.into()),
321            metadata: None,
322        }
323    }
324
325    /// Declines an interrupt.
326    pub fn cancelled(interrupt_id: impl Into<String>) -> Self {
327        Self {
328            interrupt_id: interrupt_id.into(),
329            status: ResumeStatus::Cancelled,
330            payload: None,
331            metadata: None,
332        }
333    }
334
335    /// Attaches envelope metadata to the answer.
336    #[must_use]
337    pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
338        self.metadata = Some(metadata);
339        self
340    }
341}