Skip to main content

vtcode_skills/
command_skills.rs

1use crate::model::{SkillMetadata, SkillScope};
2use crate::types::{SkillContext, SkillManifest, SkillManifestMetadata, SkillVariety};
3use hashbrown::HashMap;
4use serde_json::json;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum BuiltInCommandExecutor {
9    SlashAlias,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum CommandSkillBackend {
14    TraditionalSkill {
15        skill_name: &'static str,
16        skill_path: &'static str,
17    },
18    BuiltInCommand {
19        executor: BuiltInCommandExecutor,
20    },
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct CommandSkillSpec {
25    pub slash_name: &'static str,
26    pub skill_name: &'static str,
27    pub description: &'static str,
28    pub usage: &'static str,
29    category: &'static str,
30    /// Additional slash names that resolve to this command (the canonical name
31    /// stays `slash_name`). Used so legacy commands keep working after a rename.
32    aliases: &'static [&'static str],
33    pub backend: CommandSkillBackend,
34}
35
36impl CommandSkillSpec {
37    /// Category used to group the command in host-specific command surfaces.
38    pub const fn category(self) -> &'static str {
39        self.category
40    }
41
42    const fn is_traditional(self) -> bool {
43        matches!(self.backend, CommandSkillBackend::TraditionalSkill { .. })
44    }
45
46    const fn is_built_in(self) -> bool {
47        matches!(self.backend, CommandSkillBackend::BuiltInCommand { .. })
48    }
49}
50
51#[derive(Debug, Clone)]
52pub struct BuiltInCommandSkill {
53    spec: &'static CommandSkillSpec,
54    manifest: SkillManifest,
55    path: PathBuf,
56}
57
58impl BuiltInCommandSkill {
59    fn from_spec(spec: &'static CommandSkillSpec) -> Self {
60        Self {
61            spec,
62            manifest: built_in_manifest(spec),
63            path: built_in_path(spec.skill_name),
64        }
65    }
66
67    pub fn spec(&self) -> &'static CommandSkillSpec {
68        self.spec
69    }
70
71    pub fn manifest(&self) -> &SkillManifest {
72        &self.manifest
73    }
74
75    pub fn name(&self) -> &str {
76        &self.manifest.name
77    }
78
79    pub fn description(&self) -> &str {
80        &self.manifest.description
81    }
82
83    pub fn usage(&self) -> &'static str {
84        self.spec.usage
85    }
86
87    pub fn category(&self) -> &'static str {
88        self.spec.category
89    }
90
91    pub fn slash_name(&self) -> &'static str {
92        self.spec.slash_name
93    }
94
95    pub fn path(&self) -> &PathBuf {
96        &self.path
97    }
98
99    pub fn scope(&self) -> SkillScope {
100        SkillScope::System
101    }
102
103    pub fn instructions(&self) -> String {
104        format!(
105            "# {}\n\nThis built-in command skill executes the existing `/{}` slash command backend.\n\n- Slash alias: `/{}`
106\n- Usage: `{}`
107\n- Category: `{}`
108\n- Backend: `built_in`\n",
109            self.name(),
110            self.slash_name(),
111            self.slash_name(),
112            self.usage(),
113            self.category()
114        )
115    }
116}
117
118macro_rules! built_in_command_spec {
119    ($slash:literal, $description:literal, $usage:literal, $category:literal) => {
120        CommandSkillSpec {
121            slash_name: $slash,
122            skill_name: concat!("cmd-", $slash),
123            description: $description,
124            usage: $usage,
125            category: $category,
126            aliases: &[],
127            backend: CommandSkillBackend::BuiltInCommand { executor: BuiltInCommandExecutor::SlashAlias },
128        }
129    };
130}
131
132macro_rules! traditional_command_spec {
133    ($slash:literal, $description:literal, $usage:literal, $category:literal, $skill_path:literal) => {
134        CommandSkillSpec {
135            slash_name: $slash,
136            skill_name: concat!("cmd-", $slash),
137            description: $description,
138            usage: $usage,
139            category: $category,
140            aliases: &[],
141            backend: CommandSkillBackend::TraditionalSkill {
142                skill_name: concat!("cmd-", $slash),
143                skill_path: $skill_path,
144            },
145        }
146    };
147}
148
149const COMMAND_SKILL_SPECS: &[CommandSkillSpec] = &[
150    built_in_command_spec!(
151        "init",
152        "Guided workspace setup for vtcode.toml, AGENTS.md, and indexing (usage: /init [--force])",
153        "/init [--force]",
154        "workspace"
155    ),
156    built_in_command_spec!(
157        "config",
158        "Browse settings and run workspace panels: memory, permissions, model, ide, tasks, jobs, log, subprocess, notify, checkup, or reset the active layer (usage: /config [memory|permissions|model|ide|tasks|jobs|log|subprocess|notify|checkup|<path>|reset])",
159        "/config [memory|permissions|model|ide|tasks|jobs|log|subprocess|notify|checkup|<path>|reset]",
160        "configuration"
161    ),
162    built_in_command_spec!(
163        "doctor",
164        "Run the setup checkup or audit always-loaded guidance (usage: /doctor [--quick|--full|prompt-audit])",
165        "/doctor [--quick|--full|prompt-audit]",
166        "support"
167    ),
168    CommandSkillSpec {
169        slash_name: "model",
170        skill_name: "cmd-model",
171        description: "Launch the interactive model picker (includes reasoning effort)",
172        usage: "/model (alias: /models)",
173        category: "configuration",
174        aliases: &["models"],
175        backend: CommandSkillBackend::BuiltInCommand { executor: BuiltInCommandExecutor::SlashAlias },
176    },
177    built_in_command_spec!(
178        "fast",
179        "Toggle native OpenAI ultrafast or Claude fast at premium pricing (usage: /fast [on|off])",
180        "/fast [on|off]",
181        "configuration"
182    ),
183    built_in_command_spec!(
184        "mode",
185        "Switch the active agent mode (usage: /mode [agent-name])",
186        "/mode [agent-name]",
187        "configuration"
188    ),
189    built_in_command_spec!("theme", "Switch UI theme (usage: /theme <theme-id>)", "/theme [theme-id]", "configuration"),
190    traditional_command_spec!(
191        "review",
192        "Review the current diff or selected files (usage: /review [instructions | --last-diff | --target <expr> | --file <path> | files...] [--style <style>])",
193        "/review [instructions | --last-diff | --target <expr> | --file <path> | files...] [--style <style>]",
194        "tools",
195        ".system/cmd-review"
196    ),
197    built_in_command_spec!(
198        "files",
199        "Browse and select files from workspace (usage: /files [filter])",
200        "/files [filter]",
201        "tools"
202    ),
203    built_in_command_spec!("copy", "Copy the latest complete assistant reply to clipboard", "/copy", "tools"),
204    built_in_command_spec!(
205        "skills",
206        "Open interactive skills manager (usage: /skills, /skills manager)",
207        "/skills [manager|list|search|create|load|unload|info|use|validate|package|regenerate-index|doctor|help]",
208        "tools"
209    ),
210    built_in_command_spec!(
211        "agent",
212        "Manage subagents and delegated child threads (usage: /agent [list|threads|inspect <id>|close <id>|create [project|user] [name]|edit [name]|delete <name>])",
213        "/agent [list|threads|inspect <id>|close <id>|create [project|user] [name]|edit [name]|delete <name>]",
214        "tools"
215    ),
216    built_in_command_spec!("status", "Show model, provider, workspace, and tool status", "/status", "status"),
217    built_in_command_spec!("splash", "Show CLI, Desktop, and WebMCP connection wiring status", "/splash", "status"),
218    built_in_command_spec!("stop", "Stop the active turn immediately", "/stop", "status"),
219    built_in_command_spec!("pause", "Pause the active turn at the next safe boundary", "/pause", "status"),
220    built_in_command_spec!(
221        "goal",
222        "Set, pause, resume, clear, or budget the thread goal loop (usage: /goal [<objective>|status|edit|pause|resume|clear|budget [<tokens>|0 to clear]])",
223        "/goal [<objective>|status|edit|pause|resume|clear|budget [<tokens>|0 to clear]]",
224        "status"
225    ),
226    built_in_command_spec!(
227        "update",
228        "Check for new VT Code releases and install updates (usage: /update [check|install] [--force], or run `vtcode update` from the CLI)",
229        "/update [check|install] [--force]",
230        "status"
231    ),
232    built_in_command_spec!(
233        "mcp",
234        "Open interactive MCP manager (usage: /mcp, optional subcommands still supported)",
235        "/mcp [status|list|tools|refresh|config|config edit|repair|diagnose|login <name>|logout <name>]",
236        "integration"
237    ),
238    built_in_command_spec!(
239        "webmcp",
240        "Manage the opt-in authenticated browser editor bridge (usage: /webmcp [help|status|tools|roots|pair [--replace] <origin>|unpair])",
241        "/webmcp [help|status|tools|roots|pair [--replace] <origin>|unpair]",
242        "integration"
243    ),
244    built_in_command_spec!(
245        "explain",
246        "Explain recorded execution without a model call",
247        "/explain [--scope task|session] [--details|diagram|--web|--export html]",
248        "status"
249    ),
250    built_in_command_spec!(
251        "plugin",
252        "Open interactive Agent Plugins manager (usage: /plugin, /plugin manager)",
253        "/plugin [manager|list|info <name>|add <source> [--name <id>]|remove <name>|validate <path>|refresh|help]",
254        "integration"
255    ),
256    built_in_command_spec!(
257        "local",
258        "Manage local inference servers: Ollama, LM Studio, llama.cpp (usage: /local [action] [provider])",
259        "/local [status|start|stop|configure|troubleshoot] [ollama|lmstudio|llamacpp]",
260        "integration"
261    ),
262    built_in_command_spec!(
263        "desktop",
264        "Open the VT Code desktop app linked to the current thread (macOS only)",
265        "/desktop",
266        "integration"
267    ),
268    built_in_command_spec!(
269        "resume",
270        "List archived sessions when idle; resume the active turn while it is paused",
271        "/resume [limit|--all]",
272        "session"
273    ),
274    built_in_command_spec!(
275        "fork",
276        "Fork an archived session into a new thread (usage: /fork [limit] [--all])",
277        "/fork [limit] [--all]",
278        "session"
279    ),
280    built_in_command_spec!(
281        "history",
282        "Open command history picker (usage: /history, same as Ctrl+R)",
283        "/history",
284        "session"
285    ),
286    built_in_command_spec!("clear", "Clear visible screen (usage: /clear [new])", "/clear [new]", "session"),
287    built_in_command_spec!(
288        "transcript",
289        "Inspect or manage the bounded TUI transcript snapshot (usage: /transcript [stats|clear|export [path]])",
290        "/transcript [stats|clear|export [path]]",
291        "session"
292    ),
293    built_in_command_spec!(
294        "compact",
295        "Compact the current conversation immediately or manage the saved manual compaction prompt",
296        "/compact [--instructions <text>] [--max-output-tokens <n>] [--reasoning-effort <none|minimal|low|medium|high|xhigh>] [--verbosity <low|medium|high>] [--native-only] | /compact edit-prompt | /compact reset-prompt",
297        "session"
298    ),
299    built_in_command_spec!("new", "Start a new session", "/new", "session"),
300    built_in_command_spec!(
301        "share",
302        "Export the current session as JSON, Markdown, or self-contained HTML timeline (usage: /share [json|markdown|md|html|--format <fmt>])",
303        "/share [json|markdown|md|html|--format <fmt>]",
304        "session"
305    ),
306    built_in_command_spec!(
307        "rewind",
308        "Open the rewind picker or restore a specific checkpoint (usage: /rewind [turn] [conversation|code|both])",
309        "/rewind [turn] [conversation|code|both]",
310        "session"
311    ),
312    built_in_command_spec!("redo", "Restore files and conversation from before the last rewind", "/redo", "session"),
313    built_in_command_spec!(
314        "plan",
315        "Start or continue the planning workflow with an optional task prompt (usage: /plan [task])",
316        "/plan [task]",
317        "session"
318    ),
319    built_in_command_spec!("docs", "Open vtcode documentation in web browser", "/docs", "support"),
320    built_in_command_spec!(
321        "feedback",
322        "Open a new GitHub issue to report a bug or request a feature",
323        "/feedback",
324        "support"
325    ),
326    built_in_command_spec!("help", "Show slash command help", "/help [command]", "support"),
327    built_in_command_spec!("exit", "Exit the session", "/exit", "session"),
328    built_in_command_spec!("donate", "Support the project by buying the author a coffee", "/donate", "support"),
329    built_in_command_spec!(
330        "terminal-setup",
331        "Configure terminal for VT Code (multiline, copy/paste, shell, themes, tab icon)",
332        "/terminal-setup [install-iterm2-icon|reset-iterm2-icon|icon [light|dark|clear|tinted|dynamic]]",
333        "terminal"
334    ),
335    built_in_command_spec!(
336        "statusline",
337        "Set up a custom status line with target selection (usage: /statusline [instructions...])",
338        "/statusline [instructions...]",
339        "terminal"
340    ),
341    built_in_command_spec!("title", "Configure the terminal title items interactively", "/title", "terminal"),
342    built_in_command_spec!(
343        "vim",
344        "Toggle Vim-style prompt editing for this session (usage: /vim [on|off])",
345        "/vim [on|off]",
346        "terminal"
347    ),
348    built_in_command_spec!(
349        "login",
350        "Authenticate with OpenAI, OpenRouter, or GitHub Copilot (usage: /login [provider])",
351        "/login [provider]",
352        "auth"
353    ),
354    built_in_command_spec!(
355        "logout",
356        "Clear stored provider authentication (usage: /logout [provider])",
357        "/logout [provider]",
358        "auth"
359    ),
360    built_in_command_spec!(
361        "auth",
362        "Show authentication status for providers (usage: /auth [provider])",
363        "/auth [provider]",
364        "auth"
365    ),
366    built_in_command_spec!(
367        "refresh-oauth",
368        "Refresh stored provider credentials when supported (usage: /refresh-oauth [provider])",
369        "/refresh-oauth [provider]",
370        "auth"
371    ),
372    built_in_command_spec!(
373        "secret",
374        "Manage provider API keys in your OS keyring (usage: /secret [list|status [provider] [key-name]|add <provider> [key-name]|delete <provider> [key-name]|migrate [provider]|help])",
375        "/secret [list|status [provider] [key-name]|add <provider> [key-name]|delete <provider> [key-name]|migrate [provider]|help]",
376        "auth"
377    ),
378];
379
380pub fn command_skill_specs() -> &'static [CommandSkillSpec] {
381    COMMAND_SKILL_SPECS
382}
383
384pub fn find_command_skill_by_slash_name(name: &str) -> Option<&'static CommandSkillSpec> {
385    COMMAND_SKILL_SPECS
386        .iter()
387        .find(|spec| spec.slash_name == name || spec.aliases.contains(&name))
388}
389
390pub fn find_command_skill_by_skill_name(name: &str) -> Option<&'static CommandSkillSpec> {
391    COMMAND_SKILL_SPECS.iter().find(|spec| spec.skill_name == name)
392}
393
394fn is_command_skill_name(name: &str) -> bool {
395    find_command_skill_by_skill_name(name).is_some()
396}
397
398pub fn is_model_catalog_eligible(skill: &SkillMetadata) -> bool {
399    if skill
400        .manifest
401        .as_ref()
402        .and_then(|manifest| manifest.disable_model_invocation)
403        .unwrap_or(false)
404    {
405        return false;
406    }
407
408    !is_command_skill_name(&skill.name)
409}
410
411pub fn built_in_command_skill_contexts() -> Vec<SkillContext> {
412    COMMAND_SKILL_SPECS
413        .iter()
414        .copied()
415        .filter(|spec| spec.is_built_in())
416        .map(|spec| SkillContext::MetadataOnly(built_in_manifest(&spec), built_in_path(spec.skill_name)))
417        .collect()
418}
419
420pub fn built_in_command_skill(name: &str) -> Option<BuiltInCommandSkill> {
421    find_command_skill_by_skill_name(name)
422        .filter(|spec| spec.is_built_in())
423        .map(BuiltInCommandSkill::from_spec)
424}
425
426pub fn merge_built_in_command_skill_contexts(skills: &mut Vec<SkillContext>) {
427    skills.extend(built_in_command_skill_contexts());
428    skills.sort_by(|left, right| left.manifest().name.cmp(&right.manifest().name));
429    skills.dedup_by(|left, right| left.manifest().name == right.manifest().name);
430}
431
432pub fn merge_built_in_command_skill_metadata(skills: &mut Vec<SkillMetadata>) {
433    skills.extend(built_in_command_skill_contexts().into_iter().map(|skill_ctx| SkillMetadata {
434        name: skill_ctx.manifest().name.clone(),
435        description: skill_ctx.manifest().description.clone(),
436        short_description: None,
437        path: skill_ctx.path().clone(),
438        scope: SkillScope::System,
439        manifest: Some(skill_ctx.manifest().clone().into()),
440    }));
441    skills.sort_by(|left, right| left.name.cmp(&right.name));
442    skills.dedup_by(|left, right| left.name == right.name);
443}
444
445fn built_in_manifest(spec: &CommandSkillSpec) -> SkillManifest {
446    SkillManifest {
447        name: spec.skill_name.to_string(),
448        description: spec.description.to_string(),
449        disable_model_invocation: Some(true),
450        variety: SkillVariety::BuiltIn,
451        metadata: Some(command_skill_metadata(spec, "built_in_command")),
452        ..Default::default()
453    }
454}
455
456fn command_skill_metadata(spec: &CommandSkillSpec, backend: &str) -> SkillManifestMetadata {
457    let mut metadata = HashMap::new();
458    metadata.insert("slash_alias".to_string(), json!(format!("/{}", spec.slash_name)));
459    metadata.insert("usage".to_string(), json!(spec.usage));
460    metadata.insert("category".to_string(), json!(spec.category));
461    metadata.insert("backend".to_string(), json!(backend));
462    metadata
463}
464
465fn built_in_path(skill_name: &str) -> PathBuf {
466    PathBuf::from(format!("<built-in>/{skill_name}"))
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472
473    #[test]
474    fn traditional_and_built_in_commands_are_mapped() {
475        let review = find_command_skill_by_slash_name("review").expect("review spec");
476        assert!(review.is_traditional());
477        assert_eq!(review.skill_name, "cmd-review");
478
479        let status = find_command_skill_by_slash_name("status").expect("status spec");
480        assert!(status.is_built_in());
481        assert_eq!(status.skill_name, "cmd-status");
482
483        let splash = find_command_skill_by_slash_name("splash").expect("splash spec");
484        assert!(splash.is_built_in());
485        assert_eq!(splash.usage, "/splash");
486    }
487
488    #[test]
489    fn models_alias_opens_the_model_picker() {
490        let model = find_command_skill_by_slash_name("models").expect("models alias");
491        assert_eq!(model.slash_name, "model");
492        assert!(model.is_built_in());
493    }
494
495    #[test]
496    fn built_in_contexts_are_tagged_correctly() {
497        let built_in = built_in_command_skill_contexts();
498        let status = built_in
499            .iter()
500            .find(|ctx| ctx.manifest().name == "cmd-status")
501            .expect("cmd-status context");
502        assert_eq!(status.manifest().variety, SkillVariety::BuiltIn);
503    }
504
505    #[test]
506    fn removed_generate_agent_file_command_is_not_registered() {
507        assert!(find_command_skill_by_slash_name("generate-agent-file").is_none());
508        assert!(find_command_skill_by_skill_name("cmd-generate-agent-file").is_none());
509    }
510
511    #[test]
512    fn mode_command_switches_active_agent_mode() {
513        // The `/mode` command was re-introduced (commit ef1b52b6f) as a live
514        // feature: with no argument it opens the mode palette, with an argument
515        // (build|auto|duck|plan) it selects the primary agent directly. It must
516        // remain registered alongside the dedicated mode commands.
517        let mode = find_command_skill_by_slash_name("mode").expect("mode spec");
518        assert!(mode.description.contains("mode"));
519    }
520
521    #[test]
522    fn plan_command_skill_uses_workflow_copy() {
523        let plan = find_command_skill_by_slash_name("plan").expect("plan spec");
524        assert!(plan.description.contains("planning workflow"));
525        assert!(!plan.description.contains("mode"));
526        assert_eq!(plan.usage, "/plan [task]");
527    }
528
529    #[test]
530    fn desktop_command_skill_opens_the_desktop_app() {
531        let desktop = find_command_skill_by_slash_name("desktop").expect("desktop spec");
532        assert!(desktop.is_built_in());
533        assert_eq!(desktop.usage, "/desktop");
534        assert_eq!(desktop.category(), "integration");
535    }
536
537    #[test]
538    fn doctor_covers_setup_and_prompt_audit() {
539        let doctor = find_command_skill_by_slash_name("doctor").expect("doctor spec");
540        assert!(doctor.is_built_in());
541        assert_eq!(doctor.category(), "support");
542        assert!(doctor.usage.contains("prompt-audit"));
543        assert!(doctor.usage.contains("--quick"));
544    }
545
546    #[test]
547    fn removed_config_consolidated_commands_are_not_registered() {
548        for removed in [
549            "checkup",
550            "permissions",
551            "ide",
552            "tasks",
553            "jobs",
554            "log",
555            "subprocess",
556            "notify",
557            "memory",
558            "effort",
559            "continue",
560            "edit",
561            "analyze",
562        ] {
563            assert!(
564                find_command_skill_by_slash_name(removed).is_none(),
565                "/{removed} must not be registered; use /config instead"
566            );
567        }
568        let config = find_command_skill_by_slash_name("config").expect("config spec");
569        assert!(config.usage.contains("checkup"));
570    }
571}