Skip to main content

strands/agent/
agent_as_tool.rs

1//! An agent used as another agent's tool, with the `AgentToolStreamer` that forwards the
2//! sub-agent's interrupts to the calling agent.
3
4use std::fmt;
5use std::ops::DerefMut;
6use std::sync::Arc;
7
8use futures::{SinkExt, StreamExt};
9use serde_json::json;
10use tokio::sync::Mutex;
11
12use super::agent::Agent;
13use super::config::InvokeOptions;
14use super::invoke_args::InvokeArgs;
15use super::result::AgentResult;
16use super::snapshot::take_session_snapshot;
17use crate::cancel::CancelHandle;
18use crate::error::{Error, Result};
19use crate::hooks::AgentStreamEvent;
20use crate::interrupt::{Interrupt, InterruptError, InterruptSource, InterruptState};
21use crate::tools::{
22    DelegationToken, Tool, ToolContext, ToolOutcome, ToolSource, ToolStream, ToolStreamEvent, ToolStreamItem,
23    create_error_result,
24};
25use crate::types::{
26    InterruptResponse, InterruptResponseContent, JsonValue, Snapshot, StopReason, ToolResultBlock, ToolResultContent,
27    ToolSpec,
28};
29
30/// Appended to a delegating tool's description (`DELEGATION_DESCRIPTION_SUFFIX`).
31pub const DELEGATION_DESCRIPTION_SUFFIX: &str = " Calling this tool will return its response directly to the user as the final answer. It should be the only tool called in the turn.";
32
33const INTERRUPTED_TURNS_KEY: &str = "subAgentInterruptedTurns";
34
35/// Options for [`Agent::as_tool`] (`AgentAsToolOptions`).
36#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
37pub struct AgentAsToolOptions {
38    /// The tool name. Defaults to the agent's name, which must then be a valid tool name
39    /// (letters, digits, `-` and `_`): name the agent with `.name("researcher")`, or set this. The
40    /// default `Strands Agent` is not a valid tool name.
41    #[builder(into)]
42    pub name: Option<String>,
43    /// The tool description. Defaults to the agent's description, then
44    /// `Use the <name> agent by providing a natural language input`.
45    #[builder(into)]
46    pub description: Option<String>,
47    /// Keep the agent's conversation across calls. Defaults to `false`: each call starts from the
48    /// state the agent had when it became a tool.
49    pub preserve_context: Option<bool>,
50    /// Return the agent's answer directly to the user as the final answer (`delegate`). The
51    /// description says so to the model.
52    pub delegate: Option<bool>,
53}
54
55/// An agent wrapped as a tool (`AgentAsTool`): the tool takes an `input` string, invokes the
56/// agent with it and returns the agent's answer.
57///
58/// The wrapped agent's events stream as the tool's progress events, and its interrupts surface
59/// on the calling agent with ids scoped to the tool call, so resuming the caller resumes it.
60pub struct AgentAsTool {
61    inner: Arc<Inner>,
62}
63
64struct Inner {
65    name: String,
66    description: String,
67    spec: ToolSpec,
68    delegate: bool,
69    agent: Arc<Mutex<Agent>>,
70    preserve_context: bool,
71    initial_snapshot: Option<Snapshot>,
72    conflict: Option<String>,
73}
74
75impl Agent {
76    /// Wraps the agent as a tool for another agent. An agent passed to
77    /// [`AgentBuilder::tools`](crate::AgentBuilder::tools) is wrapped with default options.
78    ///
79    /// ```
80    /// use strands::Agent;
81    /// use strands::agent::AgentAsToolOptions;
82    /// use strands::testing::MockModel;
83    ///
84    /// let researcher = Agent::builder()
85    ///     .model(MockModel::new())
86    ///     .name("researcher")
87    ///     .description("Finds information")
88    ///     .printer(false)
89    ///     .build()?;
90    /// let tool = researcher.as_tool(AgentAsToolOptions::default());
91    /// let writer = Agent::builder().model(MockModel::new()).tools([tool]).printer(false).build()?;
92    /// assert!(writer.tool_registry().get("researcher").is_some());
93    /// # Ok::<(), strands::Error>(())
94    /// ```
95    ///
96    /// An agent with a session manager needs `preserve_context(true)`: a tool built from one
97    /// without it fails every call with the error [`try_as_tool`](Self::try_as_tool) returns.
98    #[must_use]
99    pub fn as_tool(self, options: AgentAsToolOptions) -> AgentAsTool {
100        AgentAsTool::new(self, options)
101    }
102
103    /// Wraps the agent as a tool, rejecting a session manager that conflicts with the options.
104    ///
105    /// # Errors
106    ///
107    /// The agent has a session manager and `preserve_context` is not `true`: the session manager
108    /// persists the history while the tool resets it between calls.
109    pub fn try_as_tool(self, options: AgentAsToolOptions) -> Result<AgentAsTool> {
110        if let Some(conflict) = session_manager_conflict(&self, &options) {
111            return Err(Error::other(conflict));
112        }
113        Ok(AgentAsTool::new(self, options))
114    }
115}
116
117/// The error for an agent whose session manager conflicts with `preserveContext=false`.
118fn session_manager_conflict(agent: &Agent, options: &AgentAsToolOptions) -> Option<String> {
119    let preserve_context = options.preserve_context.unwrap_or(false);
120    (!preserve_context && agent.session_manager().is_some()).then(|| {
121        format!(
122            "Agent '{}' has a SessionManager, which conflicts with preserveContext=false. The SessionManager persists conversation history externally, but preserveContext=false resets state between invocations. Use preserveContext=true or remove the SessionManager.",
123            agent.name()
124        )
125    })
126}
127
128impl AgentAsTool {
129    fn new(agent: Agent, options: AgentAsToolOptions) -> Self {
130        let conflict = session_manager_conflict(&agent, &options);
131        if let Some(conflict) = &conflict {
132            tracing::error!("agent_name=<{}> | {conflict}", agent.name());
133        }
134        let preserve_context = options.preserve_context.unwrap_or(false);
135        let delegate = options.delegate.unwrap_or(false);
136        let initial_snapshot = if preserve_context {
137            None
138        } else {
139            take_session_snapshot(&agent.local)
140                .inspect_err(|error| tracing::warn!("error=<{error}> | failed to snapshot the agent used as a tool"))
141                .ok()
142        };
143        let name = options.name.unwrap_or_else(|| agent.name().to_owned());
144        let mut description = options
145            .description
146            .or_else(|| agent.description().map(str::to_owned))
147            .unwrap_or_else(|| format!("Use the {name} agent by providing a natural language input"));
148        if delegate {
149            description.push_str(DELEGATION_DESCRIPTION_SUFFIX);
150        }
151        let spec = ToolSpec::new(&name, &description).with_input_schema(json!({
152            "type": "object",
153            "properties": {
154                "input": {
155                    "type": "string",
156                    "description": "The natural language input to send to the agent."
157                }
158            },
159            "required": ["input"]
160        }));
161        Self {
162            inner: Arc::new(Inner {
163                name,
164                description,
165                spec,
166                delegate,
167                agent: Arc::new(Mutex::new(agent)),
168                preserve_context,
169                initial_snapshot,
170                conflict,
171            }),
172        }
173    }
174
175    /// Whether the tool hands the agent's answer to the user as the final answer (`delegate`).
176    #[must_use]
177    pub fn delegate(&self) -> bool {
178        self.inner.delegate
179    }
180
181    /// The wrapped agent (`agent`); waits while a call is running.
182    pub async fn agent(&self) -> impl DerefMut<Target = Agent> + Send + '_ {
183        self.inner.agent.lock().await
184    }
185}
186
187impl Inner {
188    async fn run(
189        self: Arc<Self>,
190        context: ToolContext,
191        mut events: futures::channel::mpsc::Sender<ToolStreamEvent>,
192    ) -> ToolOutcome {
193        let tool_use_id = context.tool_use().tool_use_id.clone();
194        if let Some(conflict) = &self.conflict {
195            return create_error_result(conflict.clone(), tool_use_id).into();
196        }
197        let Ok(mut child) = self.agent.clone().try_lock_owned() else {
198            return create_error_result(
199                format!("Agent '{}' is already processing a request", self.name),
200                tool_use_id,
201            )
202            .into();
203        };
204        let mut streamer = AgentToolStreamer::new(
205            context.agent().interrupt_state().clone(),
206            &tool_use_id,
207            "agent_as_tool",
208            !self.preserve_context,
209            format!("Agent '{}'", self.name),
210        );
211        let input = if streamer.is_resuming() {
212            let unavailable = format!(
213                "Agent '{}' did NOT run and the human's response was NOT applied: its interrupted turn is not available. Do not report the requested action as completed; tell the user it failed and ask them to respond again.",
214                self.name
215            );
216            match streamer.resume(Some(&mut *child), &unavailable).await {
217                Resume::Responses(responses) => {
218                    tracing::debug!(
219                        "tool_name=<{}>, tool_use_id=<{tool_use_id}> | resuming sub-agent from interrupt",
220                        self.name
221                    );
222                    InvokeArgs::InterruptResponses(responses)
223                }
224                Resume::Raise(interrupts) => return raise(interrupts, &tool_use_id),
225                Resume::Stop => return streamer.terminal_result(render_success),
226            }
227        } else {
228            let text = context.tool_use().input["input"]
229                .as_str()
230                .unwrap_or_default()
231                .to_owned();
232            if let Some(snapshot) = &self.initial_snapshot
233                && let Err(error) = child.load_snapshot(snapshot)
234            {
235                return create_error_result(error, tool_use_id).into();
236            }
237            InvokeArgs::Text(text)
238        };
239
240        let options = InvokeOptions {
241            invocation_state: Some(context.invocation_state().clone()),
242            cancel_signal: Some(context.cancel_signal().clone()),
243            invocation_context: context.invocation_context().cloned(),
244            ..InvokeOptions::default()
245        };
246        if let Err(error) = streamer
247            .stream(&mut child, input, options, &self.name, &mut events)
248            .await
249        {
250            return create_error_result(error, tool_use_id).into();
251        }
252        if streamer.interrupts.is_some() && self.preserve_context && child.session_manager().is_none() {
253            tracing::warn!(
254                "tool_name=<{}>, tool_use_id=<{tool_use_id}> | interrupted sub-agent has preserveContext=true and no session manager, so its interrupt cannot be resumed after a restart",
255                self.name
256            );
257        }
258        streamer.terminal_result(render_success)
259    }
260}
261
262fn raise(interrupts: Vec<Interrupt>, tool_use_id: &str) -> ToolOutcome {
263    if interrupts.is_empty() {
264        return create_error_result("sub-agent interrupted without any interrupts", tool_use_id).into();
265    }
266    ToolOutcome::Interrupt(InterruptError::new(interrupts))
267}
268
269fn render_success(result: &AgentResult) -> Vec<ToolResultContent> {
270    match result.structured_output_value() {
271        Some(value) => vec![ToolResultContent::json(value.clone())],
272        None => vec![ToolResultContent::text(result.to_string())],
273    }
274}
275
276impl Tool for AgentAsTool {
277    fn name(&self) -> &str {
278        &self.inner.name
279    }
280
281    fn description(&self) -> &str {
282        &self.inner.description
283    }
284
285    fn tool_spec(&self) -> ToolSpec {
286        self.inner.spec.clone()
287    }
288
289    fn is_delegation_tool(&self, _: DelegationToken) -> bool {
290        self.inner.delegate
291    }
292
293    fn stream(&self, context: ToolContext) -> ToolStream {
294        // No buffer: the sub-agent advances only as the caller takes its events, so a call holds
295        // the agent until its stream is finished or dropped.
296        let (sender, receiver) = futures::channel::mpsc::channel(0);
297        let run = self.inner.clone().run(context, sender);
298        let outcome = futures::stream::once(run).map(ToolStreamItem::Outcome);
299        ToolStream::new(merge_events_first(receiver.map(ToolStreamItem::Event), outcome))
300    }
301}
302
303/// Streams every progress event, then the outcome: the run future feeds the events while it
304/// runs and finishes with the outcome.
305pub(crate) fn merge_events_first(
306    events: impl futures::Stream<Item = ToolStreamItem> + Send + 'static,
307    outcome: impl futures::Stream<Item = ToolStreamItem> + Send + 'static,
308) -> impl futures::Stream<Item = ToolStreamItem> + Send + 'static {
309    async_stream::stream! {
310        let mut events = Box::pin(events);
311        let mut outcome = Box::pin(outcome);
312        let mut finished = None;
313        loop {
314            tokio::select! {
315                biased;
316                event = events.next() => match event {
317                    Some(event) => yield event,
318                    None => break,
319                },
320                item = outcome.next(), if finished.is_none() => finished = item,
321            }
322        }
323        if let Some(item) = finished {
324            yield item;
325        }
326    }
327}
328
329impl fmt::Debug for AgentAsTool {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        f.debug_struct("AgentAsTool")
332            .field("name", &self.inner.name)
333            .field("delegate", &self.inner.delegate)
334            .field("preserve_context", &self.inner.preserve_context)
335            .finish_non_exhaustive()
336    }
337}
338
339impl From<Agent> for ToolSource {
340    fn from(agent: Agent) -> Self {
341        Self::from(agent.as_tool(AgentAsToolOptions::default()))
342    }
343}
344
345/// How resuming an interrupted sub-agent turn goes.
346pub(crate) enum Resume {
347    Responses(Vec<InterruptResponseContent>),
348    Raise(Vec<Interrupt>),
349    Stop,
350}
351
352/// Forwards a sub-agent's interrupts to the calling agent and resumes them.
353pub(crate) struct AgentToolStreamer {
354    state: InterruptState,
355    tool_use_id: String,
356    prefix: String,
357    persist_interrupted_turn: bool,
358    label: String,
359    result: Option<AgentResult>,
360    interrupts: Option<Vec<Interrupt>>,
361    error: Option<String>,
362}
363
364impl AgentToolStreamer {
365    /// A streamer for the call `tool_use_id`, scoping the child's interrupt ids under
366    /// `namespace`; `label` names the child in error messages.
367    pub(crate) fn new(
368        state: InterruptState,
369        tool_use_id: &str,
370        namespace: &str,
371        persist_interrupted_turn: bool,
372        label: String,
373    ) -> Self {
374        Self {
375            state,
376            tool_use_id: tool_use_id.to_owned(),
377            prefix: format!("{namespace}:{}:", encode_uri_component(tool_use_id)),
378            persist_interrupted_turn,
379            label,
380            result: None,
381            interrupts: None,
382            error: None,
383        }
384    }
385
386    pub(crate) fn is_resuming(&self) -> bool {
387        self.state.activated()
388            && self
389                .state
390                .interrupt_list()
391                .iter()
392                .any(|interrupt| interrupt.id.starts_with(&self.prefix))
393    }
394
395    fn turns(&self) -> serde_json::Map<String, JsonValue> {
396        match self.state.context_value(INTERRUPTED_TURNS_KEY) {
397            Some(JsonValue::Object(turns)) => turns,
398            _ => serde_json::Map::new(),
399        }
400    }
401
402    fn set_turn(&self, turn: Option<JsonValue>) {
403        let mut turns = self.turns();
404        match turn {
405            Some(turn) => {
406                turns.insert(self.tool_use_id.clone(), turn);
407            }
408            None => {
409                turns.shift_remove(&self.tool_use_id);
410            }
411        }
412        let value = (!turns.is_empty()).then_some(JsonValue::Object(turns));
413        self.state.set_context_value(INTERRUPTED_TURNS_KEY, value);
414    }
415
416    pub(crate) async fn stream(
417        &mut self,
418        child: &mut Agent,
419        input: InvokeArgs,
420        options: InvokeOptions,
421        name: &str,
422        events: &mut futures::channel::mpsc::Sender<ToolStreamEvent>,
423    ) -> crate::Result<()> {
424        let child_cancel = child.cancel_handle();
425        let external = options.cancel_signal.clone();
426        let mut outcome = None;
427        let mut classified = false;
428        {
429            let mut stream = child.stream_with(input, options);
430            while let Some(event) = stream.next().await {
431                let event = event?;
432                if !classified && let AgentStreamEvent::AgentResult(result) = &event {
433                    outcome = Some(self.classify(&child_cancel, external.as_ref(), result, name));
434                    classified = true;
435                }
436                let tool_event = match &event {
437                    AgentStreamEvent::ToolStreamUpdate(update) => update.event.clone(),
438                    other => ToolStreamEvent::new(serde_json::to_value(other)?),
439                };
440                let _ = events.send(tool_event).await;
441            }
442            self.result = stream.take_result();
443        }
444        let Some(result) = &self.result else {
445            self.error = Some(format!("{} did not produce a result.", self.label));
446            return Ok(());
447        };
448        let outcome = match outcome {
449            Some(outcome) => outcome,
450            None => self.classify(&child_cancel, external.as_ref(), result, name),
451        };
452        match outcome {
453            Classified::Interrupts(interrupts) => {
454                if self.persist_interrupted_turn {
455                    let snapshot = take_session_snapshot(&child.local)?;
456                    self.set_turn(Some(serde_json::to_value(snapshot)?));
457                }
458                let registered = interrupts
459                    .iter()
460                    .map(|interrupt| {
461                        let mut scoped =
462                            Interrupt::new(format!("{}{}", self.prefix, interrupt.id), interrupt.name.clone())
463                                .with_source(InterruptSource::Tool);
464                        scoped.reason.clone_from(&interrupt.reason);
465                        self.state.register_interrupt(&scoped)
466                    })
467                    .collect();
468                self.interrupts = Some(registered);
469            }
470            Classified::Error(error) => {
471                self.set_turn(None);
472                self.error = Some(error);
473            }
474            Classified::Success => self.set_turn(None),
475        }
476        Ok(())
477    }
478
479    /// Classifies a sub-agent result: interrupts to forward, an error (an interrupt stop without
480    /// interrupts, a cancel from either side, a limit stop, a content-filtered or refused answer),
481    /// or success.
482    fn classify(
483        &self,
484        child_cancel: &CancelHandle,
485        external: Option<&crate::cancel::CancelSignal>,
486        result: &AgentResult,
487        name: &str,
488    ) -> Classified {
489        match result.stop_reason() {
490            StopReason::Interrupt if result.interrupts().is_empty() => {
491                Classified::Error(format!("{} interrupted without any interrupts", self.label))
492            }
493            StopReason::Interrupt => Classified::Interrupts(result.interrupts().to_vec()),
494            StopReason::Cancelled => {
495                let aborted =
496                    child_cancel.signal().is_cancelled() || external.is_some_and(|signal| signal.is_cancelled());
497                if aborted {
498                    Classified::Error(format!("{} cancelled", self.label))
499                } else {
500                    Classified::Success
501                }
502            }
503            stop_reason @ (StopReason::LimitTurns
504            | StopReason::LimitTotalTokens
505            | StopReason::LimitOutputTokens
506            | StopReason::LimitStructuredOutputAttempts) => Classified::Error(format!(
507                "Agent '{name}' stopped early ({stop_reason}): a limit on this call was reached, so its answer is incomplete"
508            )),
509            // `GuardrailIntervened` stays a success: Bedrock also reports it for masked output, which
510            // is a complete answer.
511            stop_reason @ (StopReason::ContentFiltered | StopReason::Refusal) => {
512                let message = format!("{} stopped before finishing (stopReason={stop_reason}).", self.label);
513                let partial = result.to_string();
514                let partial = partial.trim_end_matches('\n');
515                if partial.is_empty() {
516                    Classified::Error(message)
517                } else {
518                    Classified::Error(format!("{message}\n\nPartial output:\n{partial}"))
519                }
520            }
521            _ => Classified::Success,
522        }
523    }
524
525    /// The tool's outcome: a failure is an `Error: <message>` result, checked before interrupts and
526    /// the rendered result.
527    pub(crate) fn terminal_result(&self, render: impl FnOnce(&AgentResult) -> Vec<ToolResultContent>) -> ToolOutcome {
528        if let Some(error) = &self.error {
529            return create_error_result(error.clone(), self.tool_use_id.clone()).into();
530        }
531        if let Some(interrupts) = &self.interrupts {
532            return raise(interrupts.clone(), &self.tool_use_id);
533        }
534        let content = self.result.as_ref().map(render).unwrap_or_default();
535        ToolResultBlock::success(self.tool_use_id.clone(), content).into()
536    }
537
538    /// The tool's terminal result: a failure is an error result with the message as its text, and
539    /// interrupts are raised before it.
540    pub(crate) fn terminal_tool_result(
541        &self,
542        render: impl FnOnce(&AgentResult) -> Vec<ToolResultContent>,
543    ) -> ToolOutcome {
544        if let Some(interrupts) = &self.interrupts {
545            return raise(interrupts.clone(), &self.tool_use_id);
546        }
547        if let Some(error) = &self.error {
548            let content = vec![ToolResultContent::text(error.clone())];
549            return ToolResultBlock::error(self.tool_use_id.clone(), content).into();
550        }
551        let content = self.result.as_ref().map(render).unwrap_or_default();
552        ToolResultBlock::success(self.tool_use_id.clone(), content).into()
553    }
554
555    /// `resume`: the responses addressed to this call, stripped of the scope prefix. `None` is a
556    /// child that could not be rebuilt, handled as a failed restore.
557    pub(crate) async fn resume(&mut self, child: Option<&mut Agent>, unavailable: &str) -> Resume {
558        let responses: Vec<InterruptResponseContent> = self
559            .state
560            .resume_responses()
561            .into_iter()
562            .filter(|response| response.interrupt_response.interrupt_id.starts_with(&self.prefix))
563            .collect();
564        if responses.is_empty() {
565            let pending = self
566                .state
567                .interrupt_list()
568                .into_iter()
569                .filter(|interrupt| interrupt.id.starts_with(&self.prefix) && interrupt.response.is_none())
570                .collect();
571            return Resume::Raise(pending);
572        }
573        let turn = self.turns().get(&self.tool_use_id).cloned();
574        let restored = match child {
575            Some(child) => Some(restore(child, turn.clone()).await),
576            None => None,
577        };
578        let awaiting = match restored {
579            Some(Ok(awaiting)) => {
580                self.set_turn(None);
581                if !awaiting {
582                    tracing::error!(
583                        "tool_use_id=<{}> | interrupted sub-agent turn is not available to resume",
584                        self.tool_use_id
585                    );
586                    self.error = Some(unavailable.to_owned());
587                }
588                awaiting
589            }
590            Some(Err(error)) => {
591                tracing::error!(
592                    "tool_use_id=<{}>, error=<{error}> | failed to restore interrupted sub-agent turn",
593                    self.tool_use_id
594                );
595                self.handle_failed_restore(turn.as_ref(), unavailable);
596                false
597            }
598            None => {
599                self.handle_failed_restore(turn.as_ref(), unavailable);
600                false
601            }
602        };
603        if let Some(interrupts) = self.interrupts.take() {
604            return Resume::Raise(interrupts);
605        }
606        if !awaiting {
607            return Resume::Stop;
608        }
609        Resume::Responses(
610            responses
611                .into_iter()
612                .map(|response| {
613                    let id = response.interrupt_response.interrupt_id[self.prefix.len()..].to_owned();
614                    InterruptResponseContent::new(InterruptResponse::new(id, response.interrupt_response.response))
615                })
616                .collect(),
617        )
618    }
619
620    fn handle_failed_restore(&mut self, turn: Option<&JsonValue>, unavailable: &str) {
621        let Some(pending) = turn.and_then(pending_interrupt_ids) else {
622            tracing::error!(
623                "tool_use_id=<{}> | stored turn has no readable interrupt state",
624                self.tool_use_id
625            );
626            self.error = Some(unavailable.to_owned());
627            return;
628        };
629        let interrupts: Vec<Interrupt> = self
630            .state
631            .interrupt_list()
632            .into_iter()
633            .filter(|interrupt| {
634                interrupt
635                    .id
636                    .strip_prefix(&self.prefix)
637                    .is_some_and(|id| pending.iter().any(|pending| pending == id))
638            })
639            .collect();
640        if interrupts.is_empty() {
641            self.error = Some(unavailable.to_owned());
642            return;
643        }
644        for interrupt in &interrupts {
645            self.state.clear_response(&interrupt.id);
646        }
647        self.interrupts = Some(
648            interrupts
649                .into_iter()
650                .map(|mut interrupt| {
651                    interrupt.response = None;
652                    interrupt
653                })
654                .collect(),
655        );
656    }
657}
658
659enum Classified {
660    Interrupts(Vec<Interrupt>),
661    Error(String),
662    Success,
663}
664
665/// Restores a sub-agent: loads the stored turn, or initializes a context-preserving
666/// child that keeps its own; returns whether the child awaits responses.
667async fn restore(child: &mut Agent, turn: Option<JsonValue>) -> crate::Result<bool> {
668    match turn {
669        Some(turn) => {
670            let snapshot: Snapshot = serde_json::from_value(turn)?;
671            child.load_snapshot(&snapshot)?;
672        }
673        None => child.initialize().await?,
674    }
675    Ok(child.local.interrupt_state().activated())
676}
677
678/// The ids of the interrupts stored in an interrupted turn.
679fn pending_interrupt_ids(turn: &JsonValue) -> Option<Vec<String>> {
680    let interrupts = turn.get("data")?.get("interrupts")?.get("interrupts")?.as_object()?;
681    Some(interrupts.keys().cloned().collect())
682}
683
684/// Percent-encodes every byte outside the URI-component unreserved set, so forwarded interrupt ids
685/// match the other Strands SDKs.
686fn encode_uri_component(text: &str) -> String {
687    let mut encoded = String::with_capacity(text.len());
688    for byte in text.bytes() {
689        let unreserved = byte.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&byte);
690        if unreserved {
691            encoded.push(char::from(byte));
692        } else {
693            encoded.push_str(&format!("%{byte:02X}"));
694        }
695    }
696    encoded
697}
698
699/// Interrupts raised inside an agent used as a tool.
700#[cfg(test)]
701mod tests;
702
703/// `AgentToolStreamer` cases with real child agents.
704#[cfg(test)]
705mod streamer_tests;