vtcode-core 0.104.1

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Dynamic Skill Discovery System
//!
//! Implements filesystem-based skill discovery with support for:
//! - Traditional VT Code skills (SKILL.md files)
//! - CLI tool skills (executable + README.md)
//! - Auto-discovery of tools in standard locations
//! - Progressive metadata loading

use crate::skills::cli_bridge::{CliToolBridge, CliToolConfig, discover_cli_tools};
use crate::skills::manifest::parse_skill_file;
use crate::skills::types::{SkillContext, SkillManifest, SkillVariety};
use anyhow::Result;
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Enhanced skill discovery configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoveryConfig {
    /// Search paths for traditional skills
    pub skill_paths: Vec<PathBuf>,

    /// Search paths for CLI tools
    pub tool_paths: Vec<PathBuf>,

    /// Auto-discover system tools
    pub auto_discover_system_tools: bool,

    /// Maximum depth for recursive directory scanning
    pub max_depth: usize,

    /// File patterns to consider as skills
    pub skill_patterns: Vec<String>,

    /// Tool file patterns
    pub tool_patterns: Vec<String>,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            skill_paths: Vec::new(),
            tool_paths: vec![
                PathBuf::from("./tools"),
                PathBuf::from("./vendor/tools"),
                PathBuf::from("~/.vtcode/tools"),
            ],
            auto_discover_system_tools: false,
            max_depth: 3,
            skill_patterns: vec!["SKILL.md".to_string()],
            tool_patterns: vec!["*.exe".to_string(), "*.sh".to_string(), "*.py".to_string()],
        }
    }
}

/// Discovery result containing both traditional skills and CLI tools
#[derive(Debug, Clone)]
pub struct DiscoveryResult {
    /// Traditional VT Code skills
    pub skills: Vec<SkillContext>,

    /// CLI tool configurations
    pub tools: Vec<CliToolConfig>,

    /// Discovery statistics
    pub stats: DiscoveryStats,
}

/// Discovery statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiscoveryStats {
    pub directories_scanned: usize,
    pub files_checked: usize,
    pub skills_found: usize,
    pub tools_found: usize,
    pub errors_encountered: usize,
    pub discovery_time_ms: u64,
}

/// Dynamic skill discovery engine
pub struct SkillDiscovery {
    config: DiscoveryConfig,
    cache: HashMap<PathBuf, DiscoveryCacheEntry>,
}

#[derive(Debug, Clone)]
struct DiscoveryCacheEntry {
    #[allow(dead_code)]
    timestamp: std::time::SystemTime,
    skills: Vec<SkillContext>,
    tools: Vec<CliToolConfig>,
}

impl SkillDiscovery {
    /// Create new discovery engine with default configuration
    pub fn new() -> Self {
        Self::with_config(DiscoveryConfig::default())
    }

    /// Create new discovery engine with custom configuration
    pub fn with_config(config: DiscoveryConfig) -> Self {
        Self {
            config,
            cache: HashMap::new(),
        }
    }
}

impl Default for SkillDiscovery {
    fn default() -> Self {
        Self::new()
    }
}

impl SkillDiscovery {
    /// Discover all available skills and tools
    pub async fn discover_all(&mut self, workspace_root: &Path) -> Result<DiscoveryResult> {
        let start_time = std::time::Instant::now();
        let mut stats = DiscoveryStats::default();

        info!("Starting skill discovery in: {}", workspace_root.display());

        // Discover traditional skills
        let skills = self
            .discover_traditional_skills(workspace_root, &mut stats)
            .await?;

        // Discover CLI tools
        let tools = self.discover_cli_tools(workspace_root, &mut stats).await?;

        // Auto-discover system tools if enabled
        if self.config.auto_discover_system_tools {
            let system_tools = self.discover_system_tools(&mut stats).await?;
            let mut all_tools = tools;
            all_tools.extend(system_tools);

            stats.discovery_time_ms = start_time.elapsed().as_millis() as u64;

            Ok(DiscoveryResult {
                skills,
                tools: all_tools,
                stats,
            })
        } else {
            stats.discovery_time_ms = start_time.elapsed().as_millis() as u64;

            Ok(DiscoveryResult {
                skills,
                tools,
                stats,
            })
        }
    }

