# AggRoot - AI Coding Assistant

A powerful, extensible AI coding assistant built with Node.js and TypeScript. It provides file operations, web search, code execution, Git integration, and more through a modern DDD + plugin architecture.

[![Node.js Version](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen)](https://nodejs.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

**[中文文档](README_CN.md)**

## Table of Contents

- [Core Features](#core-features)
- [CLI Interface](#cli-interface)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Usage](#usage)
- [Available Tools](#available-tools)
- [Skills System](#skills-system)
- [MCP Integration](#mcp-integration)
- [Agent System](#agent-system)
- [Memory Management](#memory-management)
- [Cross-Platform Support](#cross-platform-support)
- [Changelog](#changelog)
- [License](#license)

## Core Features

- **TypeScript First**: Full TypeScript support with strict type checking and modern ES modules
- **DDD + Plugin Architecture**: Clean domain-driven design with hot-pluggable plugins
- **Extensible Tool System**: 10 tool plugins providing 30+ built-in tools, easily extensible
- **Multi AI Agents**: Code agent, chat agent, and specialized sub-agents
- **Smart Memory**: Context-aware memory with auto-compression and project-level persistence
- **Advanced File Operations**: Read, Write, Edit, Glob, Grep, DirectoryTree with smart pagination and outline mode
- **Web Tools**: Web search, web fetch, and HTTP requests with automatic encoding handling
- **Code Intelligence**: Execute, validate, format, analyze, refactor, and search code symbols
- **Git Integration**: Full Git operations with cross-platform support
- **Stock Quotes**: Real-time stock quotes and market data
- **Modern CLI Interface**: Interactive terminal UI with split-screen layout and Markdown rendering
- **Skills System**: Reusable skill templates (explain, refactor, test, debug, and more)
- **MCP Integration**: Model Context Protocol for external tool integration
- **Security Controls**: Built-in risk control, safe command execution, and dangerous command interception
- **Cross-Platform**: Seamless operation on Windows, Linux, and macOS
- **Session Management**: Multi-session support with history, undo, and export
- **YOLO Mode**: Toggle auto-execution mode to skip tool confirmation prompts

## CLI Interface

AggRoot provides a modern terminal UI with a split-screen layout:

```
┌──────────────────────────────────────────────────────────────┐
│                                                              │
│                     Output Area                              │
│              (scrollable conversation history)               │
│              (Markdown rendering support)                    │
│                                                              │
├──────────────────────────────────────────────────────────────┤  ← top separator
│ Agent> _                                                     │  ← input line
├──────────────────────────────────────────────────────────────┤  ← bottom separator
│ deepseek-chat | Token: 1234/5678 | Mode: coding             │  ← status bar
└──────────────────────────────────────────────────────────────┘
```

### CLI Features

- **Split-Screen Layout**: Clear separation between output and input areas
- **Visual Separators**: Double-line separators clearly mark the input area
- **Status Bar**: Shows current model, token usage, and working mode
- **Thinking Animation**: Animated status display during AI processing
- **Raw Mode Input**: Full keyboard support including arrow keys and history navigation
- **Quick Menus**:
  - Press `/` to view commands
  - Press `$` to select a model
  - Press `#` to select an agent
  - Press `@` to insert a file reference
- **Markdown Rendering**: Rich text formatting for AI responses

### CLI Commands

| Command | Alias | Description |
|---------|-------|-------------|
| `/help` | `/h`, `/?` | Show help information |
| `/model <id>` | — | Switch AI model |
| `/agents` | — | List all available agents |
| `/switch [n]` | — | Switch session (by number) |
| `/reset` | — | Reset current session |
| `/sessions` | — | List all sessions |
| `/undo [path]` | — | Undo file changes |
| `/memory` | — | Manage project memory (list/add/delete/search) |
| `/init` | — | Generate AGGROOT.md project documentation |
| `/yolo` | — | Toggle auto-execution mode (skip confirmations) |
| `/export [format]` | — | Export conversation |
| `/config` | — | Show current configuration |
| `/history` | — | Show command history |
| `/clear` | `/cls` | Clear screen |
| `/exit` | `/quit`, `/q` | Exit program |

## Quick Start

### Prerequisites

- **Node.js** >= 20.0.0
- AI provider API key (DeepSeek, OpenAI, etc.)

### Installation

```bash
# Install globally via npm
npm install -g aggroot

# Run the assistant (CLI mode)
aggroot
```

### Web Gateway Mode

Start the web gateway server with built-in frontend:

```bash
# Start gateway (serves frontend + API on port 8642)
aggroot gateway

# Custom port and host
aggroot gateway --port 8080 --host 0.0.0.0

# Disable frontend static serving (API only)
aggroot gateway --no-static

# Custom static directory
aggroot gateway --static-dir /path/to/frontend/dist
```

| Endpoint | Description |
|----------|-------------|
| `http://localhost:8642` | Web frontend (SPA) |
| `http://localhost:8642/health` | Health check |
| `http://localhost:8642/v1/chat/completions` | OpenAI-compatible chat API |
| `http://localhost:8642/v1/models` | Available models |
| `ws://localhost:8642/ws` | WebSocket chat |

## Configuration

### Environment Variables

Create a `.env` file in your project directory or set environment variables directly:

```env
# === AI Providers (at least one required) ===
DEEPSEEK_API_KEY=your_deepseek_api_key       # DeepSeek (default provider)
OPENAI_API_KEY=your_openai_api_key           # OpenAI GPT
CLAUDE_API_KEY=your_claude_api_key           # Anthropic Claude
ZHIPU_API_KEY=your_zhipu_api_key             # Zhipu AI
KIMI_API_KEY=your_kimi_api_key               # Kimi (Moonshot)
MINIMAX_API_KEY=your_minimax_api_key         # MiniMax

# === Ollama (Local Models) ===
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL_NAME=llama3.2

# === Shell Configuration ===
DEFAULT_SHELL=auto          # auto | powershell | cmd | bash | nushell | wsl
SHELL_TIMEOUT=30000         # Shell command timeout (ms)
CODE_EXECUTION_TIMEOUT=30   # Code execution timeout (seconds)

# === Session Management ===
MAX_SESSION_HISTORY=50       # Max messages per session
SESSION_TIMEOUT=60           # Session timeout (minutes)

# === Logging ===
LOG_LEVEL=info              # debug | info | warn | error | fatal

# === Security ===
SAFE_MODE=true              # Enable safe mode for code execution
DANGEROUS_COMMANDS=rm -rf,format,del /f /q,shutdown,reboot
```

> **Important:** At least one AI provider API key is required. DeepSeek is the default provider.

## Usage

### Interactive Mode

Start AggRoot and interact with the AI assistant:

```bash
aggroot
```

Then type your questions or instructions naturally:

```
Agent> Read the README.md file and summarize it
Agent> Search for all TypeScript files in the src directory
Agent> Run the test suite and fix any failing tests
Agent> What's the current git status?
```

### Quick Menus

- **`$`** — Open model selection menu
- **`#`** — Open agent selection menu
- **`@`** — Insert file reference
- **`/`** — Show command list

### YOLO Mode

Enable YOLO mode to auto-execute tools without confirmation:

```
Agent> /yolo
✅ YOLO mode enabled - tools will auto-execute
```

### Session Management

```bash
/sessions          # List all sessions
/switch 2          # Switch to session 2
/reset             # Reset current session
/export markdown   # Export conversation as Markdown
```

### Memory Management

```bash
/memory            # Show memory stats
/memory list       # List all project memories
/memory add        # Add a new memory
/memory search     # Search memories
```

## Available Tools

### Core Tools (`@aggroot/core-tools`)

**File Operations:**
| Tool | Description |
|------|-------------|
| `Read` | Read file contents with smart pagination, outline mode, and context search |
| `Write` | Create new files or overwrite existing ones |
| `Edit` | Precise file editing with diff-style replacement (minimizes token consumption) |
| `Glob` | Find files by name/path pattern (e.g., `**/*.ts`, `src/**/*.py`) |
| `Grep` | Search file contents with regex (preferred tool for finding code) |
| `DirectoryTree` | Quickly list directory tree structure with configurable depth and exclusions |

**User Interaction:**
| Tool | Description |
|------|-------------|
| `AskUser` | Ask the user questions with multi-select or free-text input |

**Planning:**
| Tool | Description |
|------|-------------|
| `EnterPlanMode` | Enter plan mode to break down complex tasks before execution |
| `ExitPlanMode` | Exit plan mode and submit the plan for approval |

### Code Tools (`@aggroot/code-tools`)

| Tool | Description |
|------|-------------|
| `CodeExecute` | Safely execute TypeScript/JavaScript code with timeout control |
| `CodeValidate` | Validate code syntax with TypeScript compiler (real type checking) |
| `CodeFormat` | Format code with configurable indentation |
| `CodeAnalyze` | Analyze code for symbols, complexity, imports/exports, and issues |
| `CodeSearch` | Unified symbol search (definitions, references, workspace symbols) |
| `CodeRefactor` | Code refactoring operations (extract function, rename, organize imports) |

### Git Tools (`@aggroot/git-tools`)

| Tool | Description |
|------|-------------|
| `GitStatus` | Show working tree status |
| `GitDiff` | Show differences between commits, or between commits and working tree |
| `GitLog` | Show commit logs |
| `GitBranch` | List, create, or delete branches |
| `GitShow` | Show various types of objects (commits, tags, trees, etc.) |
| `GitAdd` | Stage file contents |
| `GitCommit` | Record changes to the repository |
| `GitPush` | Push to remote repositories |
| `GitPull` | Pull from remote repositories |
| `GitCheckout` | Switch branches or restore working tree files |
| `GitRemote` | Manage remote repository sets |
| `GitStash` | Stash changes in a dirty working directory |

### Web Tools (`@aggroot/web-tools`)

| Tool | Description |
|------|-------------|
| `WebSearch` | Search the web (with query optimization) |
| `WebFetch` | Fetch web content from URLs (auto-retry with multiple URLs) |
| `HttpRequest` | Make HTTP requests (GET, POST, PUT, DELETE, PATCH) |

### Shell Tools (`@aggroot/shell-tools`)

| Tool | Description |
|------|-------------|
| `Shell` | Execute shell commands with security controls and timeout |

> **Important:** Prefer core tools (read/write/edit/glob/grep) for file operations over shell commands. Use Shell only for system-level operations that core tools cannot accomplish.

### Todo Tools (`@aggroot/todo-tools`)

| Tool | Description |
|------|-------------|
| `TodoCreate` | Create a new todo item |
| `TodoList` | List all todo items |
| `TodoUpdate` | Update a todo item |
| `TodoDelete` | Delete a todo item |
| `TodoComplete` | Mark a todo item as completed |

### Skill Tools (`@aggroot/skill-tools`)

| Tool | Description |
|------|-------------|
| `Skill` | Invoke a skill by name (reusable task template) |
| `ListSkills` | List all available skills |

### MCP Tools (`@aggroot/mcp-tools`)

| Tool | Description |
|------|-------------|
| `MCP` | Model Context Protocol integration for connecting external tool servers |

### Risk Control Tools (`@aggroot/risk-control-tools`)

Security and risk management tools for safe command execution and domain reputation checks.

### Stock Tools (`@aggroot/stock-tools`)

| Tool | Description |
|------|-------------|
| `StockQuote` | Get real-time stock quotes |

## Skills System

AggRoot includes a built-in skills system that provides reusable templates for common tasks:

**Built-in Skills:**
- `explain` — Explain code or concepts
- `refactor` — Refactor code to improve quality
- `test` — Generate test cases
- `document` — Generate documentation
- `debug` — Debug issues and errors
- `analyze` — Analyze codebase structure
- `security-check` — Security audit and vulnerability scanning
- `commit` — Generate meaningful commit messages

**Using Skills:**
```
Agent> /explain this function
Agent> /refactor src/utils/helpers.ts
Agent> /test src/domain/agent/
```

## MCP Integration

AggRoot supports the **Model Context Protocol (MCP)** for integrating external tool servers:

- Connect MCP-compatible tool servers
- Dynamically discover and use external tools
- Supports **stdio**, **HTTP**, **WebSocket**, and **SSE** transport protocols
- Auto-reconnect (with exponential backoff) and health monitoring
- Configure MCP servers at project or user level

### Configuration

MCP servers are configured via `.aggroot/mcp.json` (project-level) or `~/.aggroot/mcp.json` (user-global):

```json
{
  "servers": [
    {
      "name": "powerpoint-server",
      "transport": {
        "type": "stdio",
        "command": "uvx",
        "args": ["--from", "office-powerpoint-mcp-server", "ppt_mcp_server"]
      },
      "enabled": true
    },
    {
      "name": "word-document-server",
      "transport": {
        "type": "stdio",
        "command": "uvx",
        "args": ["--from", "office-word-mcp-server", "word_mcp_server"]
      },
      "enabled": true
    }
  ],
  "settings": {
    "defaultTimeout": 30000,
    "autoReconnect": true
  }
}
```

### Pre-configured MCP Servers

| Server | Package | Description |
|--------|---------|-------------|
| `powerpoint-server` | `office-powerpoint-mcp-server` | Create, edit, and manipulate PowerPoint presentations (34 tools: charts, shapes, tables, gradients, etc.) |
| `word-document-server` | `office-word-mcp-server` | Create, read, and manipulate Word documents (42 tools: paragraphs, tables, images, formatting, etc.) |

### Installing MCP Servers

```bash
# Option 1: Use uvx (recommended — no global install needed, requires uv/uvx)
# Already configured in mcp.json, just ensure uv/uvx is installed

# Option 2: Global pip install
pip install office-powerpoint-mcp-server office-word-mcp-server
```

> **Note:** The `name` in the config determines the tool prefix. For example, `powerpoint-server` generates tools like `mcp_powerpoint-server_create_presentation`.

## Agent System

AggRoot features a powerful **agent** system with multiple specialized agents for different tasks:

### Built-in Agents

| Agent | Name | Description |
|-------|------|-------------|
| Code Agent | Code Deity | Professional coding assistant — directive refactoring, code generation, multi-file collaboration with sub-agent support |
| Content Agent | Content Creator | Content creation assistant — articles, copywriting, professional PPT presentations and Word documents (via MCP) |
| Resume Agent | Resume Optimizer | Resume optimization expert — diagnostics, STAR rewriting, keyword analysis, Word document formatting (via MCP) |
| Companion Agent | Xiao Ai | Warm and caring virtual companion — cute and friendly, supports web search and file operations |
| Lei Jun Assistant | Lei Jun Classmate | Lei Jun-style assistant — investment insights, stock analysis, business strategy |
| Investment Agent | Investment Master | Investment analysis expert — data-driven stock analysis (A-shares and HK stocks), quotes/financials/technical/news |
| Ops Agent | Ops Master | System operations expert — system administration, environment management, deployment |
| Risk Control Agent | Risk Detective | Risk detective — payment fraud detection, phishing detection, domain reputation, security scanning |

### Sub-Agent System

The Code Agent can delegate tasks to specialized sub-agents:

- **Explore Agent**: Quick read-only codebase exploration with parallel tool calls
- **Plan Agent**: Plan and design tasks
- **Code Reviewer Agent**: Code review and quality analysis
- **General Purpose Agent**: Complex multi-step tasks

Sub-agents run autonomously and return complete output, enabling efficient task decomposition and parallel execution.

## Memory Management

AggRoot includes an intelligent memory system:

- **Context-Aware Memory**: Automatically tracks conversation context with auto-compression when needed
- **Project Memory**: Cross-session persistent project-level memory
- **Memory Commands**: `/memory list`, `/memory add`, `/memory delete`, `/memory search`
- **Auto-Compression**: Intelligently summarizes old conversations to stay within token limits
- **File Tracking**: Tracks file changes during conversations with undo support

## Cross-Platform Support

AggRoot is designed to work seamlessly across all major operating systems:

| Platform | Architecture | Shell Support | Notes |
|----------|-------------|---------------|-------|
| **Windows** | x64, arm64 | PowerShell, CMD, Git Bash, Nushell, WSL | Auto encoding detection (GBK/UTF-8) |
| **Linux** | x64, arm64 | Bash, Zsh, Fish | — |
| **macOS** | x64, arm64 (Apple Silicon) | Zsh, Bash | Native Apple Silicon support |

### Platform Compatibility

| Feature | Windows | Linux | macOS |
|---------|---------|-------|-------|
| File Operations | ✅ | ✅ | ✅ |
| Shell Commands | ✅ (Git Bash / Nushell / PowerShell) | ✅ | ✅ |
| Web Tools | ✅ | ✅ | ✅ |
| Git Integration | ✅ | ✅ | ✅ |
| Encoding Support | ✅ (GBK/UTF-8) | ✅ (UTF-8) | ✅ (UTF-8) |

## Changelog

### v1.4.2

- **Menu Selection Echo Fix**: Commands selected from the quick menu (via `/`, `$`, `#`) now correctly display the echo line (e.g., `Code Deity ❯ /help`) just like manually typed commands
- **`/clear` Command Fix**: Eliminated excessive blank lines when executing `/clear` — now properly clears the visible area without affecting scrollback history
- **Multi-Step Output Fix**: Fixed blank line issues in multi-step output commands (e.g., `/upgrade`) where the echo line was being overwritten by subsequent output
- **Split-Screen Rendering Improvements**: Refactored `addOutput()` to correctly handle the transition from input echo to AI output, preventing text overlap and cursor positioning errors

### v1.3.4

- **Nushell Shell Support**: Added Nushell (`nu`) as a supported shell on Windows, with automatic detection via common install paths and PATH lookup
- **Updated Shell Priority**: Default shell priority on Windows is now Git Bash > Nushell > PowerShell
- **Smart Shell Syntax**: System prompt now generates shell syntax compatible with the detected default shell instead of always assuming Git Bash
- **Bug Fixes**:
  - Read tool auto-corrects `../` relative paths via searchFilePath fallback
  - SubAgent robust summary round with tool result fallback when no output
  - Glob tool description clarifies it matches files only, not directories

## License

This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
