Expand description
§vtcode-core - Runtime for VT Code
vtcode-core powers the VT Code terminal coding agent. It provides the
reusable building blocks for multi-provider LLM orchestration, tool
execution, semantic code analysis, and configurable safety policies.
§Highlights
- Provider Abstraction: unified LLM interface with adapters for OpenAI, Anthropic, xAI, DeepSeek, Gemini, OpenRouter, and Ollama (local), including automatic failover and spend controls.
- Prompt Caching: cross-provider prompt caching system that leverages provider-specific caching capabilities (OpenAI’s automatic caching, Anthropic’s cache_control blocks, Gemini’s implicit/explicit caching) to reduce costs and latency, with configurable settings per provider.
- Semantic Workspace Model: LLM-native code analysis and navigation across all modern programming languages.
- Bash Shell Safety: tree-sitter-bash integration for critical command validation and security enforcement.
- Tool System: trait-driven registry for shell execution, file IO, search, and custom commands, with Tokio-powered concurrency and PTY streaming.
- Configuration-First: everything is driven by
vtcode.toml, with model, safety, and automation constants centralized inconfig::constantsand curated metadata indocs/models.json. - Safety & Observability: workspace boundary enforcement, command allow/deny lists, human-in-the-loop confirmation, and structured event logging for comprehensive audit trails.
§Architecture Overview
The crate is organized into several key modules:
config/: configuration loader, defaults, and schema validation.llm/: provider clients, request shaping, and response handling.tools/: built-in tool implementations plus registration utilities.context/: conversation management and memory.executor/: async orchestration for tool invocations and streaming output.core/prompt_caching: cross-provider prompt caching system that leverages provider-specific caching mechanisms for cost optimization and reduced latency.
§Quickstart
use vtcode_core::{Agent, VTCodeConfig};
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
// Load configuration from vtcode.toml or environment overrides
let config = VTCodeConfig::load()?;
// Construct the agent runtime
let agent = Agent::new(config).await?;
// Execute an interactive session
agent.run().await?;
Ok(())
}§Extending VT Code
Register custom tools or providers by composing the existing traits:
use vtcode_core::tools::{ToolRegistry, ToolRegistration};
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let workspace = std::env::current_dir()?;
let mut registry = ToolRegistry::new(workspace);
let custom_tool = ToolRegistration {
name: "my_custom_tool".into(),
description: "A custom tool for specific tasks".into(),
parameters: serde_json::json!({
"type": "object",
"properties": { "input": { "type": "string" } }
}),
handler: |_args| async move {
// Implement your tool behavior here
Ok(serde_json::json!({ "result": "success" }))
},
};
registry.register_tool(custom_tool).await?;
Ok(())
}For a complete tour of modules and extension points, read
docs/ARCHITECTURE.md and the guides in docs/project/.
§Agent Client Protocol (ACP)
VT Code’s binary exposes an ACP bridge for Zed. Enable it via the [acp] section in
vtcode.toml, launch the vtcode acp subcommand, and register the binary under
agent_servers in Zed’s settings.json. Detailed instructions and troubleshooting live in the
Zed ACP integration guide,
with a rendered summary on
docs.rs.
§Bridge guarantees
- Tool exposure follows capability negotiation:
read_filestays disabled unless Zed advertisesfs.read_text_file. - Each filesystem request invokes
session/request_permission, ensuring explicit approval within the editor before data flows. - Cancellation signals propagate into VT Code, cancelling active tool calls and ending the
turn with
StopReason::Cancelled. - ACP
planentries track analysis, context gathering, and response drafting for timeline parity with Zed. - Absolute-path checks guard every
read_fileargument before forwarding it to the client. - Non-tool-capable models trigger reasoning notices and an automatic downgrade to plain completions without losing plan consistency.
VT Code Core Library
This crate provides the core functionality for the VT Code agent, including tool implementations, LLM integration, and utility functions.
Re-exports§
pub use exec_policy::command_validation as execpolicy;pub use cli::args::Cli;pub use cli::args::Commands;pub use code::code_completion::CompletionEngine;pub use code::code_completion::CompletionSuggestion;pub use commands::stats::handle_stats_command;pub use core::agent::core::Agent;pub use core::agent::runner::AgentRunner;pub use core::agent::task::ContextItem as RunnerContextItem;pub use core::agent::task::Task as RunnerTask;pub use core::agent::task::TaskOutcome as RunnerTaskOutcome;pub use core::agent::task::TaskResults as RunnerTaskResults;pub use core::memory_pool::MemoryPool;pub use core::memory_pool::global_pool;pub use core::performance_profiler::BenchmarkResults;pub use core::performance_profiler::BenchmarkUtils;pub use core::performance_profiler::PerformanceProfiler;pub use core::threads::SubmissionId;pub use core::threads::ThreadBootstrap;pub use core::threads::ThreadEventRecord;pub use core::threads::ThreadId;pub use core::threads::ThreadManager;pub use core::threads::ThreadRuntimeHandle;pub use core::threads::ThreadSnapshot;pub use core::threads::build_thread_archive_metadata;pub use core::threads::loaded_skills_from_session_listing;pub use core::threads::messages_from_session_listing;pub use ide_context::EditorContextSnapshot;pub use ide_context::EditorFileContext;pub use ide_context::EditorLineRange;pub use ide_context::EditorSelectionContext;pub use ide_context::EditorSelectionRange;pub use primary_agent::ActivePrimaryAgent;pub use primary_agent::ActivePrimaryAgentSpecIdentity;pub use primary_agent::ActivePrimaryAgentState;pub use primary_agent::PrimaryAgentResolutionError;pub use primary_agent::apply_primary_agent_tool_policy;pub use primary_agent::clamp_primary_permission_mode;pub use primary_agent::resolve_discovered_primary_agent;pub use primary_agent::resolve_primary_agent;pub use subagents::SendInputRequest as SubagentSendInputRequest;pub use subagents::SpawnAgentRequest as SubagentSpawnRequest;pub use subagents::SpawnBackgroundSubprocessRequest as SubagentSpawnBackgroundSubprocessRequest;pub use subagents::SubagentController;pub use subagents::SubagentControllerConfig;pub use subagents::SubagentInputItem;pub use subagents::SubagentStatus;pub use subagents::SubagentStatusEntry;pub use core::prompt_caching::CacheStats;pub use core::prompt_caching::PromptCache;pub use core::prompt_caching::PromptCacheConfig;pub use core::prompt_caching::PromptOptimizer;pub use core::timeout_detector::TimeoutDetector;pub use diagnostics::DiagnosticReport;pub use diagnostics::HealthSample;pub use diagnostics::LabeledAction;pub use diagnostics::PredictiveMonitor;pub use diagnostics::RecoveryAction;pub use diagnostics::RecoveryPlaybook;pub use dotfile_protection::AccessType as DotfileAccessType;pub use dotfile_protection::AuditEntry as DotfileAuditEntry;pub use dotfile_protection::AuditLog as DotfileAuditLog;pub use dotfile_protection::AuditOutcome as DotfileAuditOutcome;pub use dotfile_protection::BackupManager as DotfileBackupManager;pub use dotfile_protection::DotfileBackup;pub use dotfile_protection::DotfileGuardian;pub use dotfile_protection::ProtectionDecision;pub use dotfile_protection::ProtectionViolation;pub use dotfile_protection::get_global_guardian;pub use dotfile_protection::init_global_guardian;pub use dotfile_protection::is_protected_dotfile;pub use error::ErrorCode as VtCodeErrorCode;pub use error::Result as VtCodeResult;pub use error::VtCodeError;pub use exec::CodeExecutor;pub use exec::ExecutionConfig;pub use exec::ExecutionResult;pub use exec::Language;pub use llm::providers::gemini::wire::Content;pub use llm::providers::gemini::wire::FunctionDeclaration;pub use llm::providers::gemini::wire::Part;pub use llm::AnyClient;pub use llm::make_client;pub use mcp::tool_discovery::DetailLevel;pub use mcp::tool_discovery::ToolDiscovery;pub use mcp::tool_discovery::ToolDiscoveryResult;pub use mcp::validate_mcp_config;pub use memory::MemoryCheckpoint;pub use memory::MemoryMonitor;pub use memory::MemoryPressure;pub use memory::MemoryReport;pub use models_manager::ModelFamily;pub use models_manager::ModelPreset;pub use models_manager::ModelsCache;pub use models_manager::ModelsManager;pub use models_manager::builtin_model_presets;pub use models_manager::model_family::find_family_for_model;pub use notifications::NotificationConfig;pub use notifications::NotificationEvent;pub use notifications::NotificationManager;pub use notifications::apply_global_notification_config;pub use notifications::apply_global_notification_config_from_vtcode;pub use notifications::get_global_notification_manager;pub use notifications::init_global_notification_manager;pub use notifications::init_global_notification_manager_with_config;pub use notifications::notify_command_failure;pub use notifications::notify_error;pub use notifications::notify_human_in_the_loop;pub use notifications::notify_tool_failure;pub use notifications::notify_tool_success;pub use notifications::send_global_notification;pub use orchestrator::DistributedOrchestrator;pub use orchestrator::ExecutionTarget;pub use orchestrator::ExecutorRegistry;pub use orchestrator::LocalExecutor;pub use orchestrator::ScheduledWork;pub use orchestrator::WorkExecutor;pub use prompts::generate_lightweight_instruction;pub use prompts::generate_specialized_instruction;pub use prompts::generate_system_instruction;pub use retry::RetryDecision;pub use retry::RetryPolicy;pub use security::IntegrityTag;pub use security::PayloadEnvelope;pub use security::ZeroTrustContext;pub use telemetry::TelemetryEvent;pub use telemetry::TelemetryPipeline;pub use open_responses::ContentPart;pub use open_responses::CustomItem;pub use open_responses::DualEventEmitter;pub use open_responses::FunctionCallItem;pub use open_responses::FunctionCallOutputItem;pub use open_responses::IncompleteDetails;pub use open_responses::IncompleteReason;pub use open_responses::InputTokensDetails;pub use open_responses::ItemStatus;pub use open_responses::MessageItem;pub use open_responses::MessageRole;pub use open_responses::OpenResponseError;pub use open_responses::OpenResponseErrorCode;pub use open_responses::OpenResponseErrorType;pub use open_responses::OpenResponsesCallback;pub use open_responses::OpenResponsesIntegration;pub use open_responses::OpenResponsesProvider;pub use open_responses::OpenUsage;pub use open_responses::OutputItem;pub use open_responses::OutputItemId;pub use open_responses::OutputTokensDetails;pub use open_responses::ReasoningItem as OpenReasoningItem;pub use open_responses::Response as OpenResponse;pub use open_responses::ResponseBuilder;pub use open_responses::ResponseId;pub use open_responses::ResponseStatus;pub use open_responses::ResponseStreamEvent;pub use open_responses::StreamEventEmitter;pub use open_responses::ToOpenResponse;pub use open_responses::VecStreamEmitter;pub use open_responses::generate_item_id;pub use open_responses::generate_response_id;pub use tool_policy::ToolPolicy;pub use tool_policy::ToolPolicyManager;pub use exec_policy::AskForApproval;pub use exec_policy::Decision;pub use exec_policy::ExecApprovalRequirement;pub use exec_policy::ExecPolicyAmendment;pub use exec_policy::ExecPolicyConfig;pub use exec_policy::ExecPolicyManager;pub use exec_policy::Policy;pub use exec_policy::PolicyEvaluation;pub use exec_policy::PolicyParser;pub use exec_policy::PrefixRule;pub use exec_policy::RuleMatch;pub use sandboxing::CommandSpec as SandboxCommandSpec;pub use sandboxing::ExecEnv as SandboxExecEnv;pub use sandboxing::ExecExpiration;pub use sandboxing::SandboxManager as CodexSandboxManager;pub use sandboxing::SandboxPermissions as CodexSandboxPermissions;pub use sandboxing::SandboxPolicy as CodexSandboxPolicy;pub use sandboxing::SandboxType;pub use sandboxing::WritableRoot;pub use tools::OptimizedToolRegistry;pub use tools::grep_file::GrepSearchManager;pub use tools::ToolRegistration;pub use tools::ToolRegistry;pub use ui::diff_renderer::DiffRenderer;pub use utils::dot_config::CacheConfig;pub use utils::dot_config::DotConfig;pub use utils::dot_config::DotManager;pub use utils::dot_config::ProviderConfigs;pub use utils::dot_config::UiConfig;pub use utils::dot_config::UserPreferences;pub use utils::dot_config::WorkspaceTrustRecord;pub use utils::dot_config::WorkspaceTrustStore;pub use utils::dot_config::initialize_dot_folder;pub use utils::dot_config::load_user_config;pub use utils::dot_config::load_workspace_trust_level;pub use utils::dot_config::save_user_config;pub use utils::dot_config::update_model_preference;pub use utils::dot_config::update_theme_preference;pub use utils::dot_config::update_workspace_trust;pub use pods::*;
Modules§
- a2a
- Agent2Agent (A2A) Protocol support for VT Code
- acp
- anthropic_
api - Anthropic API compatibility layer for VT Code
- audit
- auth
- Authentication module for VT Code.
- cache
- Unified caching system for VT Code
- cli
- Command-line interface module
- code
- command_
safety - Command safety detection module
- commands
- Command implementations for different agent workflows
- compaction
- components
- Context-Generic Programming (CGP) substrate for VT Code
- config
- Configuration facade for vtcode-core.
- constants
- Constants used throughout the application
- context
- Context management for vibe coding support
- copilot
- core
- Core Agent Architecture
- diagnostics
- Self-healing diagnostics including predictive monitors and recovery playbooks.
- dotfile_
protection - Comprehensive dotfile protection system.
- error
- Structured error handling for VT Code.
- exec
- exec_
policy - Execution Policy Module
- gemini
- Gemini API compatibility facade for VT Code.
- git_
info - Git repository information collection
- hooks
- http_
client - HTTP client utilities
- ide_
context - instructions
- llm
- LLM Integration Layer
- marketplace
- Plugin marketplace system for VT Code
- mcp
- MCP client management built on top of the Codex MCP building blocks.
- memory
- Memory monitoring and pressure detection system.
- metrics
- models
- Model definitions and constants
- models_
manager - Models Manager Module
- notifications
- Push notification system for VT Code terminal clients Handles important events like command failures, errors, policy approval requests, human in the loop interactions, completion and requests.
- open_
responses - Open Responses specification conformance layer.
- orchestrator
- Distributed orchestration primitives for cloud/edge/on-prem scheduling.
- permissions
- persistent_
memory - plugins
- Plugin system for VT Code
- pods
- VT Code GPU pod management.
- primary_
agent - project_
doc - prompts
- System prompt generation with modular architecture
- retry
- Shared retry policy and classification helpers for VT Code.
- review
- safety
- Safety validation utilities
- sandboxing
- Sandboxing module for VT Code
- scheduler
- security
- session
- shutdown
- Shared shutdown signal helpers.
- skills
- Agent Skills Integration
- subagents
- telemetry
- Telemetry pipeline for real-time KPIs and historical benchmarking.
- terminal_
setup - Terminal setup wizard for configuring terminal emulators for optimal VT Code experience.
- tool_
policy - Tool policy management system
- tools
- Tool System Architecture
- trace
- Agent Trace storage layer for VT Code.
- turn_
metadata - Turn metadata for LLM requests
- types
- Type definitions used throughout the application
- ui
- User interface utilities and shared UI components
- utils
- Utility Functions and Helpers
Macros§
- benchmark
- Macro for easy benchmarking
- create_
provider_ builder - Macro kept for source compatibility with older builder-based call sites.
- ctx_err
- Helper macro for context errors Usage: ctx_err!(operation, context) -> “operation context”
- delegate_
components - Wire multiple component names to provider types for a context.
- file_
err - Helper macro for file operation errors with context Usage: file_err!(“path”, “read”) -> “failed to read path”
- model_
family - Macro to simplify model family definitions
Structs§
- Agent
Client Protocol Config - Agent Client Protocol configuration root
- Agent
Client Protocol ZedConfig - Zed-specific configuration
- Agent
Client Protocol ZedTools Config - Zed bridge tool configuration flags
- Agent
Config - Agent-wide configuration
- Agent
Message Item - Bash
Runner - Command
Execution Item - Command
Result - Command execution result
- Context
Config - Context management settings
- Display
Error Formatter - Default formatter that surfaces the error’s display output.
- Error
Item - File
Change Item - File
Update Change - IdeContext
Config - IdeContext
Provider Config - IdeContext
Providers Config - Item
Completed Event - Item
Started Event - Item
Updated Event - Logging
Config - Logging configuration
- Markdown
Storage - Simple markdown storage manager
- McpTool
Call Item - Noop
Error Reporter - Error reporting implementation that drops every event. Useful for tests or when a consumer does not yet integrate with error monitoring.
- Performance
Metrics - Performance metrics
- Plan
Delta Event - Plan
Item - Plugin
Runtime Config - Runtime configuration for dynamic plugin loading.
- Project
Data - Simple project metadata storage
- Project
Storage - Project storage using markdown
- Reasoning
Item - Session
Info - Session information
- Simple
Cache - Simple cache using file system
- Simple
Indexer - Simple file indexer.
- SimpleKV
Storage - Simple key-value storage using markdown
- Simple
Project Manager - Simple project manager that orchestrates project metadata persistence.
- Thread
Item - Thread
Started Event - Tool
Config - Configuration for tool behavior
- Tool
Invocation Item - Tool
Output Item - Turn
Completed Event - Turn
Failed Event - Turn
Started Event - Usage
- VTCode
Config - Main configuration structure for VT Code
- Versioned
Thread Event - Wraps a
ThreadEventwith schema metadata so downstream consumers can negotiate compatibility before processing an event stream. - WebSearch
Item
Enums§
- Agent
Client Protocol Transport - Transport options supported by the ACP bridge
- Analysis
Depth - Analysis depth for workspace analysis
- Capability
Level - Workshop agent capability levels
- Command
Execution Status - IdeContext
Provider Family - IdeContext
Provider Mode - McpTool
Call Status - Output
Format - Output format for commands
- Patch
Apply Status - Patch
Change Kind - Plugin
Trust Level - Trust model for third-party plugins.
- Reasoning
Effort Level - Supported reasoning effort levels configured via vtcode.toml These map to different provider-specific parameters:
- Thread
Event - Structured events emitted during autonomous execution.
- Thread
Item Details - Tool
Call Status - VtCode
Error Category - Canonical error category used throughout VT Code for consistent retry decisions, user-facing messages, and error handling strategies.
- Workspace
Trust Level - Workspace trust levels exposed through the Agent Client Protocol configuration.
Constants§
- ERR_
CANONICALIZE_ PATH - ERR_
CREATE_ AUDIT_ DIR - ERR_
CREATE_ CHECKPOINT_ DIR - ERR_
CREATE_ DIR - ERR_
CREATE_ IPC_ DIR - ERR_
CREATE_ POLICY_ DIR - ERR_
CREATE_ SKILLS_ DIR - ERR_
CREATE_ SKILL_ DIR - ERR_
CREATE_ WORKSPACE_ POLICY_ DIR - ERR_
DELETE_ SKILL - ERR_
DESERIALIZE - ERR_
GET_ FILE_ TYPE - ERR_
GET_ METADATA - ERR_
PARSE_ ARGS - ERR_
PARSE_ REQUEST_ JSON - ERR_
PARSE_ RESULT - ERR_
PARSE_ SKILL_ METADATA - ERR_
READ_ CHECKPOINT - ERR_
READ_ DIR - ERR_
READ_ DIR_ ENTRY - ERR_
READ_ FILE - ERR_
READ_ REQUEST_ FILE - ERR_
READ_ REQUEST_ JSON - ERR_
READ_ SKILLS_ DIR - ERR_
READ_ SKILL_ CODE - ERR_
READ_ SKILL_ METADATA - ERR_
READ_ SYMLINK - ERR_
REMOVE_ DIR - ERR_
REMOVE_ FILE - ERR_
SERIALIZE_ METADATA - ERR_
SERIALIZE_ STATE - ERR_
TOOL_ DENIED - ERR_
WRITE_ AUDIT_ LOG - ERR_
WRITE_ CHECKPOINT - ERR_
WRITE_ FILE - ERR_
WRITE_ SKILL_ CODE - ERR_
WRITE_ SKILL_ DOCS - ERR_
WRITE_ SKILL_ METADATA - EVENT_
SCHEMA_ VERSION - Semantic version of the serialized event schema exported by this crate.
Traits§
- Error
Formatter - Formats an error into a user-facing description. This allows extracted components to present consistent error messaging without depending on the CLI presentation layer.
- Error
Reporter - Reports non-fatal errors to an observability backend.
Functions§
- initialize_
vtcode_ gitignore - Initialize the global .vtcodegitignore instance
- maybe_
run_ zsh_ exec_ wrapper_ mode