Skip to main content

vtcode_core/tools/
registry_adapters.rs

1//! Workspace-aware adapters that bridge `vtcode-core` with the
2//! `vtcode-commons` traits.
3//!
4//! These helpers allow downstream consumers to construct a `ToolRegistry`
5//! using their own path, telemetry, and error-reporting implementations
6//! without relying on VT Code's built-in `.vtcode` directory layout.
7
8use std::path::PathBuf;
9
10use vtcode_commons::PathScope;
11
12#[cfg(feature = "policies")]
13use crate::config::PtyConfig;
14#[cfg(feature = "policies")]
15use crate::tool_policy::ToolPolicyManager;
16#[cfg(feature = "policies")]
17use crate::tools::registry::ToolRegistry;
18#[cfg(feature = "policies")]
19use anyhow::{Context, Error, Result};
20#[cfg(feature = "policies")]
21use vtcode_commons::{ErrorFormatter, ErrorReporter, PathResolver, TelemetrySink, WorkspacePaths};
22
23/// Telemetry events emitted by the registry builder when it resolves policy
24/// storage or encounters recoverable failures.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum RegistryEvent {
27    /// Records the resolved policy configuration file and the scope it belongs to.
28    PolicyPathResolved { scope: PathScope, config_path: PathBuf },
29    /// Raised when telemetry recording itself fails so callers can surface the
30    /// fallback behaviour.
31    TelemetryFailure { message: String },
32    /// Emitted when the builder reports a validation or initialization error.
33    AdapterError { message: String },
34}
35
36/// Builder that wires a [`ToolRegistry`] using [`WorkspacePaths`], telemetry,
37/// and error-reporting hooks supplied by the caller.
38#[cfg(feature = "policies")]
39#[must_use = "build the registry before discarding the builder"]
40pub struct RegistryBuilder<'a, Paths, Telemetry, Reporter, Formatter>
41where
42    Paths: WorkspacePaths + ?Sized,
43    Telemetry: TelemetrySink<RegistryEvent> + ?Sized,
44    Reporter: ErrorReporter + ?Sized,
45    Formatter: ErrorFormatter + ?Sized,
46{
47    workspace_paths: &'a Paths,
48    telemetry: &'a Telemetry,
49    error_reporter: &'a Reporter,
50    error_formatter: &'a Formatter,
51    policy_manager: Option<ToolPolicyManager>,
52    policy_path: Option<PathBuf>,
53    pty_config: PtyConfig,
54}
55
56#[cfg(feature = "policies")]
57impl<'a, Paths, Telemetry, Reporter, Formatter> RegistryBuilder<'a, Paths, Telemetry, Reporter, Formatter>
58where
59    Paths: WorkspacePaths + ?Sized,
60    Telemetry: TelemetrySink<RegistryEvent> + ?Sized,
61    Reporter: ErrorReporter + ?Sized,
62    Formatter: ErrorFormatter + ?Sized,
63{
64    /// Creates a new [`RegistryBuilder`] that records events via the provided
65    /// telemetry sink and reports errors using the supplied reporter.
66    pub fn new(
67        workspace_paths: &'a Paths,
68        telemetry: &'a Telemetry,
69        error_reporter: &'a Reporter,
70        error_formatter: &'a Formatter,
71    ) -> Self {
72        Self {
73            workspace_paths,
74            telemetry,
75            error_reporter,
76            error_formatter,
77            policy_manager: None,
78            policy_path: None,
79            pty_config: PtyConfig::default(),
80        }
81    }
82
83    /// Overrides the PTY configuration applied to the registry.
84    pub fn with_pty_config(mut self, config: PtyConfig) -> Self {
85        self.pty_config = config;
86        self
87    }
88
89    /// Supplies a pre-built [`ToolPolicyManager`], bypassing policy path resolution.
90    pub fn with_policy_manager(mut self, manager: ToolPolicyManager) -> Self {
91        self.policy_manager = Some(manager);
92        self
93    }
94
95    /// Overrides the policy configuration path resolved from [`WorkspacePaths`].
96    pub fn with_policy_path<P>(mut self, path: P) -> Self
97    where
98        P: Into<PathBuf>,
99    {
100        self.policy_path = Some(path.into());
101        self
102    }
103
104    /// Builds a [`ToolRegistry`] using the configured hooks.
105    pub async fn build(mut self) -> Result<ToolRegistry> {
106        let workspace_root = self.workspace_paths.workspace_root().to_path_buf();
107        let policy_manager = match self.policy_manager.take() {
108            Some(manager) => manager,
109            None => {
110                let config_path = self
111                    .policy_path
112                    .clone()
113                    .unwrap_or_else(|| self.workspace_paths.resolve_config("tool-policy.json"));
114                self.record_event(RegistryEvent::PolicyPathResolved {
115                    scope: self.workspace_paths.scope_for_path(&config_path),
116                    config_path: config_path.clone(),
117                });
118
119                match ToolPolicyManager::new_with_config_path(&config_path)
120                    .await
121                    .with_context(|| format!("failed to initialize tool policy manager at {}", config_path.display()))
122                {
123                    Ok(manager) => manager,
124                    Err(err) => {
125                        self.report_error(&err);
126                        return Err(err);
127                    }
128                }
129            }
130        };
131
132        Ok(ToolRegistry::new_with_custom_policy_and_config(workspace_root, self.pty_config, policy_manager).await)
133    }
134
135    fn record_event(&self, event: RegistryEvent) {
136        if let Err(err) = self.telemetry.record(&event) {
137            self.handle_error(err.context("failed to record registry adapter telemetry event"));
138        }
139    }
140
141    fn report_error(&self, error: &Error) {
142        let message = self.error_formatter.format_error(error).into_owned();
143        let _ = self.error_reporter.capture(error);
144        let _ = self.telemetry.record(&RegistryEvent::AdapterError { message });
145    }
146
147    fn handle_error(&self, error: Error) {
148        let message = self.error_formatter.format_error(&error).into_owned();
149        let _ = self.error_reporter.capture(&error);
150        let _ = self.telemetry.record(&RegistryEvent::TelemetryFailure { message });
151    }
152}
153
154#[cfg(all(test, feature = "policies"))]
155mod tests {
156    use super::*;
157    use assert_fs::TempDir;
158    use vtcode_commons::{DisplayErrorFormatter, MemoryErrorReporter, MemoryTelemetry, StaticWorkspacePaths};
159
160    #[tokio::test]
161    async fn builds_registry_with_workspace_paths() {
162        let temp = TempDir::new().expect("tempdir");
163        let workspace_root = temp.path().join("workspace");
164        let config_dir = temp.path().join("config");
165        std::fs::create_dir_all(&workspace_root).expect("workspace");
166        std::fs::create_dir_all(&config_dir).expect("config");
167
168        let paths = StaticWorkspacePaths::new(workspace_root.clone(), config_dir.clone());
169        let telemetry = MemoryTelemetry::new();
170        let reporter = MemoryErrorReporter::new();
171        let formatter = DisplayErrorFormatter;
172
173        let builder = RegistryBuilder::new(&paths, &telemetry, &reporter, &formatter);
174        let registry = builder.build().await.expect("registry");
175
176        assert!(registry.has_tool(crate::config::constants::tools::CODE_SEARCH).await);
177
178        let events = telemetry.take();
179        assert!(matches!(events.as_slice(), [RegistryEvent::PolicyPathResolved { scope: PathScope::Config, .. }]));
180
181        let policy_file = config_dir.join("tool-policy.json");
182        assert!(policy_file.exists(), "policy file should be created");
183        assert!(reporter.take().is_empty(), "no errors expected");
184    }
185}