1use crate::tools::improvements_errors::ObservabilityContext;
7use crate::types::CompactStr;
8use serde_json::{Map, Value};
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12use std::time::Instant;
13
14type AsyncContinuation<'a> =
16 Box<dyn Fn(ToolRequest) -> Pin<Box<dyn Future<Output = MiddlewareToolResult> + Send>> + Send + Sync + 'a>;
17
18type AsyncContinuationOwned =
20 Box<dyn Fn(ToolRequest) -> Pin<Box<dyn Future<Output = MiddlewareToolResult> + Send>> + Send + Sync>;
21
22#[async_trait::async_trait]
24pub trait AsyncMiddleware: Send + Sync {
25 fn name(&self) -> &str;
27
28 async fn execute<'a>(&'a self, request: ToolRequest, next: AsyncContinuation<'a>) -> MiddlewareToolResult;
30}
31
32#[derive(Clone, Debug)]
34pub struct ToolRequest {
35 pub tool_name: CompactStr,
36 pub arguments: String,
37 pub context: String,
38}
39
40#[derive(Clone, Debug)]
42pub struct MiddlewareToolResult {
43 pub success: bool,
44 pub output: Option<String>,
45 pub error: Option<String>,
46 pub duration_ms: u64,
47 pub from_cache: bool,
48}
49
50pub struct AsyncMiddlewareChain {
52 middlewares: Vec<Arc<dyn AsyncMiddleware>>,
53}
54
55impl AsyncMiddlewareChain {
56 pub fn new() -> Self {
57 Self { middlewares: Vec::new() }
58 }
59
60 pub fn with_middleware(mut self, middleware: Arc<dyn AsyncMiddleware>) -> Self {
61 self.middlewares.push(middleware);
62 self
63 }
64
65 pub async fn execute_simple<F>(&self, request: ToolRequest, executor: F) -> MiddlewareToolResult
67 where
68 F: Fn(ToolRequest) -> MiddlewareToolResult + Send + Sync + 'static,
69 {
70 if self.middlewares.is_empty() {
71 return executor(request);
72 }
73
74 let executor = Arc::new(executor);
75 let middlewares = self.middlewares.clone();
76
77 fn build_chain(
78 middlewares: &[Arc<dyn AsyncMiddleware>],
79 executor: Arc<dyn Fn(ToolRequest) -> MiddlewareToolResult + Send + Sync>,
80 ) -> AsyncContinuationOwned {
81 if middlewares.is_empty() {
82 Box::new(move |req: ToolRequest| {
83 let result = executor(req);
84 Box::pin(async move { result })
85 })
86 } else {
87 let current = middlewares[0].clone();
88 let rest = build_chain(&middlewares[1..], executor);
89 let rest = Arc::new(rest);
90 Box::new(move |req: ToolRequest| {
91 let current = current.clone();
92 let rest = rest.clone();
93 Box::pin(async move {
94 let next: AsyncContinuationOwned = Box::new(move |r: ToolRequest| {
95 let rest = rest.clone();
96 Box::pin(async move { rest(r).await })
97 });
98 current.execute(req, next).await
99 })
100 })
101 }
102 }
103
104 let chain = build_chain(&middlewares, executor);
105 chain(request).await
106 }
107}
108
109impl Default for AsyncMiddlewareChain {
110 fn default() -> Self {
111 Self::new()
112 }
113}
114
115fn normalize_context(context: &str) -> String {
116 let mut normalized = Map::new();
117 let parsed: Value = serde_json::from_str(context).unwrap_or_else(|_| Value::Object(Map::new()));
118
119 if let Some(session) = parsed.get("session_id").and_then(Value::as_str)
120 && !session.is_empty()
121 {
122 normalized.insert("session_id".into(), Value::String(session.to_string()));
123 }
124
125 if let Some(task) = parsed.get("task_id").and_then(Value::as_str)
126 && !task.is_empty()
127 {
128 normalized.insert("task_id".into(), Value::String(task.to_string()));
129 }
130
131 if let Some(version) = parsed.get("plan_version").and_then(Value::as_u64) {
132 normalized.insert("plan_version".into(), Value::Number(version.into()));
133 }
134
135 if let Some(plan) = parsed.get("plan_summary").and_then(Value::as_object) {
136 let mut summary = Map::new();
137 if let Some(status) = plan.get("status").and_then(Value::as_str) {
138 summary.insert("status".into(), Value::String(status.to_string()));
139 }
140 if let Some(total) = plan.get("total_steps").and_then(Value::as_u64) {
141 summary.insert("total_steps".into(), Value::Number(total.into()));
142 }
143 if let Some(completed) = plan.get("completed_steps").and_then(Value::as_u64) {
144 summary.insert("completed_steps".into(), Value::Number(completed.into()));
145 }
146 if !summary.is_empty() {
147 normalized.insert("plan_summary".into(), Value::Object(summary));
148 }
149 }
150
151 if let Some(phase) = parsed.get("plan_phase").and_then(|v| v.as_str()).filter(|p| !p.is_empty()) {
152 normalized.insert("plan_phase".into(), Value::String(phase.to_string()));
153 }
154
155 serde_json::to_string(&Value::Object(normalized)).unwrap_or_else(|_| "{}".to_string())
156}
157
158pub struct AsyncLoggingMiddleware {
160 obs_context: Arc<ObservabilityContext>,
161}
162
163impl AsyncLoggingMiddleware {
164 pub fn new(obs_context: Arc<ObservabilityContext>) -> Self {
165 Self { obs_context }
166 }
167}
168
169#[async_trait::async_trait]
170impl AsyncMiddleware for AsyncLoggingMiddleware {
171 fn name(&self) -> &str {
172 "async_logging"
173 }
174
175 async fn execute<'a>(
176 &'a self,
177 request: ToolRequest,
178 next: Box<
179 dyn Fn(ToolRequest) -> Pin<Box<dyn std::future::Future<Output = MiddlewareToolResult> + Send>>
180 + Send
181 + Sync
182 + 'a,
183 >,
184 ) -> MiddlewareToolResult {
185 let tool_name = request.tool_name.clone();
186 let normalized_context = normalize_context(&request.context);
187 let context_json: Option<Value> = serde_json::from_str(&normalized_context).ok();
188 let session_id = context_json
189 .as_ref()
190 .and_then(|v| v.get("session_id").and_then(|s| s.as_str()))
191 .unwrap_or("");
192 let task_id = context_json
193 .as_ref()
194 .and_then(|v| v.get("task_id").and_then(|s| s.as_str()))
195 .unwrap_or("");
196 let plan_summary = context_json.as_ref().and_then(|v| v.get("plan_summary"));
197 let plan_status = plan_summary
198 .and_then(|v| v.get("status").and_then(|s| s.as_str()))
199 .unwrap_or("");
200 let plan_phase = context_json
201 .as_ref()
202 .and_then(|v| v.get("plan_phase").and_then(|p| p.as_str()))
203 .unwrap_or("");
204 let plan_total_steps = plan_summary
205 .and_then(|v| v.get("total_steps").and_then(|n| n.as_u64()))
206 .unwrap_or(0);
207 let plan_completed_steps = plan_summary
208 .and_then(|v| v.get("completed_steps").and_then(|n| n.as_u64()))
209 .unwrap_or(0);
210 let plan_version = context_json
211 .as_ref()
212 .and_then(|v| v.get("plan_version").and_then(|n| n.as_u64()))
213 .unwrap_or(0);
214
215 tracing::debug!(
216 tool = %tool_name,
217 session_id = %session_id,
218 task_id = %task_id,
219 plan_version,
220 plan_status = %plan_status,
221 plan_phase = %plan_phase,
222 plan_total_steps,
223 plan_completed_steps,
224 "tool execution started"
225 );
226 tracing::trace!(
227 tool = %tool_name,
228 context = %normalized_context,
229 "tool execution context payload"
230 );
231
232 let start = Instant::now();
233 let mut result = next(request).await;
234 let duration = start.elapsed().as_millis().min(u64::MAX as u128) as u64;
235
236 result.duration_ms = duration;
237
238 if result.success {
239 tracing::debug!(
240 tool = %tool_name,
241 duration_ms = duration,
242 session_id = %session_id,
243 task_id = %task_id,
244 plan_version,
245 plan_status = %plan_status,
246 plan_phase = %plan_phase,
247 plan_total_steps,
248 plan_completed_steps,
249 from_cache = result.from_cache,
250 "tool execution completed"
251 );
252 self.obs_context.event(
253 crate::tools::EventType::ToolSelected,
254 "executor",
255 format!("executed {tool_name} in {duration}ms"),
256 Some(1.0),
257 );
258 } else {
259 tracing::error!(
260 tool = %tool_name,
261 error = ?result.error,
262 session_id = %context_json
263 .as_ref()
264 .and_then(|v| v.get("session_id").and_then(|s| s.as_str()))
265 .unwrap_or(""),
266 task_id = %context_json
267 .as_ref()
268 .and_then(|v| v.get("task_id").and_then(|s| s.as_str()))
269 .unwrap_or(""),
270 "tool execution failed"
271 );
272 }
273
274 result
275 }
276}
277
278pub struct AsyncCachingMiddleware {
280 cache: Arc<crate::cache::UnifiedCache<AsyncCacheKey, String>>,
281 obs_context: Arc<ObservabilityContext>,
282}
283
284#[derive(Debug, Clone, Hash, PartialEq, Eq)]
285struct AsyncCacheKey(String);
286
287impl crate::cache::CacheKey for AsyncCacheKey {
288 fn to_cache_key(&self) -> String {
289 self.0.clone()
290 }
291}
292
293impl AsyncCachingMiddleware {
294 pub fn new(max_entries: usize, ttl_seconds: u64, obs_context: Arc<ObservabilityContext>) -> Self {
295 let cache = crate::cache::UnifiedCache::new(
296 max_entries,
297 std::time::Duration::from_secs(ttl_seconds),
298 crate::cache::EvictionPolicy::Lru,
299 );
300
301 Self { cache: Arc::new(cache), obs_context }
302 }
303
304 fn cache_key(tool: &str, args: &str, context: &str) -> String {
305 use std::collections::hash_map::DefaultHasher;
307 use std::hash::Hasher;
308 let mut hasher = DefaultHasher::new();
309 hasher.write(args.as_bytes());
310 let normalized = normalize_context(context);
311 if !normalized.is_empty() {
312 hasher.write(normalized.as_bytes());
313 }
314 format!("{}::{}", tool, hasher.finish())
315 }
316}
317
318#[async_trait::async_trait]
319impl AsyncMiddleware for AsyncCachingMiddleware {
320 fn name(&self) -> &str {
321 "async_caching"
322 }
323
324 async fn execute<'a>(
325 &'a self,
326 request: ToolRequest,
327 next: Box<
328 dyn Fn(ToolRequest) -> Pin<Box<dyn std::future::Future<Output = MiddlewareToolResult> + Send>>
329 + Send
330 + Sync
331 + 'a,
332 >,
333 ) -> MiddlewareToolResult {
334 let key = AsyncCacheKey(Self::cache_key(&request.tool_name, &request.arguments, &request.context));
335
336 if let Some(cached) = self.cache.get_owned(&key) {
338 self.obs_context
339 .event(crate::tools::EventType::CacheHit, "cache", "returning cached result", Some(1.0));
340
341 return MiddlewareToolResult {
342 success: true,
343 output: Some(cached),
344 error: None,
345 duration_ms: 0,
346 from_cache: true,
347 };
348 }
349
350 let result = next(request).await;
352
353 if result.success
355 && let Some(ref output) = result.output
356 {
357 let size = output.len() as u64;
358 self.cache.insert(key, output.clone(), size);
359 }
360
361 result
362 }
363}
364
365pub struct AsyncRetryMiddleware {
367 max_attempts: u32,
368 initial_backoff_ms: u64,
369 max_backoff_ms: u64,
370 obs_context: Arc<ObservabilityContext>,
371}
372
373impl AsyncRetryMiddleware {
374 pub fn new(
375 max_attempts: u32,
376 initial_backoff_ms: u64,
377 max_backoff_ms: u64,
378 obs_context: Arc<ObservabilityContext>,
379 ) -> Self {
380 Self {
381 max_attempts,
382 initial_backoff_ms,
383 max_backoff_ms,
384 obs_context,
385 }
386 }
387
388 #[must_use]
389 fn backoff_duration(&self, attempt: u32) -> std::time::Duration {
390 crate::retry::RetryPolicy::from_retries(
392 self.max_attempts,
393 std::time::Duration::from_millis(self.initial_backoff_ms),
394 std::time::Duration::from_millis(self.max_backoff_ms),
395 2.0,
396 )
397 .with_jitter(crate::retry::RetryPolicy::DEFAULT_JITTER)
398 .delay_for_attempt(attempt)
399 }
400}
401
402#[async_trait::async_trait]
403impl AsyncMiddleware for AsyncRetryMiddleware {
404 fn name(&self) -> &str {
405 "async_retry"
406 }
407
408 async fn execute<'a>(
409 &'a self,
410 request: ToolRequest,
411 next: Box<
412 dyn Fn(ToolRequest) -> Pin<Box<dyn std::future::Future<Output = MiddlewareToolResult> + Send>>
413 + Send
414 + Sync
415 + 'a,
416 >,
417 ) -> MiddlewareToolResult {
418 for attempt in 0..self.max_attempts {
419 if attempt > 0 {
420 let backoff = self.backoff_duration(attempt - 1);
421 tracing::debug!(attempt = attempt, backoff_ms = backoff.as_millis(), "retrying after backoff");
422 tokio::time::sleep(backoff).await;
423 }
424
425 let mut result = next(request.clone()).await;
426
427 if result.success {
428 if attempt > 0 {
429 self.obs_context.event(
430 crate::tools::EventType::FallbackSuccess,
431 "retry",
432 format!("succeeded on attempt {}", attempt + 1),
433 Some(1.0),
434 );
435 }
436 return result;
437 }
438
439 if let Some(error_msg) = result.error.clone() {
442 let category = vtcode_commons::classify_error_message(&error_msg);
443 let guidance = vtcode_commons::detect_misconfiguration(category, &error_msg);
444 if !category.is_retryable() || guidance.is_some() {
445 if let Some(guidance) = guidance {
446 result.error = Some(format!("{error_msg}: {}", guidance.user_message()));
447 }
448 tracing::debug!(
449 attempt = attempt,
450 category = ?category,
451 "non-retryable error, skipping remaining attempts"
452 );
453 return result;
454 }
455 }
456
457 self.obs_context.event(
458 crate::tools::EventType::FallbackAttempt,
459 "retry",
460 format!("attempt {} failed", attempt + 1),
461 None,
462 );
463 }
464
465 MiddlewareToolResult {
466 success: false,
467 output: None,
468 error: Some(format!("all {} attempts failed", self.max_attempts)),
469 duration_ms: 0,
470 from_cache: false,
471 }
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478 use std::future::Future;
479 use std::pin::Pin;
480 use std::sync::atomic::{AtomicUsize, Ordering};
481
482 type BoxedToolFuture = Pin<Box<dyn Future<Output = MiddlewareToolResult> + Send>>;
483 type BoxedExecutor = Box<dyn Fn(ToolRequest) -> BoxedToolFuture + Send + Sync>;
484
485 fn make_executor(output: &'static str) -> BoxedExecutor {
486 Box::new(move |_req: ToolRequest| {
487 Box::pin(async move {
488 MiddlewareToolResult {
489 success: true,
490 output: Some(output.to_string()),
491 error: None,
492 duration_ms: 0,
493 from_cache: false,
494 }
495 })
496 })
497 }
498
499 #[tokio::test]
500 async fn test_async_logging_middleware() {
501 let obs = Arc::new(ObservabilityContext::noop());
502 let middleware = AsyncLoggingMiddleware::new(obs);
503
504 let request = ToolRequest {
505 tool_name: "test_tool".into(),
506 arguments: "arg1".to_string(),
507 context: "ctx".to_string(),
508 };
509
510 let executor = make_executor("result");
511
512 let result = middleware.execute(request, executor).await;
513
514 assert!(result.success);
515 }
516
517 #[tokio::test]
518 async fn test_async_caching_middleware() {
519 let obs = Arc::new(ObservabilityContext::noop());
520 let cache = AsyncCachingMiddleware::new(10, 60, obs);
521
522 let request = ToolRequest {
523 tool_name: "cached_tool".into(),
524 arguments: "arg1".to_string(),
525 context: "ctx".to_string(),
526 };
527
528 let executor1 = make_executor("result1");
530
531 let result1 = cache.execute(request.clone(), executor1).await;
532 assert!(!result1.from_cache);
533
534 let executor2 = make_executor("result2");
536
537 let result2 = cache.execute(request, executor2).await;
538 assert!(result2.from_cache);
539 assert_eq!(result2.output, Some("result1".to_string())); }
541
542 #[test]
543 fn async_retry_backoff_saturates_and_respects_the_cap() {
544 let obs = Arc::new(ObservabilityContext::noop());
545 let middleware = AsyncRetryMiddleware::new(u32::MAX, 1_000, 5_000, obs);
546 assert_eq!(middleware.backoff_duration(0), std::time::Duration::from_millis(1_000));
547 assert_eq!(middleware.backoff_duration(1), std::time::Duration::from_millis(2_031));
548 let capped = middleware.backoff_duration(u32::MAX);
549 assert!(
550 (std::time::Duration::from_millis(5_000)..=std::time::Duration::from_millis(5_750)).contains(&capped),
551 "an overflowing exponent must cap near max_backoff_ms instead of panicking, got {capped:?}"
552 );
553 }
554
555 #[tokio::test]
556 async fn async_retry_skips_non_retryable_errors() {
557 let obs = Arc::new(ObservabilityContext::noop());
558 let middleware = AsyncRetryMiddleware::new(3, 1, 2, obs);
559 let attempts = Arc::new(AtomicUsize::new(0));
560
561 let executor_attempts = attempts.clone();
562 let executor: BoxedExecutor = Box::new(move |_req: ToolRequest| {
563 let executor_attempts = executor_attempts.clone();
564 Box::pin(async move {
565 executor_attempts.fetch_add(1, Ordering::SeqCst);
566 MiddlewareToolResult {
567 success: false,
568 output: None,
569 error: Some("invalid api key".to_string()),
570 duration_ms: 0,
571 from_cache: false,
572 }
573 })
574 });
575
576 let result = middleware
577 .execute(
578 ToolRequest {
579 tool_name: "auth_tool".into(),
580 arguments: "{}".to_string(),
581 context: "{}".to_string(),
582 },
583 executor,
584 )
585 .await;
586
587 assert!(!result.success);
588 assert_eq!(attempts.load(Ordering::SeqCst), 1);
589 }
590
591 #[tokio::test]
592 async fn async_retry_skips_misconfiguration_with_network_category() {
593 let obs = Arc::new(ObservabilityContext::noop());
594 let middleware = AsyncRetryMiddleware::new(3, 1, 2, obs);
595 let attempts = Arc::new(AtomicUsize::new(0));
596
597 let executor_attempts = attempts.clone();
598 let executor: BoxedExecutor = Box::new(move |_req: ToolRequest| {
599 let executor_attempts = executor_attempts.clone();
600 Box::pin(async move {
601 executor_attempts.fetch_add(1, Ordering::SeqCst);
602 MiddlewareToolResult {
603 success: false,
604 output: None,
605 error: Some("network error: invalid endpoint in base_url".to_string()),
606 duration_ms: 0,
607 from_cache: false,
608 }
609 })
610 });
611
612 let result = middleware
613 .execute(
614 ToolRequest {
615 tool_name: "provider_tool".into(),
616 arguments: "{}".to_string(),
617 context: "{}".to_string(),
618 },
619 executor,
620 )
621 .await;
622
623 assert!(!result.success);
624 assert_eq!(attempts.load(Ordering::SeqCst), 1);
625 assert!(
626 result
627 .error
628 .as_deref()
629 .is_some_and(|error| error.contains("Check settings/config first"))
630 );
631 }
632
633 #[tokio::test]
634 async fn async_retry_retries_retryable_errors_until_success() {
635 let obs = Arc::new(ObservabilityContext::noop());
636 let middleware = AsyncRetryMiddleware::new(3, 1, 2, obs);
637 let attempts = Arc::new(AtomicUsize::new(0));
638
639 let executor_attempts = attempts.clone();
640 let executor: BoxedExecutor = Box::new(move |_req: ToolRequest| {
641 let executor_attempts = executor_attempts.clone();
642 Box::pin(async move {
643 let attempt = executor_attempts.fetch_add(1, Ordering::SeqCst);
644 if attempt < 2 {
645 MiddlewareToolResult {
646 success: false,
647 output: None,
648 error: Some("429 Too Many Requests".to_string()),
649 duration_ms: 0,
650 from_cache: false,
651 }
652 } else {
653 MiddlewareToolResult {
654 success: true,
655 output: Some("ok".to_string()),
656 error: None,
657 duration_ms: 0,
658 from_cache: false,
659 }
660 }
661 })
662 });
663
664 let result = middleware
665 .execute(
666 ToolRequest {
667 tool_name: "rate_limited_tool".into(),
668 arguments: "{}".to_string(),
669 context: "{}".to_string(),
670 },
671 executor,
672 )
673 .await;
674
675 assert!(result.success);
676 assert_eq!(result.output.as_deref(), Some("ok"));
677 assert_eq!(attempts.load(Ordering::SeqCst), 3);
678 }
679}