Skip to main content

vtcode_core/tools/registry/execution_facade/
dispatch.rs

1use super::*;
2
3impl ToolRegistry {
4    pub(super) fn annotate_timeout_error_payload(
5        payload: &mut Value,
6        timeout_category: &str,
7        timeout_ms: u64,
8        circuit_breaker: bool,
9    ) {
10        if let Some(obj) = payload.get_mut("error").and_then(|value| value.as_object_mut()) {
11            obj.insert("timeout_category".into(), Value::String(timeout_category.to_string()));
12            obj.insert("timeout_ms".into(), Value::from(timeout_ms));
13            obj.insert("circuit_breaker".into(), Value::Bool(circuit_breaker));
14        }
15    }
16
17    pub fn safety_gateway(&self) -> std::sync::Arc<crate::tools::safety_gateway::SafetyGateway> {
18        std::sync::Arc::clone(&self.safety_gateway)
19    }
20
21    /// Inline-delegating wrapper that returns the inner future directly to
22    /// avoid an extra coroutine state machine (audit section 16).
23    pub fn execute_public_tool_request(
24        &self,
25        request: ToolExecutionRequest,
26    ) -> impl Future<Output = ToolExecutionOutcome> + '_ {
27        self.execute_tool_request_internal(request, None)
28    }
29
30    /// Execute with the caller's remaining wall-clock budget. Retry waits must
31    /// fit this deadline; the caller still owns cancellation and timeout delivery.
32    pub fn execute_public_tool_request_with_deadline(
33        &self,
34        request: ToolExecutionRequest,
35        deadline: Instant,
36    ) -> impl Future<Output = ToolExecutionOutcome> + '_ {
37        self.execute_tool_request_internal(request, Some(deadline))
38    }
39
40    pub async fn execute_prepared_public_tool_request(
41        &self,
42        prepared: &PreparedToolCall,
43        policy: ExecutionPolicySnapshot,
44    ) -> ToolExecutionOutcome {
45        self.execute_prepared_public_tool_request_until(prepared, policy, None).await
46    }
47
48    /// Keep the caller's outer deadline available to retry admission as well as
49    /// timeout enforcement. Prepared calls still require fresh safety admission.
50    pub(crate) async fn execute_prepared_public_tool_request_until(
51        &self,
52        prepared: &PreparedToolCall,
53        policy: ExecutionPolicySnapshot,
54        deadline: Option<Instant>,
55    ) -> ToolExecutionOutcome {
56        let request = ToolExecutionRequest::new(prepared.canonical_name.clone(), prepared.effective_args.clone())
57            .with_policy(
58                policy
59                    .with_prevalidated(prepared.already_preflighted)
60                    .with_safety_prevalidated(false),
61            );
62        self.execute_tool_request_internal(request, deadline).await
63    }
64
65    pub(super) async fn should_skip_loop_detection_for_exec_continuation(&self, tool_name: &str, args: &Value) -> bool {
66        if tool_name == tools::WRITE_STDIN {
67            return matches!(
68                crate::tools::command_args::write_stdin_dispatch(args),
69                Ok(crate::tools::command_args::WriteStdinDispatch::Poll
70                    | crate::tools::command_args::WriteStdinDispatch::Wait,)
71            );
72        }
73
74        if tool_name != tools::UNIFIED_EXEC {
75            return false;
76        }
77
78        if !tool_intent::command_session_action_in(args, &["poll", "continue"]) {
79            return false;
80        }
81        if tool_intent::command_session_action_is(args, "continue")
82            && crate::tools::command_args::interactive_input_text(args).is_some()
83        {
84            return false;
85        }
86
87        let Some(session_id) = crate::tools::command_args::session_id_text(args) else {
88            return false;
89        };
90
91        matches!(self.exec_session_completed(session_id).await, Ok(None))
92    }
93
94    pub(super) async fn public_tool_catalog_for_error(&self, requested_name: &str) -> (Vec<String>, Vec<String>) {
95        let mut tool_names = self.available_tools().await;
96        tool_names.sort_unstable();
97        tool_names.dedup();
98
99        let requested_candidates = public_tool_name_candidates(requested_name);
100        let mut similar_tools = Vec::new();
101
102        if let Ok(resolved) = self.resolve_public_tool_name_sync(requested_name)
103            && tool_names.iter().any(|tool| tool == &resolved)
104        {
105            similar_tools.push(resolved);
106        }
107
108        for tool in &tool_names {
109            if similar_tools.len() >= 3 {
110                break;
111            }
112
113            if similar_tools.iter().any(|candidate| candidate == tool) {
114                continue;
115            }
116
117            if requested_candidates.iter().any(|candidate| fuzzy_match(candidate, tool)) {
118                similar_tools.push(tool.clone());
119            }
120        }
121
122        (tool_names, similar_tools)
123    }
124
125    pub fn preflight_validate_call(&self, name: &str, args: &Value) -> Result<super::super::ToolPreflightOutcome> {
126        execution_kernel::preflight_validate_call(self, name, args)
127    }
128
129    /// Preflight a tool call from the harness path, allowing dispatch to
130    /// internal (model-hidden) tool registrations such as read_file/write_file.
131    /// Direct model-originated entry should use `preflight_validate_call`.
132    pub fn preflight_validate_harness_call(
133        &self,
134        name: &str,
135        args: &Value,
136    ) -> Result<super::super::ToolPreflightOutcome> {
137        execution_kernel::preflight_validate_call_with_mode(self, name, args, execution_kernel::DispatchMode::Harness)
138    }
139
140    pub fn admit_public_tool_call(&self, name: &str, args: &Value) -> Result<PreparedToolCall> {
141        let preflight = self.preflight_validate_harness_call(name, args)?;
142        Ok(PreparedToolCall::new(
143            preflight.normalized_tool_name,
144            preflight.readonly_classification,
145            preflight.parallel_safe_after_preflight,
146            preflight.effective_args,
147        ))
148    }
149
150    pub async fn execute_tool(&self, name: &str, args: Value) -> Result<Value> {
151        self.execute_tool_ref(name, &args).await
152    }
153
154    /// Execute a model-originated tool call through the public routing assembly.
155    pub async fn execute_public_tool_ref(&self, name: &str, args: &Value) -> Result<Value> {
156        self.execute_public_tool_ref_internal(name, args, false).await
157    }
158
159    /// Reference-taking version of execute_tool to avoid cloning by callers
160    /// that already have access to an existing `Value`.
161    pub async fn execute_tool_ref(&self, name: &str, args: &Value) -> Result<Value> {
162        self.execute_tool_ref_internal(name, args, false, ExecSettlementMode::Manual)
163            .await
164    }
165
166    /// Reference-taking execution entrypoint for calls that were already preflight-validated.
167    ///
168    /// This avoids re-running argument/schema/path/command preflight in hot paths
169    /// where validation already happened in the runloop.
170    pub async fn execute_tool_ref_prevalidated(&self, name: &str, args: &Value) -> Result<Value> {
171        self.execute_tool_ref_internal(name, args, true, ExecSettlementMode::Manual)
172            .await
173    }
174
175    /// Prevalidated model-originated execution that still routes through the public assembly.
176    pub async fn execute_public_tool_ref_prevalidated(&self, name: &str, args: &Value) -> Result<Value> {
177        self.execute_public_tool_ref_prevalidated_with_mode(name, args, ExecSettlementMode::Manual)
178            .await
179    }
180
181    #[doc(hidden)]
182    pub async fn execute_public_tool_ref_prevalidated_with_mode(
183        &self,
184        name: &str,
185        args: &Value,
186        exec_settlement_mode: ExecSettlementMode,
187    ) -> Result<Value> {
188        self.execute_public_tool_ref_internal_with_mode(name, args, true, exec_settlement_mode)
189            .await
190    }
191
192    pub async fn execute_prepared_public_tool_ref_with_mode(
193        &self,
194        prepared: &PreparedToolCall,
195        exec_settlement_mode: ExecSettlementMode,
196    ) -> Result<Value> {
197        // Prepared calls come from the harness admission gate
198        // (`admit_public_tool_call`), which is the only producer of
199        // `PreparedToolCall`, so internal (model-hidden) dispatch is authorized.
200        self.execute_public_tool_ref_dispatch(
201            prepared.canonical_name.as_str(),
202            &prepared.effective_args,
203            prepared.already_preflighted,
204            execution_kernel::DispatchMode::Harness,
205            exec_settlement_mode,
206        )
207        .await
208    }
209
210    async fn execute_public_tool_ref_internal(&self, name: &str, args: &Value, prevalidated: bool) -> Result<Value> {
211        self.execute_public_tool_ref_dispatch(
212            name,
213            args,
214            prevalidated,
215            execution_kernel::DispatchMode::ModelPublic,
216            ExecSettlementMode::Manual,
217        )
218        .await
219    }
220
221    async fn execute_public_tool_ref_internal_with_mode(
222        &self,
223        name: &str,
224        args: &Value,
225        prevalidated: bool,
226        exec_settlement_mode: ExecSettlementMode,
227    ) -> Result<Value> {
228        self.execute_public_tool_ref_dispatch(
229            name,
230            args,
231            prevalidated,
232            execution_kernel::DispatchMode::ModelPublic,
233            exec_settlement_mode,
234        )
235        .await
236    }
237
238    /// Core public-routing execution entrypoint.
239    ///
240    /// `dispatch_mode` is the authority to fall back to internal (model-hidden)
241    /// tool registrations and is fully independent of `prevalidated` (a pure
242    /// performance flag that skips re-running preflight). Only callers that went
243    /// through the harness admission gate (`admit_public_tool_call`) pass
244    /// [`execution_kernel::DispatchMode::Harness`]; direct model-originated entry always passes
245    /// [`execution_kernel::DispatchMode::ModelPublic`], so a stray `prevalidated=true` can never by
246    /// itself widen the dispatchable surface.
247    pub(in crate::tools::registry) async fn execute_public_tool_ref_dispatch(
248        &self,
249        name: &str,
250        args: &Value,
251        prevalidated: bool,
252        dispatch_mode: execution_kernel::DispatchMode,
253        exec_settlement_mode: ExecSettlementMode,
254    ) -> Result<Value> {
255        let routed_name = execution_kernel::resolve_dispatch_target(self, name, dispatch_mode)
256            .map_err(|err| anyhow!(err.to_string()))?;
257        let effective_args = execution_kernel::remap_public_file_operation_alias_args(name, routed_name.as_str(), args)
258            .or_else(|| execution_kernel::remap_consolidated_action_alias_args(name, routed_name.as_str(), args));
259        self.execute_tool_ref_internal(
260            routed_name.as_str(),
261            effective_args.as_ref().unwrap_or(args),
262            prevalidated,
263            exec_settlement_mode,
264        )
265        .await
266    }
267}