vtcode_core/lib.rs
1//! # vtcode-core - Runtime for VT Code
2//!
3//! `vtcode-core` powers the VT Code terminal coding agent. It provides the
4//! reusable building blocks for multi-provider LLM orchestration, tool
5//! execution, semantic code analysis, and configurable safety policies.
6//!
7//! ## Highlights
8//!
9//! - **Provider Abstraction**: unified LLM interface with adapters for OpenAI,
10//! Anthropic, xAI, DeepSeek, Gemini, and OpenRouter, including automatic
11//! failover and spend controls.
12//! - **Prompt Caching**: cross-provider prompt caching system that leverages
13//! provider-specific caching capabilities (OpenAI's automatic caching, Anthropic's
14//! cache_control blocks, Gemini's implicit/explicit caching) to reduce costs and
15//! latency, with configurable settings per provider.
16//! - **Semantic Workspace Model**: incremental tree-sitter parsing for Rust,
17//! Python, JavaScript, TypeScript, Go, and Java augmented by ast-grep based
18//! structural search and refactoring.
19//! - **Tool System**: trait-driven registry for shell execution, file IO,
20//! search, and custom commands, with Tokio-powered concurrency and PTY
21//! streaming.
22//! - **Configuration-First**: everything is driven by `vtcode.toml`, with
23//! model, safety, and automation constants centralized in
24//! `config::constants` and curated metadata in `docs/models.json`.
25//! - **Safety & Observability**: workspace boundary enforcement, command
26//! allow/deny lists, human-in-the-loop confirmation, and structured event
27//! logging.
28//!
29//! ## Architecture Overview
30//!
31//! The crate is organized into several key modules:
32//!
33//! - `config/`: configuration loader, defaults, and schema validation.
34//! - `llm/`: provider clients, request shaping, and response handling.
35//! - `tools/`: built-in tool implementations plus registration utilities.
36//! - `context/`: conversation management, summarization, and memory.
37//! - `executor/`: async orchestration for tool invocations and streaming output.
38//! - `tree_sitter/`: language-specific parsers, syntax tree caching, and
39//! semantic extraction helpers.
40//! - `core/prompt_caching`: cross-provider prompt caching system that leverages
41//! provider-specific caching mechanisms for cost optimization and reduced latency.
42//!
43//! ## Quickstart
44//!
45//! ```rust,ignore
46//! use vtcode_core::{Agent, VTCodeConfig};
47//!
48//! #[tokio::main]
49//! async fn main() -> Result<(), anyhow::Error> {
50//! // Load configuration from vtcode.toml or environment overrides
51//! let config = VTCodeConfig::load()?;
52//!
53//! // Construct the agent runtime
54//! let agent = Agent::new(config).await?;
55//!
56//! // Execute an interactive session
57//! agent.run().await?;
58//!
59//! Ok(())
60//! }
61//! ```
62//!
63//! ## Extending VT Code
64//!
65//! Register custom tools or providers by composing the existing traits:
66//!
67//! ```rust,ignore
68//! use vtcode_core::tools::{ToolRegistry, ToolRegistration};
69//!
70//! #[tokio::main]
71//! async fn main() -> Result<(), anyhow::Error> {
72//! let workspace = std::env::current_dir()?;
73//! let mut registry = ToolRegistry::new(workspace);
74//!
75//! let custom_tool = ToolRegistration {
76//! name: "my_custom_tool".into(),
77//! description: "A custom tool for specific tasks".into(),
78//! parameters: serde_json::json!({
79//! "type": "object",
80//! "properties": { "input": { "type": "string" } }
81//! }),
82//! handler: |_args| async move {
83//! // Implement your tool behavior here
84//! Ok(serde_json::json!({ "result": "success" }))
85//! },
86//! };
87//!
88//! registry.register_tool(custom_tool).await?;
89//! Ok(())
90//! }
91//! ```
92//!
93//! For a complete tour of modules and extension points, read
94//! `docs/ARCHITECTURE.md` and the guides in `docs/project/`.
95
96//! VTCode Core Library
97//!
98//! This crate provides the core functionality for the VTCode agent,
99//! including tool implementations, LLM integration, and utility functions.
100
101// Public modules
102pub mod bash_runner;
103pub mod cli;
104pub mod code;
105pub mod commands;
106pub mod config;
107pub mod constants;
108pub mod core;
109pub mod gemini;
110pub mod llm;
111pub mod markdown_storage;
112pub mod models;
113pub mod project;
114pub mod project_doc;
115pub mod prompts;
116pub mod safety;
117pub mod simple_indexer;
118pub mod tool_policy;
119pub mod tools;
120pub mod types;
121pub mod ui;
122pub mod utils;
123
124// Re-exports for convenience
125pub use bash_runner::BashRunner;
126pub use cli::args::{Cli, Commands};
127pub use code::code_completion::{CompletionEngine, CompletionSuggestion};
128pub use commands::stats::handle_stats_command;
129pub use config::types::{
130 AnalysisDepth, CapabilityLevel, CommandResult, CompressionLevel, ContextConfig, LoggingConfig,
131 OutputFormat, PerformanceMetrics, ReasoningEffortLevel, SessionInfo, ToolConfig,
132};
133pub use config::{AgentConfig, VTCodeConfig};
134pub use core::agent::core::Agent;
135pub use core::context_compression::{
136 CompressedContext, ContextCompressionConfig, ContextCompressor,
137};
138pub use core::conversation_summarizer::ConversationSummarizer;
139pub use core::performance_profiler::PerformanceProfiler;
140pub use core::prompt_caching::{CacheStats, PromptCache, PromptCacheConfig, PromptOptimizer};
141pub use core::timeout_detector::TimeoutDetector;
142pub use gemini::{Content, FunctionDeclaration, Part};
143pub use llm::{AnyClient, make_client};
144pub use markdown_storage::{MarkdownStorage, ProjectData, ProjectStorage, SimpleKVStorage};
145pub use project::{SimpleCache, SimpleProjectManager};
146pub use prompts::{
147 generate_lightweight_instruction, generate_specialized_instruction, generate_system_instruction,
148};
149pub use simple_indexer::SimpleIndexer;
150pub use tool_policy::{ToolPolicy, ToolPolicyManager};
151pub use tools::advanced_search::{AdvancedSearchTool, SearchOptions};
152pub use tools::grep_search::GrepSearchManager;
153pub use tools::tree_sitter::TreeSitterAnalyzer;
154pub use tools::{
155 ToolRegistration, ToolRegistry, build_function_declarations,
156 build_function_declarations_for_level,
157};
158pub use ui::diff_renderer::DiffRenderer;
159pub use utils::dot_config::{
160 CacheConfig, DotConfig, DotManager, ProviderConfigs, UiConfig, UserPreferences,
161 WorkspaceTrustLevel, WorkspaceTrustRecord, WorkspaceTrustStore, initialize_dot_folder,
162 load_user_config, save_user_config, update_theme_preference,
163};
164pub use utils::vtcodegitignore::initialize_vtcode_gitignore;
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 use tempfile::TempDir;
171
172 #[test]
173 fn test_library_exports() {
174 // Test that all public exports are accessible
175 let _cache = PromptCache::new();
176 }
177
178 #[test]
179 fn test_module_structure() {
180 // Test that all modules can be imported
181 // This is a compile-time test that ensures module structure is correct
182 }
183
184 #[test]
185 fn test_version_consistency() {
186 // Test that version information is consistent across modules
187 // This would be more meaningful with actual version checking
188 }
189
190 #[tokio::test]
191 async fn test_tool_registry_integration() {
192 use crate::config::constants::tools;
193
194 let temp_dir = TempDir::new().unwrap();
195 std::env::set_current_dir(&temp_dir).unwrap();
196
197 let mut registry = ToolRegistry::new(temp_dir.path().to_path_buf());
198
199 // Test that we can execute basic tools
200 let list_args = serde_json::json!({
201 "path": "."
202 });
203
204 let result = registry.execute_tool(tools::LIST_FILES, list_args).await;
205 assert!(result.is_ok());
206
207 let response: serde_json::Value = result.unwrap();
208 assert!(response["files"].is_array());
209 }
210
211 #[tokio::test]
212 async fn test_pty_basic_command() {
213 let temp_dir = TempDir::new().unwrap();
214 let workspace = temp_dir.path().to_path_buf();
215 let mut registry = ToolRegistry::new(workspace.clone());
216
217 // Test a simple PTY command
218 let args = serde_json::json!({
219 "command": "echo",
220 "args": ["Hello, PTY!"]
221 });
222
223 let result = registry.execute_tool("run_pty_cmd", args).await;
224 assert!(result.is_ok());
225 let response: serde_json::Value = result.unwrap();
226 assert_eq!(response["success"], true);
227 assert_eq!(response["code"], 0);
228 assert!(response["output"].as_str().unwrap().contains("Hello, PTY!"));
229 }
230
231 #[tokio::test]
232 async fn test_pty_session_management() {
233 let temp_dir = TempDir::new().unwrap();
234 let workspace = temp_dir.path().to_path_buf();
235 let mut registry = ToolRegistry::new(workspace.clone());
236
237 // Test creating a PTY session
238 let args = serde_json::json!({
239 "session_id": "test_session",
240 "command": "bash"
241 });
242
243 let result = registry.execute_tool("create_pty_session", args).await;
244 assert!(result.is_ok());
245 let response: serde_json::Value = result.unwrap();
246 assert_eq!(response["success"], true);
247 assert_eq!(response["session_id"], "test_session");
248
249 // Test listing PTY sessions
250 let args = serde_json::json!({});
251 let result = registry.execute_tool("list_pty_sessions", args).await;
252 assert!(result.is_ok());
253 let response: serde_json::Value = result.unwrap();
254 assert!(
255 response["sessions"]
256 .as_array()
257 .unwrap()
258 .contains(&"test_session".into())
259 );
260
261 // Test closing a PTY session
262 let args = serde_json::json!({
263 "session_id": "test_session"
264 });
265
266 let result = registry.execute_tool("close_pty_session", args).await;
267 assert!(result.is_ok());
268 let response: serde_json::Value = result.unwrap();
269 assert_eq!(response["success"], true);
270 assert_eq!(response["session_id"], "test_session");
271 }
272}