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