erosolar 1.3.2
Unified AI Agent Framework - Multi-provider CLI with schema-driven tools, code intelligence, and Alpha Zero competitive RL
Requires Python: >=3.10

# Erosolar CLI

A modular AI coding assistant with a clean plugin architecture. The core provides essential coding tools, while optional plugins extend functionality for competitive RL, enhanced code analysis, and security research.

```
┌─────────────────────────────────────────────────────────────────────┐
│                         EROSOLAR CLI                                │
├─────────────────────────────────────────────────────────────────────┤
│  CORE (Always Available)          │  PLUGINS (Optional)             │
│  ─────────────────────────        │  ────────────────────           │
│  • Filesystem (read/write/list)   │  • alpha_zero (RL framework)    │
│  • Edit (surgical replacement)    │  • coding (analysis tools)      │
│  • Bash (safe shell execution)    │  • security (vuln scanning)     │
│  • Glob (pattern matching)        │                                 │
│  • Grep (regex search)            │                                 │
└─────────────────────────────────────────────────────────────────────┘
```

## Installation

```bash
# From source
pip install -e ".[dev]"

# Or install dependencies directly
pip install anthropic openai google-generativeai tiktoken typer rich prompt-toolkit pydantic
```

## Quick Start

### Basic Usage (Core Only)

```bash
# Interactive REPL with core coding tools
erosolar --interactive

# Single command
erosolar "List all Python files and summarize the architecture"

# Specify provider
erosolar --provider openai --model gpt-4 "Explain this function"
```

### With Plugins

```bash
# Enable Alpha Zero 2 (competitive RL + code metrics)
erosolar --interactive --alpha-zero

# Enable enhanced coding tools
erosolar --interactive --coding

# Enable all plugins
erosolar --interactive --all-plugins
```

## Architecture

### Core Design Philosophy

The core is intentionally minimal - **five essential tools** that cover 95% of coding assistance needs:

| Tool | Purpose | Example |
|------|---------|---------|
| **Read** | Read file contents | `Read README.md` |
| **Write** | Create/overwrite files | `Write hello.py with print("hi")` |
| **Edit** | Surgical string replacement | `Replace "foo" with "bar" in config.py` |
| **Bash** | Execute shell commands | `Run pytest -v` |
| **Glob** | Find files by pattern | `Find all *.tsx files` |
| **Grep** | Search file contents | `Search for "TODO" in src/` |

### Plugin System

Plugins are **opt-in** extensions that add specialized capabilities:

```
erosolar_cli/
├── core/                    # Essential runtime (always loaded)
│   ├── agent.py            # Conversation orchestration
│   ├── tool_runtime.py     # Tool execution engine
│   └── types.py            # Type definitions
│
├── tools/                   # Core tool implementations
│   ├── file_tools.py       # Read, Write, List
│   ├── edit_tools.py       # Edit (surgical replacement)
│   ├── bash_tools.py       # Bash (with safety)
│   ├── glob_tools.py       # Glob (pattern matching)
│   └── grep_tools.py       # Grep (regex search)
│
├── plugins/                 # Optional plugin system
│   ├── __init__.py         # Plugin registry & base classes
│   ├── alpha_zero_plugin.py    # Competitive RL framework
│   ├── coding_plugin.py        # Enhanced coding tools
│   └── security_plugin.py      # Security research tools
│
├── alpha_zero/              # Alpha Zero 2 implementation
│   ├── competitive_framework.py
│   ├── reward_system.py
│   ├── introspection.py
│   └── tournament.py
│
└── shell/
    └── interactive.py       # REPL with prompt-toolkit
```

## Plugins

### Alpha Zero 2 (`--alpha-zero`)

A competitive multi-agent reinforcement learning framework for code optimization.

**Features:**
- Code quality evaluation across 10+ dimensions
- Competitive tournaments between agents
- Performance introspection and metrics
- Self-improvement suggestions

**CLI Commands:**
```bash
# Run a tournament
erosolar alpha-zero tournament --rounds 10

# Evaluate code quality
erosolar alpha-zero evaluate myfile.py

# View competition history
erosolar alpha-zero history
```

**Shell Commands:**
```
/metrics      Show performance metrics
/suggestions  Show improvement suggestions
```