    /// Discover traditional VT Code skills
    async fn discover_traditional_skills(
        &mut self,
        workspace_root: &Path,
        stats: &mut DiscoveryStats,
    ) -> Result<Vec<SkillContext>> {
        let mut skills = vec![];
        let skill_paths = if self.config.skill_paths.is_empty() {
            default_skill_paths(workspace_root)
        } else {
            self.config.skill_paths.clone()
        };

        for skill_path in &skill_paths {
            let full_path = self.expand_path(skill_path, workspace_root);

            if !full_path.exists() {
                debug!("Skill path does not exist: {}", full_path.display());
                continue;
            }

            stats.directories_scanned += 1;

            // Scan for skill directories
            match self.scan_for_skills(&full_path, stats) {
                Ok(found_skills) => {
                    info!(
                        "Found {} skills in {}",
                        found_skills.len(),
                        full_path.display()
                    );
                    skills.extend(found_skills);
                }
                Err(e) => {
                    warn!("Failed to scan {}: {}", full_path.display(), e);
                    stats.errors_encountered += 1;
                }
            }
        }

        Ok(skills)
    }

    /// Scan directory for traditional skills
    fn scan_for_skills(&self, dir: &Path, stats: &mut DiscoveryStats) -> Result<Vec<SkillContext>> {
        self.scan_for_skills_recursive(dir, stats, 0)
    }

    fn scan_for_skills_recursive(
        &self,
        dir: &Path,
        stats: &mut DiscoveryStats,
        depth: usize,
    ) -> Result<Vec<SkillContext>> {
        let mut skills = vec![];

        if depth > self.config.max_depth {
            return Ok(skills);
        }

        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_dir() {
                stats.directories_scanned += 1;

                // Check for SKILL.md file
                let skill_file = path.join("SKILL.md");
                if skill_file.exists() {
                    stats.files_checked += 1;

                    match parse_skill_file(&path) {
                        Ok((manifest, _instructions)) => {
                            skills.push(SkillContext::MetadataOnly(manifest, path.to_path_buf()));
                            stats.skills_found += 1;
                            let skill_name = skills
                                .last()
                                .map(|ctx| ctx.manifest().name.clone())
                                .unwrap_or_else(|| "<unknown>".to_string());
                            info!("Discovered skill: {} from {}", skill_name, path.display());
                        }
                        Err(e) => {
                            warn!("Failed to parse skill from {}: {}", path.display(), e);
                            stats.errors_encountered += 1;
                        }
                    }
                }

                if depth < self.config.max_depth {
                    skills.extend(self.scan_for_skills_recursive(&path, stats, depth + 1)?);
                }
            }
        }

