Skip to main content

strands/tools/executors/
executor.rs

1//! Shared executor types.
2
3use std::sync::Arc;
4
5use futures::future::BoxFuture;
6use indexmap::IndexMap;
7use tokio::sync::mpsc;
8
9use super::concurrent::{ConcurrentToolExecutor, execute_concurrent};
10use super::sequential::{SequentialToolExecutor, execute_sequential};
11use crate::cancel::CancelSignal;
12use crate::error::Error;
13use crate::interrupt::Interrupt;
14use crate::models::BoxStream;
15use crate::telemetry::in_current_context;
16use crate::tools::ToolOutcome;
17use crate::types::{ToolResultBlock, ToolResultContent, ToolUseBlock};
18
19/// How the tool calls of one model turn run (`ToolExecutorStrategy`).
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum ToolExecutorStrategy {
23    /// Every call runs on its own task ([`ConcurrentToolExecutor`]); the default.
24    #[default]
25    Concurrent,
26    /// Calls run one at a time, in order ([`SequentialToolExecutor`]).
27    Sequential,
28}
29
30impl From<ConcurrentToolExecutor> for ToolExecutorStrategy {
31    fn from(_: ConcurrentToolExecutor) -> Self {
32        Self::Concurrent
33    }
34}
35
36impl From<SequentialToolExecutor> for ToolExecutorStrategy {
37    fn from(_: SequentialToolExecutor) -> Self {
38        Self::Sequential
39    }
40}
41
42/// Runs one tool call through the per-tool pipeline: reports its events through the sink and
43/// returns its outcome.
44pub(crate) type ToolPipelineFn<E> =
45    Arc<dyn Fn(ToolUseBlock, EventSink<E>) -> BoxFuture<'static, CallOutcome> + Send + Sync>;
46
47/// How one tool call of a batch ended: a result, the interrupts its tool or hooks raised, a
48/// hook error, which stops the batch and fails the invocation, or a tool-stage failure (a
49/// middleware error), which the concurrent executor turns into that call's error result and the
50/// sequential executor treats like a hook error.
51#[derive(Debug)]
52pub(crate) enum CallOutcome {
53    Result(ToolResultBlock),
54    Interrupts(Vec<Interrupt>),
55    Error(Error),
56    StageError(Error),
57}
58
59impl From<ToolOutcome> for CallOutcome {
60    fn from(outcome: ToolOutcome) -> Self {
61        match outcome {
62            ToolOutcome::Result(result) => Self::Result(result),
63            ToolOutcome::Interrupt(interrupts) => Self::Interrupts(interrupts.into_interrupts()),
64        }
65    }
66}
67
68pub(crate) enum Message<E> {
69    Event(E),
70    Done(usize, Box<CallOutcome>),
71}
72
73/// Where a tool call's pipeline reports its events. Events of one call keep their order.
74///
75/// The channel is bounded and [`send`](Self::send) waits for room, so a tool produces events only
76/// as fast as the agent stream is consumed.
77pub(crate) struct EventSink<E> {
78    sender: Option<mpsc::Sender<Message<E>>>,
79}
80
81impl<E> Clone for EventSink<E> {
82    fn clone(&self) -> Self {
83        Self {
84            sender: self.sender.clone(),
85        }
86    }
87}
88
89impl<E> EventSink<E> {
90    pub(crate) fn new(sender: mpsc::Sender<Message<E>>) -> Self {
91        Self { sender: Some(sender) }
92    }
93
94    /// A sink that drops every event.
95    pub(crate) fn discard() -> Self {
96        Self { sender: None }
97    }
98
99    /// Reports an event, waiting while the batch has not taken the earlier ones. Does nothing
100    /// once the batch's stream is gone.
101    pub(crate) async fn send(&self, event: E) {
102        if let Some(sender) = &self.sender {
103            let _ = sender.send(Message::Event(event)).await;
104        }
105    }
106}
107
108/// The tool calls of one model turn.
109pub(crate) struct ToolBatch {
110    /// The calls, in the order the model made them.
111    pub(crate) tool_uses: Vec<ToolUseBlock>,
112    /// Results restored on resume, by tool use id; those calls do not run again.
113    pub(crate) completed: IndexMap<String, ToolResultBlock>,
114    /// Checked between sequential calls.
115    pub(crate) cancel_signal: CancelSignal,
116}
117
118/// How a batch ended.
119#[derive(Debug, Default)]
120pub(crate) struct BatchOutcome {
121    /// The results for the tool result message, in call order.
122    pub(crate) results: Vec<ToolResultBlock>,
123    /// Every finished result by tool use id, restored ones included, for the pending execution
124    /// an interrupt saves.
125    pub(crate) completed: IndexMap<String, ToolResultBlock>,
126    /// The interrupts the calls raised, in the order they ended.
127    pub(crate) interrupts: Vec<Interrupt>,
128    /// The hook error that stopped the batch; the invocation fails with it after
129    /// `AfterToolsEvent`.
130    pub(crate) error: Option<Error>,
131}
132
133/// One item of an executor's stream.
134pub(crate) enum ExecutorItem<E> {
135    /// An event a call reported.
136    Event(E),
137    /// A call's final result; the agent fires `ToolResultEvent` for it.
138    Result(ToolResultBlock),
139    /// The batch finished; always the last item.
140    Done(BatchOutcome),
141}
142
143impl ToolExecutorStrategy {
144    /// Runs a batch. The stream owns the running calls: dropping it aborts them.
145    pub(crate) fn execute<E: Send + 'static>(
146        self,
147        batch: ToolBatch,
148        pipeline: ToolPipelineFn<E>,
149    ) -> BoxStream<'static, ExecutorItem<E>> {
150        match self {
151            Self::Concurrent => execute_concurrent(batch, pipeline),
152            Self::Sequential => execute_sequential(batch, pipeline),
153        }
154    }
155}
156
157/// The capacity of a batch's event channel: room for one undelivered item per call.
158pub(crate) fn channel_capacity(calls: usize) -> usize {
159    calls.max(1)
160}
161
162/// The text of a panicking tool's error result: the panic message.
163pub(crate) fn panic_result(tool_use_id: &str, payload: &(dyn std::any::Any + Send)) -> ToolResultBlock {
164    let message = payload
165        .downcast_ref::<&str>()
166        .map(|message| (*message).to_owned())
167        .or_else(|| payload.downcast_ref::<String>().cloned())
168        .unwrap_or_else(|| "tool execution panicked".to_owned());
169    ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(message)])
170}
171
172/// The error result of a call whose tool stage failed: the error's message, with the error kept.
173pub(crate) fn failure_result(tool_use_id: &str, error: Error) -> ToolResultBlock {
174    ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(error.to_string())]).with_error(error)
175}
176
177pub(crate) fn text_result(tool_use_id: &str, text: &str) -> ToolResultBlock {
178    ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(text)])
179}
180
181/// Spawns one call's pipeline in the caller's span and OpenTelemetry context, so its hooks and
182/// middleware see them; it reports its events and then its outcome on `sender`.
183pub(crate) fn spawn_call<E: Send + 'static>(
184    tasks: &mut tokio::task::JoinSet<()>,
185    index: usize,
186    tool_use: ToolUseBlock,
187    pipeline: &ToolPipelineFn<E>,
188    sender: &mpsc::Sender<Message<E>>,
189) -> tokio::task::Id {
190    let future = in_current_context(pipeline(tool_use, EventSink::new(sender.clone())));
191    let sender = sender.clone();
192    tasks
193        .spawn(async move {
194            let outcome = future.await;
195            let _ = sender.send(Message::Done(index, Box::new(outcome))).await;
196        })
197        .id()
198}
199
200/// The result of a call whose task ended without an outcome. A panic outside the tool body (a
201/// hook or middleware) is a bug in that code and resumes on the caller, as it would for a
202/// sequential hook; tool panics never get here, the pipeline turns them into error results.
203pub(crate) fn ended_without_outcome(error: tokio::task::JoinError, tool_use_id: &str) -> ToolResultBlock {
204    match error.try_into_panic() {
205        Ok(payload) => std::panic::resume_unwind(payload),
206        Err(_) => text_result(tool_use_id, "Tool execution interrupted"),
207    }
208}