Default: http://localhost:8000
Configurable via CODERRR_BACKEND environment variable.
The backend API requires authentication via GitHub Models or Mistral AI:
GitHub Models (default):
GITHUB_TOKEN=your_github_personal_access_token
MISTRAL_ENDPOINT=https://models.inference.ai.azure.com
MISTRAL_MODEL=mistral-large-2411Mistral AI:
MISTRAL_API_KEY=your_mistral_api_key
MISTRAL_ENDPOINT=https://api.mistral.ai
MISTRAL_MODEL=mistral-large-latestHealth check endpoint.
Response:
{
"message": "Coderrr backend is running 🚀",
"version": "1.0.0",
"status": "healthy"
}Status Codes:
200 OK- Backend is running
Send a chat request to the AI backend.
Request Body:
{
"prompt": "string", // Required: User's request
"temperature": 0.2, // Optional: Response randomness (0.0-1.0)
"max_tokens": 2000, // Optional: Maximum response length
"top_p": 1.0 // Optional: Nucleus sampling (0.0-1.0)
}Example Request:
curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{
"prompt": "Create a simple Node.js HTTP server",
"temperature": 0.2,
"max_tokens": 2000
}'Response:
{
"response": "{\"explanation\": \"Creating a basic HTTP server...\", \"plan\": [...]}"
}Error Response:
{
"error": "string", // Error type
"details": "string" // Detailed error message
}Status Codes:
200 OK- Request successful400 Bad Request- Invalid request body401 Unauthorized- Missing or invalid API key500 Internal Server Error- Backend error
Expected JSON Response Schema:
The AI must return this structure:
{
"explanation": "Brief summary of the plan",
"plan": [
{
"action": "create_file|update_file|patch_file|delete_file|read_file|run_command",
"path": "relative/path/to/file.js",
"content": "full file content (for file actions)",
"command": "shell command (for run_command)",
"summary": "one-line description of this step"
}
]
}Supported Actions:
create_file- Create new file (requirespath,content)update_file- Replace entire file (requirespath,content)patch_file- Modify specific parts (requirespath,content)delete_file- Remove file (requirespath)read_file- Read file (requirespath)run_command- Execute command (requirescommand)
Main orchestrator for AI interactions.
const Agent = require('./src/agent');
const agent = new Agent({
workingDir: '/path/to/project', // Optional: defaults to process.cwd()
backendUrl: 'http://localhost:8000' // Optional: defaults to CODERRR_BACKEND env var
});Process a user request and execute the resulting plan.
Parameters:
userInput(string) - User's natural language request
Returns: Promise<void>
Example:
await agent.process('Create a TODO app with React');Behavior:
- Scans codebase (if first request)
- Enhances prompt with project context
- Sends request to backend
- Parses JSON response
- Displays TODO list
- Executes plan
- Runs tests (if applicable)
Send a raw chat request to the backend.
Parameters:
prompt(string) - Prompt text (can include codebase context)
Returns: Promise<string> - Raw AI response
Example:
const response = await agent.chat('Explain this code: ...');
console.log(response);Execute a parsed plan.
Parameters:
plan(array) - Array of operation objects
Returns: Promise<void>
Example:
const plan = [
{ action: 'create_file', path: 'test.js', content: 'console.log("hi");' }
];
await agent.executePlan(plan);Auto-detect and run tests for the project.
Returns: Promise<void>
Example:
await agent.runTests();Detection Logic:
package.json→npm testpytest.iniortests/→pytestgo.mod→go test ./...Cargo.toml→cargo test
Force refresh the codebase scan cache.
Returns: Promise<void>
Example:
await agent.refreshCodebase();Search for files matching a pattern.
Parameters:
searchTerm(string) - Search pattern (case-insensitive)
Returns: Array<{path, name, size}> - Matching files
Example:
const jsFiles = agent.findFiles('.js');
console.log(jsFiles);
// [{ path: 'src/agent.js', name: 'agent.js', size: 31234 }, ...]Get summary of the scanned codebase.
Returns: string - Formatted codebase summary
Example:
const summary = agent.getCodebaseSummary();
console.log(summary);
// Working Directory: /path/to/project
// Total Files: 25
// Total Directories: 4
// ...Handle file operations.
const FileOperations = require('./src/fileOps');
const fileOps = new FileOperations('/path/to/project');Create a new file.
Parameters:
path(string) - Relative file pathcontent(string) - File content
Returns: Promise<void>
Example:
await fileOps.createFile('src/utils.js', 'module.exports = {};');Read a file.
Parameters:
path(string) - Relative file path
Returns: Promise<string> - File content
Example:
const content = await fileOps.readFile('package.json');
console.log(content);Replace entire file content.
Parameters:
path(string) - Relative file pathcontent(string) - New file content
Returns: Promise<void>
Example:
await fileOps.updateFile('README.md', '# New Title\n\n...');Modify parts of a file (simple string replacement).
Parameters:
path(string) - Relative file pathcontent(string) - New content to replace old
Returns: Promise<void>
Example:
await fileOps.patchFile('config.js', 'port: 5000');Delete a file.
Parameters:
path(string) - Relative file path
Returns: Promise<void>
Example:
await fileOps.deleteFile('old-file.js');Execute a file operation from a plan step.
Parameters:
operation(object) - Operation object withaction,path,content
Returns: Promise<void>
Example:
await fileOps.execute({
action: 'create_file',
path: 'test.js',
content: 'console.log("test");'
});Execute shell commands safely.
const Executor = require('./src/executor');
const executor = new Executor('/path/to/project');Execute a shell command.
Parameters:
command(string) - Shell command to executeoptions(object) - Execution optionsrequirePermission(boolean) - Prompt user for permission (default: true)cwd(string) - Working directory (default: workingDir)shell(string) - Shell to use (default: 'powershell.exe' on Windows)
Returns: Promise<{stdout, stderr, code}> - Execution result
Example:
const result = await executor.execute('npm install', {
requirePermission: true,
cwd: '/path/to/project'
});
console.log(result.stdout);Scan project structure.
const CodebaseScanner = require('./src/codebaseScanner');
const scanner = new CodebaseScanner('/path/to/project');Scan the codebase.
Parameters:
forceRefresh(boolean) - Bypass cache (default: false)
Returns: Promise<{structure, files, summary}> - Scan results
Example:
const results = await scanner.scan();
console.log(results.summary);
// { totalFiles: 25, totalDirectories: 4, totalSize: 512000 }Get formatted summary for AI context.
Returns: string - Formatted summary
Example:
const summary = scanner.getSummaryForAI();
// Includes file list, directory structure, working dirSearch for files.
Parameters:
searchTerm(string) - Search pattern (case-insensitive)
Returns: Array<{path, name, size}> - Matching files
Example:
const tests = scanner.findFiles('test');
console.log(tests);Clear the scan cache.
Returns: void
Example:
scanner.clearCache();User interface utilities.
Display a section header.
Parameters:
title(string) - Section title
Example:
ui.section('Starting Build');Display success message.
Parameters:
message(string) - Success message
Example:
ui.success('Build complete!');Display error message.
Parameters:
message(string) - Error message
Example:
ui.error('Failed to connect');Display warning message.
Parameters:
message(string) - Warning message
Example:
ui.warning('Deprecated API usage');Display info message.
Parameters:
message(string) - Info message
Example:
ui.info('Scanning codebase...');Prompt for confirmation.
Parameters:
message(string) - Prompt messagedefaultValue(boolean) - Default answer (default: true)
Returns: Promise<boolean> - User's answer
Example:
const proceed = await ui.confirm('Continue?', true);
if (proceed) {
// Do something
}Create a spinner.
Parameters:
message(string) - Spinner message
Returns: Ora - Spinner instance
Example:
const spin = ui.spinner('Loading...');
spin.start();
// ... do work ...
spin.succeed('Done!');Display file operation.
Parameters:
action(string) - Operation typepath(string) - File pathstatus(string) - Status (optional: 'success', 'error')
Example:
ui.displayFileOp('create_file', 'src/test.js', 'success');
// Output: ✓ create_file: src/test.jsDisplay command before execution.
Parameters:
command(string) - Command to display
Example:
ui.displayCommand('npm install');
// Output: $ npm installInteractive mode - starts a REPL session.
Usage:
coderrrExample:
$ coderrr
? What would you like me to do? Create a REST API with Express
[Agent processes request...]Execute a single request.
Usage:
coderrr exec "<natural language request>"Example:
$ coderrr exec "Add error handling to server.js"
[Agent processes request...]Start the backend server.
Usage:
coderrr startBehavior:
- Starts FastAPI backend on port 5000
- Enables auto-reload in development
- Logs to stdout
| Code | Meaning | Resolution |
|---|---|---|
ECONNREFUSED |
Cannot connect to backend | Start backend with uvicorn main:app --reload --port 5000 |
AUTH_ERROR |
Invalid API key | Check GITHUB_TOKEN or MISTRAL_API_KEY |
JSON_PARSE_ERROR |
Invalid AI response | Check backend logs for raw response |
TIMEOUT |
Request timeout | Increase TIMEOUT_MS in .env |
| Code | Meaning | Resolution |
|---|---|---|
FILE_NOT_FOUND |
File doesn't exist | Check file path |
PERMISSION_DENIED |
No write permissions | Check directory permissions |
INVALID_ACTION |
Unknown operation | Check plan action type |
USER_CANCELLED |
User declined permission | Expected behavior |
- Rate Limit: 15 requests/minute (free tier)
- Token Limit: 128,000 tokens/request
- Retry: Exponential backoff recommended
- Rate Limit: Varies by plan
- Token Limit: Varies by model
- Retry: Check
Retry-Afterheader
-
Always check backend health before requests:
curl http://localhost:8000
-
Use appropriate temperature:
0.0-0.3for code generation (deterministic)0.5-0.7for creative tasks0.8-1.0for brainstorming
-
Set max_tokens wisely:
- Small changes: 1000 tokens
- Medium projects: 2000 tokens
- Large projects: 4000 tokens
-
Handle errors gracefully:
try { await agent.process(request); } catch (error) { if (error.code === 'ECONNREFUSED') { // Handle connection error } else { // Generic error handling } }
-
Clear cache when needed:
// After major file changes await agent.refreshCodebase();
For more details, see ARCHITECTURE.md and examples/