Skip to content

[Medium] Custom Slash Commands #22

@marklicata

Description

@marklicata

Summary

Allow users to define custom slash commands as Markdown files that expand into prompts, enabling reusable workflows and team-shared commands.

Current State

Amplifier CLI has hardcoded slash commands (/help, /clear, /model, etc.) but no way for users to:

  • Define their own commands
  • Share commands with team via repository
  • Create parameterized command templates

Proposed Implementation

1. Custom Command Location

~/.amplifier/commands/           # User-level commands
.amplifier/commands/             # Project-level commands

Command file: .amplifier/commands/review.md

---
name: review
description: Review code for best practices
args:
  - name: file
    description: File to review
    required: true
  - name: focus
    description: What to focus on
    required: false
    default: "general"
---

Please review the following file for {{focus}} best practices:

File: {{file}}

Focus areas:
- Code clarity and readability
- Error handling
- Performance considerations
- Security issues

Provide specific, actionable feedback.

2. Usage

amplifier> /review src/main.py
[Expands to full review prompt for src/main.py with focus="general"]

amplifier> /review src/api.py --focus security
[Expands to full review prompt with focus="security"]

amplifier> /commands
Available commands:
  /review <file> [--focus]  - Review code for best practices
  /explain <file>           - Explain how code works
  /test <file>              - Generate tests for file
  /refactor <file>          - Suggest refactoring improvements

3. Command File Format

---
# Frontmatter (YAML)
name: command-name           # Required
description: What it does    # Required
aliases:                     # Optional
  - cmd
  - c
args:                        # Optional
  - name: arg_name
    description: What this arg is
    required: true/false
    default: "default value"
    type: string/file/choice
    choices: ["a", "b", "c"]  # If type=choice
flags:                       # Optional
  - name: verbose
    short: v
    description: Enable verbose output
    type: boolean
    default: false
---

# Prompt Template (Markdown with {{variables}})

Your prompt content here.

Use {{arg_name}} for argument substitution.
Use {{verbose}} for flag values.

