1use std::collections::HashSet;
4use std::fmt;
5use std::future::Future;
6use std::sync::Arc;
7
8use indexmap::IndexMap;
9
10use super::registry::{MiddlewareRegistry, StageRegistry};
11use super::types::{Middleware, MiddlewareNext, MiddlewareStage, StageResult, StageStream, private};
12use crate::agent::{InvocationContext, InvocationState, ToolAgent};
13use crate::cancel::CancelSignal;
14use crate::interrupt::{Interrupt, InterruptError, InterruptSource, InterruptState};
15use crate::models::{Model, StreamAggregatedResult};
16use crate::tools::Tool;
17use crate::types::{
18 InterruptParams, JsonSchema, JsonValue, Message, SystemPrompt, ToolChoice, ToolResultBlock, ToolSpec, ToolUse,
19};
20
21macro_rules! stage_constructors {
22 ($stage:ident) => {
23 impl $stage {
24 pub fn input<F, Fut>(handler: F) -> Middleware<Self>
26 where
27 F: Fn(<Self as MiddlewareStage>::Context) -> Fut + Send + Sync + 'static,
28 Fut: Future<Output = StageResult<<Self as MiddlewareStage>::Context>> + Send + 'static,
29 {
30 Middleware::input(handler)
31 }
32
33 pub fn output<F, Fut>(handler: F) -> Middleware<Self>
35 where
36 F: Fn(<Self as MiddlewareStage>::Result) -> Fut + Send + Sync + 'static,
37 Fut: Future<Output = StageResult<<Self as MiddlewareStage>::Result>> + Send + 'static,
38 {
39 Middleware::output(handler)
40 }
41
42 pub fn wrap<F>(handler: F) -> Middleware<Self>
44 where
45 F: Fn(<Self as MiddlewareStage>::Context, MiddlewareNext<Self>) -> StageStream<Self>
46 + Send
47 + Sync
48 + 'static,
49 {
50 Middleware::wrap(handler)
51 }
52 }
53 };
54}
55
56#[derive(Debug, Clone, Copy)]
80#[non_exhaustive]
81pub struct InvokeModelStage;
82
83impl private::Sealed for InvokeModelStage {
84 fn slot(registry: &MiddlewareRegistry) -> &StageRegistry<Self> {
85 registry.invoke_model()
86 }
87}
88
89impl MiddlewareStage for InvokeModelStage {
90 type Context = InvokeModelContext;
91 type Result = InvokeModelResult;
92 const NAME: &'static str = "invokeModel";
93}
94
95stage_constructors!(InvokeModelStage);
96
97#[derive(Debug, Clone, Copy)]
116#[non_exhaustive]
117pub struct ExecuteToolStage;
118
119impl private::Sealed for ExecuteToolStage {
120 fn slot(registry: &MiddlewareRegistry) -> &StageRegistry<Self> {
121 registry.execute_tool()
122 }
123}
124
125impl MiddlewareStage for ExecuteToolStage {
126 type Context = ExecuteToolContext;
127 type Result = ExecuteToolResult;
128 const NAME: &'static str = "executeTool";
129}
130
131stage_constructors!(ExecuteToolStage);
132
133#[derive(Clone)]
136#[non_exhaustive]
137pub struct InvokeModelContext {
138 pub agent: ToolAgent,
140 pub model: Arc<dyn Model>,
142 pub messages: Vec<Message>,
144 pub system_prompt: Option<SystemPrompt>,
146 pub tool_specs: Vec<ToolSpec>,
148 pub tool_choice: Option<ToolChoice>,
150 pub invocation_state: InvocationState,
152 pub projected_input_tokens: Option<u64>,
154 pub dynamic_trailing_blocks: Option<usize>,
157 pub structured_output_schema: Option<JsonSchema>,
159 pub deferred_tools: HashSet<String>,
162 pub invocation_context: Option<InvocationContext>,
164}
165
166impl fmt::Debug for InvokeModelContext {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 f.debug_struct("InvokeModelContext")
169 .field("model", &self.model.model_id())
170 .field("messages", &self.messages.len())
171 .field("tool_specs", &self.tool_specs.len())
172 .field("tool_choice", &self.tool_choice)
173 .finish_non_exhaustive()
174 }
175}
176
177#[derive(Debug, Clone, PartialEq)]
179#[non_exhaustive]
180pub struct InvokeModelResult {
181 pub result: StreamAggregatedResult,
183}
184
185impl InvokeModelResult {
186 #[must_use]
188 pub fn new(result: StreamAggregatedResult) -> Self {
189 Self { result }
190 }
191}
192
193type InterruptFn = Arc<dyn Fn(&InterruptParams) -> Result<JsonValue, InterruptError> + Send + Sync>;
194
195#[derive(Clone)]
198#[non_exhaustive]
199pub struct ExecuteToolContext {
200 pub agent: ToolAgent,
202 pub tool: Option<Arc<dyn Tool>>,
204 pub tool_use: ToolUse,
206 pub invocation_state: InvocationState,
208 cancel_signal: CancelSignal,
209 interrupt: InterruptFn,
210}
211
212impl ExecuteToolContext {
213 pub(crate) fn new(
214 agent: ToolAgent,
215 tool: Option<Arc<dyn Tool>>,
216 tool_use: ToolUse,
217 invocation_state: InvocationState,
218 cancel_signal: CancelSignal,
219 ) -> Self {
220 let interrupt = middleware_interrupt(
221 agent.interrupt_state().clone(),
222 format!("middleware:executeTool:{}", tool_use.tool_use_id),
223 None,
224 );
225 Self {
226 agent,
227 tool,
228 tool_use,
229 invocation_state,
230 cancel_signal,
231 interrupt,
232 }
233 }
234
235 pub(crate) fn with_interrupt(mut self, interrupt: InterruptFn) -> Self {
236 self.interrupt = interrupt;
237 self
238 }
239
240 #[must_use]
242 pub fn cancel_signal(&self) -> &CancelSignal {
243 &self.cancel_signal
244 }
245
246 pub fn interrupt(&self, params: impl Into<InterruptParams>) -> Result<MiddlewareInterruptResult, InterruptError> {
257 (self.interrupt)(¶ms.into()).map(MiddlewareInterruptResult::new)
258 }
259}
260
261impl fmt::Debug for ExecuteToolContext {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 f.debug_struct("ExecuteToolContext")
264 .field("tool_use", &self.tool_use)
265 .field("tool", &self.tool.as_ref().map(|tool| tool.name().to_owned()))
266 .finish_non_exhaustive()
267 }
268}
269
270#[derive(Debug, Clone, PartialEq)]
272#[non_exhaustive]
273pub struct ExecuteToolResult {
274 pub result: ToolResultBlock,
276}
277
278impl ExecuteToolResult {
279 #[must_use]
281 pub fn new(result: ToolResultBlock) -> Self {
282 Self { result }
283 }
284}
285
286#[derive(Debug, Clone, PartialEq)]
289#[non_exhaustive]
290pub struct MiddlewareInterruptResult {
291 pub response: JsonValue,
293}
294
295impl MiddlewareInterruptResult {
296 #[must_use]
298 pub fn new(response: JsonValue) -> Self {
299 Self { response }
300 }
301}
302
303pub(crate) fn middleware_interrupt(
307 state: InterruptState,
308 prefix: String,
309 prior: Option<IndexMap<String, Interrupt>>,
310) -> InterruptFn {
311 Arc::new(move |params: &InterruptParams| {
312 let id = format!("{prefix}:{}", params.name);
313 let existing = match &prior {
314 Some(prior) => prior.get(&id).and_then(|interrupt| interrupt.response.clone()),
315 None => state.response(&id),
316 };
317 if let Some(response) = existing.or_else(|| params.response.clone()) {
318 return Ok(response);
319 }
320 let mut interrupt = Interrupt::new(id, params.name.clone()).with_source(InterruptSource::Middleware);
321 interrupt.reason.clone_from(¶ms.reason);
322 Err(interrupt.into())
323 })
324}