**Code Quality Dimensions:**
| Metric | Weight | Description |
|--------|--------|-------------|
| Code Quality | 25% | Structure, naming, organization |
| Algorithm Efficiency | 20% | Data structures, complexity |
| Error Handling | 20% | Try/catch, validation, edge cases |
| Documentation | 15% | Docstrings, comments |
| Maintainability | 10% | Function length, coupling |
| Security | 10% | Injection risks, secrets |

### Coding Tools (`--coding`)

Enhanced code analysis and development assistance.

**Tools:**
- `analyze_complexity` - Cyclomatic complexity, maintainability index
- `find_dependencies` - Import analysis (stdlib/third-party/local)
- `generate_docstring` - Auto-generate docstrings (Google/NumPy style)
- `suggest_refactorings` - Identify refactoring opportunities
- `generate_test_stub` - Create pytest test templates

**Example:**
```bash
erosolar --interactive --coding

> Analyze the complexity of src/agent.py
> Generate test stubs for utils.py
> What refactorings would improve this file?
```

### Security Tools (`--security`)

Security research and vulnerability assessment (requires authorization context).

**Tools:**
- `dependency_audit` - Check dependencies for known vulnerabilities
- `code_security_scan` - Pattern-based security issue detection
- `analyze_attack_surface` - Project security posture analysis

**Detected Issues:**
- Hardcoded secrets (passwords, API keys)
- Code injection risks (eval, exec, subprocess with shell=True)
- Insecure deserialization (pickle)
- SQL injection patterns
- XSS risks

## Interactive Shell

The REPL provides a persistent coding environment:

```bash
erosolar --interactive
```

**Commands:**
```
/help         Show available commands
/exit         Exit the shell
/clear        Clear screen
/model        Show or change model
/save         Save session
/session      Load saved session
/plugins      Show plugin status
/metrics      Show Alpha Zero metrics (if enabled)
/suggestions  Show improvement suggestions (if enabled)
```

**Example Session:**
```
╭─────────────────────────────────────────────────────────╮
│  Erosolar CLI v2.0.0                                    │
│  Profile: default | Model: claude-sonnet-4              │
│  Working: /Users/dev/myproject                          │
╰─────────────────────────────────────────────────────────╯

> List all Python files in src/

Found 12 files:
  src/__init__.py
  src/main.py
  src/utils.py
  ...

> Read src/main.py and explain the architecture

[Reading src/main.py...]

This file implements a FastAPI application with the following structure:
1. Configuration loading from environment
2. Database connection setup
3. Router registration for /api/v1 endpoints
...

> Create a test file for the User model

[Writing tests/test_user.py...]

Created tests/test_user.py with 5 test cases covering:
- User creation
- Validation
- ...
```

## Programmatic Usage

### Basic Agent

```python
import asyncio
from erosolar_cli.core.agent import AgentRuntime, AgentOptions
from erosolar_cli.core.tool_runtime import create_default_tool_runtime, ToolExecutionContext
from erosolar_cli.capabilities import build_core_suites
from erosolar_cli.providers.provider_factory import create_provider

async def main():
    # Create provider
    provider = create_provider("anthropic", "claude-sonnet-4")

    # Create tool runtime with core tools
    context = ToolExecutionContext(
        profile_name="default",
        provider="anthropic",
        model="claude-sonnet-4",
    )
    tool_runtime = create_default_tool_runtime(context)

    # Register core tools
    for suite in build_core_suites("/path/to/workspace"):
        tool_runtime.register_suite(suite)

    # Create agent
    agent = AgentRuntime(AgentOptions(
        provider=provider,
        tool_runtime=tool_runtime,
        system_prompt="You are a helpful coding assistant.",
    ))

    # Send message
    response = await agent.send("List all Python files")
    print(response)

asyncio.run(main())
```

### With Plugins

```python
from erosolar_cli.plugins import registry, load_builtin_plugins
from erosolar_cli.capabilities import build_capability_suites

# Load plugins
load_builtin_plugins()

# Build suites with specific plugins
suites = build_capability_suites(
    working_dir="/path/to/workspace",
    enable_plugins=["alpha_zero", "coding"]
)

# Or load plugins manually
alpha_zero = registry.load("alpha_zero", "/path/to/workspace")
for suite in alpha_zero.get_tool_suites():
    tool_runtime.register_suite(suite)
```

### Alpha Zero 2 Direct Usage

