Skip to main content

vtcode_core/tools/registry/cgp_facade/
mod.rs

1//! CGP integration facade for ToolRegistry.
2//!
3//! Provides `enable_cgp_pipeline()` which prefers tool-specific native CGP
4//! facades when available and otherwise wraps registered `TraitObject` tools
5//! through the CGP approval → sandbox → logging/cache/retry pipeline while
6//! preserving registration-sourced metadata.
7
8use std::borrow::Cow;
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use super::ToolRegistry;
13use super::registration::{ToolExecutorFn, ToolHandler, ToolRegistration};
14use crate::components::{wrap_native_tool_ci, wrap_native_tool_interactive, wrap_tool_ci, wrap_tool_interactive};
15use crate::tool_policy::ToolPolicy;
16use crate::tools::result::ToolResult as SplitToolResult;
17use crate::tools::traits::Tool;
18use anyhow::Result;
19use async_trait::async_trait;
20use serde_json::Value;
21
22fn registration_uses_live_task_tracker_metadata(registration: &ToolRegistration) -> bool {
23    registration.name() == crate::config::constants::tools::TASK_TRACKER
24}
25
26fn leak_pattern_str(value: impl Into<String>) -> &'static str {
27    Box::leak(value.into().into_boxed_str())
28}
29
30fn leak_patterns(patterns: &[String]) -> Option<&'static [&'static str]> {
31    if patterns.is_empty() {
32        return None;
33    }
34
35    let leaked_patterns = patterns
36        .iter()
37        .cloned()
38        .map(leak_pattern_str)
39        .collect::<Vec<_>>()
40        .into_boxed_slice();
41    Some(Box::leak(leaked_patterns))
42}
43
44#[derive(Clone)]
45struct RegistrationMetadataSnapshot {
46    name: Arc<str>,
47    description: Arc<str>,
48    parameter_schema: Option<Value>,
49    config_schema: Option<Value>,
50    state_schema: Option<Value>,
51    prompt_path: Option<String>,
52    default_permission: ToolPolicy,
53    allow_patterns: Option<&'static [&'static str]>,
54    deny_patterns: Option<&'static [&'static str]>,
55}
56
57impl RegistrationMetadataSnapshot {
58    fn from_registration(registration: &ToolRegistration) -> Self {
59        Self {
60            name: Arc::<str>::from(registration.name()),
61            description: Arc::<str>::from(registration.metadata().description().unwrap_or_default()),
62            parameter_schema: registration.parameter_schema().cloned(),
63            config_schema: registration.config_schema().cloned(),
64            state_schema: registration.state_schema().cloned(),
65            prompt_path: registration.prompt_path().map(str::to_string),
66            default_permission: registration.default_permission().unwrap_or(ToolPolicy::Prompt),
67            allow_patterns: leak_patterns(registration.metadata().allowlist()),
68            deny_patterns: leak_patterns(registration.metadata().denylist()),
69        }
70    }
71
72    fn from_registration_with_tool<T>(registration: &ToolRegistration, tool: &T) -> Self
73    where
74        T: Tool + ?Sized,
75    {
76        let use_live_task_tracker_metadata = registration_uses_live_task_tracker_metadata(registration);
77        Self {
78            name: Arc::<str>::from(registration.name()),
79            description: if use_live_task_tracker_metadata {
80                Arc::<str>::from(tool.description())
81            } else {
82                registration
83                    .metadata()
84                    .description()
85                    .map(Arc::<str>::from)
86                    .unwrap_or_else(|| Arc::<str>::from(tool.description()))
87            },
88            parameter_schema: if use_live_task_tracker_metadata {
89                tool.parameter_schema()
90            } else {
91                registration.parameter_schema().cloned().or_else(|| tool.parameter_schema())
92            },
93            config_schema: registration.config_schema().cloned().or_else(|| tool.config_schema()),
94            state_schema: registration.state_schema().cloned().or_else(|| tool.state_schema()),
95            prompt_path: registration
96                .prompt_path()
97                .map(str::to_string)
98                .or_else(|| tool.prompt_path().map(Cow::into_owned)),
99            default_permission: registration.default_permission().unwrap_or_else(|| tool.default_permission()),
100            allow_patterns: leak_patterns(registration.metadata().allowlist()).or_else(|| tool.allow_patterns()),
101            deny_patterns: leak_patterns(registration.metadata().denylist()).or_else(|| tool.deny_patterns()),
102        }
103    }
104
105    /// Shared metadata accessors for the three wrapper tools below.
106    ///
107    /// These bodies are intentionally identical across `RegistryFnTool`,
108    /// `RegistrationBackedTool`, and `RegistrationBackedDynTool`: keep them
109    /// here so a future per-wrapper edit cannot silently diverge one copy.
110    /// `description()` / `parameter_schema()` stay per-impl: they carry the
111    /// task_tracker live-metadata branch, which `RegistryFnTool` cannot
112    /// share (it holds no inner tool to delegate to).
113    fn name(&self) -> &str {
114        self.name.as_ref()
115    }
116
117    fn config_schema(&self) -> Option<Value> {
118        self.config_schema.clone()
119    }
120
121    fn state_schema(&self) -> Option<Value> {
122        self.state_schema.clone()
123    }
124
125    fn prompt_path(&self) -> Option<Cow<'static, str>> {
126        self.prompt_path.clone().map(Cow::Owned)
127    }
128
129    fn default_permission(&self) -> ToolPolicy {
130        self.default_permission.clone()
131    }
132
133    fn allow_patterns(&self) -> Option<&'static [&'static str]> {
134        self.allow_patterns
135    }
136
137    fn deny_patterns(&self) -> Option<&'static [&'static str]> {
138        self.deny_patterns
139    }
140}
141
142struct RegistryFnTool {
143    registry: ToolRegistry,
144    executor: ToolExecutorFn,
145    metadata: RegistrationMetadataSnapshot,
146}
147
148impl RegistryFnTool {
149    fn from_registration(registry: ToolRegistry, registration: &ToolRegistration) -> Option<Self> {
150        let executor = match registration.handler() {
151            ToolHandler::RegistryFn(executor) => executor,
152            ToolHandler::TraitObject(_) => return None,
153        };
154
155        Some(Self {
156            registry,
157            executor,
158            metadata: RegistrationMetadataSnapshot::from_registration(registration),
159        })
160    }
161}
162
163#[async_trait]
164impl Tool for RegistryFnTool {
165    async fn execute(&self, args: Value) -> Result<Value> {
166        (self.executor)(&self.registry, args).await
167    }
168
169    fn name(&self) -> &str {
170        self.metadata.name()
171    }
172
173    fn description(&self) -> &str {
174        self.metadata.description.as_ref()
175    }
176
177    fn parameter_schema(&self) -> Option<Value> {
178        self.metadata.parameter_schema.clone()
179    }
180
181    fn config_schema(&self) -> Option<Value> {
182        self.metadata.config_schema()
183    }
184
185    fn state_schema(&self) -> Option<Value> {
186        self.metadata.state_schema()
187    }
188
189    fn prompt_path(&self) -> Option<Cow<'static, str>> {
190        self.metadata.prompt_path()
191    }
192
193    fn default_permission(&self) -> ToolPolicy {
194        self.metadata.default_permission()
195    }
196
197    fn allow_patterns(&self) -> Option<&'static [&'static str]> {
198        self.metadata.allow_patterns()
199    }
200
201    fn deny_patterns(&self) -> Option<&'static [&'static str]> {
202        self.metadata.deny_patterns()
203    }
204}
205
206struct RegistrationBackedTool<T> {
207    inner: T,
208    metadata: RegistrationMetadataSnapshot,
209}
210
211impl<T> RegistrationBackedTool<T>
212where
213    T: Tool + Send + Sync,
214{
215    fn from_registration(inner: T, registration: &ToolRegistration) -> Self {
216        let metadata = RegistrationMetadataSnapshot::from_registration_with_tool(registration, &inner);
217        Self { inner, metadata }
218    }
219}
220
221#[async_trait]
222impl<T> Tool for RegistrationBackedTool<T>
223where
224    T: Tool + Send + Sync,
225{
226    async fn execute(&self, args: Value) -> Result<Value> {
227        self.inner.execute(args).await
228    }
229
230    async fn execute_dual(&self, args: Value) -> Result<SplitToolResult> {
231        let mut result = self.inner.execute_dual(args).await?;
232        result.tool_name = self.name().to_string();
233        Ok(result)
234    }
235
236    fn name(&self) -> &str {
237        self.metadata.name()
238    }
239
240    fn description(&self) -> &str {
241        if self.metadata.name.as_ref() == crate::config::constants::tools::TASK_TRACKER {
242            self.inner.description()
243        } else {
244            self.metadata.description.as_ref()
245        }
246    }
247
248    fn validate_args(&self, args: &Value) -> Result<()> {
249        self.inner.validate_args(args)
250    }
251
252    fn parameter_schema(&self) -> Option<Value> {
253        if self.metadata.name.as_ref() == crate::config::constants::tools::TASK_TRACKER {
254            self.inner.parameter_schema()
255        } else {
256            self.metadata.parameter_schema.clone()
257        }
258    }
259
260    fn config_schema(&self) -> Option<Value> {
261        self.metadata.config_schema()
262    }
263
264    fn state_schema(&self) -> Option<Value> {
265        self.metadata.state_schema()
266    }
267
268    fn prompt_path(&self) -> Option<Cow<'static, str>> {
269        self.metadata.prompt_path()
270    }
271
272    fn default_permission(&self) -> ToolPolicy {
273        self.metadata.default_permission()
274    }
275
276    fn allow_patterns(&self) -> Option<&'static [&'static str]> {
277        self.metadata.allow_patterns()
278    }
279
280    fn deny_patterns(&self) -> Option<&'static [&'static str]> {
281        self.metadata.deny_patterns()
282    }
283
284    fn is_mutating(&self) -> bool {
285        self.inner.is_mutating()
286    }
287
288    fn is_parallel_safe(&self) -> bool {
289        self.inner.is_parallel_safe()
290    }
291
292    fn kind(&self) -> &'static str {
293        self.inner.kind()
294    }
295
296    fn resource_hints(&self, args: &Value) -> Vec<String> {
297        self.inner.resource_hints(args)
298    }
299
300    fn execution_cost(&self) -> u8 {
301        self.inner.execution_cost()
302    }
303}
304
305struct RegistrationBackedDynTool {
306    inner: Arc<dyn Tool>,
307    metadata: RegistrationMetadataSnapshot,
308}
309
310impl RegistrationBackedDynTool {
311    fn from_registration(inner: Arc<dyn Tool>, registration: &ToolRegistration) -> Self {
312        let metadata = RegistrationMetadataSnapshot::from_registration_with_tool(registration, inner.as_ref());
313        Self { inner, metadata }
314    }
315}
316
317#[async_trait]
318impl Tool for RegistrationBackedDynTool {
319    async fn execute(&self, args: Value) -> Result<Value> {
320        self.inner.execute(args).await
321    }
322
323    async fn execute_dual(&self, args: Value) -> Result<SplitToolResult> {
324        let mut result = self.inner.execute_dual(args).await?;
325        result.tool_name = self.name().to_string();
326        Ok(result)
327    }
328
329    fn name(&self) -> &str {
330        self.metadata.name()
331    }
332
333    fn description(&self) -> &str {
334        if self.metadata.name.as_ref() == crate::config::constants::tools::TASK_TRACKER {
335            self.inner.description()
336        } else {
337            self.metadata.description.as_ref()
338        }
339    }
340
341    fn validate_args(&self, args: &Value) -> Result<()> {
342        self.inner.validate_args(args)
343    }
344
345    fn parameter_schema(&self) -> Option<Value> {
346        if self.metadata.name.as_ref() == crate::config::constants::tools::TASK_TRACKER {
347            self.inner.parameter_schema()
348        } else {
349            self.metadata.parameter_schema.clone()
350        }
351    }
352
353    fn config_schema(&self) -> Option<Value> {
354        self.metadata.config_schema()
355    }
356
357    fn state_schema(&self) -> Option<Value> {
358        self.metadata.state_schema()
359    }
360
361    fn prompt_path(&self) -> Option<Cow<'static, str>> {
362        self.metadata.prompt_path()
363    }
364
365    fn default_permission(&self) -> ToolPolicy {
366        self.metadata.default_permission()
367    }
368
369    fn allow_patterns(&self) -> Option<&'static [&'static str]> {
370        self.metadata.allow_patterns()
371    }
372
373    fn deny_patterns(&self) -> Option<&'static [&'static str]> {
374        self.metadata.deny_patterns()
375    }
376
377    fn is_mutating(&self) -> bool {
378        self.inner.is_mutating()
379    }
380
381    fn is_parallel_safe(&self) -> bool {
382        self.inner.is_parallel_safe()
383    }
384
385    fn kind(&self) -> &'static str {
386        self.inner.kind()
387    }
388
389    fn resource_hints(&self, args: &Value) -> Vec<String> {
390        self.inner.resource_hints(args)
391    }
392
393    fn execution_cost(&self) -> u8 {
394        self.inner.execution_cost()
395    }
396}
397
398/// Fallback bridge for registrations that already carry shared tool ownership.
399///
400/// Prefer `wrap_registered_native_tool()` when the caller still owns the
401/// concrete tool instance and does not need to preserve an existing
402/// `Arc<dyn Tool>` handle.
403fn wrap_registered_trait_object_tool(
404    registration: &ToolRegistration,
405    tool: Arc<dyn Tool>,
406    workspace_root: PathBuf,
407    mode: CgpRuntimeMode,
408) -> Arc<dyn Tool> {
409    let tool: Arc<dyn Tool> = Arc::new(RegistrationBackedDynTool::from_registration(tool, registration));
410    match mode {
411        CgpRuntimeMode::Interactive => Arc::new(wrap_tool_interactive(tool, workspace_root)),
412        CgpRuntimeMode::Ci => Arc::new(wrap_tool_ci(tool, workspace_root)),
413    }
414}
415
416pub fn wrap_registered_native_tool<T>(
417    registration: &ToolRegistration,
418    tool: T,
419    workspace_root: PathBuf,
420    mode: CgpRuntimeMode,
421) -> Arc<dyn Tool>
422where
423    T: Tool + Send + Sync + 'static,
424{
425    let tool = RegistrationBackedTool::from_registration(tool, registration);
426    match mode {
427        CgpRuntimeMode::Interactive => Arc::new(wrap_native_tool_interactive(tool, workspace_root)),
428        CgpRuntimeMode::Ci => Arc::new(wrap_native_tool_ci(tool, workspace_root)),
429    }
430}
431
432pub fn native_cgp_tool_factory<T, F>(build_tool: F) -> super::registration::NativeCgpToolFactory
433where
434    T: Tool + Send + Sync + 'static,
435    F: Fn() -> T + Send + Sync + 'static,
436{
437    Arc::new(move |registration, workspace_root, mode| {
438        wrap_registered_native_tool(registration, build_tool(), workspace_root, mode)
439    })
440}
441
442/// Runtime mode for CGP pipeline selection.
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444pub enum CgpRuntimeMode {
445    /// Interactive TUI sessions: prompt approval + workspace sandbox + tracing.
446    Interactive,
447    /// CI/automation: auto-approval + strict sandbox + no middleware.
448    Ci,
449}
450
451impl ToolRegistry {
452    pub(crate) fn current_cgp_mode(&self) -> Option<CgpRuntimeMode> {
453        *self.cgp_runtime_mode.read().unwrap_or_else(|e| e.into_inner())
454    }
455
456    fn set_cgp_runtime_mode(&self, mode: CgpRuntimeMode) {
457        if let Ok(mut current_mode) = self.cgp_runtime_mode.write() {
458            *current_mode = Some(mode);
459        }
460    }
461
462    pub(crate) fn cgp_handler_for_registration(
463        &self,
464        registration: &ToolRegistration,
465        mode: CgpRuntimeMode,
466    ) -> Option<ToolHandler> {
467        let workspace = self.workspace_root_owned();
468        if let Some(factory) = registration.native_cgp_factory() {
469            return Some(ToolHandler::TraitObject(factory(registration, workspace, mode)));
470        }
471
472        match registration.handler() {
473            ToolHandler::TraitObject(tool) => {
474                Some(ToolHandler::TraitObject(wrap_registered_trait_object_tool(registration, tool, workspace, mode)))
475            }
476            ToolHandler::RegistryFn(_) => {
477                let tool = RegistryFnTool::from_registration(self.clone(), registration)?;
478                Some(ToolHandler::TraitObject(match mode {
479                    CgpRuntimeMode::Interactive => Arc::new(wrap_native_tool_interactive(tool, workspace)),
480                    CgpRuntimeMode::Ci => Arc::new(wrap_native_tool_ci(tool, workspace)),
481                }))
482            }
483        }
484    }
485
486    /// Enable the CGP pipeline for all registered tools.
487    ///
488    /// This replaces each eligible tool's handler with a CGP `ToolFacade`
489    /// determined by the runtime mode. Registrations that provide a native CGP
490    /// factory use that directly; `TraitObject` handlers are wrapped with
491    /// registration-backed metadata before entering the passthrough bridge, and
492    /// `RegistryFn` handlers are projected through a concrete `RegistryFnTool`.
493    pub async fn enable_cgp_pipeline(&self, mode: CgpRuntimeMode) {
494        self.set_cgp_runtime_mode(mode);
495        let snapshot = self.inventory.registrations_snapshot();
496        let mut wrapped_count = 0u32;
497
498        for reg in &snapshot {
499            if reg.is_cgp_wrapped() {
500                continue;
501            }
502
503            let Some(handler) = self.cgp_handler_for_registration(reg, mode) else {
504                continue;
505            };
506
507            if let Err(err) = self.inventory.replace_tool_handler(reg.name(), handler) {
508                tracing::warn!(
509                    tool = %reg.name(),
510                    %err,
511                    "Failed to wrap tool with CGP pipeline"
512                );
513            } else {
514                wrapped_count += 1;
515            }
516        }
517
518        if wrapped_count > 0 {
519            self.rebuild_tool_assembly().await;
520            self.tool_catalog_state.note_explicit_refresh("cgp_pipeline_enable");
521            self.invalidate_hot_cache();
522            tracing::info!(
523                count = wrapped_count,
524                mode = ?mode,
525                "CGP pipeline enabled for registered tools"
526            );
527        }
528    }
529
530    /// Wrap a single tool through the CGP pipeline and register it.
531    ///
532    /// This is the preferred path for new tool registrations that should
533    /// participate in the CGP approval/sandbox/logging/cache/retry pipeline.
534    pub async fn register_cgp_tool(
535        &self,
536        tool: Arc<dyn Tool>,
537        capability: crate::config::types::CapabilityLevel,
538        mode: CgpRuntimeMode,
539    ) -> Result<()> {
540        let workspace = self.workspace_root_owned();
541        let tool_name = Arc::<str>::from(tool.name());
542        let registration = match mode {
543            CgpRuntimeMode::Interactive => {
544                ToolRegistration::from_cgp_tool(tool_name, capability, wrap_tool_interactive(tool, workspace))
545            }
546            CgpRuntimeMode::Ci => ToolRegistration::from_cgp_tool(tool_name, capability, wrap_tool_ci(tool, workspace)),
547        };
548        self.register_tool(registration).await
549    }
550
551    /// Invalidate the hot tool cache after CGP wrapping.
552    fn invalidate_hot_cache(&self) {
553        self.hot_tool_cache.write().clear();
554        *self.cached_available_tools.write() = None;
555    }
556}
557
558#[cfg(test)]
559mod tests;