Skip to content

chhlga/zsh-opencode-plugin

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

# zsh-opencode-ai 🤖 - AI-Powered Shell Command Generation

Convert natural language comments to shell commands with a single Tab press
Lightning-fast AI completion powered by OpenCode and GitHub Copilot

Zsh OpenCode Required GitHub Copilot

Quick StartFeaturesConfigurationUsageDevelopment


Why zsh-opencode-ai?

Stop googling shell commands. Just describe what you want in plain English, press Tab, and get the exact command you need.

zsh-opencode-ai gives you:

  • ⚡ Instant AI completion: Type # list all files → press Tab → get ls -la
  • 🎯 Context-aware suggestions: Understands your intent and generates precise commands
  • 🔄 Seamless integration: Works alongside existing completions (fzf-tab, zsh-autosuggestions)
  • 🎨 Clean UX: Animated spinner feedback, no prompt clutter
  • 🔧 Configurable: Switch AI models, adjust behavior via environment variables

Table of Contents


Installation

Prerequisites

  • Zsh (shell)
  • OpenCode installed and configured (installation guide)
  • Authenticated AI provider (GitHub Copilot recommended, OpenAI supported)
  • Oh My Zsh (optional, recommended)

Option 1: Install with Oh My Zsh (Recommended)

# Clone this repository to Oh My Zsh custom plugins directory
git clone https://github.com/USER/zsh-opencode-plugin ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-opencode-ai

# Add to plugins in ~/.zshrc
plugins=(... zsh-opencode-ai)

# Reload shell
source ~/.zshrc

Option 2: Manual Installation

# Clone the repository
git clone https://github.com/USER/zsh-opencode-plugin ~/zsh-opencode-ai

# Add to ~/.zshrc
source ~/zsh-opencode-ai/zsh-opencode-ai.plugin.zsh

# Reload shell
source ~/.zshrc

Verify Installation

# Type a comment and press Tab
# remove all log files
<Tab>

# Should see spinner, then command appears

Quick Start

1. Authenticate OpenCode

Ensure you have an AI provider authenticated:

# Check authentication status
opencode auth list

# If GitHub Copilot not authenticated
opencode config
# Select GitHub Copilot and follow prompts

2. Try Your First Command

# Type a natural language comment (starts with #)
$ # list all files

# Press Tab key
⠋ AI generating command...

# Command appears clean
$ ls -la

# Press Enter to execute

3. Explore Examples

# Find files
# find all PDF files modified in last week
<Tab>
→ find . -type f -name "*.pdf" -mtime -7

# System operations
# show disk usage sorted by size
<Tab>
→ du -sh * | sort -h

# Git operations
# show git commits from last month
<Tab>
→ git log --since="1 month ago" --oneline

# Process management
# kill all node processes
<Tab>
→ pkill -f node

Press ? for examples, Ctrl+C to cancel generation.


Features

🚀 Core Features

  • Natural language → command conversion: Describe intent, get executable command
  • Tab key trigger: Seamless integration with existing Tab completion
  • Animated spinner: Visual feedback during AI generation (~8s response time)
  • Clean prompt handling: Original comment removed, only command visible
  • Multiple AI models: GitHub Copilot, OpenAI GPT-4, Anthropic Claude supported

🎨 Advanced Features

  • fzf-tab compatibility: Falls back to standard completion for non-# lines
  • Multi-format response parsing: Handles markdown blocks, inline code, raw text
  • Prompt echo removal: Strips duplicated prompt from AI responses
  • Configurable model selection: Switch models via environment variable
  • Spinner customization: Adjust animation speed and style

🤖 Integration Features

  • OpenCode integration: Uses local OpenCode server for AI access
  • GitHub Copilot support: Authenticated provider, ~8s response time
  • OpenAI support: Requires re-authentication, ~2-4s response time
  • Anthropic support: Alternative AI provider option

Configuration

Configuration is merged from multiple sources (in order of precedence):

  1. Defaults (hardcoded in plugin)
  2. Environment variables (highest priority)

Environment Variables

# Set AI model (default: github-copilot/gpt-4o)
export OPENCODE_MODEL="github-copilot/gpt-4o"

# Alternative models (requires authentication)
export OPENCODE_MODEL="openai/gpt-4"
export OPENCODE_MODEL="anthropic/claude-3-5-sonnet-20241022"

# Adjust spinner animation speed (default: 0.1 seconds)
export OPENCODE_SPINNER_DELAY=0.1

# Set in ~/.zshrc for persistence
echo 'export OPENCODE_MODEL="github-copilot/gpt-4o"' >> ~/.zshrc

Plugin Configuration

No config file needed. All settings via environment variables.


Usage

Common Workflows

# File operations
# copy all images to backup folder
<Tab>
→ cp *.{jpg,png,gif} backup/

# compress all logs into archive
<Tab>
→ tar -czf logs.tar.gz *.log

# find files larger than 100MB
<Tab>
→ find . -type f -size +100M

# System monitoring
# show top 10 memory consuming processes
<Tab>
→ ps aux --sort=-%mem | head -11

# check listening ports
<Tab>
→ lsof -iTCP -sTCP:LISTEN -n -P

# Git workflows
# undo last commit but keep changes
<Tab>
→ git reset --soft HEAD~1

