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
//! Run outcomes and the human-in-the-loop interrupt protocol.
//!
//! A run does not only end in success or error. It can also *pause*: the agent
//! emits `RUN_FINISHED` with an [`RunOutcome::Interrupt`] outcome listing one or
//! more [`Interrupt`]s, the client collects the answers, and the next request
//! resumes the run by passing [`ResumeEntry`] values in
//! [`RunAgentInput::resume`](crate::input::RunAgentInput::resume).
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::JsonObject;
use crate::error::{Error, Result};
use crate::ids::{SubagentRunId, ToolCallId};
/// A request for human input that pauses the run.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct Interrupt {
/// Correlation id — echoed back as
/// [`ResumeEntry::interrupt_id`] when the run resumes.
pub id: String,
/// Machine-readable reason, for example `"tool_approval"`.
pub reason: String,
/// Human-readable prompt to show the user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
/// The tool call awaiting approval, when the interrupt is about one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_call_id: Option<ToolCallId>,
/// JSON Schema the resume payload must satisfy — lets a client render a
/// form for the answer.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
)]
#[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
pub response_schema: Option<JsonObject>,
/// When the interrupt stops being answerable, as an ISO-8601 timestamp.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
/// Integration-specific extras.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
)]
#[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
pub metadata: Option<JsonObject>,
/// The subagent whose work raised this interrupt, when it was raised
/// inside one — absent for a root-raised interrupt. Attribution lives on
/// each interrupt rather than on `RUN_FINISHED` because one run can carry
/// interrupts from several subagents; a client uses it to render the
/// approval request inside that subagent's group. A JSON `null` is
/// rejected — see [`crate::event::subagent`].
#[serde(
default,
deserialize_with = "crate::serde_util::reject_null",
skip_serializing_if = "Option::is_none"
)]
pub subagent_run_id: Option<SubagentRunId>,
}
impl Interrupt {
/// Builds an interrupt from its two required fields.
pub fn new(id: impl Into<String>, reason: impl Into<String>) -> Self {
Self {
id: id.into(),
reason: reason.into(),
..Default::default()
}
}
/// Sets the prompt to show the user.
///
/// ```
/// use ag_ui::Interrupt;
///
/// let interrupt = Interrupt::new("i-1", "tool_approval")
/// .with_message("Delete the staging database?")
/// .with_tool_call_id("call-7");
/// assert_eq!(interrupt.message.as_deref(), Some("Delete the staging database?"));
/// assert_eq!(interrupt.tool_call_id.as_ref().map(|id| id.as_str()), Some("call-7"));
/// ```
#[must_use]
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = Some(message.into());
self
}
/// Names the tool call this interrupt asks to approve.
#[must_use]
pub fn with_tool_call_id(mut self, tool_call_id: impl Into<ToolCallId>) -> Self {
self.tool_call_id = Some(tool_call_id.into());
self
}
/// Sets the JSON Schema the resume payload must satisfy.
#[must_use]
pub fn with_response_schema(mut self, schema: JsonObject) -> Self {
self.response_schema = Some(schema);
self
}
/// Attributes the interrupt to the subagent that raised it.
#[must_use]
pub fn with_subagent_run_id(mut self, subagent_run_id: impl Into<SubagentRunId>) -> Self {
self.subagent_run_id = Some(subagent_run_id.into());
self
}
}
/// How a run ended.
///
/// The field is optional on `RUN_FINISHED`: producers that predate the
/// interrupt protocol omit it entirely, which consumers must read as success.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum RunOutcome {
/// The run completed.
Success,
/// The run completed with frontend tool calls still awaiting answers.
///
/// This has the same wire discriminator as [`Self::Success`]. The separate
/// Rust variant keeps existing `RunOutcome::Success` callers working while
/// preserving the list supplied by an AG-UI 1.0 producer.
#[serde(rename = "success")]
SuccessWithPendingToolCalls {
/// Tool calls to answer in the next run's input, in call order.
#[serde(rename = "pendingToolCallIds")]
pending_tool_call_ids: Vec<ToolCallId>,
},
/// The run is paused, waiting on the answers to `interrupts`.
Interrupt {
/// The pending requests. The protocol requires at least one; see
/// [`RunOutcome::validate`].
interrupts: Vec<Interrupt>,
},
/// The run was stopped before completion without an execution error.
Cancelled,
}
// A struct-shaped success variant makes serde enforce unknown-field rejection;
// derive treats an internally tagged unit variant as an ignored payload.
impl<'de> Deserialize<'de> for RunOutcome {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum Wire {
Success {
#[serde(
rename = "pendingToolCallIds",
default,
deserialize_with = "crate::serde_util::reject_null"
)]
pending_tool_call_ids: Option<Vec<ToolCallId>>,
},
Interrupt {
interrupts: Vec<Interrupt>,
},
Cancelled {},
}
Ok(match Wire::deserialize(deserializer)? {
Wire::Success {
pending_tool_call_ids: Some(pending_tool_call_ids),
} => Self::SuccessWithPendingToolCalls {
pending_tool_call_ids,
},
Wire::Success {
pending_tool_call_ids: None,
} => Self::Success,
Wire::Interrupt { interrupts } => Self::Interrupt { interrupts },
Wire::Cancelled {} => Self::Cancelled,
})
}
}
impl RunOutcome {
/// A successful run with frontend tool calls to answer in the next input.
pub fn success_with_pending_tool_calls(
ids: impl IntoIterator<Item = impl Into<ToolCallId>>,
) -> Self {
Self::SuccessWithPendingToolCalls {
pending_tool_call_ids: ids.into_iter().map(Into::into).collect(),
}
}
/// Builds an interrupt outcome.
pub fn interrupt(interrupts: impl Into<Vec<Interrupt>>) -> Self {
Self::Interrupt {
interrupts: interrupts.into(),
}
}
/// Whether the run is paused rather than finished.
pub const fn is_interrupt(&self) -> bool {
matches!(self, Self::Interrupt { .. })
}
/// Whether execution stopped without completing or failing.
pub const fn is_cancelled(&self) -> bool {
matches!(self, Self::Cancelled)
}
/// Frontend tool calls still awaiting answers, in call order.
pub fn pending_tool_call_ids(&self) -> &[ToolCallId] {
match self {
Self::SuccessWithPendingToolCalls {
pending_tool_call_ids,
} => pending_tool_call_ids,
_ => &[],
}
}
/// The pending interrupts, or an empty slice for a success outcome.
pub fn interrupts(&self) -> &[Interrupt] {
match self {
Self::Interrupt { interrupts } => interrupts,
_ => &[],
}
}
/// Checks that an interrupt outcome carries at least one interrupt and each ID is unique.
///
/// Deserializing does not enforce this, so that a stray empty array from a
/// buggy producer surfaces as a protocol error you can log rather than as
/// an unparseable event that kills the stream.
pub fn validate(&self) -> Result<()> {
match self.interrupt_error() {
Some(reason) => Err(Error::Protocol(reason)),
None => Ok(()),
}
}
pub(crate) fn interrupt_error(&self) -> Option<String> {
let Self::Interrupt { interrupts } = self else {
return None;
};
if interrupts.is_empty() {
return Some("RUN_FINISHED outcome `interrupt` requires at least one interrupt".into());
}
let mut seen = std::collections::HashSet::new();
let repeated = interrupts.iter().find(|entry| !seen.insert(&entry.id))?;
Some(format!(
"RUN_FINISHED carries interrupt id \"{}\" more than once: an interrupt's id is unique within its run",
crate::serde_util::excerpt(&repeated.id, false)
))
}
}
/// How the client answered one interrupt.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum ResumeStatus {
/// The user answered; `payload` carries the answer.
Resolved,
/// The user declined or the request timed out.
Cancelled,
}
impl ResumeStatus {
/// The status string as it appears on the wire.
pub const fn as_str(&self) -> &'static str {
match self {
Self::Resolved => "resolved",
Self::Cancelled => "cancelled",
}
}
}
/// One answer to one [`Interrupt`], sent on the resuming request.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ResumeEntry {
/// The [`Interrupt::id`] being answered.
pub interrupt_id: String,
/// Whether the user answered or declined.
pub status: ResumeStatus,
/// The answer. Shape is up to the agent; when the interrupt supplied a
/// `responseSchema`, this should satisfy it. For a tool approval that was
/// edited before approval, agents that advertise `approveWithEdits` expect
/// `{"editedArgs": …}` here. `Some(Value::Null)` is written as an
/// omitted field, which is how AG-UI 1.0 spells no answer.
#[serde(default, skip_serializing_if = "crate::serde_util::is_none_or_null")]
pub payload: Option<Value>,
/// Envelope data about the answer — signatures, routing keys — as opposed
/// to `payload`, which is the answer the agent asked for and will act on.
/// A request field, so nothing merges into it. Absent or an object — a
/// JSON `null` is rejected. See [`crate::metadata`].
#[serde(
default,
deserialize_with = "crate::serde_util::reject_null",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(
feature = "schemars",
schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
)]
#[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
pub metadata: Option<JsonObject>,
}
impl ResumeEntry {
/// Answers an interrupt with a payload.
pub fn resolved(interrupt_id: impl Into<String>, payload: impl Into<Value>) -> Self {
Self {
interrupt_id: interrupt_id.into(),
status: ResumeStatus::Resolved,
payload: Some(payload.into()),
metadata: None,
}
}
/// Declines an interrupt.
pub fn cancelled(interrupt_id: impl Into<String>) -> Self {
Self {
interrupt_id: interrupt_id.into(),
status: ResumeStatus::Cancelled,
payload: None,
metadata: None,
}
}
/// Attaches envelope metadata to the answer.
#[must_use]
pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
self.metadata = Some(metadata);
self
}
}