vtcode 0.99.1

A Rust-based terminal coding agent with modular architecture supporting multiple LLM providers
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
//! Slash command handlers for in-chat skill management
//!
//! Implements `/skills` command palette for loading, listing, and executing skills
//! within interactive chat sessions.
//!
//! Supports both explicit commands (`/skills load pdf-analyzer`) and Codex-style
//! mention detection (`$pdf-analyzer` or description keyword matching).

use anyhow::Result;
use std::path::PathBuf;
#[cfg(test)]
use vtcode_core::config::loader::ConfigManager;
use vtcode_core::skills::authoring::SkillAuthor;
use vtcode_core::skills::loader::EnhancedSkillLoader;
#[cfg(test)]
use vtcode_core::skills::loader::{
    SkillMentionDetectionOptions, detect_skill_mentions_with_options,
};
use vtcode_core::skills::types::{Skill, SkillManifest};

use super::skills_commands_parser::parse_skill_command as parse_skill_command_impl;

async fn regenerate_skills_index_best_effort(workspace: &std::path::Path) {
    if let Err(e) = crate::cli::skills_index::generate_comprehensive_skills_index(workspace).await {
        tracing::warn!("Failed to regenerate skills index: {}", e);
    }
}

fn workspace_skill_dir(workspace: &std::path::Path, name: &str) -> PathBuf {
    workspace.join(".agents").join("skills").join(name)
}

fn list_label_for_manifest(manifest: &SkillManifest) -> &'static str {
    match manifest.variety {
        vtcode_core::skills::types::SkillVariety::BuiltIn => "built_in",
        vtcode_core::skills::types::SkillVariety::SystemUtility => "system_utility",
        vtcode_core::skills::types::SkillVariety::AgentSkill => "agent_skill",
    }
}

/// Skill-related command actions
#[derive(Clone, Debug)]
pub(crate) enum SkillCommandAction {
    /// Open interactive skill manager
    Interactive,
    /// Show help
    Help,
    /// List available skills
    List { query: Option<String> },
    /// Create a new skill from template
    Create { name: String, path: Option<PathBuf> },
    /// Validate a skill
    Validate { name: String },
    /// Package a skill into .skill file
    Package { name: String },
    /// Load a skill by name
    Load { name: String },
    /// Unload a skill
    Unload { name: String },
    /// Execute a skill with input
    Use { name: String, input: String },
    /// Show skill details
    Info { name: String },
    /// Regenerate skills index file
    RegenerateIndex,
}

/// Result of a skill command
#[derive(Clone, Debug)]
pub(crate) enum SkillCommandOutcome {
    /// Command handled, display info
    Handled { message: String },
    /// Load skill into session
    LoadSkill { skill: Skill, message: String },
    /// Unload skill from session
    UnloadSkill { name: String },
    /// Execute skill with input
    UseSkill { skill: Skill, input: String },
    /// Execute a built-in command skill with input
    UseBuiltInCommand {
        name: String,
        slash_name: String,
        input: String,
    },
    /// Error occurred
    Error { message: String },
}

/// Parse skill subcommand from input
pub(crate) fn parse_skill_command(input: &str) -> Result<Option<SkillCommandAction>> {
    parse_skill_command_impl(input)
}

