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