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,ignore
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**: native content search 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,ignore
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,ignore
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 use apply_patch::mutation_target_paths;
123pub mod builder;
124pub(crate) mod code_language;
125pub mod constants;
126pub mod error_messages;
127pub(crate) mod rate_limit_config;
128pub mod request_user_input;
129
130pub mod autonomous_executor;
131pub mod cache;
132pub(crate) mod code_search;
133pub use code_search::normalised_identity as normalised_code_search_identity;
134pub use code_search::normalised_loop_identity as normalised_code_search_loop_identity;
135pub use code_search::normalised_path as normalised_code_search_path;
136pub use code_search::scope_contains_mutated_path as code_search_scope_contains_mutated_path;
137pub mod command;
138pub mod command_args;
139pub mod command_cache;
140pub mod command_policy;
141pub mod command_resolver;
142pub mod continuation;
143pub mod edited_file_monitor;
144pub mod editing;
145pub mod error_helpers;
146pub mod exec_read_target;
147pub mod exec_session;
148pub mod exec_session_id;
149pub mod execution_context;
150pub mod execution_tracker;
151pub mod file_ops;
152pub mod file_search_bridge;
153pub mod file_search_rpc;
154pub mod file_tracker;
155mod grep_backend;
156pub mod grep_cache;
157pub mod grep_file;
158pub mod handlers;
159pub mod invocation;
160pub mod mcp;
161pub mod names;
162pub mod native_memory;
163pub(crate) mod output_limits;
164pub mod path_env;
165pub mod plugins;
166pub mod pty;
167pub mod read_limits;
168pub mod resilience;
169
170pub use resilience::rate_limiter;
171pub mod defuddle;
172pub mod outline_search;
173pub mod registry;
174pub mod result;
175pub mod result_cache;
176pub mod result_metadata;
177pub mod safety_gateway;
178pub mod search_metrics;
179pub(crate) mod search_runtime;
180pub mod shell;
181pub mod shell_snapshot;
182pub mod skills;
183pub mod summarizers;
184#[cfg(feature = "tui")]
185pub mod terminal_app;
186pub mod tool_effectiveness;
187pub mod tool_intent;
188pub mod traits;
189pub mod types;
190pub mod validation;
191pub mod validation_cache;
192pub mod web_fetch;
193pub mod web_search;
194
195// Production-grade improvements modules
196pub use resilience::adaptive_rate_limiter;
197pub mod async_middleware;
198pub mod cached_executor;
199pub mod lru_cache;
200pub mod pattern_detection;
201pub mod registry_adapters;
202pub mod tool_middleware;
203pub mod workflow_optimizer;
204pub use resilience::circuit_breaker;
205pub mod health;
206pub mod improvement_algorithms;
207pub mod improvements_config;
208pub mod improvements_errors;
209pub mod improvements_registry_ext;
210pub mod optimized_registry;
211pub mod output_spooler;
212pub mod pattern_engine;
213pub mod request_response;
214pub mod unified_error;
215pub mod untrusted_data;
216
217// Re-export main types and traits for backward compatibility
218pub use autonomous_executor::{AutonomousExecutor, AutonomousPolicy};
219pub use cache::FileCache;
220pub use command_cache::PermissionCache;
221pub use command_resolver::CommandResolver;
222pub use editing::{Patch, PatchError, PatchHunk, PatchLine, PatchOperation};
223pub use exec_read_target::{ExecReadTarget, parse_exec_read_target};
224pub use exec_session_id::ExecSessionId;
225pub use execution_context::{ToolExecutionContext, ToolExecutionRecord, ToolPattern};
226pub use execution_tracker::{ExecutionRecord, ExecutionStats, ExecutionStatus, ExecutionTracker};
227pub use file_search_rpc::{
228    FileMatchRpc, FileSearchRpcHandler, ListFilesRequest, ListFilesResponse, RpcError, RpcRequest, RpcResponse,
229    SearchFilesRequest, SearchFilesResponse,
230};
231pub use grep_file::GrepSearchManager;
232pub use invocation::{InvocationBuilder, ToolInvocation as UnifiedToolInvocation, ToolInvocationId};
233pub use search_runtime::{
234    SearchToolBundleStatus, SearchToolReadiness, dominant_workspace_language, search_tool_bundle_status,
235};
236
237pub use defuddle::DefuddleTool;
238pub use optimized_registry::{CachedToolMetadata as OptimizedToolMetadata, OptimizedToolRegistry};
239pub use plugins::{PluginHandle, PluginId, PluginInstaller, PluginManifest, PluginRuntime};
240pub use pty::{PtyCommandRequest, PtyCommandResult, PtyManager};
241pub use registry::{
242    ApprovalPattern, ApprovalRecorder, CgpRuntimeMode, JustificationExtractor, JustificationManager, RiskLevel,
243    ToolJustification, ToolRegistration, ToolRegistry, ToolRiskContext, ToolRiskScorer, ToolSource, WorkspaceTrust,
244    native_cgp_tool_factory, wrap_registered_native_tool,
245};
246pub use request_response::{ToolCallRequest, ToolCallResponse};
247pub use result::{TokenCounts, ToolMetadata, ToolMetadataBuilder, ToolResult as SplitToolResult};
248pub use result_cache::{ToolCacheKey, ToolResultCache};
249pub use result_metadata::{EnhancedToolResult, ResultCompleteness, ResultMetadata, ResultScorer, ScorerRegistry};
250pub use safety_gateway::{
251    SafetyCheckResult, SafetyContext, SafetyDecision, SafetyError, SafetyGateway, SafetyGatewayConfig, SafetyStats,
252    SafetyTrustLevel,
253};
254pub use search_metrics::{SearchMetric, SearchMetrics, SearchMetricsStats};
255pub use shell_snapshot::{
256    FileFingerprint, ShellKind, ShellSnapshot, ShellSnapshotManager, SnapshotStats, apply_snapshot_env,
257    global_snapshot_manager,
258};
259pub use tool_effectiveness::{
260    AdaptiveToolSelector, ToolEffectiveness, ToolEffectivenessTracker, ToolFailureMode, ToolSelectionContext,
261    ToolSelector,
262};
263pub use traits::{Tool, ToolExecutor};
264pub use types::*;
265pub use unified_error::{
266    DebugContext as UnifiedToolDebugContext, ErrorSeverity as UnifiedErrorSeverity, UnifiedErrorKind, UnifiedToolError,
267};
268pub use web_fetch::WebFetchTool;
269pub use web_search::WebSearchTool;
270
271// Dynamic context discovery
272pub use output_spooler::{SpoolResult, SpoolState, SpooledOutputReference, SpoolerConfig, ToolOutputSpooler};
273
274// Production-grade improvements re-exports
275pub use async_middleware::{
276    AsyncCachingMiddleware, AsyncLoggingMiddleware, AsyncMiddleware, AsyncMiddlewareChain, AsyncRetryMiddleware,
277    MiddlewareToolResult, ToolRequest as MiddlewareToolRequest,
278};
279pub use cached_executor::{CachedToolExecutor, ExecutorStats};
280pub use handlers::{
281    // Apply patch handler
282    // Orchestrator and sandboxing
283    Approvable,
284    // Core handler traits and types
285    ApprovalPolicy,
286    AskForApproval,
287    // Turn diff tracker with Agent Trace support
288    ChangeAttribution,
289    CommandSpec,
290    ConfiguredToolSpec,
291    ContentItem,
292    DiffTracker,
293    ExecApprovalRequirement,
294    // Event emission
295    ExecEnv,
296    ExecPolicyAmendment,
297    ExecToolCallOutput,
298    FileChange,
299    FileChangeKind,
300    FreeformTool,
301    FreeformToolFormat,
302    JsonSchema as ToolJsonSchema,
303    McpToolResult,
304    RejectConfig,
305    ResponsesApiTool,
306    SandboxAttempt,
307    SandboxConfig,
308    SandboxManager,
309    SandboxPermissions,
310    SandboxPolicy,
311    SandboxTransformError,
312    Sandboxable,
313    SandboxablePreference,
314    SharedDiffTracker,
315    SharedTurnDiffTracker,
316    ShellEnvironmentPolicy,
317    ShellToolCallParams,
318    ToolCallError,
319    ToolCtx,
320    ToolError,
321    ToolHandler,
322    ToolInvocation,
323    ToolKind,
324    ToolOutput,
325    ToolPayload,
326    ToolRuntime,
327    ToolSession,
328    ToolSpec,
329    TurnContext,
330    TurnDiffTracker,
331    default_exec_approval_requirement,
332    new_shared_tracker,
333};
334pub use improvement_algorithms::{
335    MLScoreComponents, PatternState, TimeDecayedScore, ToolCallRecord, detect_pattern, jaro_winkler_similarity,
336};
337pub use improvements_config::{
338    CacheConfig, ContextConfig, FallbackConfig, ImprovementsConfig, PatternConfig, SimilarityConfig, TimeDecayConfig,
339};
340pub use improvements_errors::{
341    ErrorKind, EventType, ImprovementError, ImprovementEvent, ImprovementResult, ImprovementSeverity,
342    ImprovementSeverity as ErrorSeverity, ObservabilityContext, ObservabilitySink,
343};
344pub use improvements_registry_ext::{ToolMetrics, ToolRegistryImprovement};
345pub use lru_cache::{CacheObserver, CacheStats, LruCache};
346pub use pattern_detection::{DetectedPattern, PatternDetector};
347pub use tool_middleware::{Middleware, MiddlewareChain};
348pub use vtcode_utility_tool_specs::parse_tool_input_schema;
349pub use workflow_optimizer::{Optimization, OptimizationType, WorkflowOptimizer};
350
351pub mod source_inspection;