{{#if verbose}}
Please provide detailed explanations.
{{/if}}

4. Template Syntax

Simple substitution:

Review {{file}} for {{focus}} issues.

Conditionals:

{{#if verbose}}
Provide detailed explanations for each issue.
{{/if}}

{{#unless brief}}
Include code examples in your response.
{{/unless}}

File inclusion:

Here's the file content:
{{include file}}

Or with line numbers:
{{include file with_lines=true}}

Iteration (for multi-file commands):

{{#each files}}
## File: {{this}}
{{include this}}
{{/each}}

5. Built-in Variables

Variable Description
{{cwd}} Current working directory
{{git_branch}} Current git branch
{{git_status}} Output of git status --short
{{date}} Current date
{{time}} Current time
{{session_id}} Current session ID
{{model}} Current model name

6. New Module Structure

src/amplifier_app_cli/commands_custom/
├── __init__.py
├── loader.py         # Load command files from directories
├── parser.py         # Parse frontmatter and template
├── template.py       # Template rendering engine
├── registry.py       # Register and look up commands
└── executor.py       # Execute expanded commands

7. Core Interfaces

from dataclasses import dataclass, field
from pathlib import Path

@dataclass
class CommandArg:
    name: str
    description: str
    required: bool = False
    default: str | None = None
    type: Literal["string", "file", "choice"] = "string"
    choices: list[str] = field(default_factory=list)

@dataclass
class CommandFlag:
    name: str
    short: str | None
    description: str
    type: Literal["boolean", "string"] = "boolean"
    default: Any = False

@dataclass
class CustomCommand:
    name: str
    description: str
    template: str
    args: list[CommandArg] = field(default_factory=list)
    flags: list[CommandFlag] = field(default_factory=list)
    aliases: list[str] = field(default_factory=list)
    source_path: Path | None = None  # Where it was loaded from

class CommandLoader:
    def __init__(self, search_paths: list[Path]): ...
    
    def load_all(self) -> list[CustomCommand]:
        """Load all commands from search paths."""
        ...
    
    def load_file(self, path: Path) -> CustomCommand:
        """Load a single command file."""
        ...

class TemplateRenderer:
    def render(
        self,
        template: str,
        args: dict[str, Any],
        flags: dict[str, Any],
        context: dict[str, Any]  # Built-in variables
    ) -> str:
        """Render template with substitutions."""
        ...

class CommandRegistry:
    def __init__(self): ...
    
    def register(self, command: CustomCommand) -> None: ...
    def get(self, name: str) -> CustomCommand | None: ...
    def list_all(self) -> list[CustomCommand]: ...
    def resolve_alias(self, name: str) -> str | None: ...

class CommandExecutor:
    def __init__(
        self,
        registry: CommandRegistry,
        renderer: TemplateRenderer,
        session: Session
    ): ...
    
    async def execute(
        self,
        command_name: str,
        args: list[str],
        flags: dict[str, Any]
    ) -> str:
        """Execute command, return expanded prompt."""
        ...

8. Example Commands

/review - Code Review

---
name: review
description: Review code for best practices and issues
args:
  - name: file
    required: true
    type: file
flags:
  - name: security
    short: s
    description: Focus on security issues
  - name: performance
    short: p
    description: Focus on performance issues
---

Please review this code:

{{include file}}

{{#if security}}
Focus especially on security vulnerabilities:
- Input validation
- SQL injection
- XSS vulnerabilities
- Authentication/authorization issues
{{/if}}

{{#if performance}}
Focus especially on performance:
- Algorithm complexity
- Memory usage
- Database queries
- Caching opportunities
{{/if}}

/explain - Code Explanation

---
name: explain
description: Explain how code works
args:
  - name: file
    required: true
    type: file
  - name: depth
    required: false
    default: "medium"
    type: choice
    choices: ["brief", "medium", "detailed"]
---

Explain how this code works at a {{depth}} level of detail:

{{include file}}

/commit - Generate Commit Message

---
name: commit
description: Generate a commit message for staged changes
---

Generate a conventional commit message for these changes:

{{git_status}}


Diff:

{{shell "git diff --cached"}}

9. Discovery and Help

amplifier> /commands
Built-in Commands:
  /help              Show help
  /clear             Clear screen
  /model             Show/change model
  /compact           Compact conversation
  /memory            Show memory files
  /checkpoint        Manage checkpoints

Custom Commands (project):
  /review <file>     Review code for best practices
  /explain <file>    Explain how code works
  /test <file>       Generate tests

Custom Commands (user):
  /commit            Generate commit message
  /standup           Generate standup summary

amplifier> /help review
/review - Review code for best practices

Usage: /review <file> [--security] [--performance]

Arguments:
  file          File to review (required)

Flags:
  -s, --security     Focus on security issues
  -p, --performance  Focus on performance issues

Source: .amplifier/commands/review.md

10. CLI Flags

# List available custom commands
amplifier commands list

# Show command details
amplifier commands show review

# Create new command (interactive)
amplifier commands create

# Edit existing command
amplifier commands edit review

# Validate command files
amplifier commands validate

Acceptance Criteria

  • Commands discovered from ~/.amplifier/commands/ and .amplifier/commands/
  • Frontmatter parsed correctly (name, description, args, flags)
  • Template variables substituted ({{arg}})
  • Conditionals work ({{#if}}, {{#unless}})
  • File inclusion works ({{include file}})
  • Built-in variables available ({{cwd}}, {{git_branch}}, etc.)
  • /commands lists all available commands
  • /help <command> shows command details
  • Aliases work
  • Tab completion for custom commands
  • Validation for required args
  • Default values applied
  • Error messages for invalid commands
  • Unit tests for parser and renderer
  • Integration tests for command execution

Related

  • Depends on: None
  • Enhances: Power user workflows, team collaboration

Estimated Effort

Medium - 1.5-2 weeks

Files to Create/Modify

  • src/amplifier_app_cli/commands_custom/ (new module)
  • src/amplifier_app_cli/commands/slash.py (integrate custom commands)
  • src/amplifier_app_cli/ui/autocomplete.py (command completion)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions