Metadata-Version: 2.4
Name: m1-m2-agent
Version: 0.3.2
Summary: Cost-Aware Hierarchical Coding Agent & Context Firewall — Universal MCP Server, CLI, and Python SDK
Author-email: Hamza <hamza@example.com>
License: Apache-2.0
Project-URL: Homepage, https://github.com/HamzaDevv/hierarchical-coding-agent
Project-URL: Repository, https://github.com/HamzaDevv/hierarchical-coding-agent
Project-URL: Documentation, https://github.com/HamzaDevv/hierarchical-coding-agent/tree/main/docs
Project-URL: Bug Tracker, https://github.com/HamzaDevv/hierarchical-coding-agent/issues
Keywords: ai-agent,mcp,coding-agent,context-firewall,deepseek,hierarchical-agent,model-context-protocol,llm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=1.0.0
Requires-Dist: mcp<2.0.0,>=1.2.0
Requires-Dist: litellm>=1.30.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: wheel>=0.40.0; extra == "dev"
Provides-Extra: providers
Requires-Dist: anthropic>=0.18.0; extra == "providers"
Requires-Dist: google-genai>=0.1.0; extra == "providers"
Dynamic: license-file

# `m1-m2-agent` — Cost-Aware Hierarchical Coding Agent & Context Firewall

> **Empower any Frontier Coding Agent (Antigravity, Cursor, Claude Code, Cline, Windsurf) with an autonomous, cost-efficient M2 worker agent and context firewall.**  
> Cut LLM token costs by up to **92%** while keeping your frontier reasoning context 100% pristine.