/// Execute a skill command
pub(crate) async fn handle_skill_command(
    action: SkillCommandAction,
    workspace: PathBuf,
) -> Result<SkillCommandOutcome> {
    let author = SkillAuthor::new(workspace.clone());
    let mut loader = EnhancedSkillLoader::new(workspace.clone());

    match action {
        SkillCommandAction::Interactive => Ok(SkillCommandOutcome::Handled {
            message: "Interactive skills manager is available in TUI sessions. Use /skills in inline mode to browse and toggle skills.".to_string(),
        }),
        SkillCommandAction::Help => {
            let help_text = r#"Skills Commands:

Interactive:
  /skills                                Open interactive skills manager in TUI
  /skills manager                        Alias for interactive skills manager

Authoring:
  /skills --create <name> [--path <dir>]   Create new skill from template
  /skills --validate <name>               Validate skill structure
  /skills --package <name>                Package skill to .skill file

Management:
  /skills --list [query]                  List available skills (optional search)
  /skills --search <query>                Search for skills by name/description
  /skills --load <name>                   Load skill into session
  /skills --unload <name>                 Unload skill from session
  /skills --info <name>                   Show skill details
  /skills --use <name> <input>            Execute skill with input
  /skills --regenerate-index              Regenerate skills index file

Shortcuts:
  /skills -l [query], /skills -s <query>, /skills -h, /skills --regen"#;

            Ok(SkillCommandOutcome::Handled {
                message: help_text.to_string(),
            })
        }

        SkillCommandAction::Create { name, path } => match author.create_skill(&name, path) {
            Ok(skill_dir) => Ok(SkillCommandOutcome::Handled {
                message: format!(
                    "✓ Created skill: {}\n\nNext steps:\n1. Edit {}/SKILL.md to complete the frontmatter and instructions\n2. Add scripts, references, or assets as needed\n3. Validate with: /skills validate {}\n4. Package with: /skills package {}",
                    name,
                    skill_dir.display(),
                    name,
                    name
                ),
            }),
            Err(e) => Ok(SkillCommandOutcome::Error {
                message: format!("Failed to create skill: {}", e),
            }),
        },

        SkillCommandAction::Validate { name } => {
            let skill_dir = workspace_skill_dir(&workspace, &name);
            if !skill_dir.exists() {
                return Ok(SkillCommandOutcome::Error {
                    message: format!("Skill directory not found: {}", skill_dir.display()),
                });
            }

            match author.validate_skill(&skill_dir) {
                Ok(report) => Ok(SkillCommandOutcome::Handled {
                    message: report.format(),
                }),
                Err(e) => Ok(SkillCommandOutcome::Error {
                    message: format!("Validation error: {}", e),
                }),
            }
        }

        SkillCommandAction::Package { name } => {
            let skill_dir = workspace_skill_dir(&workspace, &name);
            if !skill_dir.exists() {
                return Ok(SkillCommandOutcome::Error {
                    message: format!("Skill directory not found: {}", skill_dir.display()),
                });
            }

            match author.package_skill(&skill_dir, Some(workspace.clone())) {
                Ok(output_file) => Ok(SkillCommandOutcome::Handled {
                    message: format!("✓ Packaged skill to: {}", output_file.display()),
                }),
                Err(e) => Ok(SkillCommandOutcome::Error {
                    message: format!("Packaging failed: {}", e),
                }),
            }
        }

        SkillCommandAction::List { query } => {
            regenerate_skills_index_best_effort(&workspace).await;

            let discovery_result = loader.discover_all_skills().await?;
            let mut skills = discovery_result.skills;
            let mut cli_tools = discovery_result.tools;
            // Apply query filter if provided
            if let Some(q) = query {
                let q_lower = q.to_lowercase();
                skills.retain(|ctx| {
                    let manifest = ctx.manifest();
                    manifest.name.to_lowercase().contains(&q_lower)
                        || manifest.description.to_lowercase().contains(&q_lower)
                });
                cli_tools.retain(|tool| {
                    tool.name.to_lowercase().contains(&q_lower)
                        || tool.description.to_lowercase().contains(&q_lower)
                });
            }

            if skills.is_empty() && cli_tools.is_empty() {
                return Ok(SkillCommandOutcome::Handled {
                    message: "No matching skills found.".to_string(),
                });
            }

            let mut output = String::from("Available Skills:\n");
            for skill_ctx in &skills {
                let manifest = skill_ctx.manifest();
                output.push_str(&format!(
                    "  • {} [{}] - {}\n",
                    manifest.name,
                    list_label_for_manifest(manifest),
                    manifest.description
                ));
            }
            if !cli_tools.is_empty() {
                output.push_str("\nSystem Utilities:\n");
                for tool in &cli_tools {
                    output.push_str(&format!("  • {} - {}\n", tool.name, tool.description));
                }
            }
            output.push_str(
                "\nUse `/skills --info <name>` for details, `/skills --load <name>` to load",
            );

            Ok(SkillCommandOutcome::Handled { message: output })
        }

        SkillCommandAction::Load { name } => {
            regenerate_skills_index_best_effort(&workspace).await;

            match loader.get_skill(&name).await {
                Ok(enhanced_skill) => match enhanced_skill {
                    vtcode_core::skills::loader::EnhancedSkill::Traditional(skill) => {
                        let message = format!(
                            "✓ Loaded skill: {}\nℹ Instructions are now [ACTIVE] and persistent in the agent prompt.",
                            skill.name()
                        );
                        Ok(SkillCommandOutcome::LoadSkill {
                            skill: *skill,
                            message,
                        })
                    }
                    vtcode_core::skills::loader::EnhancedSkill::CliTool(_) => {
                        Ok(SkillCommandOutcome::Error {
                            message: format!(
                                "Skill '{}' is a CLI tool, not a traditional skill",
                                name
                            ),
                        })
                    }
                    vtcode_core::skills::loader::EnhancedSkill::BuiltInCommand(_) => {
                        Ok(SkillCommandOutcome::Error {
                            message: format!(
                                "Skill '{}' is a built-in command skill and cannot be loaded into the persistent session prompt. Use `/skills use {}` instead.",
                                name, name
                            ),
                        })
                    }
                    vtcode_core::skills::loader::EnhancedSkill::NativePlugin(_) => {
                        Ok(SkillCommandOutcome::Error {
                            message: format!(
                                "Skill '{}' is a native plugin, not a traditional skill",
                                name
                            ),
                        })
                    }
                },
                Err(e) => Ok(SkillCommandOutcome::Error {
                    message: format!("Failed to load skill '{}': {}", name, e),
                }),
            }
        }

        SkillCommandAction::Unload { name } => Ok(SkillCommandOutcome::UnloadSkill { name }),

        SkillCommandAction::Info { name } => {
            regenerate_skills_index_best_effort(&workspace).await;

            match loader.get_skill(&name).await {
                Ok(enhanced_skill) => match enhanced_skill {
                    vtcode_core::skills::loader::EnhancedSkill::Traditional(skill) => {
                        let mut output = String::new();
                        output.push_str(&format!("Skill: {}\n", skill.name()));
                        output.push_str(&format!("Description: {}\n", skill.description()));
                        if let Some(license) = &skill.manifest.license {
                            output.push_str(&format!("License: {}\n", license));
                        }
                        if let Some(compatibility) = &skill.manifest.compatibility {
                            output.push_str(&format!("Compatibility: {}\n", compatibility));
                        }

                        output.push_str("\n--- Instructions ---\n");
                        output.push_str(&skill.instructions);

                        if !skill.list_resources().is_empty() {
                            output.push_str("\n\n--- Resources ---\n");
                            for resource in skill.list_resources() {
                                output.push_str(&format!("  • {}\n", resource));
                            }
                        }

                        Ok(SkillCommandOutcome::Handled { message: output })
                    }
                    vtcode_core::skills::loader::EnhancedSkill::CliTool(bridge) => {
                        let mut output = String::new();
                        output.push_str(&format!("CLI Tool Skill: {}\n", bridge.config.name));
                        output.push_str(&format!("Description: {}\n", bridge.config.description));
                        output.push_str("\n--- Tool Configuration ---\n");
                        output.push_str("Tool available for execution");
                        Ok(SkillCommandOutcome::Handled { message: output })
                    }
                    vtcode_core::skills::loader::EnhancedSkill::BuiltInCommand(skill) => {
                        let mut output = String::new();
                        output.push_str(&format!("Built-In Command Skill: {}\n", skill.name()));
                        output.push_str(&format!("Description: {}\n", skill.description()));
                        output.push_str(&format!("Slash alias: /{}\n", skill.slash_name()));
                        output.push_str(&format!("Usage: {}\n", skill.usage()));
                        output.push_str(&format!("Category: {}\n", skill.category()));
                        output.push_str("\n--- Backend ---\n");
                        output.push_str("Executes the existing slash command backend");
                        Ok(SkillCommandOutcome::Handled { message: output })
                    }
                    vtcode_core::skills::loader::EnhancedSkill::NativePlugin(plugin) => {
                        let meta = plugin.metadata();
                        let mut output = String::new();
                        output.push_str(&format!("Native Plugin: {}\n", meta.name));
                        output.push_str(&format!("Description: {}\n", meta.description));
                        output.push_str("\n--- Plugin Configuration ---\n");
                        output.push_str("Native plugin available for execution");
                        Ok(SkillCommandOutcome::Handled { message: output })
                    }
                },
                Err(e) => Ok(SkillCommandOutcome::Error {
                    message: format!("Failed to load skill '{}': {}", name, e),
                }),
            }
        }

        SkillCommandAction::Use { name, input } => match loader.get_skill(&name).await {
            Ok(enhanced_skill) => match enhanced_skill {
                vtcode_core::skills::loader::EnhancedSkill::Traditional(skill) => {
                    Ok(SkillCommandOutcome::UseSkill {
                        skill: *skill,
                        input,
                    })
                }
                vtcode_core::skills::loader::EnhancedSkill::CliTool(_) => {
                    Ok(SkillCommandOutcome::Error {
                        message: format!("Skill '{}' is a CLI tool, not a traditional skill", name),
                    })
                }
                vtcode_core::skills::loader::EnhancedSkill::BuiltInCommand(skill) => {
                    Ok(SkillCommandOutcome::UseBuiltInCommand {
                        name: skill.name().to_string(),
                        slash_name: skill.slash_name().to_string(),
                        input,
                    })
                }
                vtcode_core::skills::loader::EnhancedSkill::NativePlugin(_) => {
                    Ok(SkillCommandOutcome::Error {
                        message: format!("Skill '{}' is a native plugin, not a traditional skill", name),
                    })
                }
            },
            Err(e) => Ok(SkillCommandOutcome::Error {
                message: format!("Failed to load skill '{}': {}", name, e),
            }),
        },

        SkillCommandAction::RegenerateIndex => {
            // Use the EnhancedSkillLoader to discover all skills and regenerate the index
            let discovery_result = loader.discover_all_skills().await?;
            let total_skills = discovery_result.skills.len() + discovery_result.tools.len();

            match crate::cli::skills_index::generate_comprehensive_skills_index(&workspace).await {
                Ok(index_path) => {
                    let message = format!(
                        "Skills index regenerated successfully!\nIndex file: {}\nFound {} skills.",
                        index_path.display(),
                        total_skills
                    );

                    Ok(SkillCommandOutcome::Handled { message })
                }
                Err(e) => Ok(SkillCommandOutcome::Error {
                    message: format!("Failed to regenerate skills index: {}", e),
                }),
            }
        }
    }
}

