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