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 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 primary_agent::ActivePrimaryAgent;
pub use primary_agent::ActivePrimaryAgentSpecIdentity;
pub use primary_agent::ActivePrimaryAgentState;
pub use primary_agent::PrimaryAgentResolutionError;
pub use primary_agent::active_primary_agent_permissions;
pub use primary_agent::apply_primary_agent_prompt_context;
pub use primary_agent::apply_primary_agent_tool_policy;
pub use primary_agent::build_primary_agent_hook_config;
pub use primary_agent::build_primary_agent_runtime_config;
pub use primary_agent::evaluate_active_primary_agent_permissions;
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 subagents::VerificationResult;
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::AnyClient;
pub use llm::make_client;
pub use memory::MemoryMonitor;
pub use memory::MemoryPressure;
pub use memory::MemoryReport;
pub use memory::RssCheckpoint;
pub use models_manager::ModelPreset;
pub use models_manager::ModelsCache;
pub use models_manager::ModelsManager;
pub use models_manager::builtin_model_presets;
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 prompts::SystemPromptReport;
pub use prompts::generate_lightweight_instruction;
pub use prompts::generate_specialized_instruction;
pub use prompts::measure_system_prompt_size;
pub use retry::RetryPolicyCoreExt;
pub use security::IntegrityTag;
pub use security::PayloadEnvelope;
pub use security::ZeroTrustContext;
pub use telemetry::TelemetryEvent;
pub use telemetry::TelemetryPipeline;
pub use tool_policy::ToolPolicyManager;
pub use tools::OptimizedToolRegistry;
pub use tools::grep_file::GrepSearchManager;
pub use tools::registry::McpBridge;
pub use tools::registry::PtySessionControl;
pub use tools::registry::SharedRegistry;
pub use tools::registry::ToolCatalog;
pub use tools::registry::ToolGroup;
pub use tools::registry::ToolMetrics;
pub use tools::registry::ToolRegistryApi;
pub use tools::registry::ToolResilience;
pub use tools::registry::ToolSecurity;
pub use tools::registry::tool_groups;
pub use tools::ToolRegistration;
pub use tools::ToolRegistry;
pub use ui::diff_renderer::DiffRenderer;
pub use ui::diff_renderer::DiffRendererOptions;
pub use utils::dot_config::CacheConfig;
pub use utils::dot_config::DotConfig;
pub use utils::dot_config::DotManager;
pub use utils::dot_config::LifecycleHookApprovalRecord;
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_lifecycle_hook_approval;
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_lifecycle_hook_approval;
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
execpolicy
gemini
Gemini API compatibility facade for VT Code.
git
Git worktree management for loop isolation.
git_info
Git repository information collection
hooks
http_client
HTTP client utilities
instructions
llm
LLM Integration Layer
loop_memory
Loop memory store for durable loop-engineering state.
loop_state
Loop run state persistence for loop-engineering workflows.
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
permissions
persistent_memory
planning
Canonical plan-mode enter/exit phrase sets and matchers.
plugins
Plugin system for VT Code
pods
VT Code GPU pod management.
primary_agent
project_doc
prompts
System prompt generation with modular architecture
retry
Domain-specific retry adapters 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
Backward-compatible alias: command-level validation now lives in exec_policy::command_validation. 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”

Structs§

