# G-Coder 🚀

**AI-powered CLI coding assistant with multi-provider support and intelligent automation**

[![npm version](https://img.shields.io/npm/v/@prdpspkt/g-coder.svg)](https://www.npmjs.com/package/@prdpspkt/g-coder)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js](https://img.shields.io/badge/node-%3E%3D16.0.0-brightgreen.svg)](https://nodejs.org/)

## Why G-Coder?

✅ **Universal Provider Support** - Use ANY OpenAI-compatible API (Ollama, DeepSeek, OpenAI, Groq, Together AI, etc.)
✅ **100% Free Option** - Run locally with Ollama (no API costs)
✅ **Smart Project Memory** - Persistent conversation history per project
✅ **Auto Token Management** - Seamless continuation when limits hit
✅ **Advanced Security** - OS-aware risk detection and approval system
✅ **Highly Customizable** - Custom commands, hooks, and configurations

---

## 📦 Installation

```bash
npm install -g @prdpspkt/g-coder
```

---

## 🚀 Quick Start

### 1. Run G-Coder (Auto Setup)

```bash
g-coder
```

First run creates default config with Ollama (local, free). If you need API providers, interactive setup will guide you.

### 2. Manual Setup (Optional)

**For Ollama (Free, Local):**
```bash
# Install Ollama
brew install ollama  # macOS
# or: https://ollama.ai/download

# Start and pull model
ollama serve
ollama pull codellama

# G-Coder default config already set for Ollama!
```

**For API Providers (DeepSeek, OpenAI, etc.):**

Edit `~/.g-coder/config.json`:
```json
{
  "provider": "deepseek",
  "model": "deepseek-chat",
  "baseUrl": "https://api.deepseek.com/v1",
  "apiKeyName": "DEEPSEEK_API_KEY"
}
```

Add API key to `~/.g-coder/.env`:
```bash
echo "DEEPSEEK_API_KEY=sk-your-key" >> ~/.g-coder/.env
```

---

## ⚙️ Configuration

### Supported Providers

G-Coder works with **ANY OpenAI-compatible API**:

| Provider | baseUrl | Model Example |
|----------|---------|---------------|
| **Ollama** | `http://localhost:11434/v1` | `codellama`, `deepseek-coder` |
| **DeepSeek** | `https://api.deepseek.com/v1` | `deepseek-chat`, `deepseek-reasoner` |
| **OpenAI** | `https://api.openai.com/v1` | `gpt-4`, `gpt-3.5-turbo` |
| **Groq** | `https://api.groq.com/openai/v1` | `llama-3.1-70b-versatile` |
| **Together AI** | `https://api.together.xyz/v1` | `meta-llama/Llama-3-70b` |
| **Custom** | `https://your-api.com/v1` | Any model name |

> **Note:** Anthropic Claude uses its own API format: `https://api.anthropic.com/v1`

### Configuration Structure

`~/.g-coder/config.json`:
```json
{
  "provider": "your-provider-name",
  "model": "model-name",
  "baseUrl": "https://api.example.com/v1",
  "apiKeyName": "YOUR_API_KEY_ENV_VAR",
  "temperature": 0.7,
  "maxTokens": 8192,
  "approval": {
    "enabled": true,
    "toolsRequiringApproval": {
      "Bash": true,
      "Write": true,
      "Edit": true
    }
  }
}
```

`~/.g-coder/.env`:
```bash
YOUR_API_KEY_ENV_VAR=your-actual-api-key
```

**📘 See [CONFIGURATION.md](./CONFIGURATION.md) for detailed examples**

---

## 📚 Usage

### Start Interactive Session

```bash
g-coder              # Start with default config
g-coder start        # Explicit start
g-coder start -v     # Verbose logging
g-coder setup        # Run setup wizard
```

### In-Session Commands

**Basic:**
- `/help` - Show help
- `/clear` - Clear conversation
- `/tools` - List available tools
- `/exit` - Exit application

**Configuration:**
- `/config` - Show configuration
- `/model` - Change model
- `/approval` - Manage approval settings

**History & Sessions:**
- `/history` - View conversation history
- `/save <name>` - Save current session
- `/load <name>` - Load saved session
- `/sessions` - List all sessions

---

## 🛠️ Available Tools

G-Coder provides intelligent tools for coding tasks:

### File Operations
- **Read** - Read file contents
- **Write** - Create/overwrite files (approval required)
- **Edit** - Smart file editing with fuzzy matching (approval required)
- **NotebookEdit** - Edit Jupyter notebooks (approval required)

### Search
- **Glob** - Find files by pattern (`**/*.ts`)
- **Grep** - Search code with regex

### Execution
- **Bash** - Run shell commands (approval required)
- **BashOutput** - Read background process output
- **KillShell** - Stop background processes

### Git
- **GitStatus**, **GitDiff** - View changes
- **GitCommit**, **GitPush** - Create commits and push (approval required)

### Web
- **WebFetch** - Fetch web content (approval required)

---

## 🔒 Security & Approval

### Risk-Based Approval System

Operations are categorized by risk:

- 🟢 **Safe** (no approval): Read, Glob, Grep, GitStatus, GitDiff
- 🟡 **Medium** (approval): Write, Edit, WebFetch
- 🟠 **High** (approval): Bash, GitCommit
- 🔴 **Critical** (approval): GitPush, destructive operations

### OS-Aware Security

Automatically detects dangerous patterns:

**Windows:** `del /s`, `format`, registry modifications
**Linux/Mac:** `rm -rf /`, `sudo rm`, root operations

### Auto-Approve

When approving, choose "auto-approve similar" to skip future prompts for the same operation.

---

## 🧠 Project Intelligence

### Automatic Features

- **Project Detection** - Recognizes Node.js, Python, Go, Rust, etc.
- **Persistent History** - Last 50 interactions saved per project
- **Context Restoration** - Previous conversations loaded on startup
- **Smart Scanning** - Understands project structure automatically

### Startup Context Example

```
📚 Previous Conversation Context:
   Previous session: 2025-01-15 10:30
   Total interactions: 42 messages
   Recent topics: Implemented auth; Fixed DB connection
   Loaded 5 interactions for context
```

---

## ♾️ Token Management

G-Coder handles token limits automatically:

**90% Warning:**
```
⚠️  Approaching limit: 7200/8000 tokens (90%)
```

**100% Auto-Save:**
```
⚠️  Token Limit Exceeded
    Auto-saving and continuing...

✓ Saved: auto-save-2025-01-15T10-30-45
  Session ID: abc123
  Load with: /load abc123

✓ Ready to continue!
```

**No manual intervention needed!**

---

## 🎨 Customization

### Custom Slash Commands

Create `~/.g-coder/commands/review.md`:
```markdown
---
description: Review code for best practices
---

Review this project for:
1. Code quality
2. Potential bugs
3. Security issues
```

Usage: `/review`

### Event Hooks

Create `~/.g-coder/hooks.json`:
```json
{
  "enabled": true,
  "hooks": {
    "session_start": ["git fetch"],
    "session_end": ["git status"]
  }
}
```

---

## 🆚 G-Coder vs Claude Code

| Feature | G-Coder | Claude Code |
|---------|---------|-------------|
| **Multi-Provider** | ✅ Ollama, DeepSeek, OpenAI, Groq, etc. | ❌ Claude only |
| **Free Option** | ✅ Ollama (local, free) | ❌ Requires API |
| **Project History** | ✅ Persistent per-project | ❌ Session only |
| **Auto Token Mgmt** | ✅ Auto-save & continue | ❌ Manual |
| **OS-Aware Security** | ✅ Risk detection | ⚠️ Basic |
| **Customization** | ✅ Commands, hooks, configs | ❌ Limited |

**Choose G-Coder if you want:**
- 🆓 Free local models
- 🔄 Provider flexibility
- 📚 Project memory
- ♾️ Automatic continuation
- 🔒 Advanced security
- 🎨 Full customization

---

## 📖 Documentation

- **[CONFIGURATION.md](./CONFIGURATION.md)** - Detailed provider setup (7+ examples)
- **[config.examples.json](./config.examples.json)** - Ready-to-use configs
- **[MINIMAL_SYSTEM_PROMPT.md](./MINIMAL_SYSTEM_PROMPT.md)** - System prompt guide
- **[TOOLS_REFERENCE.md](./TOOLS_REFERENCE.md)** - Complete tool documentation

---

## 🐛 Troubleshooting

**Ollama not connecting:**
```bash
ollama serve          # Start Ollama
ollama pull codellama # Pull model
g-coder test         # Test connection
```

**API key not found:**
```bash
cat ~/.g-coder/.env  # Check API key
g-coder config --show # Verify config
```

**Config corrupted:**
- G-Coder auto-creates backup and fresh config
- Check `~/.g-coder/config.json.backup.*`

---

## 🤝 Contributing

Contributions welcome! Please submit PRs.

```bash
git clone https://github.com/prdpspkt/g-coder.git
cd g-coder
npm install
npm run build
```

---

## 📝 License

MIT License - see [LICENSE](LICENSE)

---

## 📬 Support

- **Issues:** https://github.com/prdpspkt/g-coder/issues
- **NPM:** https://www.npmjs.com/package/@prdpspkt/g-coder

---

**Made with 🚀 by developers, for developers**

श्री गणेशाय नम:
