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        super::super::assembly::push_similar_tools(&mut similar_tools, &requested_candidates, &tool_names);
109
110        (tool_names, similar_tools)
111    }
112
113    pub fn preflight_validate_call(&self, name: &str, args: &Value) -> Result<super::super::ToolPreflightOutcome> {
114        execution_kernel::preflight_validate_call(self, name, args)
115    }
116
117    /// Preflight a tool call from the harness path, allowing dispatch to
118    /// internal (model-hidden) tool registrations such as read_file/write_file.
119    /// Direct model-originated entry should use `preflight_validate_call`.
120    pub fn preflight_validate_harness_call(
121        &self,
122        name: &str,
123        args: &Value,
124    ) -> Result<super::super::ToolPreflightOutcome> {
125        execution_kernel::preflight_validate_call_with_mode(self, name, args, execution_kernel::DispatchMode::Harness)
126    }
127
128    pub fn admit_public_tool_call(&self, name: &str, args: &Value) -> Result<PreparedToolCall> {
129        let preflight = self.preflight_validate_harness_call(name, args)?;
130        Ok(PreparedToolCall::new(
131            preflight.normalized_tool_name,
132            preflight.readonly_classification,
133            preflight.parallel_safe_after_preflight,
134            preflight.effective_args,
135        ))
136    }
137
138    pub async fn execute_tool(&self, name: &str, args: Value) -> Result<Value> {
139        self.execute_tool_ref(name, &args).await
140    }
141
142    /// Execute a model-originated tool call through the public routing assembly.
143    pub async fn execute_public_tool_ref(&self, name: &str, args: &Value) -> Result<Value> {
144        self.execute_public_tool_ref_internal(name, args, false).await
145    }
146
147    /// Reference-taking version of execute_tool to avoid cloning by callers
148    /// that already have access to an existing `Value`.
149    pub async fn execute_tool_ref(&self, name: &str, args: &Value) -> Result<Value> {
150        self.execute_tool_ref_internal(name, args, false, ExecSettlementMode::Manual)
151            .await
152    }
153
154    /// Reference-taking execution entrypoint for calls that were already preflight-validated.
155    ///
156    /// This avoids re-running argument/schema/path/command preflight in hot paths
157    /// where validation already happened in the runloop.
158    pub async fn execute_tool_ref_prevalidated(&self, name: &str, args: &Value) -> Result<Value> {
159        self.execute_tool_ref_internal(name, args, true, ExecSettlementMode::Manual)
160            .await
161    }
162
163    /// Prevalidated model-originated execution that still routes through the public assembly.
164    pub async fn execute_public_tool_ref_prevalidated(&self, name: &str, args: &Value) -> Result<Value> {
165        self.execute_public_tool_ref_prevalidated_with_mode(name, args, ExecSettlementMode::Manual)
166            .await
167    }
168
169    #[doc(hidden)]
170    pub async fn execute_public_tool_ref_prevalidated_with_mode(
171        &self,
172        name: &str,
173        args: &Value,
174        exec_settlement_mode: ExecSettlementMode,
175    ) -> Result<Value> {
176        self.execute_public_tool_ref_internal_with_mode(name, args, true, exec_settlement_mode)
177            .await
178    }
179
180    pub async fn execute_prepared_public_tool_ref_with_mode(
181        &self,
182        prepared: &PreparedToolCall,
183        exec_settlement_mode: ExecSettlementMode,
184    ) -> Result<Value> {
185        // Prepared calls come from the harness admission gate
186        // (`admit_public_tool_call`), which is the only producer of
187        // `PreparedToolCall`, so internal (model-hidden) dispatch is authorized.
188        self.execute_public_tool_ref_dispatch(
189            prepared.canonical_name.as_str(),
190            &prepared.effective_args,
191            prepared.already_preflighted,
192            execution_kernel::DispatchMode::Harness,
193            exec_settlement_mode,
194        )
195        .await
196    }
197
198    async fn execute_public_tool_ref_internal(&self, name: &str, args: &Value, prevalidated: bool) -> Result<Value> {
199        self.execute_public_tool_ref_dispatch(
200            name,
201            args,
202            prevalidated,
203            execution_kernel::DispatchMode::ModelPublic,
204            ExecSettlementMode::Manual,
205        )
206        .await
207    }
208
209    async fn execute_public_tool_ref_internal_with_mode(
210        &self,
211        name: &str,
212        args: &Value,
213        prevalidated: bool,
214        exec_settlement_mode: ExecSettlementMode,
215    ) -> Result<Value> {
216        self.execute_public_tool_ref_dispatch(
217            name,
218            args,
219            prevalidated,
220            execution_kernel::DispatchMode::ModelPublic,
221            exec_settlement_mode,
222        )
223        .await
224    }
225
226    /// Core public-routing execution entrypoint.
227    ///
228    /// `dispatch_mode` is the authority to fall back to internal (model-hidden)
229    /// tool registrations and is fully independent of `prevalidated` (a pure
230    /// performance flag that skips re-running preflight). Only callers that went
231    /// through the harness admission gate (`admit_public_tool_call`) pass
232    /// [`execution_kernel::DispatchMode::Harness`]; direct model-originated entry always passes
233    /// [`execution_kernel::DispatchMode::ModelPublic`], so a stray `prevalidated=true` can never by
234    /// itself widen the dispatchable surface.
235    pub(in crate::tools::registry) async fn execute_public_tool_ref_dispatch(
236        &self,
237        name: &str,
238        args: &Value,
239        prevalidated: bool,
240        dispatch_mode: execution_kernel::DispatchMode,
241        exec_settlement_mode: ExecSettlementMode,
242    ) -> Result<Value> {
243        let routed_name = execution_kernel::resolve_dispatch_target(self, name, dispatch_mode)
244            .map_err(|err| anyhow!(err.to_string()))?;
245        let effective_args = execution_kernel::remap_public_file_operation_alias_args(name, routed_name.as_str(), args)
246            .or_else(|| execution_kernel::remap_consolidated_action_alias_args(name, routed_name.as_str(), args));
247        self.execute_tool_ref_internal(
248            routed_name.as_str(),
249            effective_args.as_ref().unwrap_or(args),
250            prevalidated,
251            exec_settlement_mode,
252        )
253        .await
254    }
255}