        Ok(skills)
    }

    /// Discover CLI tools in workspace
    async fn discover_cli_tools(
        &mut self,
        workspace_root: &Path,
        stats: &mut DiscoveryStats,
    ) -> Result<Vec<CliToolConfig>> {
        let mut tools = vec![];

        for tool_path in &self.config.tool_paths {
            let full_path = self.expand_path(tool_path, workspace_root);

            if !full_path.exists() {
                debug!("Tool path does not exist: {}", full_path.display());
                continue;
            }

            stats.directories_scanned += 1;

            match self.scan_for_tools(&full_path, stats).await {
                Ok(found_tools) => {
                    info!(
                        "Found {} tools in {}",
                        found_tools.len(),
                        full_path.display()
                    );
                    tools.extend(found_tools);
                }
                Err(e) => {
                    warn!("Failed to scan {}: {}", full_path.display(), e);
                    stats.errors_encountered += 1;
                }
            }
        }

        Ok(tools)
    }

    /// Scan directory for CLI tools
    async fn scan_for_tools(
        &self,
        dir: &Path,
        stats: &mut DiscoveryStats,
    ) -> Result<Vec<CliToolConfig>> {
        let mut tools = vec![];

        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_file() {
                stats.files_checked += 1;

                // Check if it's an executable
                if self.is_executable(&entry)? {
                    // Look for accompanying documentation
                    let readme_path = self.find_tool_readme(&path);
                    let schema_path = self.find_tool_schema(&path);

                    let tool_name = path
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("unknown")
                        .to_string();

                    let config = CliToolConfig {
                        name: tool_name.clone(),
                        description: format!("CLI tool: {}", tool_name),
                        executable_path: path.clone(),
                        readme_path,
                        schema_path,
                        timeout_seconds: Some(30),
                        supports_json: false,
                        environment: None,
                        working_dir: Some(dir.to_path_buf()),
                    };

                    tools.push(config);
                    stats.tools_found += 1;
                    debug!("Discovered CLI tool: {} from {}", tool_name, path.display());
                }
            }
        }

        Ok(tools)
    }

    /// Discover system-wide CLI tools
    async fn discover_system_tools(
        &self,
        stats: &mut DiscoveryStats,
    ) -> Result<Vec<CliToolConfig>> {
        info!("Auto-discovering system CLI tools");

        match discover_cli_tools() {
            Ok(tools) => {
                stats.tools_found += tools.len();
                Ok(tools)
            }
            Err(e) => {
                warn!("Failed to auto-discover system tools: {}", e);
                stats.errors_encountered += 1;
                Ok(vec![])
            }
        }
    }

    /// Check if file is executable
    fn is_executable(&self, entry: &std::fs::DirEntry) -> Result<bool> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let metadata = entry.metadata()?;
            let permissions = metadata.permissions();
            Ok(permissions.mode() & 0o111 != 0)
        }

        #[cfg(windows)]
        {
            if let Some(ext) = entry.path().extension() {
                Ok(ext == "exe" || ext == "bat" || ext == "cmd")
            } else {
                Ok(false)
            }
        }
    }

    /// Find README file for tool
    fn find_tool_readme(&self, tool_path: &Path) -> Option<PathBuf> {
        let tool_name = tool_path.file_stem()?;
        let readme_name = format!("{}.md", tool_name.to_str()?);
        let readme_path = tool_path.with_file_name(&readme_name);

        if readme_path.exists() {
            Some(readme_path)
        } else {
            // Try generic README.md
            let generic_readme = tool_path.parent()?.join("README.md");
            if generic_readme.exists() {
                Some(generic_readme)
            } else {
                None
            }
        }
    }

    /// Find JSON schema file for tool
    fn find_tool_schema(&self, tool_path: &Path) -> Option<PathBuf> {
        let tool_name = tool_path.file_stem()?;
        let schema_name = format!("{}.json", tool_name.to_str()?);
        let schema_path = tool_path.with_file_name(&schema_name);

        if schema_path.exists() {
            Some(schema_path)
        } else {
            // Try tool.json
            let tool_json = tool_path.parent()?.join("tool.json");
            if tool_json.exists() {
                Some(tool_json)
            } else {
                None
            }
        }
    }

    /// Expand path with workspace root and home directory
    fn expand_path(&self, path: &Path, workspace_root: &Path) -> PathBuf {
        if path.starts_with("~") {
            // Expand home directory
            if let Ok(home) = std::env::var("HOME") {
                let stripped = path.strip_prefix("~").unwrap_or(path);
                return PathBuf::from(home).join(stripped);
            }
        }

        if path.is_relative() {
            // Make relative to workspace root
            workspace_root.join(path)
        } else {
            path.to_path_buf()
        }
    }

    /// Get cached discovery result for path
    #[allow(dead_code)]
    fn get_cached(&self, path: &Path) -> Option<&DiscoveryCacheEntry> {
        self.cache.get(path).and_then(|entry| {
            // Check if cache is still valid (5 minutes)
            let elapsed = entry.timestamp.elapsed().ok()?;
            if elapsed.as_secs() < 300 {
                Some(entry)
            } else {
                None
            }
        })
    }

    /// Cache discovery result
    #[allow(dead_code)]
    fn cache_result(
        &mut self,
        path: PathBuf,
        skills: Vec<SkillContext>,
        tools: Vec<CliToolConfig>,
    ) {
        self.cache.insert(
            path,
            DiscoveryCacheEntry {
                timestamp: std::time::SystemTime::now(),
                skills,
                tools,
            },
        );
    }

    /// Clear discovery cache
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        info!("Discovery cache cleared");
    }

    /// Get discovery statistics
    pub fn get_stats(&self) -> DiscoveryStats {
        DiscoveryStats {
            directories_scanned: 0,
            files_checked: 0,
            skills_found: self.cache.values().map(|entry| entry.skills.len()).sum(),
            tools_found: self.cache.values().map(|entry| entry.tools.len()).sum(),
            errors_encountered: 0,
            discovery_time_ms: 0,
        }
    }
}

fn default_codex_home() -> PathBuf {
    std::env::var_os("CODEX_HOME")
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .or_else(|| dirs::home_dir().map(|home| home.join(".codex")))
        .unwrap_or_else(|| PathBuf::from(".codex"))
}

