Skip to main content

Crate vtcode_core

Crate vtcode_core 

Source
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 in config::constants and curated metadata in docs/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_file stays disabled unless Zed advertises fs.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 plan entries track analysis, context gathering, and response drafting for timeline parity with Zed.
  • Absolute-path checks guard every read_file argument 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 exec_policy::SharedExecPolicyManager;
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§

AgentClientProtocolConfig
Agent Client Protocol configuration root
AgentClientProtocolZedConfig
Zed-specific configuration
AgentClientProtocolZedToolsConfig
Zed bridge tool configuration flags
AgentConfig
Agent-wide configuration
AgentMessageItem
BashRunner
CommandExecutionItem
CommandResult
Command execution result
ContextConfig
Context management settings
DisplayErrorFormatter
Default formatter that surfaces the error’s display output.
ErrorItem
FileChangeItem
FileUpdateChange
IdeContextConfig
IdeContextProviderConfig
IdeContextProvidersConfig
ItemCompletedEvent
ItemStartedEvent
ItemUpdatedEvent
LoggingConfig
Logging configuration
MarkdownStorage
Simple markdown storage manager
McpToolCallItem
NoopErrorReporter
Error reporting implementation that drops every event. Useful for tests or when a consumer does not yet integrate with error monitoring.
PerformanceMetrics
Performance metrics
PlanDeltaEvent
PlanItem
PluginRuntimeConfig
Runtime configuration for dynamic plugin loading.
ProjectData
Simple project metadata storage
ProjectStorage
Project storage using markdown
ReasoningItem
SessionInfo
Session information
SimpleCache
Simple cache using file system
SimpleIndexer
Simple file indexer.
SimpleKVStorage
Simple key-value storage using markdown
SimpleProjectManager
Simple project manager that orchestrates project metadata persistence.
ThreadItem
ThreadStartedEvent
ToolConfig
Configuration for tool behavior
ToolInvocationItem
ToolOutputItem
TurnCompletedEvent
TurnFailedEvent
TurnStartedEvent
Usage
VTCodeConfig
Main configuration structure for VT Code
VersionedThreadEvent
Wraps a ThreadEvent with schema metadata so downstream consumers can negotiate compatibility before processing an event stream.
WebSearchItem

Enums§

AgentClientProtocolTransport
Transport options supported by the ACP bridge
AnalysisDepth
Analysis depth for workspace analysis
CapabilityLevel
Workshop agent capability levels
CommandExecutionStatus
IdeContextProviderFamily
IdeContextProviderMode
McpToolCallStatus
OutputFormat
Output format for commands
PatchApplyStatus
PatchChangeKind
PluginTrustLevel
Trust model for third-party plugins.
ReasoningEffortLevel
Supported reasoning effort levels configured via vtcode.toml These map to different provider-specific parameters:
ThreadEvent
Structured events emitted during autonomous execution.
ThreadItemDetails
ToolCallStatus
VtCodeErrorCategory
Canonical error category used throughout VT Code for consistent retry decisions, user-facing messages, and error handling strategies.
WorkspaceTrustLevel
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§

ErrorFormatter
Formats an error into a user-facing description. This allows extracted components to present consistent error messaging without depending on the CLI presentation layer.
ErrorReporter
Reports non-fatal errors to an observability backend.

Functions§

initialize_vtcode_gitignore
Initialize the global .vtcodegitignore instance
maybe_run_zsh_exec_wrapper_mode