1#![cfg_attr(
2 not(test),
3 allow(
4 clippy::large_futures,
5 reason = "Core async orchestration intentionally keeps some large stateful futures together."
6 )
7)]
8#![allow(
10 clippy::expect_used,
11 clippy::panic,
12 clippy::unnecessary_safety_comment,
13 clippy::unreachable,
14 clippy::unwrap_used,
15 missing_docs,
16 reason = "Core exposes compatibility and feature-gated surfaces whose documentation is maintained in project guides."
17)]
18#![expect(
19 unused_results,
20 clippy::let_underscore_must_use,
21 clippy::indexing_slicing,
22 clippy::string_slice,
23 clippy::cast_possible_truncation,
24 clippy::cast_possible_wrap,
25 reason = "Core runtime code intentionally maintains side-effect-only caches, validated text offsets, and protocol-sized counters across feature-gated paths."
26)]
27#![recursion_limit = "256"]
28pub mod a2a; pub mod acp;
154#[cfg(feature = "anthropic-api")]
155pub mod anthropic_api; pub mod audit;
157pub mod auth; pub mod cache; pub mod cli;
160pub mod code;
161pub mod command_safety; pub mod commands;
163pub mod compaction;
164pub mod components; pub mod config;
166pub mod constants;
167pub mod context; pub mod copilot {
170 pub use vtcode_llm::copilot::*;
171}
172pub mod core;
173pub mod diagnostics;
174pub mod dotfile_protection; pub mod error; pub mod exec;
177pub mod exec_policy; pub use components::delegate_components;
180pub use exec_policy::command_validation as execpolicy;
181pub mod gemini; pub mod git; pub mod git_info; pub mod hooks;
185pub mod http_client;
186mod id_newtype;
187pub mod instructions;
188pub mod llm;
189pub mod loop_memory; pub mod loop_state; pub mod marketplace;
192pub mod mcp;
193pub mod memory; pub mod metrics;
195pub mod models;
196pub mod models_manager; pub mod notifications;
198pub mod open_responses {
200 pub use vtcode_llm::open_responses::*;
201}
202pub mod permissions;
203pub mod persistent_memory;
204pub mod planning; pub mod plugins;
206pub mod pods;
207pub mod primary_agent;
208pub mod project_doc;
209pub mod prompts;
210pub mod retry;
211mod retry_after;
212pub mod review;
213pub mod safety;
214pub mod sandboxing; pub mod scheduler;
216pub mod security;
217pub mod session;
218pub mod shutdown;
219pub mod skills;
220pub mod subagents;
221pub mod telemetry;
222pub mod tool_policy;
223pub mod tools;
224pub mod trace; pub mod turn_metadata; pub mod types;
227pub mod utils;
228mod zsh_exec_bridge;
229
230pub use vtcode_commons::errors::*;
232pub use vtcode_commons::{ctx_err, file_err};
233
234pub use cli::args::{Cli, Commands};
237pub use code::code_completion::{CompletionEngine, CompletionSuggestion};
238pub use commands::stats::handle_stats_command;
239pub use config::types::{
240 AnalysisDepth, CapabilityLevel, OutputFormat, PerformanceMetrics, ReasoningEffortLevel, SessionInfo,
241};
242pub use config::{
243 AgentClientProtocolConfig, AgentClientProtocolTransport, AgentClientProtocolZedConfig,
244 AgentClientProtocolZedToolsConfig, AgentConfig, PluginRuntimeConfig, PluginTrustLevel, ToolProfile, VTCodeConfig,
245 WorkspaceTrustLevel,
246};
247pub use core::agent::core::Agent;
248pub use core::agent::runner::AgentRunner;
249pub use core::agent::task::{
250 ContextItem as RunnerContextItem, Task as RunnerTask, TaskOutcome as RunnerTaskOutcome,
251 TaskResults as RunnerTaskResults,
252};
253pub use core::memory_pool::{MemoryPool, global_pool};
254pub use core::performance_profiler::{BenchmarkResults, BenchmarkUtils, PerformanceProfiler};
255pub use core::threads::{
256 SubmissionId, ThreadBootstrap, ThreadEventRecord, ThreadId, ThreadManager, ThreadRuntimeHandle, ThreadSnapshot,
257 build_thread_archive_metadata, loaded_skills_from_session_listing, messages_from_session_listing,
258};
259pub use primary_agent::{
260 ActivePrimaryAgent, ActivePrimaryAgentSpecIdentity, ActivePrimaryAgentState, PrimaryAgentResolutionError,
261 active_primary_agent_permissions, apply_primary_agent_prompt_context, apply_primary_agent_tool_policy,
262 build_primary_agent_hook_config, build_primary_agent_runtime_config, evaluate_active_primary_agent_permissions,
263 resolve_discovered_primary_agent, resolve_primary_agent,
264};
265pub use subagents::{
266 SendInputRequest as SubagentSendInputRequest, SpawnAgentRequest as SubagentSpawnRequest,
267 SpawnBackgroundSubprocessRequest as SubagentSpawnBackgroundSubprocessRequest, SubagentController,
268 SubagentControllerConfig, SubagentInputItem, SubagentStatus, SubagentStatusEntry, VerificationResult,
269};
270pub use vtcode_bash_runner::BashRunner;
271
272pub use core::prompt_caching::{CacheStats, PromptCache, PromptCacheConfig, PromptOptimizer};
273pub use core::timeout_detector::TimeoutDetector;
274pub use diagnostics::{
275 DiagnosticReport, HealthSample, LabeledAction, PredictiveMonitor, RecoveryAction, RecoveryPlaybook,
276};
277pub use dotfile_protection::{
278 AccessType as DotfileAccessType, AuditEntry as DotfileAuditEntry, AuditLog as DotfileAuditLog,
279 AuditOutcome as DotfileAuditOutcome, BackupManager as DotfileBackupManager, DotfileBackup, DotfileGuardian,
280 ProtectionDecision, ProtectionViolation, get_global_guardian, init_global_guardian, is_protected_dotfile,
281};
282pub use error::{
283 ConfigGuidance, ErrorCategory as VtCodeErrorCategory, ErrorCode as VtCodeErrorCode, MisconfigurationKind,
284 Result as VtCodeResult, VtCodeError,
285};
286pub use exec::events::{
287 AgentMessageItem, CommandExecutionItem, CommandExecutionStatus, ContextResetEvent, ContextResetTrigger,
288 EVENT_SCHEMA_VERSION, ErrorItem, FileChangeItem, FileUpdateChange, ItemCompletedEvent, ItemStartedEvent,
289 ItemUpdatedEvent, McpToolCallItem, McpToolCallStatus, PatchApplyStatus, PatchChangeKind, PlanApprovalDecision,
290 PlanApprovalRequestedEvent, PlanApprovalResolvedEvent, PlanDeltaEvent, PlanItem, ReasoningItem, ThreadEvent,
291 ThreadItem, ThreadItemDetails, ThreadStartedEvent, ToolCallStatus, ToolInvocationItem, ToolOutputItem,
292 TurnCompletedEvent, TurnFailedEvent, TurnStartedEvent, Usage, VersionedThreadEvent, WebSearchItem,
293};
294pub use exec::{CodeExecutor, ExecutionConfig, ExecutionResult, Language};
295pub use llm::providers::gemini::wire::{Content, FunctionDeclaration, Part};
296pub use llm::{AnyClient, make_client};
297pub use mcp::{
298 tool_discovery::{DetailLevel, ToolDiscovery, ToolDiscoveryResult},
299 validate_mcp_config,
300};
301pub use memory::{MemoryMonitor, MemoryPressure, MemoryReport, RssCheckpoint};
302pub use models_manager::{
303 ModelFamily, ModelPreset, ModelsCache, ModelsManager, builtin_model_presets, model_family::find_family_for_model,
304};
305pub use notifications::{
306 NotificationConfig, NotificationEvent, NotificationManager, apply_global_notification_config,
307 apply_global_notification_config_from_vtcode, get_global_notification_manager, init_global_notification_manager,
308 init_global_notification_manager_with_config, notify_command_failure, notify_error, notify_human_in_the_loop,
309 notify_tool_failure, notify_tool_success, send_global_notification,
310};
311pub use pods::*;
312pub use prompts::SystemPromptReport;
313pub use prompts::{generate_lightweight_instruction, generate_specialized_instruction, measure_system_prompt_size};
314pub use retry::{RetryDecision, RetryPolicy, RetryPolicyCoreExt};
315pub use security::{IntegrityTag, PayloadEnvelope, ZeroTrustContext};
316pub use telemetry::{TelemetryEvent, TelemetryPipeline};
317pub use zsh_exec_bridge::maybe_run_zsh_exec_wrapper_mode;
318
319pub use open_responses::{
321 ContentPart, CustomItem, DualEventEmitter, FunctionCallItem, FunctionCallOutputItem, IncompleteDetails,
322 IncompleteReason, InputTokensDetails, ItemStatus, MessageItem, MessageRole, OpenResponseError,
323 OpenResponseErrorCode, OpenResponseErrorType, OpenResponsesCallback, OpenResponsesIntegration,
324 OpenResponsesProvider, OpenUsage, OutputItem, OutputItemId, OutputTokensDetails,
325 ReasoningItem as OpenReasoningItem, Response as OpenResponse, ResponseBuilder, ResponseId, ResponseStatus,
326 ResponseStreamEvent, StreamEventEmitter, ToOpenResponse, VecStreamEmitter, generate_item_id, generate_response_id,
327};
328
329pub use tool_policy::{ToolPolicy, ToolPolicyManager};
330
331pub use exec_policy::{
333 AskForApproval, Decision, ExecApprovalRequirement, ExecPolicyAmendment, ExecPolicyConfig, ExecPolicyManager,
334 Policy, PolicyEvaluation, PolicyParser, PrefixRule, RuleMatch, SharedExecPolicyManager,
335};
336pub use sandboxing::{
337 CommandSpec as SandboxCommandSpec, ExecEnv as SandboxExecEnv, ExecExpiration,
338 SandboxManager as CodexSandboxManager, SandboxPermissions as CodexSandboxPermissions,
339 SandboxPolicy as CodexSandboxPolicy, SandboxType, WritableRoot,
340};
341
342pub use tools::grep_file::GrepSearchManager;
343pub use tools::registry::{
344 McpBridge, PtySessionControl, SharedRegistry, ToolCatalog, ToolGroup, ToolMetrics, ToolRegistryApi, ToolResilience,
345 ToolSecurity, tool_groups,
346};
347pub use tools::{ToolRegistration, ToolRegistry};
348pub use utils::dot_config::{
349 CacheConfig, DotConfig, DotManager, LifecycleHookApprovalRecord, ProviderConfigs, UiConfig, UserPreferences,
350 WorkspaceTrustRecord, WorkspaceTrustStore, initialize_dot_folder, load_lifecycle_hook_approval, load_user_config,
351 load_workspace_trust_level, save_user_config, update_lifecycle_hook_approval, update_model_preference,
352 update_theme_preference, update_workspace_trust,
353};
354pub use utils::vtcodegitignore::initialize_vtcode_gitignore;
355pub use vtcode_indexer::SimpleIndexer;
356pub use vtcode_indexer::markdown_store::{
357 MarkdownStorage, ProjectData, ProjectStorage, SimpleCache, SimpleKVStorage, SimpleProjectManager,
358};
359
360#[cfg(test)]
361mod memory_tests;
362
363#[cfg(test)]
364mod memory_integration_tests;
365
366#[cfg(test)]
367mod config_verification_tests;
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 use tempfile::TempDir;
374
375 struct CwdGuard {
376 previous: std::path::PathBuf,
377 }
378
379 impl CwdGuard {
380 fn new() -> Self {
381 let previous = std::env::current_dir().expect("current dir");
382 Self { previous }
383 }
384 }
385
386 impl Drop for CwdGuard {
387 fn drop(&mut self) {
388 let _ = std::env::set_current_dir(&self.previous);
389 }
390 }
391
392 #[tokio::test]
393 async fn test_library_exports() {
394 let _cache = PromptCache::new().await;
396 }
397
398 #[test]
399 fn test_module_structure() {
400 }
403
404 #[test]
405 fn test_version_consistency() {
406 }
409
410 #[tokio::test]
411 async fn test_tool_registry_integration() {
412 let temp_dir = TempDir::new().expect("Failed to create temp dir");
413 let _cwd_guard = CwdGuard::new();
414 std::env::set_current_dir(&temp_dir).expect("Failed to change dir");
415
416 let registry = ToolRegistry::new(temp_dir.path().to_path_buf()).await;
417 registry.initialize_async().await.expect("Failed to init registry");
418
419 let list_args = serde_json::json!({
421 "path": "."
422 });
423
424 let result = registry.list_files(list_args).await;
425 assert!(result.is_ok());
426
427 let response: serde_json::Value = result.expect("Failed to execute list_files");
428 assert!(response.is_object() || response.is_array());
429 }
430
431 #[tokio::test]
432 async fn test_pty_basic_command() {
433 let temp_dir = TempDir::new().expect("Failed to create temp dir");
434 let workspace = temp_dir.path().to_path_buf();
435 let registry = ToolRegistry::new(workspace.clone()).await;
436 registry.initialize_async().await.expect("Failed to init registry");
437
438 let args = serde_json::json!({
440 "command": "echo",
441 "args": ["Hello, PTY!"]
442 });
443
444 let result = registry.execute_tool("run_pty_cmd", args).await;
445 assert!(result.is_ok());
446 let response: serde_json::Value = result.expect("Failed to run PTY");
447 assert_eq!(response["is_exited"], true);
448 assert_eq!(response["exit_code"], 0);
449 assert!(response["output"].is_string());
450 }
451
452 #[tokio::test]
453 async fn test_pty_session_management() {
454 let temp_dir = TempDir::new().expect("Failed to create temp dir");
455 let workspace = temp_dir.path().to_path_buf();
456 std::fs::write(workspace.join("vtcode.toml"), "[workspace]\nuse_root_config = true\n")
457 .expect("write isolated workspace config");
458 let registry = ToolRegistry::new(workspace.clone()).await;
459 registry.initialize_async().await.expect("Failed to init registry");
460
461 let args = serde_json::json!({
463 "command": "cat",
464 "yield_time_ms": 10
465 });
466
467 let result = registry.execute_tool("create_pty_session", args).await;
468 assert!(result.is_ok());
469 let response: serde_json::Value = result.expect("Failed to create PTY session");
470 assert_eq!(response["success"], true);
471 assert_eq!(response["is_exited"], false);
472 let session_id = response["session_id"]
473 .as_str()
474 .expect("create_pty_session should return a session id")
475 .to_string();
476 assert!(!session_id.is_empty());
477
478 let args = serde_json::json!({});
480 let result = registry.execute_tool("list_pty_sessions", args).await;
481 assert!(result.is_ok());
482 let response: serde_json::Value = result.expect("Failed to list PTY sessions");
483 assert!(response.is_object() || response.is_array());
484
485 let args = serde_json::json!({
487 "session_id": session_id.clone()
488 });
489
490 let result = registry.execute_tool("close_pty_session", args).await;
491 assert!(result.is_ok());
492 let response: serde_json::Value = result.expect("Failed to close PTY session");
493 assert_eq!(response["success"], true);
494 assert_eq!(response["session_id"], session_id);
495 }
496}