Skip to main content

vtcode_core/tools/
mod.rs

1//! # Tool System Architecture
2//!
3//! This module provides a modular, composable architecture for VT Code agent tools,
4//! implementing a registry-based system for tool discovery, execution, and management.
5//!
6//! ## Architecture Overview
7//!
8//! The tool system is designed around several key principles:
9//!
10//! - **Modularity**: Each tool is a focused, reusable component
11//! - **Registry Pattern**: Centralized tool registration and discovery
12//! - **Policy-Based Execution**: Configurable execution policies and safety checks
13//! - **Type Safety**: Strong typing for tool parameters and results
14//! - **Async Support**: Full async/await support for all tool operations
15//!
16//! ## Core Components
17//!
18//! ### Tool Registry
19//! ```rust,no_run
20//! use vtcode_core::tools::{ToolRegistry, ToolRegistration};
21//!
22//! #[tokio::main]
23//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
24//!     let workspace = std::env::current_dir()?;
25//!     let mut registry = ToolRegistry::new(workspace);
26//!
27//!     // Register a custom tool
28//!     let tool = ToolRegistration {
29//!         name: "my_tool".to_string(),
30//!         description: "A custom tool".to_string(),
31//!         parameters: serde_json::json!({"type": "object"}),
32//!         handler: |args| async move {
33//!             Ok(serde_json::json!({"result": "success"}))
34//!         },
35//!     };
36//!
37//!     registry.register_tool(tool).await?;
38//!     Ok(())
39//! }
40//! ```
41//!
42//! ### Tool Categories
43//!
44//! #### File Operations
45//! - **File Operations**: Read, write, create, delete files
46//! - **Search Tools**: grep_file with ripgrep for fast regex-based pattern matching, glob patterns, type filtering
47//! - **Cache Management**: File caching and performance optimization
48//!
49//! #### Terminal Integration
50//! - **Bash Tools**: Shell command execution
51//! - **PTY Support**: Full terminal emulation
52//! - **Command Policies**: Safety and execution controls
53//!
54//! #### Code Analysis
55//! ## Tool Execution
56//!
57//! ```rust,no_run
58//! use vtcode_core::tools::ToolRegistry;
59//!
60//! #[tokio::main]
61//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
62//!     let mut registry = ToolRegistry::new(std::env::current_dir()?);
63//!
64//!     // Execute a tool
65//!     let args = serde_json::json!({"path": "."});
66//!     let result = registry.execute_tool("list_files", args).await?;
67//!
68//!     println!("Result: {}", result);
69//!     Ok(())
70//! }
71//! ```
72//!
73//! ## Safety & Policies
74//!
75//! The tool system includes comprehensive safety features:
76//!
77//! - **Path Validation**: All file operations check workspace boundaries
78//! - **Command Policies**: Configurable allow/deny lists for terminal commands
79//! - **Execution Limits**: Timeout and resource usage controls
80//! - **Audit Logging**: Complete trail of tool executions
81//!
82//! ## Custom Tool Development
83//!
84//! ```rust,no_run
85//! use vtcode_core::tools::traits::Tool;
86//! use serde_json::Value;
87//!
88//! struct MyCustomTool;
89//!
90//! #[async_trait::async_trait]
91//! impl Tool for MyCustomTool {
92//!     async fn execute(&self, args: Value) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
93//!         // Tool implementation
94//!         Ok(serde_json::json!({"status": "completed"}))
95//!     }
96//!
97//!     fn name(&self) -> &str {
98//!         "my_custom_tool"
99//!     }
100//!
101//!     fn description(&self) -> &str {
102//!         "A custom tool for specific tasks"
103//!     }
104//!
105//!     fn parameters(&self) -> Value {
106//!         serde_json::json!({
107//!             "type": "object",
108//!             "properties": {
109//!                 "input": {"type": "string"}
110//!             }
111//!         })
112//!     }
113//! }
114//! ```
115//!
116//! Modular tool system for VT Code
117//!
118//! This module provides a composable architecture for agent tools, breaking down
119//! the monolithic implementation into focused, reusable components.
120
121pub mod apply_patch;
122pub mod ast_grep_binary;
123pub mod ast_grep_installer;
124pub(crate) mod ast_grep_language;
125pub mod builder;
126pub mod constants;
127pub mod error_messages;
128pub(crate) mod rate_limit_config;
129pub mod request_user_input;
130
131pub mod autonomous_executor;
132pub mod cache;
133pub mod command;
134pub mod command_args;
135pub mod command_cache;
136pub mod command_policy;
137pub mod command_resolver;
138pub mod continuation;
139pub mod edited_file_monitor;
140pub mod editing;
141pub mod error_helpers;
142pub mod exec_session;
143pub mod exec_session_id;
144pub mod execution_context;
145pub mod execution_tracker;
146pub mod file_ops;
147pub mod file_search_bridge;
148pub mod file_search_rpc;
149pub mod file_tracker;
150pub mod generation_helpers;
151pub mod grep_cache;
152pub mod grep_file;
153pub mod handlers;
154pub mod invocation;
155pub mod mcp;
156pub mod names;
157pub mod native_memory;
158pub mod path_env;
159pub mod plugins;
160pub mod pty;
161pub mod resilience;
162
163pub use resilience::rate_limiter;
164pub mod registry;
165pub mod result;
166pub mod result_cache;
167pub mod result_metadata;
168pub mod ripgrep_binary;
169pub mod ripgrep_installer;
170pub mod safety_gateway;
171pub mod search_metrics;
172pub(crate) mod search_runtime;
173pub mod shell;
174pub mod shell_snapshot;
175pub mod skills;
176pub mod structural_search;
177pub mod summarizers;
178#[cfg(feature = "tui")]
179pub mod terminal_app;
180pub mod tool_effectiveness;
181pub mod tool_intent;
182pub mod traits;
183pub(crate) mod tree_sitter_runtime;
184pub mod types;
185pub mod validation;
186pub mod validation_cache;
187pub mod web_fetch;
188
189// Production-grade improvements modules
190pub use resilience::adaptive_rate_limiter;
191pub mod async_middleware;
192pub use resilience::circuit_breaker;
193pub mod health;
194pub mod improvement_algorithms;
195pub mod improvements_config;
196pub mod improvements_errors;
197pub mod improvements_registry_ext;
198mod install_support;
199pub mod optimized_registry;
200pub mod output_spooler;
201pub mod pattern_engine;
202pub mod request_response;
203pub mod unified_error;
204
205/// Internal helper IDs for apply_patch and tracker constructors.
206pub const CREATE_APPLY_PATCH_FREEFORM_TOOL_ID: &str = "create_apply_patch_freeform_tool";
207pub const CREATE_APPLY_PATCH_JSON_TOOL_ID: &str = "create_apply_patch_json_tool";
208pub const INTERCEPT_APPLY_PATCH_ID: &str = "intercept_apply_patch";
209pub const NEW_SHARED_TRACKER_ID: &str = "new_shared_tracker";
210
211// Re-export main types and traits for backward compatibility
212pub use ast_grep_installer::{AstGrepInstallOutcome, AstGrepStatus};
213pub use autonomous_executor::{AutonomousExecutor, AutonomousPolicy};
214pub use cache::FileCache;
215pub use command_cache::PermissionCache;
216pub use command_resolver::CommandResolver;
217pub use editing::{Patch, PatchError, PatchHunk, PatchLine, PatchOperation};
218pub use exec_session_id::ExecSessionId;
219pub use execution_context::{ToolExecutionContext, ToolExecutionRecord, ToolPattern};
220pub use execution_tracker::{ExecutionRecord, ExecutionStats, ExecutionStatus, ExecutionTracker};
221pub use file_search_rpc::{
222    FileMatchRpc, FileSearchRpcHandler, ListFilesRequest, ListFilesResponse, RpcError, RpcRequest,
223    RpcResponse, SearchFilesRequest, SearchFilesResponse,
224};
225pub use grep_file::GrepSearchManager;
226pub use invocation::{
227    InvocationBuilder, ToolInvocation as UnifiedToolInvocation, ToolInvocationId,
228};
229pub use search_runtime::{
230    SearchToolBundleStatus, SearchToolReadiness, dominant_workspace_language,
231    search_tool_bundle_status,
232};
233
234pub use optimized_registry::{OptimizedToolRegistry, ToolMetadata as OptimizedToolMetadata};
235pub use plugins::{PluginHandle, PluginId, PluginInstaller, PluginManifest, PluginRuntime};
236pub use pty::{PtyCommandRequest, PtyCommandResult, PtyManager};
237pub use registry::{
238    ApprovalPattern, ApprovalRecorder, CgpRuntimeMode, JustificationExtractor,
239    JustificationManager, RiskLevel, ToolJustification, ToolRegistration, ToolRegistry,
240    ToolRiskContext, ToolRiskScorer, ToolSource, WorkspaceTrust, native_cgp_tool_factory,
241    wrap_registered_native_tool,
242};
243pub use request_response::{ToolCallRequest, ToolCallResponse};
244pub use result::{TokenCounts, ToolMetadata, ToolMetadataBuilder, ToolResult as SplitToolResult};
245pub use result_cache::{ToolCacheKey, ToolResultCache};
246pub use result_metadata::{
247    EnhancedToolResult, ResultCompleteness, ResultMetadata, ResultScorer, ScorerRegistry,
248};
249pub use ripgrep_installer::RipgrepStatus;
250pub use safety_gateway::{
251    SafetyCheckResult, SafetyContext, SafetyDecision, SafetyError, SafetyGateway,
252    SafetyGatewayConfig, SafetyStats, SafetyTrustLevel,
253};
254pub use search_metrics::{SearchMetric, SearchMetrics, SearchMetricsStats};
255pub use shell_snapshot::{
256    FileFingerprint, ShellKind, ShellSnapshot, ShellSnapshotManager, SnapshotStats,
257    apply_snapshot_env, global_snapshot_manager,
258};
259pub use tool_effectiveness::{
260    AdaptiveToolSelector, ToolEffectiveness, ToolEffectivenessTracker, ToolFailureMode,
261    ToolSelectionContext, ToolSelector,
262};
263pub use traits::{Tool, ToolExecutor};
264pub use types::*;
265pub use unified_error::{
266    DebugContext as UnifiedToolDebugContext, ErrorSeverity as UnifiedErrorSeverity,
267    UnifiedErrorKind, UnifiedToolError, classify_error as classify_unified_error,
268};
269pub use web_fetch::WebFetchTool;
270
271// Dynamic context discovery
272pub use output_spooler::{SpoolResult, SpoolerConfig, ToolOutputSpooler};
273
274// Production-grade improvements re-exports
275pub use async_middleware::{
276    AsyncCachingMiddleware, AsyncLoggingMiddleware, AsyncMiddleware, AsyncMiddlewareChain,
277    AsyncRetryMiddleware, ToolRequest as MiddlewareToolRequest, ToolResult,
278};
279pub use handlers::{
280    // Apply patch handler
281    ApplyPatchHandler,
282    ApplyPatchRequest,
283    ApplyPatchRuntime,
284    ApplyPatchToolArgs,
285    // Orchestrator and sandboxing
286    Approvable,
287    // Core handler traits and types
288    ApprovalPolicy,
289    AskForApproval,
290    // Turn diff tracker with Agent Trace support
291    ChangeAttribution,
292    CommandSpec,
293    ConfiguredToolSpec,
294    ContentItem,
295    DiffTracker,
296    ExecApprovalRequirement,
297    // Event emission
298    ExecCommandInput,
299    ExecCommandSource,
300    ExecEnv,
301    ExecPolicyAmendment,
302    ExecToolCallOutput,
303    FileChange,
304    FileChangeKind,
305    FreeformTool,
306    FreeformToolFormat,
307    JsonSchema as ToolJsonSchema,
308    McpToolResult,
309    ParsedCommand,
310    RejectConfig,
311    ResponsesApiTool,
312    SandboxAttempt,
313    SandboxManager,
314    SandboxMode,
315    SandboxPermissions,
316    SandboxPolicy,
317    SandboxTransformError,
318    Sandboxable,
319    SandboxablePreference,
320    SharedDiffTracker,
321    SharedTurnDiffTracker,
322    ShellEnvironmentPolicy,
323    ShellToolCallParams,
324    ToolCallError,
325    ToolCtx,
326    ToolEmitter,
327    ToolError,
328    ToolEvent,
329    ToolEventBegin,
330    ToolEventCtx,
331    ToolEventFailure,
332    ToolEventFailureKind,
333    ToolEventStage,
334    ToolEventSuccess,
335    ToolHandler,
336    ToolInvocation,
337    ToolKind,
338    ToolOrchestrator,
339    ToolOutput,
340    ToolPayload,
341    ToolRuntime,
342    ToolSession,
343    ToolSpec,
344    TurnContext,
345    TurnDiffTracker,
346    create_apply_patch_freeform_tool,
347    create_apply_patch_json_tool,
348    default_exec_approval_requirement,
349    intercept_apply_patch,
350    new_shared_tracker,
351};
352pub use improvement_algorithms::{
353    MLScoreComponents, PatternState, TimeDecayedScore, detect_pattern, jaro_winkler_similarity,
354};
355pub use improvements_config::{
356    CacheConfig, ContextConfig, FallbackConfig, ImprovementsConfig, PatternConfig,
357    SimilarityConfig, TimeDecayConfig,
358};
359pub use improvements_errors::{
360    ErrorKind, ErrorSeverity, EventType, ImprovementError, ImprovementEvent, ImprovementResult,
361    ObservabilityContext, ObservabilitySink,
362};
363pub use improvements_registry_ext::{ToolMetrics, ToolRegistryImprovement};
364pub use vtcode_utility_tool_specs::parse_tool_input_schema;