This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
AI Shell Command Generator: A cross-platform CLI tool that translates natural language queries into executable shell commands using AI providers (OpenAI, Anthropic Claude, and Ollama). Features risk assessment, teaching mode, and supports multiple shells (bash, PowerShell, cmd).
Entry Points:
ai_shell_command_generator/main.py- Package initialization and environment setupai_shell_command_generator/cli/commands.py- Main CLI command handler using Click
Published to PyPI as ai-shell-command-generator with aliases ai-shell and aisc
The codebase uses a factory pattern for AI providers. All providers implement BaseProvider abstract class.
Key files:
providers/base.py- Abstract base class defining provider interfaceproviders/factory.py-ProviderFactory.create_provider()instantiates providersproviders/anthropic_provider.py- Claude implementationproviders/openai_provider.py- GPT implementationproviders/ollama_provider.py- Local AI implementationproviders/models.py-ModelRegistry- centralized model definitions and validation
Provider responsibilities:
generate_command()- Generate shell command from natural languagegenerate_teaching_response()- Generate command + educational breakdownassess_risk()- Analyze command for safety concerns (deletion, permissions, etc.)list_available_models()- Return supported models
Adding a new provider:
- Create
providers/new_provider.pyextendingBaseProvider - Implement all abstract methods
- Add factory method in
factory.py - Register models in
models.pyModelRegistry
core/config.py contains dataclasses for configuration:
CommandConfig- Main config (provider, shell, mode flags)ProviderConfig- Per-provider settings (API keys, models)TeachingConfig- Teaching mode detail levels
Configuration flows: CLI args → Environment variables → Defaults
API Key Loading Priority (see main.py:12-27):
- Environment variables (e.g.,
OPENAI_API_KEY) ./.envin current directory (project-specific)~/.ai-shell-envin home directory (user-specific)- Interactive prompt with save option (only for Anthropic/OpenAI)
Interactive Mode (default):
- User selects provider/model via prompts (
cli/prompts.py) - Shell auto-detection with confirmation
- Interactive query loop with teaching/explanation options
- Implemented in
run_interactive_mode()incommands.py:133
Non-Interactive Mode (with -q flag):
- All parameters required via CLI flags
- Shell MUST be specified explicitly for safety (
commands.py:148-156) - Direct command output for scripting/CI/CD
- Implemented in
run_non_interactive_mode()incommands.py:92
Two-phase educational system:
Phase 1: Generate teaching response
- Providers parse structured sections (COMMAND, BREAKDOWN, OS NOTES, SAFER APPROACH, WHAT YOU LEARNED)
- Common parser in
teaching/formatter.py:parse_teaching_response() - Providers use structured prompts (see
_build_teaching_prompt()in each provider)
Phase 2: Interactive teaching loop
teaching/interactive.py:teaching_loop()- handles Q&A, examples, alternatives- Options: ask questions, see examples, explore alternatives, ready to use
- User can clarify, request variations, or request different approaches
All user-facing output goes through cli/display.py:
display_command()- Show generated commanddisplay_risk_warning()- Color-coded risk levels (HIGH/MEDIUM/LOW)display_teaching_output()- Formatted teaching sectionsdisplay_provider_info()- Show current provider/model
Risk Assessment Colors:
- HIGH (red) - Destructive operations, data loss risk
- MEDIUM (yellow) - Permission changes, system modifications
- LOW (green) - Safe operations
core/os_detection.py - Platform and shell detection
- Supported shells:
bash,powershell,cmd - Detects OS-specific command variants (BSD vs GNU)
- Generates platform-appropriate commands (e.g.,
Get-ChildItemfor PowerShell vsfindfor bash)
# Clone and create virtual environment
git clone https://github.com/codingthefuturewithai/ai-shell-command-generator.git
cd ai-shell-command-generator
# Install with all dependencies
uv pip install -e ".[dev]"# Run all tests
uv run pytest tests/ -v
# Run specific test category
uv run pytest tests/unit/ -v
uv run pytest tests/integration/ -v
# Run with coverage
uv run pytest tests/ -v --cov=ai_shell_command_generator --cov-report=html
# Run single test file
uv run pytest tests/unit/test_providers.py -v
# Run single test
uv run pytest tests/unit/test_providers.py::test_specific_function -vTest Structure:
tests/unit/- Unit tests for individual componentstests/integration/- Integration tests requiring API keys (optional)tests/integration/conftest.py- Shared fixtures, API key validation
Integration tests require:
- Real API keys in environment or
~/.ai-shell-env - Skip with markers if keys not available
- Use
@pytest.mark.integrationdecorator
# Build package
uv build
# Check package
twine check dist/*
# Upload to PyPI (requires credentials)
twine upload dist/*
# Upload to TestPyPI first (recommended)
twine upload --repository testpypi dist/*# Interactive mode
uv run python -m ai_shell_command_generator.main
# Non-interactive with Ollama (no API key needed)
uv run python -m ai_shell_command_generator.main -p ollama -s bash -q "find large files"
# With teaching mode
uv run python -m ai_shell_command_generator.main --teach -p ollama -s bash -q "backup documents"
# List models
uv run python -m ai_shell_command_generator.main --list-models anthropic# Enable debug logging
export LOG_LEVEL=DEBUG
uv run python -m ai_shell_command_generator.main -p anthropic -s bash -q "test"
# Check logs in provider files for API request/response details
# All providers log: model, tokens, prompt, response via utils/logger.pyEach provider has three prompt builders:
_build_command_prompt()- Simple command generation (max_tokens: 300)_build_teaching_prompt()- Structured teaching response (max_tokens: 1500)_build_risk_prompt()- JSON-formatted risk assessment (max_tokens: 200)
Critical: OpenAI uses system messages to reduce reasoning token usage (see openai_provider.py:172-185). Anthropic uses only user messages with instructions inline.
Providers return risk dict: {"is_risky": bool, "severity": "low/medium/high", "reason": str}
Assessment checks for:
- Data deletion (
rm -rf,dd, destructive operations) - Permission changes (
chmod,chown,setfacl) - System modifications (network settings, system files, services)
- Recursive operations (widespread changes)
- Network exposure (opening ports, firewall changes)
BaseProvider._clean_command() removes markdown formatting only:
- Strips markdown code blocks (
bash ...) - Preserves actual shell syntax (pipes, redirects, quotes)
- Does NOT interpret or validate shell semantics
Structured sections parsed from AI output:
COMMAND:
[command]
BREAKDOWN:
[explanation]
OS NOTES:
[platform specifics]
SAFER APPROACH:
[preview/alternative]
WHAT YOU LEARNED:
[key concepts]
Parsing handled by teaching/formatter.py:parse_teaching_response()
Ollama requires no API key (local). OpenAI and Anthropic prompt interactively if missing:
cli/prompts.py:prompt_for_api_key()- Interactive prompt- Option to save to
~/.ai-shell-envpermanently - Saved keys loaded on next run via
main.pyinitialization
- Type hints: Use throughout (Python 3.10+ syntax)
- Docstrings: Google style for classes/methods
- Line length: 88 characters (Black formatter)
- Imports: Standard lib → Third party → Local (separated by blank lines)
- Error handling: Specific exceptions, user-friendly messages via
cli/display.py
- Shell validation in non-interactive mode - MUST require
-sflag explicitly. Seeconfig.py:148-156 - Risk assessment opt-in - Default enabled, user can disable with
--no-risk-check - Command cleaning - Only remove markdown, never modify shell syntax
- API key security - Never log API keys, use environment variables
- Cross-platform testing - Test on Windows/macOS/Linux when changing shell-specific code
- Add to
providers/models.pyModelRegistrydictionaries - Update provider's
list_available_models()if needed - Test with
--list-modelsflag
- Edit provider's
_build_*_prompt()methods - Test with debug logging:
LOG_LEVEL=DEBUG - Verify token usage (logged in response)
- Update integration tests if behavior changes
- Add Click option in
cli/commands.py:main()decorator - Add field to
CommandConfigincore/config.py - Update
CommandConfig.from_cli_args()to handle new option - Update help text and README.md
- Enable debug logging:
export LOG_LEVEL=DEBUG - Check provider logs for API calls (request/response)
- Verify prompt format matches provider expectations
- Test with simple query first:
-q "list files"