[![PyPI](https://img.shields.io/pypi/v/m1-m2-agent?color=blue)](https://pypi.org/project/m1-m2-agent/)
[![Python](https://img.shields.io/pypi/pyversions/m1-m2-agent)](https://pypi.org/project/m1-m2-agent/)
[![License](https://img.shields.io/badge/license-Apache%202.0-green)](LICENSE)
[![Tests](https://img.shields.io/badge/tests-passing-brightgreen)](https://github.com/HamzaDevv/hierarchical-coding-agent)

---

## 💡 The Core Philosophy: The Human-Agent Analogy

In modern software development, a senior human engineer never manually reads 50,000 lines of raw compiler logs or scans 1,000 files by hand when an AI coding agent can do it.
- **The Human Engineer** operates at the high cognitive tier: planning architecture, evaluating trade-offs, formulating hypotheses, and reviewing results.
- **The Coding Agent** operates at the implementation tier: searching directories, parsing AST symbols, executing tests, and writing code.

**`m1-m2-agent` brings this exact division of labor to AI Coding Agents:**
- **M1 (The Frontier Reasoner / Orchestrator)**: Powered by flagship models (Gemini 1.5 Pro, Claude 3.5 Sonnet, GPT-4o), M1 acts like the **human software architect**—focusing on strategy, architecture, and high-ambiguity decisions.
- **M2 (The Cheap Worker Agent & Context Firewall)**: Powered by fast, affordable models (Gemini Flash, DeepSeek V4-Flash, Claude Haiku, Local Ollama/Qwen), M2 acts as the **autonomous coding agent for M1**—executing multi-turn tool loops, searches, and test suites, compressing outputs (80–98% CCR) and returning structured evidence.

---

## ⚡ Quickstart

### 1. Install via pip
```bash
pip install m1-m2-agent
```

### 2. Drop into Any Project (30 seconds)
```bash
cd /path/to/your/project
m2 init
```

`m2 init` interactively configures your model and API key via LiteLLM, generates cognitive rule files (`AGENTS.md`, `.cursorrules`, `CLAUDE.md`, `.continuerules`), and displays the plug-and-play MCP configuration.

### 3. Connect to Your IDE / Agent
Add to your IDE's MCP settings (`.cursor/mcp.json`, Antigravity settings, Claude Code, Cline, etc.):
```json
{
  "mcpServers": {
    "m2-worker-agent": {
      "command": "m2-mcp-server",
      "env": {
        "WORKSPACE_ROOT": "/path/to/your/project"
      }
    }
  }
}
```

---

## 🤖 100+ Supported LLM Models via LiteLLM

Switch between cloud APIs or 100% offline local models with a single command:

```bash
# Google Gemini Flash (High speed & rate limits)
m2 config set model gemini/gemini-flash-latest

# DeepSeek V4-Flash (Ultra-low token cost)
m2 config set model deepseek/deepseek-chat

# Anthropic Claude 3.5 Haiku (High precision reasoning)
m2 config set model claude-3-5-haiku-20241022

# Local Ollama (100% Offline, 0 API cost)
m2 config set model ollama/qwen2.5-coder:7b
m2 config set api_base http://localhost:11434

# Test your active connection
m2 config test

# Inspect active configuration
m2 config show
```

For full details, see the [Multi-Provider Configuration Guide](docs/MULTI_PROVIDER_GUIDE.md).

---

## 🛠️ CLI Command Reference

`m1-m2-agent` provides a complete command-line toolkit:

| Command | Description |
| :--- | :--- |
| `m2 "<task>"` | Execute one-shot task with real-time streaming & KPI telemetry |
| `m2 run "<task>"` | Explicit task runner subcommand |
| `m2 outline [N]` | Instant zero-token AST code outline of top N modules |
| `m2 diff [--staged]` | Instant zero-token Git diff & status summary |
| `m2 hud [--port PORT]` | Launch the live Webview HUD browser dashboard (`localhost:4040`) |
| `m2 init [--dir DIR]` | Scaffold cognitive rules & MCP configuration into any repository |
| `m2 config <subcommand>` | Interactive wizard, test, show, or set models and API keys |
| `m2 tdd "<issue>"` | Path C autonomous Red-Green test diagnostic and bugfix loop |
| `m2` | Launch interactive M1 pair-programming REPL |
| `m2-mcp-server` | Run Model Context Protocol server on stdio |
| `m2-hud` | Standalone Web HUD runner |
| `m2-init` | Standalone project scaffolding CLI |
| `m2-config` | Standalone configuration manager |

For full CLI options, see the [Complete CLI Reference](docs/CLI_REFERENCE.md).

---

## 🏛️ Tri-Modal Architecture

```
                          ┌───────────────────────────────┐
                          │              L2               │
                          │   Frontier Reasoner (M1)      │
                          │   Plan • Decide • Review      │
                          └───────┬───────────────┬───────┘
                                  │               │
                          Path A  │        Path B │ (Direct Precision Fallback)
                      (Delegated) │               │
                                  ▼               │
                          ┌───────────────┐       │
                          │      L1       │       │
                          │  Worker (M2)  │       │
                          │ Context F/W   │       │
                          └───────┬───────┘       │
                                  │               │
                                  ▼               ▼
                          ┌───────────────────────────────┐
                          │              L0               │
                          │  Deterministic Fast Execution │
                          │   AST • Ripgrep • Git • LSP   │
                          └───────────────────────────────┘
```

- **Path A (Delegated Worker)**: Heavy searches, AST outlines, multi-step refactorings, test runs.
- **Path B (Direct Precision Fallback)**: Subtle race condition diagnosis, security audits, isolated single-file diffs.
- **Path C (Autonomous TDD Investigation)**: Red-Green diagnostic loop isolating test failures with reproduction scripts and verified patches.

---

## 🐍 Python SDK Usage

```python
from m1_m2_agent import M1OrchestratorAgent, TaskContract

# Initialize agent for current workspace
agent = M1OrchestratorAgent(workspace_root=".")

# Execute task with Context Firewall compression
response = agent.route_and_execute(
    objective="Locate all database connection pools and check for resource leaks",
    execution_path="PATH_A_DELEGATED"
)

print("Synthesized Result:\n", response["result"])
print("Structured Evidence:\n", response.get("evidence"))

# Inspect token savings & KPIs
telemetry = agent.get_telemetry_report()
print(f"Context Compression Ratio: {telemetry['context_compression_ratio']:.1f}%")
print(f"Frontier Token Avoidance:  {telemetry['frontier_token_avoidance_rate']:.1f}x")
print(f"Cost Reduction:            {telemetry['cost_reduction_pct']:.1f}%")
```

---

## 🌐 Live Webview HUD Dashboard

Launch the browser HUD on `http://localhost:4040`:
```bash
m2 hud
```
- **Live Event Stream**: Turn-by-turn thoughts, tool calls, and execution outputs via SSE.
- **Real-Time Gauges**: Live CCR, FTAR, and API cost reduction metrics.
- **Zero-Token AST Explorer**: Interactive visual map of all Python classes and methods.
- **Git Inspector**: Live diff hunks and file status tracking.
- **Transcript Scrubber**: Step-by-step history replay with automatic secret redaction.

---

## 📚 Documentation Index

- [2-Minute Quickstart](docs/QUICKSTART.md)
- [Complete CLI Reference](docs/CLI_REFERENCE.md)
- [Multi-Provider LLM Guide](docs/MULTI_PROVIDER_GUIDE.md)
- [The M1/M2 Architecture Philosophy](docs/M1_M2_PHILOSOPHY.md)
- [Full System Architecture](docs/ARCHITECTURE.md)
- [Real-World Setup Guide](docs/REAL_WORLD_SETUP_GUIDE.md)

---

## 📄 License

Apache License 2.0. See [LICENSE](LICENSE) for details.