fn default_skill_paths(workspace_root: &Path) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    let stop = find_git_root(workspace_root).unwrap_or_else(|| workspace_root.to_path_buf());
    let mut current = workspace_root.to_path_buf();

    loop {
        paths.push(current.join(".agents/skills"));
        if current == stop {
            break;
        }
        let Some(parent) = current.parent() else {
            break;
        };
        current = parent.to_path_buf();
    }

    if let Some(home) = dirs::home_dir() {
        paths.push(home.join(".agents/skills"));
    }
    #[cfg(unix)]
    paths.push(PathBuf::from("/etc/codex/skills"));
    paths.push(crate::skills::system::system_cache_root_dir(
        &default_codex_home(),
    ));
    paths
}

fn find_git_root(path: &Path) -> Option<PathBuf> {
    let mut current = Some(path);
    while let Some(dir) = current {
        if dir.join(".git").exists() {
            return Some(dir.to_path_buf());
        }
        current = dir.parent();
    }
    None
}

/// Convert CLI tool configuration to SkillContext
pub fn tool_config_to_skill_context(config: &CliToolConfig) -> Result<SkillContext> {
    let manifest = SkillManifest {
        name: config.name.clone(),
        description: config.description.clone(),
        version: Some("1.0.0".to_string()),
        author: Some("VT Code CLI Discovery".to_string()),
        variety: SkillVariety::SystemUtility,
        ..Default::default()
    };

    Ok(SkillContext::MetadataOnly(
        manifest,
        config.executable_path.clone(),
    ))
}

/// Progressive skill loader that can load full skill details on demand
pub struct ProgressiveSkillLoader {
    discovery: SkillDiscovery,
    skill_cache: HashMap<String, crate::skills::types::Skill>,
    #[allow(dead_code)]
    tool_cache: HashMap<String, CliToolBridge>,
}

impl ProgressiveSkillLoader {
    pub fn new(config: DiscoveryConfig) -> Self {
        Self {
            discovery: SkillDiscovery::with_config(config),
            skill_cache: HashMap::new(),
            tool_cache: HashMap::new(),
        }
    }

    /// Get skill metadata (lightweight)
    pub async fn get_skill_metadata(
        &mut self,
        workspace_root: &Path,
        name: &str,
    ) -> Result<SkillContext> {
        let result = self.discovery.discover_all(workspace_root).await?;

        // Check traditional skills
        for skill in &result.skills {
            if skill.manifest().name == name {
                return Ok(skill.clone());
            }
        }

        // Check CLI tools
        for tool in &result.tools {
            if tool.name == name {
                return tool_config_to_skill_context(tool);
            }
        }

        Err(anyhow::anyhow!("Skill '{}' not found", name))
    }

    /// Load full skill with instructions and resources
    pub async fn load_full_skill(
        &mut self,
        workspace_root: &Path,
        name: &str,
    ) -> Result<crate::skills::types::Skill> {
        // Check cache first
        if let Some(skill) = self.skill_cache.get(name) {
            return Ok(skill.clone());
        }

        let result = self.discovery.discover_all(workspace_root).await?;

        // Try traditional skills first
        for skill_ctx in &result.skills {
            if skill_ctx.manifest().name == name {
                // Load full skill details
                // This would require path information - simplified for now
                let manifest = skill_ctx.manifest().clone();
                let skill = crate::skills::types::Skill::new(
                    manifest,
                    workspace_root.to_path_buf(),
                    "# Full instructions would be loaded here".to_string(),
                )?;

                self.skill_cache.insert(name.to_string(), skill.clone());
                return Ok(skill);
            }
        }

        // Try CLI tools
        for tool_config in &result.tools {
            if tool_config.name == name {
                let bridge = CliToolBridge::new(tool_config.clone())?;
                let skill = bridge.to_skill()?;

                self.skill_cache.insert(name.to_string(), skill.clone());
                return Ok(skill);
            }
        }

        Err(anyhow::anyhow!("Skill '{}' not found", name))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_discovery_config_default() {
        let config = DiscoveryConfig::default();
        assert!(config.skill_paths.is_empty());
        assert!(!config.tool_paths.is_empty());
        assert!(!config.auto_discover_system_tools); // Disabled by default for security
    }

    #[tokio::test]
    async fn test_discovery_engine_creation() {
        let discovery = SkillDiscovery::new();
        assert_eq!(discovery.cache.len(), 0);
    }

    #[tokio::test]
    async fn test_progressive_loader() {
        let temp_dir = TempDir::new().unwrap();
        let config = DiscoveryConfig::default();
        let mut loader = ProgressiveSkillLoader::new(config);

        // Should handle empty directory gracefully
        let result = loader.discovery.discover_all(temp_dir.path()).await;
        assert!(result.is_ok());
    }
}