# show files changed in last commit
<Tab>
→ git diff --name-only HEAD~1

# Network operations
# download file from URL
<Tab>
→ curl -O <URL>

# test network connectivity to domain
<Tab>
→ ping -c 4 google.com

How It Works

  1. Type comment: Start line with # followed by natural language
  2. Press Tab: Triggers AI generation
  3. See spinner: Visual feedback during processing (~8s)
  4. Review command: AI-generated command appears in buffer
  5. Execute or edit: Press Enter to run, or edit before running

Tips

  • Be specific: More detail = better commands

    • # list files
    • # list all files including hidden sorted by modification time
  • Include context: Mention file types, paths, constraints

    • # find files
    • # find all .log files in /var/log modified today
  • Use natural language: Write like you're asking a human

    • # show me the 10 largest files in current directory
    • # kill all processes using port 8080

Development

Prerequisites

  • Zsh 5.0+ (required for ZLE widgets)
  • Python 3.x (for response parsing)
  • OpenCode (installed and running)

Project Structure

zsh-opencode-plugin/
├── zsh-opencode-ai.plugin.zsh    # Main plugin file (ZLE widget)
├── README.md                      # This file
├── AGENTS.md                      # AI agent development guidelines
├── LICENSE                        # MIT License
├── .gitignore                    # Git ignore rules
├── banner.svg                     # Project banner (generated)
├── banner.png                     # Project banner (generated)
└── docs/                          # Local documentation (gitignored)
    └── INSTALL.md                 # Detailed installation guide

How It Works (Technical)

  1. ZLE Widget Binding: ^I (Tab) bound to _opencode_ai_suggest_or_fzf
  2. Trigger Detection: Checks if BUFFER starts with #
  3. Prompt Extraction: Strips # and whitespace from buffer
  4. Line Clearing: zle kill-whole-line removes original prompt
  5. Spinner Start: Background process with Braille animation (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏)
  6. OpenCode Call: opencode run --model <MODEL> "<SYSTEM_PROMPT>"
  7. Response Parsing: Python script handles markdown/inline/raw formats
  8. Spinner Kill: Clean shutdown of background process
  9. Command Insertion: Only generated command placed in BUFFER
  10. Fallback: Non-# lines fall through to fzf-tab or default completion

Key Dependencies

Coding Guidelines

  • Formatter: shfmt -w zsh-opencode-ai.plugin.zsh before commit
  • Linter: shellcheck zsh-opencode-ai.plugin.zsh must pass
  • Keep Zsh widget logic minimal and readable
  • Test with multiple AI models (GitHub Copilot, OpenAI, Anthropic)
  • Ensure spinner cleanup on all exit paths
  • Handle edge cases (empty prompts, network failures, timeout)

Troubleshooting

"No command generated" or Empty Response

Cause: AI model not authenticated or unavailable

Fix:

# Check authentication
opencode auth list

# Re-authenticate if needed
opencode config

"Prompt still visible after Tab press"

Cause: ZLE widget not properly bound or conflicting plugin

Fix:

# Check binding
bindkey | grep '\^I'

# Should show: "^I" _opencode_ai_suggest_or_fzf

# Disable conflicting plugins temporarily
# Edit ~/.zshrc, comment out other Tab completion plugins

"Spinner leaves artifacts on screen"

Cause: /dev/tty write issue or terminal doesn't support \r\033[K

Fix:

# Test terminal capabilities
printf "\r\033[K" > /dev/tty

# Try different terminal emulator (iTerm2, Kitty, Alacritty)

"Slow response time (>15 seconds)"

Cause: Using OpenAI without authentication or network latency

Fix:

# Switch to GitHub Copilot (faster)
export OPENCODE_MODEL="github-copilot/gpt-4o"

# Or re-authenticate OpenAI for faster API access
opencode config

"Wrong command generated"

Cause: Ambiguous prompt or model misunderstanding

Fix:

  • Be more specific in your natural language description
  • Include file types, paths, constraints explicitly
  • Test different phrasings
  • Check if model supports your use case

"Authentication error: 401"

Cause: OpenAI OAuth token expired

Fix:

# Re-authenticate
opencode config

# Select OpenAI provider
# Follow OAuth flow in browser

# Verify authentication
opencode auth list

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feat/amazing-feature)
  3. Make your changes
  4. Test thoroughly (multiple shells, AI models, edge cases)
  5. Lint code (shellcheck zsh-opencode-ai.plugin.zsh)
  6. Commit your changes (git commit -m 'feat(completion): add amazing feature')
  7. Push to the branch (git push origin feat/amazing-feature)
  8. Open a Pull Request

Code Review Process

  • All PRs require review before merging
  • Code must pass shellcheck linting
  • Must test with at least 2 AI models
  • Update documentation as needed
  • Follow conventional commit format

License

This project is licensed under the MIT License - see the LICENSE file for details.


Acknowledgments

Built using:

  • OpenCode - AI model orchestration and session management
  • GitHub Copilot - Default AI provider for command generation
  • Zsh - Shell and ZLE (Zsh Line Editor) framework

Inspired by:

Special thanks to early testers and contributors.


Support


Stop googling. Start describing. 🤖

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages