Skip to content

maz557/coding-agent-free

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

132 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Coding Agent Free

Stars License Last Commit TypeScript CI
Why This Agent? β€’ Install β€’ Usage β€’ CLI β€’ Web

🌐 English β€’ فارسی β€’ Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ© β€’ TΓΌrkΓ§e β€’ EspaΓ±ol β€’ FranΓ§ais β€’ اردو

An interactive AI coding assistant that runs in your terminal or web browser β€” powered by free cloud APIs and local models (Ollama, LM Studio, Llama.cpp). It reads, writes, searches, copies, moves, and deletes files, and runs shell commands β€” all through natural language tool calling. Includes MCP (Model Context Protocol) and LSP (Language Server Protocol) support for extensibility and deep code understanding.

πŸ’‘ Offline-ready: With a local server, the agent works fully offline β€” no internet required, no data leaves your machine.


🧠 Why Coding Agent Free?

Problem Solution
Coding assistants cost $20/month (ChatGPT+, Claude Pro) 100% free β€” uses free-tier OpenRouter, Groq, Google, DeepSeek, Mistral + local models
One provider goes down / rate-limited 13 providers β€” auto-fallback on 429 + manual /model <n>
No internet access / restricted region Local models (Ollama, LM Studio, Llama.cpp) β€” fully offline
Privacy concerns with cloud APIs Run local models only β€” zero data leaves your machine
Setup is too complex npm run setup β€” interactive wizard, no manual .env editing
AI runs dangerous commands Safe mode (/safe) β€” whitelist-only shell commands
Agent gets stuck in loops Smart detection β€” stops after 3Γ— identical tool calls
Provider rate-limited Auto-fallback β€” switches provider automatically on 429
Long tool results waste tokens Token compression β€” head+tail truncation + duplicate removal
Want to extend with external tools MCP support β€” connect any Model Context Protocol server
Need deep code understanding LSP support β€” go to definition, find references, hover info
Want to use your IDE with free models OpenAI-compatible API β€” npm run setup-ide connects Cline, Continue.dev, Cursor

Key Features

  • 13 providers β€” OpenRouter, Groq, Google, DeepSeek, Mistral, Anthropic, Together AI, Perplexity, xAI (Grok), Cohere + Ollama, LM Studio, Llama.cpp
  • MCP (Model Context Protocol) β€” connect external tools (filesystem, GitHub API, databases, custom servers). Stdio + HTTP/SSE transports. /mcp list/connect/disconnect/toggle
  • LSP (Language Server Protocol) β€” code_definition, code_references, code_hover tools. Supports TypeScript, JavaScript, Python (pyright), Rust (rust-analyzer), Go (gopls). /lsp toggle
  • Multi-session management β€” named sessions in sessions/ directory, auto-title, modelPreset metadata. /session list/new/rename/delete
  • 5 built-in presets β€” start with openrouter/free (auto-discovers working free models)
  • User presets β€” save/add/remove your own models with /save, /add, /remove
  • Fallback chain β€” auto-fallback across providers on rate limit (429), plus model-level fallbacks
  • 13 built-in tools β€” read, write, list, create_folder, delete_file, delete_folder, append_file, copy_file, move_file, file_info, search_content, replace_in_file, run_command
  • Token compression β€” head+tail truncation + automatic duplicate removal
  • Sliding window context β€” keeps the last 20 exchanges, auto-trims (configurable)
  • Smart loop detection β€” stops after 3Γ— identical or 5Γ— consecutive tool calls
  • Safe mode (--safe / /safe) β€” whitelist-only shell commands
  • Setup wizard β€” npm run setup interactively configures .env
  • Automatic retry β€” exponential backoff + 120s timeout (300s for local models)
  • Zod validation β€” runtime type-checking of every tool input and output
  • CLI & Web unified β€” shared model config, system prompt, tool engine
  • AGENTS.md support β€” drop AGENTS.md in project root for project-specific context
  • Diff Viewer (Web UI) β€” line-level LCS diffs for file operations
  • Standalone binary β€” compile with npm run build:binary (no Node.js required)

πŸ› οΈ Requirements & Installation

Prerequisites

  • Node.js 18+ (or use the standalone binary β€” no Node.js needed)
  • npm (comes with Node.js)
  • Optional: One or more API keys (see Environment Variables)
  • Optional for local models: Ollama, LM Studio, or Llama.cpp
  • Optional for LSP: typescript-language-server, pyright, rust-analyzer, gopls, etc.

Quick Install

git clone https://github.com/maz557/coding-agent-free.git
cd coding-agent-free
npm install

Setup

Option A β€” Interactive wizard (recommended):

npm run setup

Option B β€” Manual .env (pick at least one provider):

# OpenRouter (easiest β€” single key for 18+ free tool-calling models)
echo "OPENROUTER_API_KEY=sk-or-v1-..." >> .env

# Optional providers:
echo "GROQ_API_KEY=gsk_..." >> .env      # Ultra-fast inference
echo "GOOGLE_API_KEY=AIza..." >> .env     # Gemini models
echo "DEEPSEEK_API_KEY=sk-..." >> .env    # DeepSeek
echo "MISTRAL_API_KEY=..." >> .env        # Mistral models

Option C β€” Local only (fully offline):

# Skip API keys β€” just start your local model server
ollama run qwen3:14b    # or LM Studio, Llama.cpp
npm start               # Inside agent: /add 6 ollama:auto && /model 6

Standalone Binary (no Node.js)

Build a single executable for Windows, Linux, or macOS:

npm run build:binary          # All platforms
npm run build:binary:win      # Windows only
npm run build:binary:web      # Web server binary
node scripts/build-binary.js node18-win-x64 coding-agent.exe  # Or via helper

IDE Integration

npm run setup-ide

Configures Cline, Continue.dev, and Cursor to use the local API proxy at http://localhost:3000/v1/chat/completions.

Environment Variables

Variable Required? Description
OPENROUTER_API_KEY No* OpenRouter β€” https://openrouter.ai/keys
GROQ_API_KEY No* Groq β€” https://console.groq.com/keys
GOOGLE_API_KEY No* Google AI Studio β€” https://aistudio.google.com/apikey
DEEPSEEK_API_KEY No* DeepSeek β€” https://platform.deepseek.com
MISTRAL_API_KEY No* Mistral β€” https://console.mistral.ai
ANTHROPIC_API_KEY No* Anthropic β€” https://console.anthropic.com
TOGETHER_API_KEY No* Together AI β€” https://api.together.xyz
PERPLEXITY_API_KEY No* Perplexity β€” https://www.perplexity.ai
XAI_API_KEY No* xAI (Grok) β€” https://console.x.ai
COHERE_API_KEY No* Cohere β€” https://dashboard.cohere.com
OLLAMA_HOST No Ollama server URL (default: http://localhost:11434/v1)
LMSTUDIO_HOST No LM Studio URL (default: http://localhost:1234/v1)
LLAMACPP_HOST No Llama.cpp URL (default: http://localhost:8080/v1)
ALLOWED_DIR No Directory for file operations (default: ./workspace)
LOCAL_TIMEOUT No Timeout (ms) for local models (default: 300000)
LOG_LEVEL No debug, info, warn, error (default: info)
MAX_EXCHANGES No Max exchanges in sliding window (default: 20)
MAX_TOOL_RESULT_LENGTH No Max chars before truncation (default: 5000)

* At least one API key required (not needed for local providers).

Project Structure

coding-agent-free/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ agent.ts                # CLI entry point
β”‚   β”œβ”€β”€ CodingAgent.ts          # Agent loop, tool execution, stuck detection
β”‚   β”œβ”€β”€ ConversationState.ts    # Sliding window, context trimming
β”‚   β”œβ”€β”€ server.ts               # Express web server (SSE, sessions, API)
β”‚   β”œβ”€β”€ persistence.ts          # Multi-session save/load
β”‚   β”œβ”€β”€ config/models.ts        # Provider definitions, presets, system prompt
β”‚   β”œβ”€β”€ tools/
β”‚   β”‚   β”œβ”€β”€ fileManager.ts      # 13 file/shell tools + safe mode
β”‚   β”‚   └── toolRegistry.ts     # Central registry (builtin + MCP + LSP)
β”‚   β”œβ”€β”€ mcp/                    # MCP support
β”‚   β”‚   β”œβ”€β”€ types.ts            # JSON-RPC types, Tool, Transport interface
β”‚   β”‚   β”œβ”€β”€ transport.ts        # StdioTransport (subprocess)
β”‚   β”‚   β”œβ”€β”€ HTTPTransport.ts    # HTTP/SSE transport
β”‚   β”‚   β”œβ”€β”€ MCPManager.ts       # Multi-server management
β”‚   β”‚   └── config.ts           # Load MCP servers from .coding-agent.json
β”‚   β”œβ”€β”€ lsp/                    # LSP support
β”‚   β”‚   β”œβ”€β”€ LSPClient.ts        # JSON-RPC LSP client over stdio
β”‚   β”‚   β”œβ”€β”€ LSPManager.ts       # Multi-language LSP server management
β”‚   β”‚   β”œβ”€β”€ config.ts           # Load LSP servers from .coding-agent.json
β”‚   β”‚   └── index.ts            # Tool definitions + execution router
β”‚   └── __tests__/              # 181 unit tests
β”œβ”€β”€ public/index.html           # Web UI (plain JS)
β”œβ”€β”€ sessions/                   # Session storage
β”œβ”€β”€ workspace/                  # Default working directory
β”œβ”€β”€ scripts/                    # Setup, build, test, cleanup scripts
β”œβ”€β”€ examples/mcp-echo-server.js # Minimal MCP server example
β”œβ”€β”€ .coding-agent.json          # MCP + LSP server configuration
β”œβ”€β”€ AGENTS.md                   # Auto-loaded project context
β”œβ”€β”€ tsconfig.json
└── package.json

πŸ“– Usage Guide

⌨️ CLI Interface

npm start

On Windows, double-click run-cli.bat. For RTL languages (Persian, Arabic, Urdu), use run-cli-rtl.bat (requires WezTerm).

The agent automatically connects MCP and LSP servers on startup, loads project context from AGENTS.md, and restores the last session.

🌐 Web Interface

npm run web
# Open http://localhost:3000 in your browser

On Windows, double-click run-web.bat.

Web UI features:

  • Streaming responses β€” token-by-token via SSE
  • Diff Viewer β€” line-level LCS diffs for write/replace/append operations
  • Session Manager β€” create, switch, list sessions with auto-title & metadata
  • Slash Commands β€” /active, /model <n>, /safe, /allow, /reset, /models, /exit, /mcp list, /mcp toggle, /lsp
  • Help Modal β€” click ? for usage guide, commands reference
  • OpenAI-compatible API β€” http://localhost:3000/v1/chat/completions

Example session:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  πŸ’¬ Coding Agent                       [πŸ”’ Safe] [🌐 P] β”‚
β”‚  ──────────────────────────────────────────────────────── β”‚
β”‚  You: create a hello.py that prints "Hello from Web UI"  β”‚
β”‚  ⏳ Thinking...                                           β”‚
β”‚  πŸ›   write_file(path="hello.py", content="...")           β”‚
β”‚  βœ”  File written (25 bytes)                               β”‚
β”‚  πŸ›   run_command(command="python hello.py")               β”‚
β”‚  βœ”  Hello from Web UI                                     β”‚
β”‚  Done! Created hello.py and verified it prints.           β”‚
β”‚  ──────────────────────────────────────────────────────── β”‚
β”‚  [Message input...                        ] [Send]       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Available Tools

Built-in Tools (always available)

Tool Description
read_file Read contents of a file
write_file Write content to a file (creates/overwrites)
list_files List directory contents. Use details:true for size + timestamps
create_folder Create a new folder
delete_file Delete a single file
delete_folder Delete a folder. Set recursive:true for non-empty folders
append_file Append content to an existing file
copy_file Copy a file from source to destination
move_file Move or rename a file
file_info Get detailed metadata (size, permissions, timestamps)
search_content Search for exact text in files. Supports filePattern and maxResults
replace_in_file Replace the first occurrence of exact text (case-sensitive)
run_command Run a shell command in the workspace

LSP Tools (toggle with /lsp)

Tool Description
code_definition Find where a symbol is defined (file:line:column)
code_references Find all references to a symbol
code_hover Get type signature / documentation for a symbol

MCP Tools (from connected servers)

Tools from connected MCP servers appear automatically alongside built-in tools. See MCP section.

Commands

Command Description
/model <n> Switch to preset n
/save <n> Save current model as preset n
/add <n> <m> Add model m as preset n (provider:model or just model)
/remove <n> Remove a user preset
/allow <p> Allow model to access a path outside workspace
/safe Toggle safe mode
/models Show all presets
/active Show current active model
/reset Clear conversation history
/session list List all sessions
/session new <name> Create a new session
/session rename <old> <new> Rename a session
/session delete <name> Delete a session
/mcp list List connected MCP servers and their tools
/mcp connect <name> <cmd> Connect a new MCP server
/mcp disconnect <name> Disconnect an MCP server
/mcp toggle Enable / disable all MCP tools
/lsp Toggle LSP tools
/list-providers Show providers with valid keys
/exit Quit

🧩 MCP (Model Context Protocol)

Connect external tools to the agent via MCP servers β€” filesystem, GitHub API, databases, custom tools, and more. Supports both stdio (subprocess) and HTTP/SSE (remote) transports.

Quick start:

  1. Install an MCP server: npm install -g @modelcontextprotocol/server-filesystem
  2. Add to .coding-agent.json:
    {
      "mcpServers": {
        "filesystem": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-filesystem", "./workspace"]
        }
      }
    }
  3. Start the agent β€” it connects automatically: πŸ”Œ MCP "filesystem" connected (2 tools)

Example MCP servers:

Server Install Purpose
Filesystem @modelcontextprotocol/server-filesystem Safe file operations with path boundaries
GitHub @modelcontextprotocol/server-github Repository management, PRs, issues
PostgreSQL @modelcontextprotocol/server-postgres Read-only database queries
Puppeteer @modelcontextprotocol/server-puppeteer Browser automation, screenshots

Create your own MCP server β€” see examples/mcp-echo-server.js for a minimal example.

πŸ”¬ LSP (Language Server Protocol)

Deep code understanding via code_definition, code_references, and code_hover tools. Auto-detects project files and starts appropriate LSP servers.

Supported languages (default):

Language LSP Server File Patterns
TypeScript/TSX typescript-language-server **/*.ts, **/*.tsx
JavaScript/JSX typescript-language-server **/*.js, **/*.jsx, **/*.mjs
Python pyright **/*.py
Rust rust-analyzer **/*.rs
Go gopls **/*.go

Custom LSP servers β€” add to .coding-agent.json:

{
  "lspServers": [
    {
      "command": "clangd",
      "args": [],
      "languageId": "cpp",
      "filePatterns": ["**/*.cpp", "**/*.h"]
    }
  ]
}

Toggle LSP at any time with /lsp. Falls back gracefully if no LSP server binary is installed.

Multi-Provider Usage

# Add a model from any provider
/add 10 groq:llama-3.3-70b-versatile
/add 11 google:gemini-2.0-flash-exp

# Switch presets
/model 10

Auto-fallback: if a provider returns 429, the agent automatically tries the next model in the fallback chain.

Local Models

# Ollama
ollama pull llama3.2 && ollama serve
# Inside agent: /add 6 ollama:auto

# LM Studio
lms get llama-3.2-3b-instruct && lms server start --port 1234
# Inside agent: /add 7 lmstudio:auto

# Llama.cpp
llama-server -m qwen2.5-coder-1.5b-instruct-q4_k_m.gguf --port 8080
# Inside agent: /add 8 llamacpp:auto

No API key required. The model must support tool calling (function calling).

Workspace & Permissions

By default, the agent can only access files inside ./workspace. Change with:

  • ALLOWED_DIR=. in .env (access everything)
  • /allow "C:\path" during a session (temporary)

Built-in Presets

# Model Provider Notes
1 openrouter/free OpenRouter Auto-routes to available free models
2 Qwen 3 Next 80B OpenRouter Good general purpose
3 Nemotron 3 Super 120B OpenRouter 1M context
4 OpenAI GPT-OSS 120B OpenRouter Strong reasoning
5 Nemotron 3 Ultra 550B OpenRouter Largest free model with tools

Recommended Free Coding Models

Groq (fastest):

/add 6 groq:openai/gpt-oss-120b       # 120B, 500 t/s
/add 7 groq:llama-3.3-70b-versatile   # 70B, 280 t/s

Mistral:

/add 10 mistral:codestral-latest       # Dedicated coding model
/add 11 mistral:mistral-large-latest   # Best quality

Google:

/add 14 google:gemini-2.0-flash-exp    # Fast, good coding

Example Interactions

You: /model 4
βœ… Switched to preset 4: openai/gpt-oss-120b:free

You: create a folder named demo and write a hello.py
⏳ Thinking... [Model: openai/gpt-oss-120b:free]
  πŸ”§ create_folder({"path":"demo"})
  πŸ”§ write_file({"path":"demo/hello.py","content":"print('Hello, world!')\n"})
Agent: Done! Created demo/hello.py with a Hello World script.

You: run the file
  πŸ”§ run_command({"command":"python demo/hello.py"})
Agent: Hello, world! β€” the script runs correctly.

You: /model 6
βœ… Switched to preset 6: [Groq] openai/gpt-oss-120b
   (now using Groq β€” same model, 500 t/s)

Troubleshooting

Error Likely Cause Fix
403 Forbidden API key missing or invalid Check .env has the right key
429 Rate limit Free tier daily limit hit Wait or use auto-fallback. Manual: /model <n>
Agent stopped: stuck detected Same tool called 3Γ—+ consecutively Recovery message injected automatically
All 3 attempts failed Model unreachable or too slow Try smaller model or local model
tool_calls empty arguments Model doesn't support tool calling Use a different model
ENOTFOUND / ECONNREFUSED Internet restrictions or proxy needed Enable VPN/proxy or use local models

Quick checks: /list-providers β€” shows configured keys. /safe β€” toggle safe mode. npm run setup β€” re-run wizard.

Limitations

  • System prompt adherence: Some free models may ignore or partially follow system instructions
  • Rate limits: Free-tier API keys have daily limits. Retry with backoff (max 3 attempts)
  • Token window: With 128K context and 20-exchange window, large codebases may hit limits. Increase MAX_EXCHANGES and MAX_TOOL_RESULT_LENGTH
  • Stuck detection: Stops after 3Γ— identical or 5Γ— consecutive tool calls β€” rephrase your request to continue
  • Windows shell: PowerShell pipeline operators may trigger permission prompts under strict rules
  • LSP availability: Requires the LSP server binary to be installed (e.g., typescript-language-server, pyright)
  • MCP servers: Some servers require internet (GitHub API, etc.) and proper configuration

Security

  • All file operations restricted to ALLOWED_DIR β€” path traversal prevented
  • Shell commands run inside the workspace directory
  • API keys stored in .env (gitignored, never committed)
  • Safe mode (/safe) restricts commands to a whitelist
  • Dangerous commands blocked by denylist (rm -rf, dd, mkfs, wget, etc.)

Large Projects

For medium-to-large projects, increase in .env:

MAX_EXCHANGES=50
MAX_TOOL_RESULT_LENGTH=20000

Reset mid-session with /reset if context gets stale.


Tests

  • npm run test:unit β€” 181 unit tests (12 files: ConversationState, comprehensive, CodingAgent, loadProjectContext, fileManager, agent, server, mcp, lsp, persistence, toolRegistry, models)
  • npm run test:integration β€” 26 provider integration tests
  • npm test β€” 35 integration tests
  • CI: .github/workflows/ci.yml runs all tests on push/PR

Contributing

Contributions welcome! Open an issue or submit a pull request. Star the repo if you find it useful.

License

MIT