Skip to main content

vtcode_core/tools/registry/
execution_facade.rs

1//! Tool execution entrypoints for ToolRegistry.
2
3use anyhow::{Context, Result, anyhow};
4use serde_json::{Value, json};
5use std::borrow::Cow;
6use std::future::Future;
7use std::time::{Duration, Instant};
8use tracing::{trace, warn};
9use vtcode_commons::ErrorCategory;
10
11use crate::config::constants::tools;
12use crate::core::agent::harness_kernel::PreparedToolCall;
13use crate::core::memory_pool::SizeRecommendation;
14use crate::tool_policy::ToolExecutionDecision;
15use crate::tools::error_messages::agent_execution;
16use crate::tools::request_response::{ToolCallRequest, ToolCallResponse};
17use crate::tools::tool_intent;
18use crate::tools::unified_error::UnifiedErrorKind;
19use crate::tools::unified_error::UnifiedToolError;
20use crate::ui::search::fuzzy_match;
21
22use super::assembly::public_tool_name_candidates;
23use super::execution_kernel;
24use super::reentrancy::ToolReentrancyGuard;
25use super::{
26    ExecSettlementMode, ExecutionPolicySnapshot, ToolErrorType, ToolExecutionError, ToolExecutionOutcome,
27    ToolExecutionRecord, ToolExecutionRequest, ToolRegistry,
28};
29use vtcode_config::constants::execution::{LOOP_THROTTLE_MAX_MS, LOOP_THROTTLE_REGISTRY_BASE_MS};
30
31/// When a read-only tool call has been repeated this many times, stop returning
32/// cached results and return a hard error instead.  Must be greater than
33/// MIN_READONLY_IDENTICAL_LIMIT (currently 2).
34const LOOP_HARD_BLOCK_REPEAT_COUNT: usize = 5;
35
36impl ToolRegistry {
37    fn annotate_timeout_error_payload(
38        payload: &mut Value,
39        timeout_category: &str,
40        timeout_ms: u64,
41        circuit_breaker: bool,
42    ) {
43        if let Some(obj) = payload.get_mut("error").and_then(|value| value.as_object_mut()) {
44            obj.insert("timeout_category".into(), Value::String(timeout_category.to_string()));
45            obj.insert("timeout_ms".into(), Value::from(timeout_ms));
46            obj.insert("circuit_breaker".into(), Value::Bool(circuit_breaker));
47        }
48    }
49
50    pub fn safety_gateway(&self) -> std::sync::Arc<crate::tools::safety_gateway::SafetyGateway> {
51        std::sync::Arc::clone(&self.safety_gateway)
52    }
53
54    /// Inline-delegating wrapper that returns the inner future directly to
55    /// avoid an extra coroutine state machine (audit section 16).
56    pub fn execute_public_tool_request(
57        &self,
58        request: ToolExecutionRequest,
59    ) -> impl Future<Output = ToolExecutionOutcome> + '_ {
60        self.execute_tool_request_internal(request, None)
61    }
62
63    /// Execute with the caller's remaining wall-clock budget. Retry waits must
64    /// fit this deadline; the caller still owns cancellation and timeout delivery.
65    pub fn execute_public_tool_request_with_deadline(
66        &self,
67        request: ToolExecutionRequest,
68        deadline: Instant,
69    ) -> impl Future<Output = ToolExecutionOutcome> + '_ {
70        self.execute_tool_request_internal(request, Some(deadline))
71    }
72
73    pub async fn execute_prepared_public_tool_request(
74        &self,
75        prepared: &PreparedToolCall,
76        policy: ExecutionPolicySnapshot,
77    ) -> ToolExecutionOutcome {
78        self.execute_prepared_public_tool_request_until(prepared, policy, None).await
79    }
80
81    /// Keep the caller's outer deadline available to retry admission as well as
82    /// timeout enforcement. Prepared calls still require fresh safety admission.
83    pub(crate) async fn execute_prepared_public_tool_request_until(
84        &self,
85        prepared: &PreparedToolCall,
86        policy: ExecutionPolicySnapshot,
87        deadline: Option<Instant>,
88    ) -> ToolExecutionOutcome {
89        let request = ToolExecutionRequest::new(prepared.canonical_name.clone(), prepared.effective_args.clone())
90            .with_policy(
91                policy
92                    .with_prevalidated(prepared.already_preflighted)
93                    .with_safety_prevalidated(false),
94            );
95        self.execute_tool_request_internal(request, deadline).await
96    }
97
98    async fn should_skip_loop_detection_for_exec_continuation(&self, tool_name: &str, args: &Value) -> bool {
99        if tool_name == tools::WRITE_STDIN {
100            return matches!(
101                crate::tools::command_args::write_stdin_dispatch(args),
102                Ok(crate::tools::command_args::WriteStdinDispatch::Poll
103                    | crate::tools::command_args::WriteStdinDispatch::Wait,)
104            );
105        }
106
107        if tool_name != tools::UNIFIED_EXEC {
108            return false;
109        }
110
111        if !tool_intent::command_session_action_in(args, &["poll", "continue"]) {
112            return false;
113        }
114        if tool_intent::command_session_action_is(args, "continue")
115            && crate::tools::command_args::interactive_input_text(args).is_some()
116        {
117            return false;
118        }
119
120        let Some(session_id) = crate::tools::command_args::session_id_text(args) else {
121            return false;
122        };
123
124        matches!(self.exec_session_completed(session_id).await, Ok(None))
125    }
126
127    async fn public_tool_catalog_for_error(&self, requested_name: &str) -> (Vec<String>, Vec<String>) {
128        let mut tool_names = self.available_tools().await;
129        tool_names.sort_unstable();
130        tool_names.dedup();
131
132        let requested_candidates = public_tool_name_candidates(requested_name);
133        let mut similar_tools = Vec::new();
134
135        if let Ok(resolved) = self.resolve_public_tool_name_sync(requested_name)
136            && tool_names.iter().any(|tool| tool == &resolved)
137        {
138            similar_tools.push(resolved);
139        }
140
141        for tool in &tool_names {
142            if similar_tools.len() >= 3 {
143                break;
144            }
145
146            if similar_tools.iter().any(|candidate| candidate == tool) {
147                continue;
148            }
149
150            if requested_candidates.iter().any(|candidate| fuzzy_match(candidate, tool)) {
151                similar_tools.push(tool.clone());
152            }
153        }
154
155        (tool_names, similar_tools)
156    }
157
158    pub fn preflight_validate_call(&self, name: &str, args: &Value) -> Result<super::ToolPreflightOutcome> {
159        execution_kernel::preflight_validate_call(self, name, args)
160    }
161
162    /// Preflight a tool call from the harness path, allowing dispatch to
163    /// internal (model-hidden) tool registrations such as read_file/write_file.
164    /// Direct model-originated entry should use `preflight_validate_call`.
165    pub fn preflight_validate_harness_call(&self, name: &str, args: &Value) -> Result<super::ToolPreflightOutcome> {
166        execution_kernel::preflight_validate_call_with_mode(self, name, args, execution_kernel::DispatchMode::Harness)
167    }
168
169    pub fn admit_public_tool_call(&self, name: &str, args: &Value) -> Result<PreparedToolCall> {
170        let preflight = self.preflight_validate_harness_call(name, args)?;
171        Ok(PreparedToolCall::new(
172            preflight.normalized_tool_name,
173            preflight.readonly_classification,
174            preflight.parallel_safe_after_preflight,
175            preflight.effective_args,
176        ))
177    }
178
179    pub async fn execute_tool(&self, name: &str, args: Value) -> Result<Value> {
180        self.execute_tool_ref(name, &args).await
181    }
182
183    /// Execute a model-originated tool call through the public routing assembly.
184    pub async fn execute_public_tool_ref(&self, name: &str, args: &Value) -> Result<Value> {
185        self.execute_public_tool_ref_internal(name, args, false).await
186    }
187
188    /// Reference-taking version of execute_tool to avoid cloning by callers
189    /// that already have access to an existing `Value`.
190    pub async fn execute_tool_ref(&self, name: &str, args: &Value) -> Result<Value> {
191        self.execute_tool_ref_internal(name, args, false, ExecSettlementMode::Manual)
192            .await
193    }
194
195    /// Reference-taking execution entrypoint for calls that were already preflight-validated.
196    ///
197    /// This avoids re-running argument/schema/path/command preflight in hot paths
198    /// where validation already happened in the runloop.
199    pub async fn execute_tool_ref_prevalidated(&self, name: &str, args: &Value) -> Result<Value> {
200        self.execute_tool_ref_internal(name, args, true, ExecSettlementMode::Manual)
201            .await
202    }
203
204    /// Prevalidated model-originated execution that still routes through the public assembly.
205    pub async fn execute_public_tool_ref_prevalidated(&self, name: &str, args: &Value) -> Result<Value> {
206        self.execute_public_tool_ref_prevalidated_with_mode(name, args, ExecSettlementMode::Manual)
207            .await
208    }
209
210    #[doc(hidden)]
211    pub async fn execute_public_tool_ref_prevalidated_with_mode(
212        &self,
213        name: &str,
214        args: &Value,
215        exec_settlement_mode: ExecSettlementMode,
216    ) -> Result<Value> {
217        self.execute_public_tool_ref_internal_with_mode(name, args, true, exec_settlement_mode)
218            .await
219    }
220
221    pub async fn execute_prepared_public_tool_ref_with_mode(
222        &self,
223        prepared: &PreparedToolCall,
224        exec_settlement_mode: ExecSettlementMode,
225    ) -> Result<Value> {
226        // Prepared calls come from the harness admission gate
227        // (`admit_public_tool_call`), which is the only producer of
228        // `PreparedToolCall`, so internal (model-hidden) dispatch is authorized.
229        self.execute_public_tool_ref_dispatch(
230            prepared.canonical_name.as_str(),
231            &prepared.effective_args,
232            prepared.already_preflighted,
233            execution_kernel::DispatchMode::Harness,
234            exec_settlement_mode,
235        )
236        .await
237    }
238
239    async fn execute_public_tool_ref_internal(&self, name: &str, args: &Value, prevalidated: bool) -> Result<Value> {
240        self.execute_public_tool_ref_dispatch(
241            name,
242            args,
243            prevalidated,
244            execution_kernel::DispatchMode::ModelPublic,
245            ExecSettlementMode::Manual,
246        )
247        .await
248    }
249
250    async fn execute_public_tool_ref_internal_with_mode(
251        &self,
252        name: &str,
253        args: &Value,
254        prevalidated: bool,
255        exec_settlement_mode: ExecSettlementMode,
256    ) -> Result<Value> {
257        self.execute_public_tool_ref_dispatch(
258            name,
259            args,
260            prevalidated,
261            execution_kernel::DispatchMode::ModelPublic,
262            exec_settlement_mode,
263        )
264        .await
265    }
266
267    /// Core public-routing execution entrypoint.
268    ///
269    /// `dispatch_mode` is the authority to fall back to internal (model-hidden)
270    /// tool registrations and is fully independent of `prevalidated` (a pure
271    /// performance flag that skips re-running preflight). Only callers that went
272    /// through the harness admission gate (`admit_public_tool_call`) pass
273    /// [`execution_kernel::DispatchMode::Harness`]; direct model-originated entry always passes
274    /// [`execution_kernel::DispatchMode::ModelPublic`], so a stray `prevalidated=true` can never by
275    /// itself widen the dispatchable surface.
276    pub(super) async fn execute_public_tool_ref_dispatch(
277        &self,
278        name: &str,
279        args: &Value,
280        prevalidated: bool,
281        dispatch_mode: execution_kernel::DispatchMode,
282        exec_settlement_mode: ExecSettlementMode,
283    ) -> Result<Value> {
284        let routed_name = execution_kernel::resolve_dispatch_target(self, name, dispatch_mode)
285            .map_err(|err| anyhow!(err.to_string()))?;
286        let effective_args = execution_kernel::remap_public_file_operation_alias_args(name, routed_name.as_str(), args)
287            .or_else(|| execution_kernel::remap_consolidated_action_alias_args(name, routed_name.as_str(), args));
288        self.execute_tool_ref_internal(
289            routed_name.as_str(),
290            effective_args.as_ref().unwrap_or(args),
291            prevalidated,
292            exec_settlement_mode,
293        )
294        .await
295    }
296
297    async fn execute_tool_ref_internal(
298        &self,
299        name: &str,
300        args: &Value,
301        prevalidated: bool,
302        exec_settlement_mode: ExecSettlementMode,
303    ) -> Result<Value> {
304        let resolved = self.resolve_tool_name_with_display(name);
305        self.enforce_matrix_role(&resolved.canonical)?;
306        if let Err(error) = crate::core::agent::snapshots::declare_prompt_edit(
307            self.harness_context_snapshot().session_id,
308            name.to_owned(),
309            args.clone(),
310        )
311        .await
312        {
313            tracing::warn!(
314                tool = %name,
315                error = %error,
316                "Checkpoint pre-image capture failed; rewind may not restore this edit"
317            );
318        }
319        // PERFORMANCE OPTIMIZATION: Use memory pool for string allocations if enabled
320        let _pool_guard = if self.optimization_config.memory_pool.enabled {
321            Some(self.memory_pool.get_string())
322        } else {
323            None
324        };
325
326        // PERFORMANCE OPTIMIZATION: Auto-tune memory pool based on usage patterns
327        if self.optimization_config.memory_pool.enabled {
328            let recommendation = self.memory_pool.auto_tune(&self.optimization_config.memory_pool);
329
330            // Log recommendation if significant changes are suggested
331            if !matches!(
332                (
333                    recommendation.string_size_recommendation,
334                    recommendation.value_size_recommendation,
335                    recommendation.vec_size_recommendation
336                ),
337                (SizeRecommendation::Maintain, SizeRecommendation::Maintain, SizeRecommendation::Maintain)
338            ) {
339                tracing::debug!(
340                    "Memory pool tuning recommendation: string={:?}, value={:?}, vec={:?}, allocations_avoided={}",
341                    recommendation.string_size_recommendation,
342                    recommendation.value_size_recommendation,
343                    recommendation.vec_size_recommendation,
344                    recommendation.total_allocations_avoided
345                );
346            }
347        }
348
349        let resolved_name = self.resolve_tool_name_with_display(name);
350        let tool_name = resolved_name.canonical;
351        let tool_name_owned = tool_name.clone();
352        let display_name = resolved_name.display;
353
354        // PERFORMANCE OPTIMIZATION: Check hot cache for tool lookup using the canonical name.
355        // This must happen AFTER alias resolution so that aliased tools resolve to their
356        // canonical cache entry on the first hit. Without this, the cache lookup uses the
357        // raw alias string while insertion uses the canonical name, making aliased tools
358        // perpetually miss the cache.
359        let cached_tool = if self.optimization_config.tool_registry.use_optimized_registry {
360            let cache = self.hot_tool_cache.read();
361            cache.peek(&tool_name).cloned()
362        } else {
363            None
364        };
365
366        // PERFORMANCE OPTIMIZATION: Update hot cache with resolved tool if optimizations enabled
367        if let Some(tool_arc) = cached_tool.as_ref()
368            && self.optimization_config.tool_registry.use_optimized_registry
369            && tool_name != name
370        {
371            // Cache the canonical name too for faster future lookups
372            self.hot_tool_cache.write().put(tool_name.clone(), tool_arc.clone());
373        }
374
375        let execution_args = self.prepare_execution_args(&tool_name, args)?;
376        let is_verification_command = execution_args.is_verification_command;
377        let max_output_tokens = execution_args.max_output_tokens;
378        let args = execution_args.handler_args.as_ref();
379        let requested_name = name.to_string();
380
381        // Clone args once at the start for error recording paths (clone only here)
382        let args_for_recording = args.clone();
383        // Capture harness context snapshot for structured telemetry and history
384        let context_snapshot = self.harness_context_snapshot();
385        let record_failure = |tool_name: String,
386                              is_mcp_tool: bool,
387                              mcp_provider: Option<String>,
388                              args: Value,
389                              error_msg: String,
390                              timeout_category: Option<String>,
391                              base_timeout_ms: Option<u64>,
392                              adaptive_timeout_ms: Option<u64>,
393                              effective_timeout_ms: Option<u64>,
394                              circuit_breaker: bool| {
395            self.execution_history.add_record(ToolExecutionRecord::failure(
396                tool_name,
397                requested_name.clone(),
398                is_mcp_tool,
399                mcp_provider,
400                args,
401                error_msg,
402                context_snapshot.clone(),
403                timeout_category,
404                base_timeout_ms,
405                adaptive_timeout_ms,
406                effective_timeout_ms,
407                circuit_breaker,
408            ));
409        };
410
411        let allow_parallel_sibling = prevalidated && tool_intent::is_parallel_safe_call(&tool_name, args);
412        let _reentrancy_guard = match ToolReentrancyGuard::enter(&tool_name, allow_parallel_sibling) {
413            Ok(guard) => guard,
414            Err(violation) => {
415                let reentry_count = violation.tool_reentry_count + 1;
416                let error_message = format!(
417                    "Reentrancy guard: tool '{}' is already running in this call stack, so this recursive call was blocked. \
418                     Repeating the same call is blocked the same way; change the control flow or use a different tool.\n\
419                     Current stack depth: {}. Re-entry count for this tool in the current task: {}.\n\
420                     Stack trace: {}",
421                    display_name, violation.stack_depth, reentry_count, violation.stack_trace
422                );
423                let error = ToolExecutionError::new(
424                    tool_name_owned.clone(),
425                    ToolErrorType::PolicyViolation,
426                    error_message.clone(),
427                );
428                let mut payload = error.to_json_value();
429                if let Some(obj) = payload.as_object_mut() {
430                    obj.insert("reentrant_call_blocked".into(), json!(true));
431                    obj.insert("stack_depth".into(), json!(violation.stack_depth));
432                    obj.insert("reentry_count".into(), json!(reentry_count));
433                    obj.insert("tool".into(), json!(display_name));
434                    obj.insert("stack_trace".into(), json!(violation.stack_trace));
435                }
436                record_failure(
437                    tool_name_owned.clone(),
438                    false,
439                    None,
440                    args_for_recording.clone(),
441                    error_message.clone(),
442                    None,
443                    None,
444                    None,
445                    None,
446                    false,
447                );
448                return Err(anyhow!(error_message).context("tool reentrancy blocked"));
449            }
450        };
451
452        // Classify the tool intent once: the prevalidated fast path skips full
453        // preflight and classifies here; the full-preflight path reuses the
454        // intent the kernel already computed on the validated (executed) args,
455        // so planning enforcement below cannot disagree with
456        // `readonly_classification`.
457        let (intent, readonly_classification) = if prevalidated {
458            #[cfg(debug_assertions)]
459            {
460                if let Err(err) = execution_kernel::preflight_validate_resolved_call(self, &tool_name, args)
461                    && !agent_execution::is_planning_active_denial(&err.to_string())
462                {
463                    debug_assert!(false, "prevalidated execution received invalid call for '{tool_name}': {err}");
464                }
465            }
466            let intent = tool_intent::classify_tool_intent(&tool_name, args);
467            (intent, !intent.mutating)
468        } else {
469            match execution_kernel::preflight_validate_resolved_call(self, &tool_name, args) {
470                Ok(outcome) => (outcome.intent, outcome.readonly_classification),
471                Err(err) => {
472                    let err_msg = err.to_string();
473                    record_failure(
474                        tool_name_owned.clone(),
475                        false,
476                        None,
477                        args_for_recording.clone(),
478                        err_msg,
479                        None,
480                        None,
481                        None,
482                        None,
483                        false,
484                    );
485                    return Err(err);
486                }
487            }
488        };
489
490        if readonly_classification {
491            trace!(tool = %tool_name, "Validation classified tool as read-only");
492        }
493
494        // Defense-in-depth: prevalidated fast path skips full preflight, but planning workflow
495        // mutating-tool enforcement remains a hard safety invariant. Reuse the already-computed
496        // `intent` so we don't reclassify on the hot path.
497        if self.is_planning_active() && !self.is_planning_active_allowed_with_intent(&tool_name, args, &intent) {
498            let error_msg = agent_execution::planning_workflow_denial_message(&display_name);
499            record_failure(
500                tool_name_owned.clone(),
501                false,
502                None,
503                args_for_recording.clone(),
504                error_msg.clone(),
505                None,
506                None,
507                None,
508                None,
509                false,
510            );
511            return Err(anyhow!(error_msg).context(agent_execution::PLANNING_DENIED_CONTEXT));
512        }
513
514        let shared_circuit_breaker = self.shared_circuit_breaker();
515        if let Some(breaker) = shared_circuit_breaker.as_ref()
516            && !breaker.allow_request_for_tool(&tool_name)
517        {
518            let diagnostics = breaker.get_diagnostics(&tool_name);
519            let retry_after = diagnostics
520                .remaining_backoff
521                .map(|backoff| format!(" retry_after={}s.", backoff.as_secs()))
522                .unwrap_or_default();
523            let error_msg = format!(
524                "Tool '{display_name}' is temporarily disabled due to high failure rate (Circuit Breaker OPEN).{retry_after}"
525            );
526            self.execution_history.add_record(
527                ToolExecutionRecord::failure(
528                    tool_name_owned.clone(),
529                    requested_name.clone(),
530                    false,
531                    None,
532                    args_for_recording.clone(),
533                    error_msg.clone(),
534                    context_snapshot.clone(),
535                    None,
536                    None,
537                    None,
538                    None,
539                    true,
540                )
541                .with_circuit_breaker_state(format!("{:?}", diagnostics.status))
542                .with_retry_after(diagnostics.remaining_backoff),
543            );
544            return Err(anyhow!(error_msg).context("tool denied by circuit breaker"));
545        }
546
547        let timeout_category = self.timeout_category_for_args(&tool_name, args).await;
548
549        if let Some(backoff) = self.should_circuit_break(timeout_category) {
550            warn!(
551                tool = %tool_name,
552                category = %timeout_category.label(),
553                delay_ms = %backoff.as_millis(),
554                "Circuit breaker active for tool category; backing off before execution"
555            );
556            tokio::time::sleep(backoff).await;
557        }
558
559        let execution_span = tracing::debug_span!(
560            "tool_execution",
561            tool = %tool_name,
562            requested = %name,
563            session_id = %context_snapshot.session_id,
564            task_id = %context_snapshot.task_id.as_deref().unwrap_or("")
565        );
566        let _span_guard = execution_span.enter();
567
568        trace!(
569            tool = %tool_name,
570            session_id = %context_snapshot.session_id,
571            task_id = %context_snapshot.task_id.as_deref().unwrap_or(""),
572            "Executing tool with harness context"
573        );
574
575        if tool_name != name {
576            trace!(
577                requested = %name,
578                canonical = %tool_name,
579                "Resolved tool alias to canonical name"
580            );
581        }
582
583        let base_timeout_ms = self
584            .timeout_policy
585            .read()
586            .ceiling_for(timeout_category)
587            .map(|d| d.as_millis() as u64);
588        let adaptive_timeout_ms = self
589            .resiliency
590            .lock()
591            .adaptive_timeout_ceiling
592            .get(&timeout_category)
593            .filter(|d| d.as_millis() > 0)
594            .map(|d| d.as_millis() as u64);
595        let timeout_category_label = Some(timeout_category.label().to_string());
596
597        if let Some(rate_limit) = self.execution_history.rate_limit_per_minute() {
598            let calls_last_minute = self.execution_history.calls_in_window(Duration::from_secs(60));
599            if calls_last_minute >= rate_limit {
600                warn!(
601                    tool = %tool_name_owned,
602                    requested = %requested_name,
603                    calls_last_minute,
604                    rate_limit,
605                    "Execution history rate-limit threshold exceeded (observability-only)"
606                );
607            }
608        }
609
610        let fresh_patch_read = self.consume_patch_recovery_read(&tool_name, args);
611        // Stateful tracker/decision calls must observe the current canonical
612        // task, including identical calls after request or permission changes.
613        let matrix_verification = self
614            .matrix_worker
615            .read()
616            .as_ref()
617            .is_some_and(|worker| worker.assignment.phase == crate::exec::events::matrix::MatrixPhase::Verify);
618        let reusable_result = readonly_classification
619            && !matrix_verification
620            && !matches!(tool_name.as_str(), tools::RECORD_DECISION | tools::TASK_TRACKER | tools::MATRIX);
621        let skip_loop_detection = self.should_skip_loop_detection_for_exec_continuation(&tool_name, args).await;
622        if skip_loop_detection {
623            trace!(
624                tool = %tool_name,
625                "Skipping identical-call loop detection for stateful exec continuation"
626            );
627        }
628
629        // FAST REUSE: Read-only inspection calls are often repeated verbatim within a
630        // single turn (e.g. `diff a b | wc -l`, `find ... | grep`). Reuse the most recent
631        // successful result immediately instead of paying for another round-trip and
632        // another spool file. This is gated by a short TTL and the read-only classification
633        // so mutating calls never take this path.
634        //
635        // Verification commands (`cargo check`, `cargo nextest run`, `cargo fmt
636        // --check`, and pure `&&` chains thereof) are read-only by intent but
637        // must always re-execute: reusing a stale success would clear the
638        // anti-blind-editing gate without verifying the current worktree, and
639        // reusing a stale failure would keep the gate pending after a fix.
640        // (`is_verification_command` is bound once at preview-budget
641        // resolution above; the stripped output-metadata field does not
642        // affect shell classification.)
643        if reusable_result && !is_verification_command && !skip_loop_detection && !fresh_patch_read {
644            let fast_reuse_max_age = Duration::from_secs(60);
645            let fast_reused = self
646                .execution_history
647                .find_recent_spooled_result(&tool_name, args, fast_reuse_max_age)
648                .or_else(|| {
649                    self.execution_history
650                        .find_recent_successful_result(&tool_name, args, fast_reuse_max_age)
651                });
652            if let Some(mut reused_value) = fast_reused {
653                if let Some(obj) = reused_value.as_object_mut() {
654                    obj.insert("reused_recent_result".into(), json!(true));
655                    obj.insert("tool".into(), json!(display_name));
656                    let reused_spooled = obj.get("spool_path").and_then(|v| v.as_str()).is_some();
657                    let note = if reused_spooled {
658                        "Reusing a recent spooled output for this identical read-only call. Continue from the spool file instead of re-running the tool."
659                    } else {
660                        "Reusing a recent successful output for this identical read-only call."
661                    };
662                    obj.insert("reused_result_note".into(), json!(note));
663                }
664                // Record a synthetic "reused" entry so subsequent
665                // `detect_loop` / `find_recent_*` queries see this call in the
666                // history.  Previously the fast-reuse path returned the
667                // cached payload without recording, which meant `detect_loop`
668                // could not account for the reused call — leading to
669                // undercounting on the very next turn and silent cache
670                // poisoning.
671                //
672                // We pass `is_mcp_tool = false` and `mcp_provider = None`
673                // because the fast-reuse gate has already filtered for
674                // read-only calls and we don't have those locals in scope at
675                // this point in the function.  The cached record itself
676                // (added when the original call ran) carries the true MCP
677                // metadata; the synthetic record exists only to make
678                // `detect_loop` see this call in the rolling window.
679                self.execution_history.add_record(ToolExecutionRecord::success(
680                    tool_name.clone(),
681                    requested_name.clone(),
682                    false,
683                    None,
684                    args_for_recording.clone(),
685                    reused_value.clone(),
686                    context_snapshot.clone(),
687                    timeout_category_label.clone(),
688                    base_timeout_ms,
689                    adaptive_timeout_ms,
690                    None,
691                    false,
692                ));
693                trace!(
694                    tool = %tool_name,
695                    "Fast-reusing recent successful read-only result"
696                );
697                self.observe_source_output(&tool_name, args, &reused_value).await;
698                return Ok(reused_value);
699            }
700        }
701
702        // LOOP DETECTION: Check if we're calling the same tool repeatedly with identical params
703        let loop_limit = if skip_loop_detection {
704            0
705        } else {
706            self.execution_history.loop_limit_for(&tool_name, args)
707        };
708        let loop_result = if skip_loop_detection {
709            crate::tools::registry::execution_history::LoopDetectionResult {
710                detected: false,
711                repeat_count: 0,
712                tool_name: tool_name.clone(),
713            }
714        } else {
715            self.execution_history.detect_loop(&tool_name, args)
716        };
717        if loop_result.detected && loop_result.repeat_count > 1 {
718            let delay_ms = (LOOP_THROTTLE_REGISTRY_BASE_MS * loop_result.repeat_count as u64).min(LOOP_THROTTLE_MAX_MS);
719            if delay_ms > 0 {
720                tokio::time::sleep(Duration::from_millis(delay_ms)).await;
721            }
722        }
723        if loop_limit > 0 && loop_result.detected {
724            warn!(
725                tool = %tool_name,
726                repeats = loop_result.repeat_count,
727                "Loop detected: agent calling same tool with identical parameters {} times",
728                loop_result.repeat_count
729            );
730            if loop_result.repeat_count >= loop_limit {
731                // Hard block: when the model has been repeating the same call far
732                // beyond the limit, stop returning cached results and return an
733                // error.  Returning a cached result at high repeat counts causes
734                // the model to see "success" and keep retrying.
735                let hard_block = loop_result.repeat_count >= LOOP_HARD_BLOCK_REPEAT_COUNT;
736
737                if reusable_result && !is_verification_command && !hard_block && !fresh_patch_read {
738                    let reuse_max_age = Duration::from_secs(120);
739                    let reused = self
740                        .execution_history
741                        .find_recent_spooled_result(&tool_name, args, reuse_max_age)
742                        .or_else(|| {
743                            self.execution_history
744                                .find_recent_successful_result(&tool_name, args, reuse_max_age)
745                        });
746                    if let Some(mut reused_value) = reused {
747                        if let Some(obj) = reused_value.as_object_mut() {
748                            obj.insert("reused_recent_result".into(), json!(true));
749                            obj.insert("loop_detected".into(), json!(true));
750                            obj.insert("repeat_count".into(), json!(loop_result.repeat_count));
751                            obj.insert("limit".into(), json!(loop_limit));
752                            obj.insert("tool".into(), json!(display_name));
753                            let reused_spooled = obj.get("spool_path").and_then(|v| v.as_str()).is_some();
754                            let note = if reused_spooled {
755                                "Loop detected: this identical read-only call has been repeated, so the earlier result was reused. The full output is in the spool file and the conversation history; further repeats return an error instead."
756                            } else {
757                                "Loop detected: this identical read-only call has been repeated with no new information, so the earlier result was reused. It is already in the conversation history; further repeats return an error instead."
758                            };
759                            obj.insert("loop_detected_note".into(), json!(note));
760                        }
761                        self.observe_source_output(&tool_name, args, &reused_value).await;
762                        return Ok(reused_value);
763                    }
764                }
765
766                let delay_ms =
767                    (LOOP_THROTTLE_REGISTRY_BASE_MS * loop_result.repeat_count as u64).min(LOOP_THROTTLE_MAX_MS);
768                if delay_ms > 0 {
769                    tokio::time::sleep(Duration::from_millis(delay_ms)).await;
770                }
771
772                let error = ToolExecutionError::new(
773                    tool_name_owned.clone(),
774                    ToolErrorType::PolicyViolation,
775                    agent_execution::loop_detection_block_message(&display_name, loop_result.repeat_count as u64, None),
776                );
777                let mut payload = error.to_json_value();
778                if let Some(obj) = payload.as_object_mut() {
779                    obj.insert("loop_detected".into(), json!(true));
780                    obj.insert("repeat_count".into(), json!(loop_result.repeat_count));
781                    obj.insert("limit".into(), json!(loop_limit));
782                    obj.insert("tool".into(), json!(display_name));
783                    obj.insert(
784                        "next_action".into(),
785                        json!("Identical calls to this tool are blocked. Use the data already in the conversation history; for different information, change the arguments or use another tool."),
786                    );
787                }
788
789                record_failure(
790                    tool_name_owned,
791                    false,
792                    None,
793                    args_for_recording,
794                    "Tool call blocked due to repeated identical invocations".to_string(),
795                    timeout_category_label.clone(),
796                    base_timeout_ms,
797                    adaptive_timeout_ms,
798                    None,
799                    false,
800                );
801
802                return Ok(payload);
803            }
804        }
805
806        let full_auto_denied = {
807            let gateway = self.policy_gateway.clone();
808            let tool_name_ref = &tool_name;
809            async move { gateway.is_denied_in_full_auto(tool_name_ref).await }
810        };
811        let full_auto_denied = full_auto_denied.await;
812        if full_auto_denied {
813            let _error = ToolExecutionError::new(
814                tool_name_owned.clone(),
815                ToolErrorType::PolicyViolation,
816                format!("Tool '{display_name}' is not permitted while full-auto permission review is active"),
817            );
818
819            record_failure(
820                tool_name_owned.clone(),
821                false,
822                None,
823                args_for_recording.clone(),
824                "Tool execution denied by policy".to_string(),
825                timeout_category_label.clone(),
826                base_timeout_ms,
827                adaptive_timeout_ms,
828                None,
829                false,
830            );
831
832            return Err(anyhow!("Tool '{display_name}' is not permitted while full-auto permission review is active")
833                .context("tool denied by full-auto allowlist"));
834        }
835
836        let policy_revision = self.policy_gateway.revision();
837        let current_policy = self.policy_gateway.get_tool_policy(&tool_name).await;
838        let retry_approved = super::execution_attempts::RETRY_APPROVAL
839            .try_with(|slot| {
840                slot.borrow().as_ref().is_some_and(|approval| {
841                    std::sync::Arc::ptr_eq(&approval.policy_gateway, &self.policy_gateway)
842                        && approval.tool_name == tool_name
843                        && approval.args == *args
844                        && approval.policy_revision == policy_revision
845                        && approval.policy == current_policy
846                })
847            })
848            .unwrap_or(false);
849        let skip_policy_prompt = retry_approved || self.policy_gateway.take_preapproved(&tool_name).await;
850
851        let decision = if skip_policy_prompt {
852            ToolExecutionDecision::Allowed
853        } else {
854            self.policy_gateway.should_execute_tool(&tool_name).await?
855        };
856
857        if !decision.is_allowed() {
858            let error_msg = match decision {
859                ToolExecutionDecision::DeniedWithFeedback(feedback) => {
860                    format!("Tool '{display_name}' denied by user: {feedback}")
861                }
862                _ => format!("Tool '{display_name}' execution denied by policy"),
863            };
864
865            let _error =
866                ToolExecutionError::new(tool_name_owned.clone(), ToolErrorType::PolicyViolation, error_msg.clone());
867
868            record_failure(
869                tool_name_owned.clone(),
870                false,
871                None,
872                args_for_recording.clone(),
873                error_msg.clone(),
874                timeout_category_label.clone(),
875                base_timeout_ms,
876                adaptive_timeout_ms,
877                None,
878                false,
879            );
880
881            return Err(anyhow!("{error_msg}").context("tool denied by policy"));
882        }
883
884        let _ = super::execution_attempts::RETRY_APPROVAL.try_with(|slot| {
885            *slot.borrow_mut() = Some(super::execution_attempts::RetryApproval {
886                tool_name: tool_name.to_string(),
887                args: args.clone(),
888                policy_revision,
889                policy_gateway: self.policy_gateway.clone(),
890                policy: current_policy,
891            });
892        });
893        let gateway = self.policy_gateway.clone();
894        let constrained_result = gateway.apply_policy_constraints(&tool_name, args).await;
895        let mut args = match constrained_result {
896            Ok(processed_args) => processed_args,
897            Err(err) => {
898                let error = ToolExecutionError::with_original_error(
899                    tool_name_owned.clone(),
900                    ToolErrorType::InvalidParameters,
901                    "Failed to apply policy constraints".to_string(),
902                    err.to_string(),
903                );
904
905                record_failure(
906                    tool_name_owned,
907                    false,
908                    None,
909                    args_for_recording,
910                    format!("Failed to apply policy constraints: {err}"),
911                    timeout_category_label.clone(),
912                    base_timeout_ms,
913                    adaptive_timeout_ms,
914                    None,
915                    false,
916                );
917
918                return Err(anyhow!(error.to_json_value()).context("tool denied by policy constraints"));
919            }
920        };
921
922        let super::execution_stages::ExecutionRoute {
923            route:
924                super::execution_stages::ToolRoute {
925                    needs_pty,
926                    tool_exists,
927                    is_mcp: is_mcp_tool,
928                    mcp_provider,
929                    mcp_tool_name,
930                },
931            mcp_lookup_error,
932        } = self.resolve_execution_route(name, &tool_name).await;
933
934        // If tool doesn't exist in either registry, return an error
935        if !tool_exists {
936            if let Some(err) = mcp_lookup_error {
937                let error = ToolExecutionError::with_original_error(
938                    tool_name_owned.clone(),
939                    ToolErrorType::ExecutionError,
940                    format!("Failed to resolve MCP tool '{display_name}': {err}"),
941                    err.to_string(),
942                );
943
944                record_failure(
945                    tool_name_owned,
946                    is_mcp_tool,
947                    mcp_provider.clone(),
948                    args_for_recording,
949                    format!("Failed to resolve MCP tool '{display_name}': {err}"),
950                    timeout_category_label.clone(),
951                    base_timeout_ms,
952                    adaptive_timeout_ms,
953                    None,
954                    false,
955                );
956
957                return Ok(error.to_json_value());
958            }
959
960            let (all_tool_names, similar_tools) = self.public_tool_catalog_for_error(name).await;
961            let suggestion = if !similar_tools.is_empty() {
962                format!(" Did you mean: {}?", similar_tools.join(", "))
963            } else {
964                String::new()
965            };
966            let available_tool_list = all_tool_names.join(", ");
967            let message = format!("Unknown tool: {display_name}. Available tools: {available_tool_list}.{suggestion}");
968            let error = ToolExecutionError::new(tool_name_owned.clone(), ToolErrorType::ToolNotFound, message.clone());
969
970            record_failure(
971                tool_name_owned,
972                is_mcp_tool,
973                mcp_provider.clone(),
974                args_for_recording,
975                message,
976                timeout_category_label.clone(),
977                base_timeout_ms,
978                adaptive_timeout_ms,
979                None,
980                false,
981            );
982
983            return Ok(error.to_json_value());
984        }
985
986        // MP-3: Circuit breaker check for MCP tools
987        if is_mcp_tool && !self.mcp_circuit_breaker.allow_request() {
988            let diag = self.mcp_circuit_breaker.diagnostics();
989            let error = ToolExecutionError::new(
990                tool_name_owned.clone(),
991                ToolErrorType::ExecutionError,
992                format!("MCP circuit breaker {:?}; skipping execution", diag.status),
993            );
994            let payload = json!({
995                "error": error.to_json_value(),
996                "circuit_breaker_state": format!("{:?}", diag.status),
997                "consecutive_failures": diag.consecutive_failures,
998                "note": "MCP provider circuit breaker open; execution skipped",
999                "last_failed_at_ago_ms": diag.last_failure_time
1000                    .map(|ts| ts.elapsed().as_millis() as u64),
1001                "current_timeout_seconds": diag.current_timeout.as_secs(),
1002                "mcp_provider": mcp_provider,
1003            });
1004            warn!(
1005                tool = %tool_name_owned,
1006                payload = %payload,
1007                "Skipping MCP tool execution due to circuit breaker"
1008            );
1009            self.execution_history.add_record(
1010                ToolExecutionRecord::failure(
1011                    tool_name_owned,
1012                    requested_name.clone(),
1013                    is_mcp_tool,
1014                    mcp_provider.clone(),
1015                    args_for_recording,
1016                    format!("MCP circuit breaker {:?}; execution skipped", diag.status),
1017                    context_snapshot.clone(),
1018                    timeout_category_label.clone(),
1019                    base_timeout_ms,
1020                    adaptive_timeout_ms,
1021                    None,
1022                    false,
1023                )
1024                .with_circuit_breaker_state(format!("{:?}", diag.status))
1025                .with_retry_after(diag.retry_after),
1026            );
1027            return Ok(payload);
1028        }
1029
1030        trace!(
1031            tool = %tool_name,
1032            requested = %name,
1033            is_mcp = is_mcp_tool,
1034            uses_pty = needs_pty,
1035            alias = %if tool_name == name { "" } else { name },
1036            mcp_provider = %mcp_provider.as_deref().unwrap_or(""),
1037            "Resolved tool route"
1038        );
1039
1040        // Start PTY session if needed (using RAII guard for automatic cleanup)
1041        let _pty_guard = if needs_pty {
1042            match self.start_pty_session() {
1043                Ok(guard) => Some(guard),
1044                Err(err) => {
1045                    let error = ToolExecutionError::with_original_error(
1046                        tool_name_owned.clone(),
1047                        ToolErrorType::ExecutionError,
1048                        "Failed to start PTY session".to_string(),
1049                        err.to_string(),
1050                    );
1051
1052                    record_failure(
1053                        tool_name_owned,
1054                        is_mcp_tool,
1055                        mcp_provider.clone(),
1056                        args_for_recording,
1057                        "Failed to start PTY session".to_string(),
1058                        timeout_category_label.clone(),
1059                        base_timeout_ms,
1060                        adaptive_timeout_ms,
1061                        None,
1062                        false,
1063                    );
1064
1065                    return Ok(error.to_json_value());
1066                }
1067            }
1068        } else {
1069            None
1070        };
1071
1072        // Execute the appropriate tool based on its type
1073        // The _pty_guard will automatically decrement the session count when dropped
1074        let execution_started_at = Instant::now();
1075        // Effective timeout: explicit waits self-bound inside the command
1076        // session executor (no outer deadline); long-running runs get the
1077        // generous long-running ceiling. See `effective_timeout_for_call`.
1078        let effective_timeout = self.effective_timeout_for_call(timeout_category, &args);
1079        let effective_timeout_ms = effective_timeout.map(|d| d.as_millis() as u64);
1080
1081        let fail_open = self.optimization_config.tool_registry.middleware_fail_open;
1082        let middleware_req = ToolCallRequest {
1083            id: requested_name.clone(),
1084            tool_name: tool_name.as_str().into(),
1085            args: args.clone(),
1086            metadata: None,
1087        };
1088        if let Err(err) = self.middleware.before_execute_opt(&middleware_req, fail_open).await {
1089            if !fail_open {
1090                let error_msg = format!("Middleware denied execution: {err}");
1091                record_failure(
1092                    tool_name_owned.clone(),
1093                    is_mcp_tool,
1094                    mcp_provider.clone(),
1095                    args_for_recording.clone(),
1096                    error_msg.clone(),
1097                    timeout_category_label.clone(),
1098                    base_timeout_ms,
1099                    adaptive_timeout_ms,
1100                    None,
1101                    false,
1102                );
1103                return Err(anyhow!(error_msg).context("tool denied by middleware"));
1104            }
1105        }
1106
1107        // Preserve registered approval/sandbox wrappers. The nonce changes any
1108        // wrapper cache key and only disables file caching; it grants no authority.
1109        if fresh_patch_read
1110            && !tool_intent::is_command_run_tool_call(&tool_name, &args)
1111            && let Some(object) = args.as_object_mut()
1112        {
1113            object.insert(
1114                crate::tools::file_ops::PATCH_READ_CACHE_NONCE.to_string(),
1115                json!(uuid::Uuid::new_v4().to_string()),
1116            );
1117        }
1118        let exec_future = async {
1119            if is_mcp_tool {
1120                let mcp_name = mcp_tool_name
1121                    .as_deref()
1122                    .context("MCP tool routing inconsistency: resolved MCP tool name missing")?;
1123                self.execute_mcp_tool(mcp_name, args).await
1124            } else if exec_settlement_mode.settle_noninteractive()
1125                && matches!(tool_name.as_str(), tools::UNIFIED_EXEC | tools::EXEC_COMMAND | tools::EXEC_PTY_CMD)
1126            {
1127                let exec_args = match tool_name.as_str() {
1128                    tools::EXEC_COMMAND => super::executors::normalize_command_session_run_alias_args(&args, false)?,
1129                    tools::EXEC_PTY_CMD => super::executors::normalize_command_session_run_alias_args(&args, true)?,
1130                    _ => args.clone(),
1131                };
1132                if self.optimization_config.memory_pool.enabled {
1133                    let _execution_guard = self.memory_pool.get_value();
1134                    let _string_guard = self.memory_pool.get_string();
1135                    let _vec_guard = self.memory_pool.get_vec();
1136                    self.execute_command_session_internal(exec_args, exec_settlement_mode).await
1137                } else {
1138                    self.execute_command_session_internal(exec_args, exec_settlement_mode).await
1139                }
1140            } else if exec_settlement_mode.settle_noninteractive() && tool_name == tools::WRITE_STDIN {
1141                self.execute_write_stdin(args, exec_settlement_mode).await
1142            } else if let Some(registration) = self.inventory.registration_for(&tool_name) {
1143                self.execute_registered_handler(&tool_name, &registration, args, cached_tool.as_ref())
1144                    .await
1145            } else {
1146                // This should theoretically never happen since we checked tool_exists above
1147                // Generate helpful error message with available tools
1148                let (tool_names, similar_tools) = self.public_tool_catalog_for_error(&requested_name).await;
1149                let available_tool_list = tool_names.join(", ");
1150
1151                let suggestion = if !similar_tools.is_empty() {
1152                    format!(" Did you mean: {}?", similar_tools.join(", "))
1153                } else {
1154                    String::new()
1155                };
1156
1157                let error_msg = format!(
1158                    "Tool '{display_name}' not found in registry. Available tools: {available_tool_list}.{suggestion}"
1159                );
1160
1161                let error =
1162                    ToolExecutionError::new(tool_name_owned.clone(), ToolErrorType::ToolNotFound, error_msg.clone());
1163
1164                record_failure(
1165                    tool_name_owned.clone(),
1166                    is_mcp_tool,
1167                    mcp_provider.clone(),
1168                    args_for_recording.clone(),
1169                    error_msg,
1170                    timeout_category_label.clone(),
1171                    base_timeout_ms,
1172                    adaptive_timeout_ms,
1173                    effective_timeout_ms,
1174                    false,
1175                );
1176
1177                Ok(error.to_json_value())
1178            }
1179        };
1180
1181        let result = if let Some(limit) = effective_timeout {
1182            trace!(
1183                tool = %tool_name_owned,
1184                category = %timeout_category.label(),
1185                timeout_ms = %limit.as_millis(),
1186                "Executing tool with effective timeout"
1187            );
1188            match tokio::time::timeout(limit, exec_future).await {
1189                Ok(res) => res,
1190                Err(_) => {
1191                    let timeout_ms = limit.as_millis() as u64;
1192                    let tripped = self.record_tool_failure(timeout_category);
1193                    if tripped {
1194                        warn!(
1195                            tool = %tool_name_owned,
1196                            category = %timeout_category.label(),
1197                            "Tool circuit breaker tripped after consecutive timeout failures"
1198                        );
1199                    }
1200                    let retry_after = self.should_circuit_break(timeout_category);
1201
1202                    let mut timeout_error = ToolExecutionError::new(
1203                        tool_name_owned.clone(),
1204                        ToolErrorType::Timeout,
1205                        format!(
1206                            "Operation '{}' exceeded the {} timeout ceiling ({}s)",
1207                            tool_name_owned,
1208                            timeout_category.label(),
1209                            limit.as_secs()
1210                        ),
1211                    )
1212                    .with_tool_call_context(&tool_name_owned, &args_for_recording)
1213                    .with_surface("tool_registry")
1214                    .with_debug_metadata("timeout_category", timeout_category.label())
1215                    .with_debug_metadata("timeout_ms", timeout_ms.to_string());
1216
1217                    if tool_name_owned == tools::UNIFIED_EXEC {
1218                        timeout_error.recovery_suggestions = vec![
1219                            Cow::Borrowed("Use write_stdin with empty chars to poll command progress"),
1220                            Cow::Borrowed("Use exec_command with a fresh command if the original session is stale"),
1221                            Cow::Borrowed("Ask for manual cleanup if a stale session is still active"),
1222                        ];
1223                    }
1224
1225                    if let Some(delay) = retry_after {
1226                        timeout_error.retry_after_ms = Some(delay.as_millis().min(u128::from(u64::MAX)) as u64);
1227                    }
1228
1229                    let mut timeout_payload = timeout_error.to_json_value();
1230                    Self::annotate_timeout_error_payload(
1231                        &mut timeout_payload,
1232                        timeout_category.label(),
1233                        timeout_ms,
1234                        tripped,
1235                    );
1236
1237                    if let Some(breaker) = shared_circuit_breaker.as_ref() {
1238                        breaker.record_failure_category_for_tool(&tool_name_owned, ErrorCategory::Timeout);
1239                    }
1240                    if is_mcp_tool {
1241                        self.mcp_circuit_breaker.record_failure_category(ErrorCategory::Timeout);
1242                    }
1243                    record_failure(
1244                        tool_name_owned,
1245                        is_mcp_tool,
1246                        mcp_provider,
1247                        args_for_recording,
1248                        timeout_error.user_message(),
1249                        timeout_category_label.clone(),
1250                        base_timeout_ms,
1251                        adaptive_timeout_ms,
1252                        Some(timeout_ms),
1253                        tripped,
1254                    );
1255                    return Ok(timeout_payload);
1256                }
1257            }
1258        } else {
1259            exec_future.await
1260        };
1261
1262        // PTY session will be automatically cleaned up when _pty_guard is dropped
1263
1264        // Handle the execution result and record it
1265
1266        match result {
1267            Ok(value) => {
1268                if let Some(breaker) = shared_circuit_breaker.as_ref() {
1269                    breaker.record_success_for_tool(&tool_name_owned);
1270                }
1271                if is_mcp_tool {
1272                    self.mcp_circuit_breaker.record_success();
1273                }
1274                self.reset_tool_failure(timeout_category);
1275                let should_decay = {
1276                    let mut state = self.resiliency.lock();
1277                    let success_streak = state.adaptive_tuning.success_streak;
1278                    if let Some(counter) = state.success_trackers.get_mut(&timeout_category) {
1279                        *counter = counter.saturating_add(1);
1280                        let counter_val = *counter;
1281                        if counter_val >= success_streak {
1282                            *counter = 0;
1283                            true
1284                        } else {
1285                            false
1286                        }
1287                    } else {
1288                        false
1289                    }
1290                };
1291                if should_decay {
1292                    self.decay_adaptive_timeout(timeout_category);
1293                }
1294                self.record_tool_latency(timeout_category, execution_started_at.elapsed());
1295                let super::execution_results::ExecutionOutput { normalized_value, structured_error } = self
1296                    .prepare_execution_output(
1297                        &tool_name_owned,
1298                        &args_for_recording,
1299                        value,
1300                        is_mcp_tool,
1301                        max_output_tokens,
1302                    )
1303                    .await;
1304
1305                if !readonly_classification {
1306                    self.invalidate_mutated_reads(&tool_name_owned, &args_for_recording);
1307                }
1308
1309                if let Some(error_msg) = structured_error {
1310                    self.execution_history.add_record(ToolExecutionRecord::failure(
1311                        tool_name_owned,
1312                        requested_name,
1313                        is_mcp_tool,
1314                        mcp_provider,
1315                        args_for_recording,
1316                        error_msg,
1317                        context_snapshot.clone(),
1318                        timeout_category_label.clone(),
1319                        base_timeout_ms,
1320                        adaptive_timeout_ms,
1321                        effective_timeout_ms,
1322                        false,
1323                    ));
1324                } else {
1325                    self.execution_history.add_record(ToolExecutionRecord::success(
1326                        tool_name_owned,
1327                        requested_name,
1328                        is_mcp_tool,
1329                        mcp_provider,
1330                        args_for_recording,
1331                        normalized_value.clone(),
1332                        context_snapshot.clone(),
1333                        timeout_category_label.clone(),
1334                        base_timeout_ms,
1335                        adaptive_timeout_ms,
1336                        effective_timeout_ms,
1337                        false,
1338                    ));
1339                }
1340
1341                let _ = self
1342                    .middleware
1343                    .after_execute(
1344                        &middleware_req,
1345                        &ToolCallResponse {
1346                            id: middleware_req.id.clone(),
1347                            success: true,
1348                            result: Some(normalized_value.clone()),
1349                            error: None,
1350                            duration_ms: Some(execution_started_at.elapsed().as_millis() as u64),
1351                            cache_hit: None,
1352                        },
1353                    )
1354                    .await;
1355
1356                Ok(normalized_value)
1357            }
1358            Err(err) => {
1359                // Reentrancy violations must surface as hard errors rather
1360                // than wrapped Ok(error_object) so nested callers see the
1361                // failure and can react appropriately.
1362                if err.to_string().contains("tool reentrancy blocked") {
1363                    return Err(err);
1364                }
1365
1366                let error = ToolExecutionError::from_anyhow(
1367                    tool_name_owned.clone(),
1368                    &err,
1369                    0,
1370                    false,
1371                    false,
1372                    Some("tool_registry"),
1373                )
1374                .with_tool_call_context(&tool_name_owned, &args_for_recording);
1375                self.grant_patch_recovery_read(&error).await;
1376                let error_category = error.category;
1377                if error.circuit_breaker_impact
1378                    && let Some(breaker) = shared_circuit_breaker.as_ref()
1379                {
1380                    breaker.record_failure_category_for_tool(&tool_name_owned, error_category);
1381                }
1382                if error.circuit_breaker_impact && is_mcp_tool {
1383                    self.mcp_circuit_breaker.record_failure_category(error_category);
1384                }
1385
1386                let tripped = if error.circuit_breaker_impact {
1387                    let tripped = self.record_tool_failure(timeout_category);
1388                    if tripped {
1389                        warn!(
1390                            tool = %tool_name_owned,
1391                            category = %timeout_category.label(),
1392                            "Tool circuit breaker tripped after consecutive failures"
1393                        );
1394                    }
1395                    tripped
1396                } else {
1397                    false
1398                };
1399
1400                let mut payload = error.to_json_value();
1401                Self::annotate_timeout_error_payload(
1402                    &mut payload,
1403                    timeout_category.label(),
1404                    effective_timeout_ms.unwrap_or(0),
1405                    tripped,
1406                );
1407
1408                record_failure(
1409                    tool_name_owned,
1410                    is_mcp_tool,
1411                    mcp_provider,
1412                    args_for_recording,
1413                    format!("Tool execution failed: {err}"),
1414                    timeout_category_label.clone(),
1415                    base_timeout_ms,
1416                    adaptive_timeout_ms,
1417                    effective_timeout_ms,
1418                    tripped,
1419                );
1420
1421                let _ = self
1422                    .middleware
1423                    .on_error(
1424                        &middleware_req,
1425                        &UnifiedToolError::new(
1426                            UnifiedErrorKind::from(vtcode_commons::classify_anyhow_error(&err)),
1427                            err.to_string(),
1428                        ),
1429                    )
1430                    .await;
1431
1432                Ok(payload)
1433            }
1434        }
1435    }
1436}