AgentClientProtocolConfig
Agent Client Protocol configuration root
AgentClientProtocolZedConfig
Zed-specific configuration
AgentClientProtocolZedToolsConfig
Zed bridge tool configuration flags
AgentConfig
Agent-wide configuration
AgentMessageItem
BashRunner
CodexSandboxManager
Manager for sandbox transformation.
CommandExecutionItem
ConfigGuidance
Actionable guidance for fixing a misconfiguration.
Content
ContextResetEvent
CustomItem
Custom/extension item type.
DisplayErrorFormatter
Default formatter that surfaces the error’s display output.
DualEventEmitter
Adapter that wraps a VT Code event sink and also emits Open Responses events.
ErrorItem
ExecPolicyAmendment
A proposed amendment to the execution policy.
ExecPolicyConfig
Configuration for the execution policy manager.
ExecPolicyManager
Manages execution policies and authorization decisions.
FileChangeItem
FileUpdateChange
FunctionCallItem
A function call item representing a tool invocation request.
FunctionCallOutputItem
Output from a function call execution.
FunctionDeclaration
IncompleteDetails
Details about why a response was incomplete.
InputTokensDetails
Detailed breakdown of input token usage.
ItemCompletedEvent
ItemStartedEvent
ItemUpdatedEvent
MarkdownStorage
Simple markdown storage manager
McpToolCallItem
MessageItem
A message item representing conversation content.
ModelFamily
A model family groups models that share certain characteristics.
MultiErrors
A collection of errors that enables continuing work while collecting failures.
NoopErrorReporter
Error reporting implementation that drops every event. Useful for tests or when a consumer does not yet integrate with error monitoring.
OpenReasoningItem
A reasoning item containing model’s internal thought process.
OpenResponse
The main response object per the Open Responses specification.
OpenResponseError
Structured error object for Open Responses.
OpenResponsesIntegration
Open Responses integration manager.
OpenUsage
Token usage statistics for a response.
OutputItemId
Unique identifier for an output item.
OutputTokensDetails
Detailed breakdown of output token usage.
PerformanceMetrics
Performance metrics
PlanApprovalRequestedEvent
PlanApprovalResolvedEvent
PlanDeltaEvent
PlanItem
PluginRuntimeConfig
Runtime configuration for dynamic plugin loading.
Policy
Execution policy containing rules for command authorization.
PolicyEvaluation
Result of evaluating multiple commands against a policy.
PolicyParser
Parser for policy files.
PrefixRule
A prefix-based rule for matching commands.
ProjectData
Simple project metadata storage
ProjectStorage
Project storage using markdown
ReasoningItem
ResponseBuilder
Builder for constructing Open Responses Response objects from VT Code events.
ResponseId
Unique identifier for a response.
RetryDecision
Result of classifying a failure for retry handling.
RetryPolicy
Typed retry policy shared across runtime layers.
SandboxCommandSpec
Specification for a command to be executed.
SandboxExecEnv
The prepared execution environment after sandbox transformation.
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
ToolDiscovery
Tool discovery service for progressive disclosure of MCP tools.
ToolDiscoveryResult
Result of a tool discovery operation.
ToolInvocationItem
ToolOutputItem
TurnCompletedEvent
TurnFailedEvent
TurnStartedEvent
Usage
VTCodeConfig
Main configuration structure for VT Code
VecStreamEmitter
Vector-based event emitter for collecting events.
VersionedThreadEvent
Wraps a ThreadEvent with schema metadata so downstream consumers can negotiate compatibility before processing an event stream.
WebSearchItem
WritableRoot
A root directory that may be written to under the sandbox policy.

Enums§

AgentClientProtocolTransport
Transport options supported by the ACP bridge
AnalysisDepth
Analysis depth for workspace analysis
AskForApproval
Policy for when to ask for approval before executing commands.
CapabilityLevel
Workshop agent capability levels
CodexSandboxPermissions
Fine-grained permissions for sandbox operations.
CodexSandboxPolicy
Sandbox policy determining what operations are permitted during execution.
CommandExecutionStatus
ContentPart
Content part types supported by Open Responses.
ContextResetTrigger
Decision
Decision made by a policy rule.
DetailLevel
Level of detail returned in tool search results.
ExecApprovalRequirement
Requirement for approval before executing a command.
ExecExpiration
Mechanism to terminate an exec invocation before it finishes naturally.
IncompleteReason
Reasons why a response may be incomplete.
ItemStatus
Lifecycle status for items in the Open Responses model.
McpToolCallStatus
MessageRole
Role of a message author.
MisconfigurationKind
Kind of user misconfiguration detected.
OpenResponseErrorCode
Specific error codes providing additional detail.
OpenResponseErrorType
Category of error that occurred.
OutputFormat
Output format for commands
OutputItem
Output items generated by the model.
Part
IMPORTANT: Variant ordering matters for #[serde(untagged)] deserialization. Serde tries variants in declaration order and returns the first successful match. Variants with required fields (FunctionCall, FunctionResponse, InlineData, Text) must come BEFORE CacheControl, which has only optional fields and would otherwise act as a catch-all, matching any JSON object.
PatchApplyStatus
PatchChangeKind
PlanApprovalDecision
PluginTrustLevel
Trust model for third-party plugins.
ReasoningEffortLevel
Supported reasoning effort levels configured via vtcode.toml These map to different provider-specific parameters:
ResponseStatus
Status of a response.
ResponseStreamEvent
Semantic streaming events per the Open Responses specification.
RuleMatch
Result of matching a command against a rule.
SandboxType
Type of sandbox being used.
ThreadEvent
Structured events emitted during autonomous execution.
ThreadItemDetails
ToolCallStatus
ToolPolicy
Tool execution policy
ToolProfile
Model-facing tool profile for a session.
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.
OpenResponsesProvider
Trait for types that can provide Open Responses integration.
StreamEventEmitter
Trait for emitting Open Responses streaming events.
ToOpenResponse
Extension trait for converting VT Code LLM responses to Open Responses format.

Functions§

find_family_for_model
Internal helper that returns a ModelFamily for the given model slug.
generate_item_id
Generates a unique output item ID.
generate_response_id
Generates a unique response ID.
initialize_vtcode_gitignore
Initialize the global .vtcodegitignore instance
maybe_run_zsh_exec_wrapper_mode
validate_mcp_config
Validate MCP configuration settings

Type Aliases§

OpenResponsesCallback
Callback type for receiving Open Responses streaming events.
SharedExecPolicyManager
Shared reference to an ExecPolicyManager.