```python
from erosolar_cli.alpha_zero import (
    CompetitiveFramework,
    RewardSystem,
    TournamentRunner,
    TournamentConfig,
)

# Evaluate code quality
reward_system = RewardSystem()
metrics = await reward_system.evaluate_code('''
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
''')

print(f"Quality Score: {metrics.code_quality_score * 100:.1f}/100")
print(f"Efficiency: {metrics.algorithm_efficiency * 100:.1f}/100")

# Run tournament
config = TournamentConfig(
    tournament_id="test-tournament",
    task_prompts=[
        "Write an efficient prime number checker",
        "Implement merge sort with O(n log n) complexity",
    ],
    rounds_per_task=3,
)

runner = TournamentRunner(data_dir=Path("./tournaments"))
result = await runner.run(config)

print(f"Winner: Agent {1 if result.agent1_wins > result.agent2_wins else 2}")
```

## Configuration

### Environment Variables

```bash
# Required: At least one provider API key
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GOOGLE_API_KEY=...

# Optional
EROSOLAR_PROFILE=default
EROSOLAR_WORKING_DIR=/path/to/workspace
```

### Profiles

Create `~/.erosolar/profiles.json`:

```json
{
  "default": {
    "provider": "anthropic",
    "model": "claude-sonnet-4",
    "temperature": 0.7,
    "max_tokens": 4096,
    "system_prompt": "You are a helpful coding assistant."
  },
  "fast": {
    "provider": "anthropic",
    "model": "claude-haiku",
    "temperature": 0.3,
    "max_tokens": 2048
  }
}
```

## Development

### Creating a Plugin

```python
from erosolar_cli.plugins import Plugin, PluginMetadata, PluginCategory, register_plugin
from erosolar_cli.core.tool_runtime import ToolDefinition, ToolSuite

@register_plugin
class MyPlugin(Plugin):
    metadata = PluginMetadata(
        id="my_plugin",
        name="My Plugin",
        version="1.0.0",
        description="Description of what this plugin does",
        category=PluginCategory.CODING,
        author="Your Name",
    )

    def get_tool_suites(self) -> list[ToolSuite]:
        async def my_tool_handler(param: str) -> dict:
            return {"result": f"Processed: {param}"}

        return [ToolSuite(
            id="plugin.my_plugin",
            name="My Plugin",
            description="My plugin tools",
            tools=[
                ToolDefinition(
                    name="my_tool",
                    description="Does something useful",
                    parameters={
                        "type": "object",
                        "properties": {
                            "param": {"type": "string", "description": "Input"}
                        },
                        "required": ["param"]
                    },
                    handler=my_tool_handler,
                )
            ]
        )]
```

### Running Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=erosolar_cli

# Type checking
mypy erosolar_cli
```

## TypeScript Version

The TypeScript implementation mirrors the Python architecture:

```
src/
├── core/                    # Same structure as Python
├── tools/
├── alpha-zero/              # TS Alpha Zero 2
│   ├── types.ts
│   ├── metricsTracker.ts
│   ├── codeEvaluator.ts
│   ├── agentWrapper.ts
│   └── competitiveRunner.ts
├── plugins/                 # TS plugin system
└── shell/
```

See the TypeScript README in `../src/README.md` for TS-specific documentation.

## Research: Alpha Zero 2

**Principal Investigator:** Bo Shang

Alpha Zero 2 demonstrates practical recursive self-improvement in autonomous coding agents through competitive dynamics.

**Key Innovations:**
1. **Competitive Learning** - Agents improve faster when competing
2. **Code Quality Metrics** - AST-based evaluation across 10+ dimensions
3. **Safe Self-Modification** - Version control with automatic rollback
4. **Meta-Learning** - Learning to improve the improvement process

**Citation:**
```bibtex
@software{alpha_zero_2,
  title={Alpha Zero 2: Recursive Self-Improvement in Competitive Multi-Agent Systems},
  author={Bo Shang},
  year={2024},
  framework={erosolar-cli}
}
```

## License

MIT License

## Links

- [GitHub Repository](https://github.com/ErosolarAI/erosolar-by-bo)
- [Issues](https://github.com/ErosolarAI/erosolar-by-bo/issues)
- TypeScript Implementation: `../src/`
- Alpha Zero 2 Research: `erosolar_cli/alpha_zero/`
- Plugin Development: `erosolar_cli/plugins/`