A powerful CLI toolkit for extending and enhancing AI capabilities through customizable rules and commands.
Project description
ai-rules
🛠️ A powerful CLI toolkit for extending and enhancing AI capabilities through customizable rules and commands.
Transform your AI assistants (Cursor, Windsurf, Cline) into more capable development companions by crafting specialized instruction sets and custom commands.
Inspiration
This project is inspired by devin.cursorrules and the blog post Turning $20 into $500 - Transforming Cursor into Devin in One Hour. We extend these ideas by providing a systematic way to manage and enhance AI rules across different platforms.
Key Features
- 🧠 Extend AI capabilities through custom rules and commands
- 🔌 Plugin system for adding new AI functionalities
- 🌍 Support multiple AI platforms (Cursor, Windsurf, Cline)
- 🤖 LLM-powered tools (search, translation, etc.)
- 📝 Global and workspace-specific rule management
- ⚡ Command extension system for AI enhancement
Installation
pip install ai-rules
Quick Start
Initialize AI Assistant Rules
# Initialize rules for Windsurf
uvx ai-rules init windsurf
# Initialize rules for Cursor
uvx ai-rules init cursor
# Initialize rules for CLI
uvx ai-rules init cli
Use Built-in Plugins
# Search the web (supports Chinese and other languages)
uvx ai-rules plugin search --query "Python best practices" --limit 5
# Translate text (auto-detect source language)
uvx ai-rules plugin translate --text "Hello World" --target zh
# Web scraping (automatically installs required browser)
uvx ai-rules plugin web-scraper --urls https://example.com --format markdown
Debug Mode
Enable debug logging with the --debug flag or AI_RULES_DEBUG environment variable:
# Enable debug logging with flag
uvx ai-rules --debug plugin search --query "Python best practices"
# Enable debug logging with environment variable
export AI_RULES_DEBUG=1
uvx ai-rules plugin search --query "Python best practices"
Plugin Development Guide
Creating a Custom Plugin
-
Create a new Python file in one of these locations:
- Built-in plugins:
src/ai_rules/plugins/ - User plugins:
~/.ai-rules/plugins/ - Virtual environment plugins:
venv/lib/ai-rules/plugins/
- Built-in plugins:
-
Implement your plugin by inheriting from the Plugin base class:
"""Example plugin demonstrating basic structure."""
# Import built-in modules
import logging
from typing import Any, Dict
# Import third-party modules
import click
from pydantic import BaseModel, Field
# Import local modules
from ai_rules.core.plugin import Plugin, PluginParameter, PluginSpec
# Configure logger
logger = logging.getLogger(__name__)
class InputModel(BaseModel):
"""Input validation model."""
text: str = Field(..., description="Input text to process")
option: int = Field(42, description="An optional parameter")
class MyCustomPlugin(Plugin):
"""Your custom plugin description."""
def __init__(self) -> None:
"""Initialize plugin instance."""
super().__init__()
self.metadata.name = "my_plugin"
self.metadata.description = "Description of what your plugin does"
self.metadata.version = "1.0.0"
self.metadata.author = "Your Name"
def get_command_spec(self) -> Dict[str, Any]:
"""Define command line parameters."""
return PluginSpec(
params=[
PluginParameter(
name="text",
type=click.STRING,
required=True,
help="Input text to process"
),
PluginParameter(
name="option",
type=click.INT,
required=False,
help="An optional parameter (default: 42)"
)
]
).model_dump()
def execute(self, **kwargs: Dict[str, Any]) -> Dict[str, Any]:
"""Execute plugin functionality.
Args:
**kwargs: Keyword arguments from command line.
Returns:
Dict containing plugin results.
"""
try:
# Validate input
input_data = InputModel(**kwargs)
# Process input (your plugin logic here)
result = f"Processed {input_data.text} with option {input_data.option}"
logger.info("Successfully processed input")
# Return result
return {"result": result}
except Exception as e:
logger.error("Plugin execution failed: %s", e)
raise click.ClickException(str(e))
Plugin Requirements
- Base Class: Must inherit from
Plugin - Required Attributes (set in
__init__):name: Plugin command namedescription: Plugin descriptionversion: Plugin versionauthor: Plugin author
- Required Methods:
get_command_spec(): Define command parametersexecute(): Implement plugin logic
- Response Format:
All plugins use a standardized response format:
{ "status": "success", // or "error" "message": "Operation completed successfully", "data": { // Plugin-specific response data }, "error": null, // Error message if status is "error" "metadata": { "plugin_name": "example", "plugin_version": "1.0.0", "timestamp": "2025-01-14T18:04:54+08:00" } }
- Best Practices:
- Use Pydantic models for input/output validation
- Use logging instead of print statements
- Implement proper input validation
- Handle errors gracefully
- Add type hints and docstrings
- Use super().format_response() and super().format_error()
Parameter Types
The following Click types are supported:
click.STRING: Text inputclick.INT: Integer numbersclick.FLOAT: Floating point numbersclick.BOOL: Boolean flagsclick.Choice(['a', 'b']): Choice from options- More types in Click documentation
Built-in Plugins
- Search Plugin (source)
- Web search using DuckDuckGo
- Supports multiple languages
- Features:
- Configurable result limit
- Retry mechanism
- Rich error handling
- Standardized response format
# Basic search
uvx ai-rules plugin search --query "Python async/await"
# Limit results
uvx ai-rules plugin search --query "Python async/await" --limit 3
# Search in other languages
uvx ai-rules plugin search --query "Python 最佳实践"
Example response:
{
"status": "success",
"message": "Found 3 results for query: Python async/await",
"data": {
"results": [
{
"title": "Python asyncio: Async/Await Tutorial",
"link": "https://example.com/python-async",
"snippet": "A comprehensive guide to async/await in Python..."
}
]
},
"metadata": {
"plugin_name": "search",
"plugin_version": "1.0.0",
"timestamp": "2025-01-14T18:04:54+08:00"
}
}
- Translate Plugin (source)
- Text translation using LibreTranslate
- Features:
- Auto language detection
- Multiple language support
- Configurable source/target languages
# Basic translation (auto-detect source)
uvx ai-rules plugin translate --text "Hello World" --target zh
# Specify source language
uvx ai-rules plugin translate --text "Bonjour" --source fr --target en
Example response:
{
"status": "success",
"message": "Translated text from English to Chinese",
"data": {
"translation": "你好世界",
"source_language": "en",
"target_language": "zh"
},
"metadata": {
"plugin_name": "translate",
"plugin_version": "1.0.0",
"timestamp": "2025-01-14T18:04:54+08:00"
}
}
- Web Scraper Plugin (source)
- Web scraping using Playwright
- Features:
- Automatic browser installation
- Configurable URL and format
# Basic web scraping
uvx ai-rules plugin web-scraper --urls https://example.com --format markdown
Example response:
{
"status": "success",
"message": "Scraped content from https://example.com",
"data": {
"content": "# Example Website\n\nThis is an example website.",
"format": "markdown"
},
"metadata": {
"plugin_name": "web-scraper",
"plugin_version": "1.0.0",
"timestamp": "2025-01-14T18:04:54+08:00"
}
}
Using Your Plugin
Once installed, your plugin will be automatically discovered and registered:
# List available plugins
uvx ai-rules plugin --help
# Run your plugin
uvx ai-rules plugin my_plugin --text "input text" --option 123
# Run with debug logging
uvx ai-rules --debug plugin my_plugin --text "input text" --option 123
Documentation
Command Structure
- Initialize Rules
uvx ai-rules init <assistant-type>
assistant-type: windsurf, cursor, or cli- Creates configuration files in the current directory
- Use Plugins
uvx ai-rules plugin <plugin-name> [arguments]
Development
Project Structure
src/ai_rules/
├── core/
│ ├── plugin.py # Plugin system
│ ├── template.py # Template conversion
│ └── __init__.py
├── plugins/ # Built-in plugins
│ ├── duckduckgo_search.py # Search plugin
│ └── translate.py # Translation plugin
│ └── web_scraper.py # Web scraper plugin
├── templates/ # Rule templates
├── cli.py # CLI implementation
└── __init__.py
Contributing
Contributions are welcome! Please read our Contributing Guidelines first.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ai_rules-0.3.0.tar.gz.
File metadata
- Download URL: ai_rules-0.3.0.tar.gz
- Upload date:
- Size: 168.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.0.1 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7ba35d281a321bc7d6a925c91ef2b20b8b8496c82da292694fe7f507fd0d500e
|
|
| MD5 |
38f16ea010a5aa6c90a176cccd1007e2
|
|
| BLAKE2b-256 |
87a4cbfa2b5f762dbe420b4c343ad9f88eae1468ff2ef3d1c9487ce80eefafc2
|
Provenance
The following attestation bundles were made for ai_rules-0.3.0.tar.gz:
Publisher:
python-publish.yml on loonghao/ai-rules
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
ai_rules-0.3.0.tar.gz -
Subject digest:
7ba35d281a321bc7d6a925c91ef2b20b8b8496c82da292694fe7f507fd0d500e - Sigstore transparency entry: 163384682
- Sigstore integration time:
-
Permalink:
loonghao/ai-rules@60e9f8aa2d8033085779883cf537f0033720e9a4 -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/loonghao
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@60e9f8aa2d8033085779883cf537f0033720e9a4 -
Trigger Event:
push
-
Statement type:
File details
Details for the file ai_rules-0.3.0-py3-none-any.whl.
File metadata
- Download URL: ai_rules-0.3.0-py3-none-any.whl
- Upload date:
- Size: 56.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.0.1 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
01997a2e93a85e2516326aeed95194ff5db5dce31c7ed40e4820abdb839e29ad
|
|
| MD5 |
8a2df75d05b24b86ccdd25a5355136f0
|
|
| BLAKE2b-256 |
77f89d839a11b48d61f6bec93b783d58209a150178553a93959a8699bb2bdd78
|
Provenance
The following attestation bundles were made for ai_rules-0.3.0-py3-none-any.whl:
Publisher:
python-publish.yml on loonghao/ai-rules
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
ai_rules-0.3.0-py3-none-any.whl -
Subject digest:
01997a2e93a85e2516326aeed95194ff5db5dce31c7ed40e4820abdb839e29ad - Sigstore transparency entry: 163384683
- Sigstore integration time:
-
Permalink:
loonghao/ai-rules@60e9f8aa2d8033085779883cf537f0033720e9a4 -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/loonghao
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@60e9f8aa2d8033085779883cf537f0033720e9a4 -
Trigger Event:
push
-
Statement type: