1use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::JsonObject;
13use crate::error::{Error, Result};
14use crate::ids::{SubagentRunId, ToolCallId};
15
16#[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 pub id: String,
25 pub reason: String,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub message: Option<String>,
30 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub tool_call_id: Option<ToolCallId>,
33 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub expires_at: Option<String>,
45 #[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 #[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 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 #[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 #[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 #[must_use]
103 pub fn with_response_schema(mut self, schema: JsonObject) -> Self {
104 self.response_schema = Some(schema);
105 self
106 }
107
108 #[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#[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 Success,
127 #[serde(rename = "success")]
133 SuccessWithPendingToolCalls {
134 #[serde(rename = "pendingToolCallIds")]
136 pending_tool_call_ids: Vec<ToolCallId>,
137 },
138 Interrupt {
140 interrupts: Vec<Interrupt>,
143 },
144 Cancelled,
146}
147
148impl<'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 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 pub fn interrupt(interrupts: impl Into<Vec<Interrupt>>) -> Self {
197 Self::Interrupt {
198 interrupts: interrupts.into(),
199 }
200 }
201
202 pub const fn is_interrupt(&self) -> bool {
204 matches!(self, Self::Interrupt { .. })
205 }
206
207 pub const fn is_cancelled(&self) -> bool {
209 matches!(self, Self::Cancelled)
210 }
211
212 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 pub fn interrupts(&self) -> &[Interrupt] {
224 match self {
225 Self::Interrupt { interrupts } => interrupts,
226 _ => &[],
227 }
228 }
229
230 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#[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 Resolved,
266 Cancelled,
268}
269
270impl ResumeStatus {
271 pub const fn as_str(&self) -> &'static str {
273 match self {
274 Self::Resolved => "resolved",
275 Self::Cancelled => "cancelled",
276 }
277 }
278}
279
280#[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 pub interrupt_id: String,
288 pub status: ResumeStatus,
290 #[serde(default, skip_serializing_if = "crate::serde_util::is_none_or_null")]
296 pub payload: Option<Value>,
297 #[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 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 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 #[must_use]
337 pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
338 self.metadata = Some(metadata);
339 self
340 }
341}