Skip to main content

strands/
interrupt.rs

1//! Human-in-the-loop interrupts and their persisted state.
2//!
3//! A hook or tool raises an [`Interrupt`]; the agent stops with `StopReason::Interrupt`; the caller
4//! resumes it with `InterruptResponseContent` blocks, and the raiser then receives the response.
5//! The interrupt state stored under `interrupts` in an agent snapshot is crate-internal.
6
7use std::fmt;
8use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
9
10use indexmap::IndexMap;
11use serde::{Deserialize, Serialize};
12
13use crate::error::{Error, Result as SdkResult, SessionError};
14use crate::types::json::present;
15use crate::types::{
16    ContentBlock, InterruptParams, InterruptResponseContent, JsonObject, JsonValue, Message, Role, ToolResultBlock,
17};
18
19/// Where an interrupt was raised (`InterruptSource`).
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[non_exhaustive]
22pub enum InterruptSource {
23    /// A tool, through its context's `interrupt`.
24    #[serde(rename = "tool")]
25    Tool,
26    /// An agent hook, such as `BeforeToolCallEvent::interrupt`. Snapshots from SDKs that did not
27    /// record a source default to it.
28    #[default]
29    #[serde(rename = "hook")]
30    Hook,
31    /// Middleware.
32    #[serde(rename = "middleware")]
33    Middleware,
34    /// A multi-agent orchestrator hook.
35    #[serde(rename = "multiagent-hook")]
36    MultiagentHook,
37}
38
39/// An interrupt that pauses agent execution for human input (`Interrupt`).
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41#[non_exhaustive]
42pub struct Interrupt {
43    /// Unique identifier, such as `tool:<toolUseId>:<name>`.
44    pub id: String,
45    /// The user-defined name.
46    pub name: String,
47    /// Why the interrupt was raised. A saved `null` stays `Some(JsonValue::Null)`.
48    #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
49    pub reason: Option<JsonValue>,
50    /// The human response provided on resume. A saved `null` stays `Some(JsonValue::Null)`, which
51    /// counts as answered.
52    #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
53    pub response: Option<JsonValue>,
54    /// Where the interrupt was raised.
55    #[serde(default)]
56    pub source: InterruptSource,
57}
58
59impl Interrupt {
60    /// Creates an interrupt raised by a hook, with no reason or response.
61    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
62        Self {
63            id: id.into(),
64            name: name.into(),
65            reason: None,
66            response: None,
67            source: InterruptSource::Hook,
68        }
69    }
70
71    /// Sets the reason.
72    #[must_use]
73    pub fn with_reason(mut self, reason: impl Into<JsonValue>) -> Self {
74        self.reason = Some(reason.into());
75        self
76    }
77
78    /// Sets the response.
79    #[must_use]
80    pub fn with_response(mut self, response: impl Into<JsonValue>) -> Self {
81        self.response = Some(response.into());
82        self
83    }
84
85    /// Sets the source.
86    #[must_use]
87    pub fn with_source(mut self, source: InterruptSource) -> Self {
88        self.source = source;
89        self
90    }
91}
92
93/// One or more unanswered interrupts as an error (`InterruptError`).
94///
95/// [`ToolContext::interrupt`](crate::ToolContext::interrupt) and the hook events' `interrupt`
96/// return it when no response is known yet. Propagate it with `?`: from a tool body it ends the
97/// tool as [`ToolOutcome::Interrupt`](crate::ToolOutcome), from a hook it stops the invocation
98/// with `StopReason::Interrupt` once every callback has run, and it survives conversion into a
99/// [`BoxError`](crate::BoxError) or a [`ToolError`](crate::ToolError) on the way. The message is
100/// `Interrupt raised: <name>`, or `<n> interrupts raised: <a>, <b>`.
101///
102/// ```
103/// use strands::{Interrupt, InterruptError};
104///
105/// let error = InterruptError::from(Interrupt::new("hook:beforeTools:confirm", "confirm"));
106/// assert_eq!(error.to_string(), "Interrupt raised: confirm");
107/// assert_eq!(error.interrupts.len(), 1);
108/// ```
109#[derive(Debug, Clone, PartialEq)]
110#[non_exhaustive]
111pub struct InterruptError {
112    /// The interrupts, in the order they were raised.
113    pub interrupts: Vec<Interrupt>,
114}
115
116impl InterruptError {
117    /// Creates the error from the interrupts it reports.
118    pub fn new(interrupts: impl IntoIterator<Item = Interrupt>) -> Self {
119        Self {
120            interrupts: interrupts.into_iter().collect(),
121        }
122    }
123
124    /// The interrupts, consuming the error.
125    #[must_use]
126    pub fn into_interrupts(self) -> Vec<Interrupt> {
127        self.interrupts
128    }
129}
130
131impl From<Interrupt> for InterruptError {
132    fn from(interrupt: Interrupt) -> Self {
133        Self {
134            interrupts: vec![interrupt],
135        }
136    }
137}
138
139impl From<Vec<Interrupt>> for InterruptError {
140    fn from(interrupts: Vec<Interrupt>) -> Self {
141        Self { interrupts }
142    }
143}
144
145impl fmt::Display for InterruptError {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        let names: Vec<&str> = self
148            .interrupts
149            .iter()
150            .map(|interrupt| interrupt.name.as_str())
151            .collect();
152        match names.as_slice() {
153            [name] => write!(f, "Interrupt raised: {name}"),
154            _ => write!(f, "{} interrupts raised: {}", names.len(), names.join(", ")),
155        }
156    }
157}
158
159impl std::error::Error for InterruptError {}
160
161/// Tool execution state saved when an interrupt stops a batch of tool calls
162/// (`PendingToolExecution`), so resuming does not call the model again.
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
164#[serde(rename_all = "camelCase")]
165pub(crate) struct PendingToolExecution {
166    /// The assistant message with the tool uses.
167    pub(crate) assistant_message_data: Message,
168    /// Results of the tools that finished before the interrupt, by tool use id. Each serializes
169    /// as `{"toolResult": {...}}`.
170    #[serde(with = "wrapped_tool_results")]
171    pub(crate) completed_tool_results: IndexMap<String, ToolResultBlock>,
172}
173
174impl PendingToolExecution {
175    /// Creates pending state for an assistant message.
176    pub(crate) fn new(
177        assistant_message_data: Message,
178        completed_tool_results: IndexMap<String, ToolResultBlock>,
179    ) -> Self {
180        Self {
181            assistant_message_data,
182            completed_tool_results,
183        }
184    }
185}
186
187/// The persisted interrupt state of an agent (`InterruptStateData`).
188#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub(crate) struct InterruptStateData {
191    /// Interrupts by id, in the order they were raised.
192    pub(crate) interrupts: IndexMap<String, Interrupt>,
193    /// The responses given when resuming.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub(crate) resume_responses: Option<Vec<InterruptResponseContent>>,
196    /// Whether the agent is in an interrupted state.
197    pub(crate) activated: bool,
198    /// Tool execution to resume.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub(crate) pending_tool_execution: Option<PendingToolExecution>,
201    /// State carried for the duration of an interrupt, such as an interrupted sub-agent turn.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub(crate) context: Option<JsonObject>,
204}
205
206impl InterruptStateData {
207    /// Creates empty, inactive state.
208    pub(crate) fn new() -> Self {
209        Self::default()
210    }
211
212    /// Restores persisted state (`InterruptState.fromJSON`). A pending tool execution is kept only
213    /// when the state is activated, and is then validated so a resume cannot run a corrupt batch.
214    ///
215    /// # Errors
216    ///
217    /// A `SessionError` naming the malformed pending-execution field, or a decode error for the
218    /// rest of the state.
219    pub(crate) fn from_json(value: JsonValue) -> SdkResult<Self> {
220        let JsonValue::Object(mut object) = value else {
221            return Err(Error::other("interrupt state must be an object"));
222        };
223        let pending = object.remove("pendingToolExecution");
224        let mut data: Self = serde_json::from_value(JsonValue::Object(object))?;
225        data.pending_tool_execution = match pending {
226            Some(pending) if data.activated && !pending.is_null() => Some(validate_pending_tool_execution(pending)?),
227            _ => None,
228        };
229        Ok(data)
230    }
231}
232
233const PENDING_MESSAGE_FIELD: &str = "field=<pendingToolExecution.assistantMessageData>";
234const PENDING_RESULTS_FIELD: &str = "field=<pendingToolExecution.completedToolResults>";
235
236/// Checks that restored pending tool execution data can be resumed: an assistant message with
237/// tool uses, and completed results keyed by tool use ids from that message.
238fn validate_pending_tool_execution(pending: JsonValue) -> SdkResult<PendingToolExecution> {
239    let mut pending = match pending {
240        JsonValue::Object(object) => object,
241        _ => JsonObject::new(),
242    };
243    let message_data = pending.remove("assistantMessageData").unwrap_or(JsonValue::Null);
244    let assistant_message: Message = parse_restored(PENDING_MESSAGE_FIELD, message_data)?;
245    if assistant_message.role != Role::Assistant {
246        return Err(SessionError::new(
247            "field=<pendingToolExecution.assistantMessageData.role> | pending tool execution message must be an assistant message",
248        )
249        .into());
250    }
251    let tool_use_ids: Vec<&str> = assistant_message
252        .content
253        .iter()
254        .filter_map(|block| match block {
255            ContentBlock::ToolUse(tool_use) => Some(tool_use.tool_use_id.as_str()),
256            _ => None,
257        })
258        .collect();
259    if tool_use_ids.is_empty() {
260        return Err(SessionError::new(
261            "field=<pendingToolExecution.assistantMessageData.content> | pending tool execution message has no tool uses",
262        )
263        .into());
264    }
265    let Some(JsonValue::Object(results)) = pending.remove("completedToolResults") else {
266        return Err(SessionError::new(format!(
267            "{PENDING_RESULTS_FIELD} | completed tool results must be an object"
268        ))
269        .into());
270    };
271    let mut completed_tool_results = IndexMap::new();
272    for (tool_use_id, value) in results {
273        let field = format!("{PENDING_RESULTS_FIELD}, tool_use_id=<{tool_use_id}>");
274        if !tool_use_ids.contains(&tool_use_id.as_str()) {
275            return Err(SessionError::new(format!(
276                "{field} | does not match a tool use in the pending assistant message"
277            ))
278            .into());
279        }
280        let wrapped = match value {
281            JsonValue::Object(mut wrapped) => wrapped.remove("toolResult").unwrap_or(JsonValue::Null),
282            _ => JsonValue::Null,
283        };
284        let result: ToolResultBlock = parse_restored(&field, wrapped)?;
285        completed_tool_results.insert(tool_use_id, result);
286    }
287    Ok(PendingToolExecution::new(assistant_message, completed_tool_results))
288}
289
290/// Parses restored data, turning a failure into a `SessionError` with the field context and the
291/// parse error as its source.
292fn parse_restored<T: serde::de::DeserializeOwned>(field: &str, value: JsonValue) -> SdkResult<T> {
293    serde_json::from_value(value).map_err(|error| {
294        SessionError::new(format!("{field} | failed to parse restored pending tool execution"))
295            .with_source(error)
296            .into()
297    })
298}
299
300mod wrapped_tool_results {
301    use indexmap::IndexMap;
302    use serde::de::Error as _;
303    use serde::ser::SerializeMap;
304    use serde::{Deserialize, Deserializer, Serialize, Serializer};
305
306    use crate::types::{JsonValue, ToolResultBlock};
307
308    #[derive(Serialize)]
309    #[serde(rename_all = "camelCase")]
310    struct Wrapped<'a> {
311        tool_result: &'a ToolResultBlock,
312    }
313
314    pub(super) fn serialize<S: Serializer>(
315        results: &IndexMap<String, ToolResultBlock>,
316        serializer: S,
317    ) -> Result<S::Ok, S::Error> {
318        let mut map = serializer.serialize_map(Some(results.len()))?;
319        for (tool_use_id, result) in results {
320            map.serialize_entry(tool_use_id, &Wrapped { tool_result: result })?;
321        }
322        map.end()
323    }
324
325    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
326        deserializer: D,
327    ) -> Result<IndexMap<String, ToolResultBlock>, D::Error> {
328        IndexMap::<String, JsonValue>::deserialize(deserializer)?
329            .into_iter()
330            .map(|(tool_use_id, value)| unwrap_tool_result(value).map(|result| (tool_use_id, result)))
331            .collect::<Result<_, _>>()
332            .map_err(D::Error::custom)
333    }
334
335    fn unwrap_tool_result(value: JsonValue) -> Result<ToolResultBlock, serde_json::Error> {
336        let JsonValue::Object(mut map) = value else {
337            return Err(serde_json::Error::custom("completed tool result must be an object"));
338        };
339        let Some(inner) = map.remove("toolResult") else {
340            return Err(serde_json::Error::custom(
341                "completed tool result must hold a toolResult",
342            ));
343        };
344        ToolResultBlock::deserialize(inner)
345    }
346}
347
348/// The live interrupt state of an agent (`InterruptState`), shared by the loop, hook events and
349/// tool contexts. Clones share the same state.
350#[derive(Debug, Clone, Default)]
351pub(crate) struct InterruptState {
352    data: Arc<Mutex<InterruptStateData>>,
353}
354
355impl InterruptState {
356    /// Creates empty, inactive state.
357    pub(crate) fn new() -> Self {
358        Self::default()
359    }
360
361    fn lock(&self) -> MutexGuard<'_, InterruptStateData> {
362        self.data.lock().unwrap_or_else(PoisonError::into_inner)
363    }
364
365    /// Returns the interrupt registered under `id`, registering a new one first.
366    pub(crate) fn get_or_create_interrupt(
367        &self,
368        id: &str,
369        params: &InterruptParams,
370        source: InterruptSource,
371    ) -> Interrupt {
372        let mut data = self.lock();
373        data.interrupts
374            .entry(id.to_owned())
375            .or_insert_with(|| Interrupt {
376                id: id.to_owned(),
377                name: params.name.clone(),
378                reason: params.reason.clone(),
379                response: params.response.clone(),
380                source,
381            })
382            .clone()
383    }
384
385    /// The response stored for the interrupt `id`, without registering it.
386    pub(crate) fn response(&self, id: &str) -> Option<JsonValue> {
387        self.lock()
388            .interrupts
389            .get(id)
390            .and_then(|interrupt| interrupt.response.clone())
391    }
392
393    /// Raises an interrupt: returns the stored response when the interrupt
394    /// was answered (or `params` carries a preemptive response), otherwise the unanswered
395    /// interrupt as the error.
396    pub(crate) fn raise(
397        &self,
398        id: &str,
399        params: &InterruptParams,
400        source: InterruptSource,
401    ) -> Result<JsonValue, InterruptError> {
402        let interrupt = self.get_or_create_interrupt(id, params, source);
403        match interrupt.response {
404            Some(response) => Ok(response),
405            None => Err(interrupt.into()),
406        }
407    }
408
409    /// Records a response for an interrupt, as resuming does.
410    /// Whether the agent stopped for interrupts and awaits responses (`activated`).
411    pub(crate) fn activated(&self) -> bool {
412        self.lock().activated
413    }
414
415    /// Marks the agent interrupted (`activate`).
416    pub(crate) fn activate(&self) {
417        self.lock().activated = true;
418    }
419
420    /// Clears every interrupt, response and stored execution (`deactivate`).
421    pub(crate) fn deactivate(&self) {
422        *self.lock() = InterruptStateData::new();
423    }
424
425    /// Records the responses of a resume on their interrupts (`resume`). Does nothing unless
426    /// activated.
427    ///
428    /// # Errors
429    ///
430    /// `interrupt_id=<id> | no interrupt found` for a response to an unknown interrupt.
431    pub(crate) fn resume(&self, responses: &[InterruptResponseContent]) -> crate::error::Result<()> {
432        let mut data = self.lock();
433        if !data.activated {
434            return Ok(());
435        }
436        for content in responses {
437            let id = &content.interrupt_response.interrupt_id;
438            let Some(interrupt) = data.interrupts.get_mut(id) else {
439                return Err(crate::error::Error::other(format!(
440                    "interrupt_id=<{id}> | no interrupt found"
441                )));
442            };
443            interrupt.response = Some(content.interrupt_response.response.clone());
444        }
445        data.resume_responses = Some(responses.to_vec());
446        Ok(())
447    }
448
449    /// Registers an interrupt raised elsewhere without its response.
450    pub(crate) fn register_interrupt(&self, interrupt: &Interrupt) -> Interrupt {
451        let params = InterruptParams {
452            name: interrupt.name.clone(),
453            reason: interrupt.reason.clone(),
454            response: None,
455        };
456        self.get_or_create_interrupt(&interrupt.id, &params, interrupt.source)
457    }
458
459    /// The interrupts still awaiting a response, in registration order.
460    pub(crate) fn unanswered_interrupts(&self) -> Vec<Interrupt> {
461        self.lock()
462            .interrupts
463            .values()
464            .filter(|interrupt| interrupt.response.is_none())
465            .cloned()
466            .collect()
467    }
468
469    /// Every registered interrupt, in registration order.
470    pub(crate) fn interrupt_list(&self) -> Vec<Interrupt> {
471        self.lock().interrupts.values().cloned().collect()
472    }
473
474    /// Forgets the response of an interrupt, so it is unanswered again.
475    pub(crate) fn clear_response(&self, id: &str) {
476        if let Some(interrupt) = self.lock().interrupts.get_mut(id) {
477            interrupt.response = None;
478        }
479    }
480
481    /// The responses of the latest resume.
482    pub(crate) fn resume_responses(&self) -> Vec<InterruptResponseContent> {
483        self.lock().resume_responses.clone().unwrap_or_default()
484    }
485
486    /// The tool batch to resume, when activated with one stored.
487    pub(crate) fn pending_execution(&self) -> Option<PendingToolExecution> {
488        let data = self.lock();
489        if !data.activated {
490            return None;
491        }
492        data.pending_tool_execution.clone()
493    }
494
495    /// Whether a tool batch is stored for resume.
496    pub(crate) fn has_pending_tool_execution(&self) -> bool {
497        self.lock().pending_tool_execution.is_some()
498    }
499
500    /// Stores the tool batch an interrupt stopped.
501    pub(crate) fn set_pending_tool_execution(&self, pending: PendingToolExecution) {
502        self.lock().pending_tool_execution = Some(pending);
503    }
504
505    /// Drops the stored tool batch.
506    pub(crate) fn clear_pending_tool_execution(&self) {
507        self.lock().pending_tool_execution = None;
508    }
509
510    /// A value of the free-form context that subsystems keep with the interrupt state.
511    pub(crate) fn context_value(&self, key: &str) -> Option<JsonValue> {
512        self.lock()
513            .context
514            .as_ref()
515            .and_then(|context| context.get(key).cloned())
516    }
517
518    /// Sets (or with `None` removes) a value of the context.
519    pub(crate) fn set_context_value(&self, key: &str, value: Option<JsonValue>) {
520        let mut data = self.lock();
521        let context = data.context.get_or_insert_with(JsonObject::new);
522        match value {
523            Some(value) => {
524                context.insert(key.to_owned(), value);
525            }
526            None => {
527                context.shift_remove(key);
528            }
529        }
530        if context.is_empty() {
531            data.context = None;
532        }
533    }
534
535    /// A copy of the state as persisted.
536    pub(crate) fn to_data(&self) -> InterruptStateData {
537        self.lock().clone()
538    }
539
540    /// Replaces the state, keeping every clone attached. A stored batch is kept only
541    /// when activated.
542    pub(crate) fn load_data(&self, mut data: InterruptStateData) {
543        if !data.activated {
544            data.pending_tool_execution = None;
545        }
546        *self.lock() = data;
547    }
548
549    #[cfg(test)]
550    pub(crate) fn respond(&self, id: &str, response: JsonValue) {
551        if let Some(interrupt) = self.lock().interrupts.get_mut(id) {
552            interrupt.response = Some(response);
553        }
554    }
555
556    /// The registered interrupts, in the order they were raised.
557    #[cfg(test)]
558    pub(crate) fn interrupts(&self) -> Vec<Interrupt> {
559        self.lock().interrupts.values().cloned().collect()
560    }
561}
562
563#[cfg(test)]
564mod tests {
565    use serde_json::json;
566
567    use super::*;
568    use crate::types::{ContentBlock, InterruptResponse, Role, ToolResultContent, ToolUseBlock, UnknownBlock};
569
570    fn pending_tool_execution() -> JsonValue {
571        json!({
572            "assistantMessageData": {
573                "role": "assistant",
574                "content": [
575                    {"toolUse": {"name": "tool", "toolUseId": "t-0", "input": {}}},
576                    {"toolUse": {"name": "tool", "toolUseId": "t-1", "input": {}}}
577                ],
578                "trackingId": "m-1"
579            },
580            "completedToolResults": {
581                "t-0": {"toolResult": {"toolUseId": "t-0", "status": "success", "content": []}}
582            }
583        })
584    }
585
586    #[test]
587    fn constructs_with_all_fields_and_supports_response_mutation() {
588        let mut interrupt = Interrupt::new("int-1", "confirm_action")
589            .with_reason("Please confirm")
590            .with_response("approved");
591        assert_eq!(
592            serde_json::to_value(&interrupt).unwrap(),
593            json!({"id": "int-1", "name": "confirm_action", "reason": "Please confirm", "response": "approved", "source": "hook"})
594        );
595        interrupt.response = Some(json!("changed"));
596        assert_eq!(interrupt.response, Some(json!("changed")));
597    }
598
599    #[test]
600    fn round_trips_through_json_serialization_with_complex_data() {
601        let original = Interrupt::new("int-1", "test")
602            .with_reason(json!({"complex": {"nested": "data"}}))
603            .with_response(json!(["array", "response"]));
604        let restored: Interrupt = serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap();
605        assert_eq!(restored, original);
606    }
607
608    #[test]
609    fn omits_undefined_reason_response_from_to_json() {
610        assert_eq!(
611            serde_json::to_value(Interrupt::new("int-1", "test")).unwrap(),
612            json!({"id": "int-1", "name": "test", "source": "hook"})
613        );
614    }
615
616    #[test]
617    fn keeps_a_null_reason_and_response() {
618        let wire = json!({"id": "int-1", "name": "test", "reason": null, "response": null, "source": "tool"});
619        let interrupt: Interrupt = serde_json::from_value(wire.clone()).unwrap();
620        assert_eq!(interrupt.response, Some(JsonValue::Null));
621        assert_eq!(serde_json::to_value(&interrupt).unwrap(), wire);
622    }
623
624    fn persisted_interrupt_states() -> Vec<(String, String)> {
625        let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../conformance/fixtures");
626        let mut states = Vec::new();
627        for area in ["interrupts", "snapshots", "sessions"] {
628            let text = std::fs::read_to_string(fixtures.join(format!("{area}.json"))).unwrap();
629            let fixture: JsonValue = serde_json::from_str(&text).unwrap();
630            for case in fixture["cases"].as_array().unwrap() {
631                let name = format!("{area}/{}", case["name"].as_str().unwrap());
632                let json = case["json"].as_str().unwrap();
633                if name.starts_with("interrupts/interrupt_state_") {
634                    states.push((name, json.to_owned()));
635                    continue;
636                }
637                let value: JsonValue = serde_json::from_str(json).unwrap();
638                let state = &value["data"]["interrupts"];
639                if state.is_object() {
640                    states.push((name, serde_json::to_string(state).unwrap()));
641                }
642            }
643        }
644        states
645    }
646
647    #[test]
648    fn interrupt_state_fixtures_round_trip_byte_identically() {
649        let states = persisted_interrupt_states();
650        assert!(states.len() >= 6);
651        for (name, json) in states {
652            let state: InterruptStateData = serde_json::from_str(&json).unwrap();
653            assert_eq!(serde_json::to_string(&state).unwrap(), json, "{name}");
654        }
655    }
656
657    #[test]
658    fn legacy_interrupts_without_a_source_default_to_hook() {
659        let interrupt: Interrupt = serde_json::from_value(json!({"id": "int-1", "name": "test"})).unwrap();
660        assert_eq!(interrupt.source, InterruptSource::Hook);
661    }
662
663    #[test]
664    fn round_trips_through_json_with_full_state() {
665        let mut state = InterruptStateData::new();
666        state.interrupts.insert(
667            "int-1".into(),
668            Interrupt::new("int-1", "test")
669                .with_reason(json!({"complex": "reason"}))
670                .with_response(json!(["array", "response"])),
671        );
672        state.activated = true;
673        let text = serde_json::to_string(&state).unwrap();
674        let restored: InterruptStateData = serde_json::from_str(&text).unwrap();
675        assert_eq!(restored, state);
676        assert_eq!(serde_json::to_string(&restored).unwrap(), text);
677    }
678
679    #[test]
680    fn round_trips_pending_tool_execution_through_json() {
681        let data = json!({"interrupts": {}, "activated": true, "pendingToolExecution": pending_tool_execution()});
682        let state: InterruptStateData = serde_json::from_value(data.clone()).unwrap();
683        let pending = state.pending_tool_execution.as_ref().unwrap();
684        assert_eq!(pending.assistant_message_data.role, Role::Assistant);
685        assert_eq!(
686            pending.completed_tool_results["t-0"],
687            ToolResultBlock::success("t-0", Vec::new())
688        );
689        assert_eq!(serde_json::to_value(&state).unwrap(), data);
690    }
691
692    #[test]
693    fn deserializes_state_with_resume_responses() {
694        let state: InterruptStateData = serde_json::from_value(json!({
695            "interrupts": {"int-1": {"id": "int-1", "name": "test", "reason": "reason", "response": "yes"}},
696            "resumeResponses": [{"interruptResponse": {"interruptId": "int-1", "response": "yes"}}],
697            "activated": true
698        }))
699        .unwrap();
700        assert!(state.activated);
701        assert_eq!(state.interrupts["int-1"].response, Some(json!("yes")));
702        assert_eq!(
703            state.resume_responses,
704            Some(vec![InterruptResponseContent::new(InterruptResponse::new(
705                "int-1", "yes"
706            ))])
707        );
708    }
709
710    #[test]
711    fn restores_a_pending_tool_execution_a_newer_sdk_saved_with_content_block_types_this_version_does_not_know() {
712        let saved = json!({
713            "assistantMessageData": {
714                "role": "assistant",
715                "content": [
716                    {"futureBlock": {"value": 1}},
717                    {"toolUse": {"name": "load_tools", "toolUseId": "t-0", "input": {}}},
718                    {"toolUse": {"name": "tool", "toolUseId": "t-1", "input": {}}}
719                ],
720                "trackingId": "m-1"
721            },
722            "completedToolResults": {
723                "t-0": {"toolResult": {
724                    "toolUseId": "t-0",
725                    "status": "success",
726                    "content": [{"text": "loaded"}, {"futureBlock": {"name": "shell"}}]
727                }}
728            }
729        });
730        let data = json!({"interrupts": {}, "activated": true, "pendingToolExecution": saved});
731        let state: InterruptStateData = serde_json::from_value(data.clone()).unwrap();
732        let pending = state.pending_tool_execution.as_ref().unwrap();
733        assert!(matches!(
734            pending.assistant_message_data.content[0],
735            ContentBlock::Unknown(_)
736        ));
737        assert_eq!(
738            pending.assistant_message_data.content[1],
739            ToolUseBlock::new("load_tools", "t-0", json!({})).into()
740        );
741        assert_eq!(
742            pending.completed_tool_results["t-0"].content[1],
743            ToolResultContent::Unknown(UnknownBlock::new(
744                json!({"futureBlock": {"name": "shell"}}).as_object().unwrap().clone()
745            ))
746        );
747        assert_eq!(serde_json::to_value(&state).unwrap(), data);
748    }
749
750    #[test]
751    fn interrupts_keep_their_insertion_order() {
752        let state: InterruptStateData = serde_json::from_value(json!({
753            "interrupts": {
754                "z": {"id": "z", "name": "z", "source": "tool"},
755                "a": {"id": "a", "name": "a", "source": "middleware"}
756            },
757            "activated": true
758        }))
759        .unwrap();
760        assert_eq!(state.interrupts.keys().collect::<Vec<_>>(), ["z", "a"]);
761        assert_eq!(state.interrupts["a"].source, InterruptSource::Middleware);
762    }
763    fn params(name: &str, reason: Option<&str>) -> InterruptParams {
764        let params = InterruptParams::new(name);
765        match reason {
766            Some(reason) => params.with_reason(reason),
767            None => params,
768        }
769    }
770
771    fn respond(id: &str, response: JsonValue) -> InterruptResponseContent {
772        InterruptResponseContent::new(InterruptResponse::new(id, response))
773    }
774
775    fn pending() -> PendingToolExecution {
776        serde_json::from_value(pending_tool_execution()).unwrap()
777    }
778
779    #[test]
780    fn creates_new_interrupt_and_stores_it() {
781        let state = InterruptState::new();
782        let interrupt = state.get_or_create_interrupt("int-1", &params("test", Some("reason")), InterruptSource::Hook);
783        assert_eq!(
784            serde_json::to_value(&interrupt).unwrap(),
785            json!({"id": "int-1", "name": "test", "reason": "reason", "source": "hook"})
786        );
787        assert_eq!(state.interrupt_list(), vec![interrupt]);
788    }
789
790    #[test]
791    fn returns_existing_interrupt_by_id_without_overwriting() {
792        let state = InterruptState::new();
793        state.get_or_create_interrupt("int-1", &params("test", Some("reason")), InterruptSource::Hook);
794        state.respond("int-1", json!("user response"));
795        let second = state.get_or_create_interrupt(
796            "int-1",
797            &params("different", Some("different reason")),
798            InterruptSource::Hook,
799        );
800        assert_eq!(second.name, "test");
801        assert_eq!(second.response, Some(json!("user response")));
802    }
803
804    #[test]
805    fn creates_separate_interrupts_for_different_ids_with_same_name() {
806        let state = InterruptState::new();
807        state.activate();
808        let confirm = params("confirm", Some("reason"));
809        state.get_or_create_interrupt("tool:tool-1:0:confirm", &confirm, InterruptSource::Tool);
810        state.respond("tool:tool-1:0:confirm", json!({"approved": true}));
811        let second = state.get_or_create_interrupt("tool:tool-2:0:confirm", &confirm, InterruptSource::Tool);
812        assert_eq!(second.id, "tool:tool-2:0:confirm");
813        assert_eq!(second.response, None);
814        assert_eq!(state.interrupt_list().len(), 2);
815    }
816
817    #[test]
818    fn creates_interrupt_with_preemptive_response() {
819        let state = InterruptState::new();
820        let interrupt = state.get_or_create_interrupt(
821            "int-1",
822            &params("confirm", Some("reason")).with_response("pre-approved"),
823            InterruptSource::Hook,
824        );
825        assert_eq!(
826            serde_json::to_value(&interrupt).unwrap(),
827            json!({"id": "int-1", "name": "confirm", "reason": "reason", "response": "pre-approved", "source": "hook"})
828        );
829    }
830
831    #[test]
832    fn ignores_preemptive_response_when_interrupt_already_exists() {
833        let state = InterruptState::new();
834        state.get_or_create_interrupt("int-1", &params("confirm", Some("reason")), InterruptSource::Hook);
835        state.respond("int-1", json!("user response"));
836        let second = state.get_or_create_interrupt(
837            "int-1",
838            &params("confirm", Some("reason")).with_response("preemptive"),
839            InterruptSource::Hook,
840        );
841        assert_eq!(
842            serde_json::to_value(&second).unwrap(),
843            json!({"id": "int-1", "name": "confirm", "reason": "reason", "response": "user response", "source": "hook"})
844        );
845    }
846
847    #[test]
848    fn deactivate_clears_all_state() {
849        let state = InterruptState::new();
850        state.get_or_create_interrupt("int-1", &params("test", None), InterruptSource::Hook);
851        state.activate();
852        state.set_pending_tool_execution(pending());
853        state.set_context_value("key", Some(json!(1)));
854        assert!(state.activated());
855
856        state.deactivate();
857
858        assert_eq!(state.to_data(), InterruptStateData::new());
859        assert!(!state.activated());
860        assert!(state.resume_responses().is_empty());
861    }
862
863    #[test]
864    fn does_nothing_when_not_activated() {
865        let state = InterruptState::new();
866        state.get_or_create_interrupt("int-1", &params("test", None), InterruptSource::Hook);
867        state.resume(&[respond("int-1", json!("yes"))]).unwrap();
868        assert_eq!(state.interrupt_list()[0].response, None);
869        assert!(state.resume_responses().is_empty());
870    }
871
872    #[test]
873    fn populates_interrupt_responses_and_stores_resume_responses_when_activated() {
874        let state = InterruptState::new();
875        state.get_or_create_interrupt("int-1", &params("first", None), InterruptSource::Hook);
876        state.get_or_create_interrupt("int-2", &params("second", None), InterruptSource::Hook);
877        state.activate();
878        let responses = vec![
879            respond("int-1", json!("response1")),
880            respond("int-2", json!({"complex": "data"})),
881        ];
882        state.resume(&responses).unwrap();
883        let interrupts = state.interrupt_list();
884        assert_eq!(interrupts[0].response, Some(json!("response1")));
885        assert_eq!(interrupts[1].response, Some(json!({"complex": "data"})));
886        assert_eq!(state.resume_responses(), responses);
887        assert!(state.unanswered_interrupts().is_empty());
888    }
889
890    #[test]
891    fn throws_error_for_unknown_interrupt_id() {
892        let state = InterruptState::new();
893        state.get_or_create_interrupt("int-1", &params("test", None), InterruptSource::Hook);
894        state.activate();
895        let error = state.resume(&[respond("unknown", json!("yes"))]).unwrap_err();
896        assert_eq!(error.to_string(), "interrupt_id=<unknown> | no interrupt found");
897    }
898
899    #[test]
900    fn drops_a_pending_tool_execution_when_the_interrupt_state_is_not_activated() {
901        let data: InterruptStateData = serde_json::from_value(
902            json!({"interrupts": {}, "activated": false, "pendingToolExecution": pending_tool_execution()}),
903        )
904        .unwrap();
905        let state = InterruptState::new();
906        state.load_data(data);
907        assert!(!state.has_pending_tool_execution());
908    }
909
910    #[test]
911    fn throws_session_error_when_the_restored_pending_tool_execution_has_description() {
912        let pending = pending_tool_execution();
913        let with = |key: &str, value: JsonValue| {
914            let mut pending = pending.clone();
915            pending[key] = value;
916            pending
917        };
918        let mut user_message = pending["assistantMessageData"].clone();
919        user_message["role"] = json!("user");
920        let cases = [
921            (
922                with("assistantMessageData", user_message),
923                "field=<pendingToolExecution.assistantMessageData.role>",
924            ),
925            (
926                with(
927                    "assistantMessageData",
928                    json!({"role": "assistant", "content": "not-a-list"}),
929                ),
930                "field=<pendingToolExecution.assistantMessageData>",
931            ),
932            (
933                json!({
934                    "assistantMessageData": {"role": "assistant", "content": [{"text": "hello"}]},
935                    "completedToolResults": {}
936                }),
937                "field=<pendingToolExecution.assistantMessageData.content>",
938            ),
939            (
940                with("completedToolResults", json!(["t-0"])),
941                "field=<pendingToolExecution.completedToolResults>",
942            ),
943            (
944                with(
945                    "completedToolResults",
946                    json!({"t-9": {"toolResult": {"toolUseId": "t-9", "status": "success", "content": []}}}),
947                ),
948                "field=<pendingToolExecution.completedToolResults>, tool_use_id=<t-9>",
949            ),
950            (
951                with(
952                    "completedToolResults",
953                    json!({"t-0": {"toolResult": {"toolUseId": "t-0"}}}),
954                ),
955                "field=<pendingToolExecution.completedToolResults>, tool_use_id=<t-0>",
956            ),
957        ];
958        for (pending, message) in cases {
959            let error = InterruptStateData::from_json(
960                json!({"interrupts": {}, "activated": true, "pendingToolExecution": pending}),
961            )
962            .unwrap_err();
963            assert_eq!(error.name(), "SessionError");
964            assert!(error.to_string().contains(message), "{error} should contain {message}");
965        }
966    }
967
968    #[test]
969    fn keeps_the_parse_error_as_the_cause_when_the_restored_pending_assistant_message_is_unparseable() {
970        let error = InterruptStateData::from_json(json!({
971            "interrupts": {},
972            "activated": true,
973            "pendingToolExecution": {
974                "assistantMessageData": {"role": "assistant", "content": "not-a-list"},
975                "completedToolResults": {}
976            }
977        }))
978        .unwrap_err();
979        assert_eq!(error.name(), "SessionError");
980        let Error::Session(session) = &error else {
981            panic!("expected a SessionError, got {error:?}");
982        };
983        assert!(
984            session
985                .source
986                .as_ref()
987                .is_some_and(|source| source.is::<serde_json::Error>())
988        );
989    }
990
991    #[test]
992    fn from_json_drops_a_pending_tool_execution_when_not_activated() {
993        let data = InterruptStateData::from_json(
994            json!({"interrupts": {}, "activated": false, "pendingToolExecution": {"bogus": true}}),
995        )
996        .unwrap();
997        assert!(data.pending_tool_execution.is_none());
998    }
999
1000    #[test]
1001    fn returns_undefined_when_the_interrupt_state_is_not_activated() {
1002        let state = InterruptState::new();
1003        state.set_pending_tool_execution(pending());
1004        assert_eq!(state.pending_execution(), None);
1005    }
1006
1007    #[test]
1008    fn returns_the_reconstructed_pending_execution_when_the_interrupt_state_is_activated() {
1009        let state = InterruptState::new();
1010        state.activate();
1011        state.set_pending_tool_execution(pending());
1012        let execution = state.pending_execution().unwrap();
1013        assert_eq!(
1014            serde_json::to_value(&execution.assistant_message_data).unwrap(),
1015            pending_tool_execution()["assistantMessageData"]
1016        );
1017        assert_eq!(execution.completed_tool_results.keys().collect::<Vec<_>>(), ["t-0"]);
1018        assert_eq!(
1019            execution.completed_tool_results["t-0"],
1020            ToolResultBlock::success("t-0", Vec::new())
1021        );
1022        state.clear_pending_tool_execution();
1023        assert!(!state.has_pending_tool_execution());
1024    }
1025
1026    #[test]
1027    fn returns_preemptive_response_immediately_without_throwing() {
1028        let state = InterruptState::new();
1029        let result = state.raise(
1030            "test-id",
1031            &params("confirm", Some("need approval")).with_response("pre-approved"),
1032            InterruptSource::Tool,
1033        );
1034        assert_eq!(result.unwrap(), json!("pre-approved"));
1035        assert_eq!(
1036            serde_json::to_value(&state.interrupt_list()[0]).unwrap(),
1037            json!({"id": "test-id", "name": "confirm", "reason": "need approval", "response": "pre-approved", "source": "tool"})
1038        );
1039    }
1040
1041    #[test]
1042    fn returns_resume_response_over_preemptive_response_for_existing_interrupt() {
1043        let state = InterruptState::new();
1044        state.get_or_create_interrupt(
1045            "test-id",
1046            &params("confirm", Some("need approval")),
1047            InterruptSource::Tool,
1048        );
1049        state.respond("test-id", json!("user-provided"));
1050        let result = state.raise(
1051            "test-id",
1052            &params("confirm", Some("need approval")).with_response("preemptive"),
1053            InterruptSource::Tool,
1054        );
1055        assert_eq!(result.unwrap(), json!("user-provided"));
1056        assert_eq!(state.interrupt_list()[0].response, Some(json!("user-provided")));
1057    }
1058
1059    #[test]
1060    fn does_not_interrupt_when_preemptive_response_is_null() {
1061        let state = InterruptState::new();
1062        let result = state.raise(
1063            "test-id",
1064            &params("confirm", None).with_response(JsonValue::Null),
1065            InterruptSource::Tool,
1066        );
1067        assert_eq!(result.unwrap(), JsonValue::Null);
1068        assert_eq!(state.interrupt_list()[0].response, Some(JsonValue::Null));
1069    }
1070
1071    #[test]
1072    fn an_unanswered_interrupt_is_raised_as_the_error() {
1073        let state = InterruptState::new();
1074        let error = state
1075            .raise("int-1", &params("confirm_delete", None), InterruptSource::Hook)
1076            .unwrap_err();
1077        assert_eq!(error.to_string(), "Interrupt raised: confirm_delete");
1078        assert_eq!(state.unanswered_interrupts(), error.interrupts);
1079    }
1080
1081    #[test]
1082    fn registers_an_interrupt_without_its_response() {
1083        let state = InterruptState::new();
1084        let registered = state.register_interrupt(
1085            &Interrupt::new("int-1", "confirm")
1086                .with_response("ignored")
1087                .with_source(InterruptSource::Tool),
1088        );
1089        assert_eq!(registered.response, None);
1090        assert_eq!(registered.source, InterruptSource::Tool);
1091        state.respond("int-1", json!("yes"));
1092        state.clear_response("int-1");
1093        assert_eq!(state.unanswered_interrupts().len(), 1);
1094    }
1095
1096    #[test]
1097    fn persists_the_stored_turn_through_interrupt_state_json() {
1098        let state = InterruptState::new();
1099        state.set_context_value("subAgentInterruptedTurns", Some(json!({"outer-1": {"data": {}}})));
1100        state.activate();
1101        let json = serde_json::to_string(&state.to_data()).unwrap();
1102        let restored = InterruptState::new();
1103        restored.load_data(serde_json::from_str(&json).unwrap());
1104        assert_eq!(
1105            restored.context_value("subAgentInterruptedTurns"),
1106            Some(json!({"outer-1": {"data": {}}}))
1107        );
1108        restored.deactivate();
1109        assert_eq!(restored.context_value("subAgentInterruptedTurns"), None);
1110        assert_eq!(restored.to_data().context, None);
1111    }
1112
1113    #[test]
1114    fn removing_the_last_context_value_drops_the_context() {
1115        let state = InterruptState::new();
1116        state.set_context_value("k", Some(json!(1)));
1117        state.set_context_value("k", None);
1118        assert_eq!(state.to_data().context, None);
1119        assert_eq!(
1120            serde_json::to_value(state.to_data()).unwrap(),
1121            json!({"interrupts": {}, "activated": false})
1122        );
1123    }
1124}