codestral
v1.1.1
Published
AI-powered terminal coding assistant using Mistral AI
Maintainers
Readme
Codestral AI Terminal Assistant
An intelligent AI-powered terminal coding assistant that integrates Mistral AI to provide comprehensive code assistance directly in your terminal. Build complete applications, get code reviews, search codebases, and let the AI autonomously execute tasks using powerful agentic capabilities.
✨ Features
- 🤖 Interactive AI Conversations - Chat with Mistral AI directly in your terminal
- 📁 File Mention System - Reference files using
@filenamesyntax for context-aware assistance - 🔍 Intelligent Codebase Understanding - Automatic indexing and analysis of your project structure
- ✏️ Autonomous Code Modification - AI can read, write, and modify files with your approval
- 🛠️ Agentic Tool Execution - AI autonomously uses tools to accomplish complex tasks
- 🏗️ Complete Project Scaffolding - Build entire websites, APIs, and applications from scratch
- 💾 Session Persistence - Maintain conversation context across sessions
- 🎨 Rich Terminal Interface - Syntax highlighting, spinners, and formatted output
- 🔒 Configurable Autonomy Modes - Control how much the AI can do without your approval
- 🔍 Advanced Search - Search through your codebase with regex and filtering support
📦 Installation
Prerequisites
- Node.js v18.0.0 or higher
- npm or yarn package manager
- Mistral AI API key (Get one here)
Install Globally
npm install -g codestralInstall Locally
git clone <repository-url>
cd codestral
npm install🚀 Quick Start
1. Install Globally
npm install -g codestral2. Run Codestral
codestral3. Web Setup (First Time Only)
On first run, a beautiful web page opens in your browser for easy setup:
- Enter your Mistral AI API key
- Choose your preferred AI model
- Select autonomy mode
- Click "Complete Setup"
Get your API key from: https://console.mistral.ai/
That's it! Your configuration is saved in ~/.codestralrc.json and you can now use codestral from any terminal, anytime!
Note: If the browser doesn't open, the URL will be shown in the terminal, or it will fall back to a simple terminal prompt.
2. Basic Usage
# Ask general questions
> What is the difference between let and const in JavaScript?
# Mention files for context-aware help
> Can you review @src/app.js and suggest improvements?
# Let AI build complete projects
> Build me a React todo app with local storage
# Search your codebase
> /search "useState" --type js
# Get help
> /help📖 Usage Guide
File Mentions (@-syntax)
Reference files in your prompts using the @ symbol:
# Single file
> Explain the code in @src/utils.js
# Multiple files
> Compare @old-version.js and @new-version.js
# Glob patterns
> Review all components in @src/components/**/*.jsx
# Autocomplete support
> @src/comp<TAB> # Shows: components/, config.js, etc.Available Commands
| Command | Description | Example |
|---------|-------------|---------|
| /help | Show all available commands | /help |
| /clear | Clear conversation context | /clear |
| /files | Show files currently in context | /files |
| /config | Display current configuration | /config |
| /setup | Run configuration setup wizard | /setup |
| /set <key> <value> | Update configuration value | /set temperature 0.8 |
| /search <query> | Search codebase | /search "function.*async" |
| /mode <mode> | Change autonomy mode | /mode autonomous |
| /tools | List available AI tools | /tools |
Autonomy Modes
Control how much the AI can do without your explicit approval:
Safe Mode (Default)
- ✅ Auto-approve: Reading files, searching, listing directories
- ❓ Requires approval: Writing files, executing commands
> /mode safeAutonomous Mode
- ✅ Auto-approve: All file operations, safe commands
- ❓ Requires approval: System commands, dangerous operations
> /mode autonomousFull Mode
- ✅ Auto-approve: All operations except dangerous commands
- ❓ Requires approval: Only destructive operations (rm -rf, sudo, etc.)
> /mode fullAI Tools
The AI has access to these tools for autonomous task execution:
| Tool | Purpose | Auto-approved in |
|------|---------|------------------|
| read_file | Read file contents | All modes |
| write_file | Create/modify files | Autonomous, Full |
| list_directory | List directory contents | All modes |
| search_code | Search through codebase | All modes |
| execute_command | Run shell commands | Full mode only |
| replace_in_file | Find and replace in files | Autonomous, Full |
| create_directory | Create directories | Autonomous, Full |
| create_multiple_files | Batch file creation | Autonomous, Full |
🔧 Configuration
Configuration File
Configuration is stored in ~/.codestralrc.json:
{
"mistral": {
"apiKey": "your-api-key",
"model": "mistral-large-latest",
"maxTokens": 4000,
"temperature": 0.7
},
"context": {
"maxMessages": 50,
"maxTokens": 32000
},
"files": {
"maxFileSize": 1048576,
"ignorePatterns": ["node_modules/**", ".git/**", "*.log"]
},
"ui": {
"theme": "default",
"syntaxHighlight": true
},
"logging": {
"level": "info",
"file": "~/.codestral/logs/app.log"
},
"agent": {
"autonomyMode": "safe",
"autoApproveTools": ["read_file", "list_directory", "search_code"],
"dangerousCommands": ["rm -rf", "sudo", "chmod 777"],
"maxToolCalls": 10
}
}Environment Variables
You can also configure using environment variables:
export MISTRAL_API_KEY="your-api-key"
export CODESTRAL_MODEL="mistral-large-latest"
export CODESTRAL_AUTONOMY_MODE="autonomous"
export CODESTRAL_LOG_LEVEL="debug"Runtime Configuration
Update configuration during a session:
# Update API key
> /set apiKey your-new-key
# Change model
> /set model mistral-medium-latest
# Adjust temperature
> /set temperature 0.9
# Change autonomy mode
> /mode autonomous🎯 Example Use Cases
Code Review and Analysis
> Can you review @src/api/users.js for security issues and performance improvements?
🤖 I'll analyze your users.js file for security and performance issues.
[AI reads the file and provides detailed analysis]
Found several areas for improvement:
1. SQL injection vulnerability on line 45
2. Missing input validation for email field
3. Inefficient database query in getUserById()
Would you like me to fix these issues?
> Yes, please fix them
🔧 I'll create improved versions of the problematic functions...
[AI uses tools to modify the file with fixes]Building Complete Applications
> Build me a complete e-commerce website with product listings, shopping cart, and checkout
🤖 I'll create a complete e-commerce website for you. Here's the plan:
📋 Project Structure:
├── index.html (Homepage)
├── products.html (Product catalog)
├── cart.html (Shopping cart)
├── checkout.html (Checkout form)
├── css/ (Stylesheets)
├── js/ (JavaScript functionality)
└── assets/ (Images and resources)
This will create 15 files total. Proceed? (y/n)
> y
🔧 Creating project files...
✅ Created index.html with responsive layout
✅ Created products.html with product grid
✅ Created cart.html with cart management
✅ Created checkout.html with form validation
✅ Created CSS files with modern styling
✅ Created JavaScript for cart functionality
✅ Created README.md with setup instructions
🎉 E-commerce website created! Open index.html to get started.Codebase Exploration
> What's the overall architecture of this project?
🤖 Let me analyze your project structure...
[AI uses tools to scan directories and read key files]
📊 Project Analysis:
- **Type**: Node.js application with Express.js
- **Architecture**: MVC pattern with service layer
- **Database**: MongoDB with Mongoose ODM
- **Frontend**: React.js with Redux for state management
- **Testing**: Jest with 85% code coverage
- **Key Dependencies**: express, mongoose, react, redux
📁 Directory Structure:
- `/src/controllers/` - Route handlers and business logic
- `/src/models/` - Database schemas and models
- `/src/services/` - Business logic and external API calls
- `/src/middleware/` - Authentication and validation
- `/client/` - React frontend application
🔍 Potential improvements:
1. Add API documentation with Swagger
2. Implement rate limiting middleware
3. Add database connection poolingDebugging and Troubleshooting
> I'm getting a "Cannot read property 'map' of undefined" error. Can you help debug @src/components/ProductList.jsx?
🤖 I'll analyze the ProductList component to identify the issue.
[AI reads the file and analyzes the code]
🐛 Found the issue! On line 23, you're trying to call `.map()` on `products` before checking if it exists.
The problem occurs when the component renders before the API call completes, so `products` is initially `undefined`.
🔧 Here's the fix:
```jsx
// Before (line 23)
{products.map(product => (
// After (recommended)
{products?.map(product => (
// or
{Array.isArray(products) && products.map(product => (Would you like me to apply this fix?
Yes
✅ Fixed the undefined error in ProductList.jsx
## 🔍 Advanced Features
### Search and Navigation
```bash
# Text search
> /search "async function"
# Regex search
> /search "function.*async" --regex
# Filter by file type
> /search "useState" --type jsx,tsx
# Search in specific directory
> /search "API_URL" --dir src/config
# Case sensitive search
> /search "MyComponent" --case-sensitiveSession Management
# Save current session
> /save my-session
# Load previous session
> /load my-session
# List saved sessions
> /sessions
# Auto-save (enabled by default)
# Sessions are automatically saved every 10 messagesProject Templates
# Available templates
> /templates
# Create from template
> Create a new React app called "my-portfolio"
🤖 I'll create a React application using the react-app template.
[AI creates complete React project structure]
# Custom templates
> Build me a Node.js REST API with authentication, rate limiting, and MongoDB🛠️ Development
Running from Source
git clone <repository-url>
cd codestral
npm install
# Development mode with auto-reload
npm run dev
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Generate coverage report
npm run test:coverageProject Structure
codestral/
├── bin/
│ └── codestral.js # CLI entry point
├── src/
│ ├── agent/ # Agent orchestration & approval
│ │ ├── AgentOrchestrator.js
│ │ └── ApprovalManager.js
│ ├── ai/ # Mistral AI integration
│ │ └── MistralClient.js
│ ├── cli/ # Terminal interface
│ │ ├── CommandHandler.js
│ │ └── TerminalInterface.js
│ ├── config/ # Configuration management
│ │ └── ConfigManager.js
│ ├── context/ # Context & session management
│ │ └── ContextManager.js
│ ├── executor/ # Command execution
│ │ └── CommandExecutor.js
│ ├── filesystem/ # File system operations
│ │ └── FileSystemManager.js
│ ├── indexer/ # Codebase indexing
│ │ └── CodebaseIndexer.js
│ ├── mentions/ # @-mention resolution
│ │ └── MentionResolver.js
│ ├── modifier/ # File modification
│ │ └── FileModifier.js
│ ├── parser/ # Input parsing
│ │ └── InputParser.js
│ ├── search/ # Search functionality
│ │ └── SearchEngine.js
│ ├── tools/ # AI tool registry
│ │ ├── ToolRegistry.js
│ │ └── handlers/ # Individual tool implementations
│ └── utils/ # Utilities & logging
│ ├── ErrorHandler.js
│ └── logger.js
├── tests/ # Test files
├── coverage/ # Test coverage reports
└── logs/ # Application logs🐛 Troubleshooting
Common Issues
API Key Issues
Problem: Authentication failed or Invalid API key
Solutions:
- Verify your API key is correct:
/config - Update API key:
/set apiKey your-new-key - Check environment variable:
echo $MISTRAL_API_KEY - Run setup wizard:
/setup
File Access Issues
Problem: Permission denied or File not found
Solutions:
- Check file permissions:
ls -la filename - Verify file path is correct (use tab completion)
- Ensure you're in the correct directory
- Check if file is in
.gitignore
Memory Issues
Problem: Out of memory or slow performance
Solutions:
- Reduce context window:
/set maxTokens 2000 - Clear context frequently:
/clear - Exclude large directories in config:
"ignorePatterns": ["node_modules/**", "dist/**", "*.log"] - Use file size limits:
/set maxFileSize 500000
Network Issues
Problem: Connection timeout or Rate limit exceeded
Solutions:
- Check internet connection
- Wait for rate limit reset (usually 1 minute)
- Reduce request frequency
- Use a different model:
/set model mistral-medium-latest
Debug Mode
Enable verbose logging for troubleshooting:
# Enable debug logging
> /set logLevel debug
# Check logs
tail -f ~/.codestral/logs/app.log
# Or set environment variable
export CODESTRAL_LOG_LEVEL=debug
codestralGetting Help
- In-app help:
/help - Check configuration:
/config - View logs: Check
~/.codestral/logs/app.log - Reset configuration: Delete
~/.codestralrc.jsonand restart - Report issues: Include logs and configuration when reporting bugs
Performance Tips
- Use specific file mentions instead of large glob patterns
- Clear context regularly to prevent memory buildup
- Configure ignore patterns to exclude unnecessary files
- Use appropriate autonomy mode for your workflow
- Limit file size for large codebases
📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