/// Detect skill mentions in user input using Codex-style patterns
///
/// Returns list of skill names that should be auto-triggered based on:
/// 1. Explicit `$skill-name` mention (e.g., "Use $pdf-analyzer")
/// 2. Description keyword matches (fuzzy, requires 2+ matches)
///
/// # Examples
/// ```
/// // Explicit mention
/// "Use $pdf-analyzer to process the document" -> ["pdf-analyzer"]
///
/// // Description matching
/// "Extract tables from PDF document" -> ["pdf-analyzer"] (if description contains "extract" + "tables" or "PDF")
/// ```
#[cfg(test)]
async fn detect_mentioned_skills(
    user_input: &str,
    workspace: PathBuf,
) -> Result<Vec<(String, Skill)>> {
    let mut loader = EnhancedSkillLoader::new(workspace.clone());

    // Discover available skills
    let discovery_result = loader.discover_all_skills().await?;
    let manifests: Vec<SkillManifest> = discovery_result
        .skills
        .iter()
        .map(|s| s.manifest().clone())
        .collect();

    // Detect mentions with workspace-aware routing config.
    let detection_options = ConfigManager::load_from_workspace(&workspace)
        .ok()
        .map(|manager| {
            let skills = &manager.config().skills;
            SkillMentionDetectionOptions {
                enable_auto_trigger: skills.enable_auto_trigger,
                enable_description_matching: skills.enable_description_matching,
                min_keyword_matches: skills.min_keyword_matches,
            }
        })
        .unwrap_or_default();
    let mentioned_names =
        detect_skill_mentions_with_options(user_input, &manifests, &detection_options);

    // Load the mentioned skills
    let mut skills = Vec::new();
    for name in mentioned_names {
        if let Ok(enhanced_skill) = loader.get_skill(&name).await
            && let vtcode_core::skills::loader::EnhancedSkill::Traditional(skill) = enhanced_skill
        {
            skills.push((name.clone(), *skill));
        }
    }

    Ok(skills)
}

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

    #[tokio::test]
    async fn test_detect_explicit_skill_mention() {
        // This test would need actual skills in a temp directory
        // Just verify the function signature compiles
        let input = "Use $pdf-analyzer to process the document";
        let workspace = PathBuf::from("/tmp");
        let _result = detect_mentioned_skills(input, workspace).await;
        // In real test, would assert skills are detected
    }

    #[tokio::test]
    async fn built_in_command_skill_info_reports_metadata() {
        let temp = tempdir().expect("tempdir");

        let outcome = handle_skill_command(
            SkillCommandAction::Info {
                name: "cmd-status".to_string(),
            },
            temp.path().to_path_buf(),
        )
        .await
        .expect("info outcome");

        match outcome {
            SkillCommandOutcome::Handled { message } => {
                assert!(message.contains("Built-In Command Skill: cmd-status"));
                assert!(message.contains("Slash alias: /status"));
                assert!(message.contains("Usage:"));
            }
            other => panic!("expected handled outcome, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn built_in_command_skill_use_returns_built_in_outcome() {
        let temp = tempdir().expect("tempdir");

        let outcome = handle_skill_command(
            SkillCommandAction::Use {
                name: "cmd-status".to_string(),
                input: "show session".to_string(),
            },
            temp.path().to_path_buf(),
        )
        .await
        .expect("use outcome");

        match outcome {
            SkillCommandOutcome::UseBuiltInCommand {
                name,
                slash_name,
                input,
            } => {
                assert_eq!(name, "cmd-status");
                assert_eq!(slash_name, "status");
                assert_eq!(input, "show session");
            }
            other => panic!("expected built-in use outcome, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn built_in_command_skill_load_is_rejected() {
        let temp = tempdir().expect("tempdir");

        let outcome = handle_skill_command(
            SkillCommandAction::Load {
                name: "cmd-status".to_string(),
            },
            temp.path().to_path_buf(),
        )
        .await
        .expect("load outcome");

        match outcome {
            SkillCommandOutcome::Error { message } => {
                assert!(message.contains("built-in command skill"));
                assert!(message.contains("/skills use cmd-status"));
            }
            other => panic!("expected error outcome, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn built_in_command_skill_list_includes_query_match() {
        let temp = tempdir().expect("tempdir");

        let outcome = handle_skill_command(
            SkillCommandAction::List {
                query: Some("cmd-status".to_string()),
            },
            temp.path().to_path_buf(),
        )
        .await
        .expect("list outcome");

        match outcome {
            SkillCommandOutcome::Handled { message } => {
                assert!(message.contains("Available Skills:"));
                assert!(message.contains("cmd-status [built_in] -"));
            }
            other => panic!("expected handled outcome, got {other:?}"),
        }
    }
}