Agent 开发框架

The Forge|多模型代码进化与 Agent 工厂平台

The Forge

The Forge 让多个大模型就同一编程挑战竞争,用 Vitalis 编译器判定并评分,再通过进化算子迭代培育更优代码,同时可生成并部署多种工程产物。

获取与使用

需要部署

按官方资料自行安装或部署

使用难度待核验
国内可用性待核验

2026-11-09 更新 · 本站尚未实测

项目介绍

Agent 开发框架 · 2026-11-09 更新 · 本站尚未实测

The Forge 是一个以 Python 3.12+ 实现的多 Agent 代码进化平台。按 README 描述,它把同一编程挑战分发给多个大模型,收集各自解法,经 Vitalis 编译器(含可回退到 Python 的路径)做词法、语法、类型、Lint、能力、编译与执行等门禁检查,再做启发式与语义评分,随后以交叉、变异、选择等进化算子迭代,以改善代码质量为目标;效果属于项目方主张,本站未运行对比测试。项目同时提供 Agent 工厂、多模型对话与研究、REST API、命令行与本地看板。README 本身标题为“Multi-Agent Code Evolution Platform”,并非单一 Agent 或 MCP 服务,需按“框架/平台”理解其定位。

核心能力

点击能力名称查看输入、输出和原文依据。

  • 多模型竞赛:把挑战分发给 Claude、GPT、Gemini、DeepSeek 等云端模型或 Ollama 本地模型,统一评分并选优。
  • 进化引擎:提供均匀/单点/AST 感知交叉,换行、插入守卫、改常量、加注释、重命名等变异,以及 Boltzmann、UCB、精英保留等选择策略,README 还列出 KLS 随机局部化等方法。
  • 编译门禁:声称 7 道编译门(词法→解析→类型检查→Lint→能力→编译→执行),任一失败即淘汰。
  • Agent 工厂:按 18 类产物(agent、MCP 服务器、API、CLI、pipeline、Rust 库、Go 服务、React 组件、Terraform、GitHub Actions 工作流、VS Code 扩展、Docker、Skill、完整项目脚手架、Lean 4 证明等)由多模型竞争生成,胜者附部署配置文件。
  • 多模型研究与共识:同一问题并行询问多模型并汇总或综合出共识答案,带成本统计。
  • 成本与治理:逐次调用记录 token、费用、延迟,设预算上限;提供 SHA-256 哈希链溯源、策略引擎、熔断器与三级记忆。
  • 接口形式:本地 HTTP REST API、CLI 子命令(demo、compile、check、arena、chat、consensus、build、orchestrate)、本地看板,以及 README 所述的 MCP stdio 接口(JSON-RPC 2.0)。

实际应用场景

适用场景

适合需要在本地对比多家模型编程能力、用统一评分做模型/方案选型,或希望用进化式迭代打磨函数级代码的开发者;也适合作为生成 agent、MCP 服务器、API、CLI 等脚手架的内部实验平台。若只需单个聊天助手或面向终端用户的在线服务,本项目偏重本地实验与编排,价值有限。

安装与接入

README 给出的前置条件为 Python 3.12+,以及至少一个厂商 API Key(OpenRouter、Anthropic、OpenAI、Google 或 DeepSeek 之一);Ollama 与 Vitalis v60 为可选项。安装与启动步骤为:克隆仓库、进入目录、执行 pip install -r requirements.txt,设置至少一个 API Key 环境变量,然后运行 python forge_server.py,本机访问 http://localhost:8777 查看看板。首次运行会在 .forge_key 中生成随机 API Key,看板经回环地址自动获取。CLI 示例包括 python forge_cli.py demo --generations 5 --population 10 等,具体参数以仓库实际文件为准。MCP 与 server 配置文件在采集时返回 404,客户端配置方式待核验;MCP 是否为 stdio 之外还支持 HTTP 传输,资料未说明。

使用条件与限制

是否需要部署
需自行准备运行环境,具体要求见正文
是否需要注册
账号和认证要求见正文;未明确说明的项目仍待核验
是否需要 API Key
待核验
费用与额度
费用边界见正文,项目许可不代表模型或托管服务免费
所需权限
待核验
许可证与服务条款
待核验

权限费用与限制

本项目会调用付费大模型 API,实际费用取决于所选模型与调用量,README 提供预算上限(FORGE_BUDGET_USD)与 402 拦截;具体单价与额度以各厂商和 OpenRouter 官方计费为准,待核验。服务默认仅绑定 127.0.0.1,除健康检查外 /api/* 需 X-Forge-Key 或 Bearer 令牌;自改进与 shell 执行属高权限能力,shell 执行默认关闭,开启后仍经策略引擎检查,且项目声明为本地自用工具,不建议暴露到公网。文件分析与部署限制在项目根目录,并拒绝读取常见凭据文件。据 README 现有信息,自改进沙箱无法评估补丁时会拒绝对待应用(失败关闭)。模型清单中出现 2026 年命名的前沿模型与 OpenRouter 模型标识,其可用性与命名是否仍有效待向各厂商核验;本地推理需相应硬件,自动检测逻辑涉及 nvidia-smi、rocm-smi 与 Apple Silicon,实际支持情况待实测核验。

国内使用情况

网友核验 用户经验分享

与站长实测独立,不代表官方认证或本站已实测。

我要核验
0 位参与者0 份有效分项记录

最近核验:暂无有效核验。参与人数按当前项目有效身份去重;不同核验项分别统计,不合并成用户总结果。仅统计审核通过且未过期的记录。

分项统计、有效期与样本量
核验项目有效人数成功 / 部分 / 失败 / 无法判断成功率最近核验 / 有效期
官方网站访问00 / 0 / 0 / 0样本不足暂无 / 7 天
GitHub 仓库访问00 / 0 / 0 / 0样本不足暂无 / 7 天
安装与运行00 / 0 / 0 / 0样本不足暂无 / 30 天
官方服务国内连接 / MCP 连接00 / 0 / 0 / 0样本不足暂无 / 30 天
国内网络情况00 / 0 / 0 / 0样本不足暂无 / 7 天
国内模型兼容性00 / 0 / 0 / 0样本不足暂无 / 30 天
自定义 API00 / 0 / 0 / 0样本不足暂无 / 30 天
海外服务依赖
00 / 0 / 0 / 0样本不足暂无 / 30 天
海外账号要求
00 / 0 / 0 / 0样本不足暂无 / 30 天
中文界面
00 / 0 / 0 / 0样本不足暂无 / 30 天
客户端兼容性00 / 0 / 0 / 0样本不足暂无 / 30 天
账号及费用信息
00 / 0 / 0 / 0样本不足暂无 / 30 天

成功率 = 成功 ÷(成功 + 部分成功 + 失败);无法判断不计入分母。至少 5 份可判断结果才显示成功率。账号、费用、海外依赖与语言等事实项,成功表示核查结论与资料吻合,具体观察另行统计;不表示免费或没有海外依赖。不同网络、客户端和版本的结果不能直接等同。

最近有效核验

暂无审核通过且未过期的网友核验。欢迎提交真实使用记录。

查看全部有效核验 →

国内实测状态:国内可用性待核验。协议兼容和官方资料说明不等于国内网络可用。

官方网站访问
尚未实测 待核验
GitHub 仓库访问
尚未实测 待核验
官方服务国内连接
尚未实测 待核验
国内网络情况
尚未实测 待核验
国内模型兼容性
尚未实测 待核验
自定义 API
尚未实测 待核验
海外服务依赖
尚未实测 待核验
海外账号要求
尚未实测 待核验
中文界面
尚未实测 待核验
国内最后核验时间
尚未实测

许可与国内使用

仓库 LICENSE 为 MIT,可复制、修改、分发与商用,需保留版权与许可声明,软件按原样提供、无担保。该许可只覆盖本仓库代码,不覆盖所调用的大模型 API、OpenRouter 中转、Ollama 模型或第三方组件,这些服务的费用与条款须分别向提供方核验。仓库是否依赖境外域名(如 openrouter.ai、api.anthropic.com)由调用方自行决定,README 未说明中国大陆网络可用性,访问与合规情况待核验。未发现独立的商业模块或托管服务声明,若日后出现付费功能,费用需向官方核验。

项目资料与来源

官方网站 ↗

GitHub 仓库 ↗

官方文档 ↗

字段依据与待核验事项

access:来源确认 · git clone https://github.com/ModernOps888/the-forge.git

project_type:来源确认 · Multi-Agent Code Evolution Platform

原始 README(折叠技术参考)
<div align="center">

# 🔥 The Forge

### Multi-Agent Code Evolution Platform

[![Version](https://img.shields.io/badge/Release-v2.5.0-f97316?style=for-the-badge)](https://github.com/ModernOps888/the-forge/releases/tag/v2.5.0)
[![Python](https://img.shields.io/badge/Python-3.12+-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://python.org)
[![Vitalis](https://img.shields.io/badge/Powered_by-Vitalis_JIT-b7410e?style=for-the-badge&logo=rust&logoColor=white)](https://github.com/ModernOps888/vitalis)
[![License](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)](LICENSE)
[![Multi-Vendor](https://img.shields.io/badge/LLMs-Multi_Vendor-6366f1?style=for-the-badge)](https://openrouter.ai)
[![Cross-Platform](https://img.shields.io/badge/Platform-Win_Linux_Mac-22c55e?style=for-the-badge)](#-compute--hardware)

**Multiple LLMs compete to solve coding challenges.<br>
The Vitalis compiler is the impartial judge.<br>
Evolution breeds the winners into code no single model could write.**

<br>

> **`Claude's elegance × GPT's brute force × Gemini's lateral thinking → native compiled code`**

<br>

![The Forge Dashboard](docs/screenshots/forge-dashboard.png)

</div>

---

## 💡 The Idea

Every AI coding agent generates code. **None of them evolve it.**

The Forge takes solutions from multiple LLMs, compiles them through a real JIT compiler (Vitalis), benchmarks them with statistical rigor, and then **breeds the winners together** — crossover, mutation, selection — for hundreds of generations.

The result: code that's measurably better than any single model wrote.

```
4 LLMs × 1 challenge × 100 generations = code no single model could write
```

---

## 🏗 Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                  8. NATIVE DESKTOP BRIDGE                    │
│  File Explorer · VS Code · PowerShell · Clipboard Sync      │
├─────────────────────────────────────────────────────────────┤
│                  7. GOVERNANCE LAYER                         │
│  SHA-256 provenance · Policy engine · Circuit breaker        │
├─────────────────────────────────────────────────────────────┤
│                  6. MEMORY & SKILLS                          │
│  Working → Episodic → Semantic · Cosine retrieval · Decay    │
├─────────────────────────────────────────────────────────────┤
│                  5. SELF-IMPROVEMENT ENGINE                  │
│  LLM patching · AST validation · Fitness gating · Backup    │
├─────────────────────────────────────────────────────────────┤
│                  4. AGENT FACTORY                            │
│  18 artifact types · 9 languages · Auto-deploy + Marketplace │
├─────────────────────────────────────────────────────────────┤
│                  3. EVOLUTION LAYER                          │
│  KLS Stochastic Localization · Boltzmann · UCB · Lévy flight │
├─────────────────────────────────────────────────────────────┤
│                  2. COMPILER LAYER (Vitalis)                 │
│  Lex → Parse → Type-check → Lint → Capability → JIT → Exec  │
├─────────────────────────────────────────────────────────────┤
│                  1. ORCHESTRATION LAYER                      │
│  Multi-LLM dispatch · Budget tracking · Cost observability   │
└─────────────────────────────────────────────────────────────┘
```

---

## 🚀 Quick Start

### Prerequisites

| Tool | Version | Purpose |
|------|---------|---------|
| **Python** | 3.12+ | Orchestration engine |
| **API Key** | Any vendor | At least one: OpenRouter, Anthropic, OpenAI, Google, or DeepSeek |
| **Ollama** *(optional)* | Latest | Local GPU/CPU inference (qwen, llama, etc.) |
| **Vitalis** *(optional)* | v60 | JIT compilation backend (falls back to Python) |

### Install & Run

```bash
# Clone The Forge
git clone https://github.com/ModernOps888/the-forge.git
cd the-forge

# Install dependencies (minimal — mostly stdlib)
pip install -r requirements.txt

# Set at least one API key (see .env.example for all options)
# Windows PowerShell:
$env:OPENROUTER_API_KEY = "<API_KEY>"
# Or use direct vendor keys for lower latency:
$env:ANTHROPIC_API_KEY = "sk-ant-..."
$env:OPENAI_API_KEY = "sk-..."

# Linux/macOS:
export OPENROUTER_API_KEY="<API_KEY>"

# Launch the server + dashboard
python forge_server.py

# Open dashboard
# → http://localhost:8777
```

On first run the server generates a random API key and stores it in `.forge_key`
(git-ignored). The dashboard fetches it automatically over loopback — you only
need it yourself for direct `curl`/CLI access. See [🔐 Security](#-security) below.

### CLI Usage

```bash
# Run a demo tournament (mock providers, no API keys needed)
python forge_cli.py demo --generations 5 --population 10

# Compile a .sl snippet through Vitalis
python forge_cli.py compile "fn main() -> i64 { 42 }"

# Type-check without executing
python forge_cli.py check "fn main() -> i64 { 42 }"

# Run a full tournament from a challenge file
python forge_cli.py arena --challenge challenges/sort_integers.json --generations 20

# Interactive chat with any model
python forge_cli.py chat --model claude

# Multi-agent research (all models answer, then synthesize)
python forge_cli.py consensus "Best practices for Rust error handling"

# Build an artifact (4 models compete)
python forge_cli.py build "Build a GitHub webhook receiver with HMAC verification"

# Orchestrate a complex task
python forge_cli.py orchestrate "Design a microservice architecture for a payment gateway"
```

---

## 🏭 Agent Factory

The Factory is the crown jewel. Tell it what to build, and 4 models compete to write the best implementation.

```python
from forge import factory_build

result = factory_build(
    description="Build a GitHub MCP server with PR review and issue triage tools",
    artifact_type="mcp_server",  # or "auto" to detect
)

print(result.leaderboard())
# Winner is auto-saved with all deployment config
```

### Supported Artifact Types

| Type | Language | What It Generates |
|------|----------|-------------------|
| `agent` | Python | Autonomous agent with tools, memory, multi-step reasoning |
| `mcp_server` | Python | MCP server with JSON-RPC, tool schemas, stdio transport |
| `api` | Python | FastAPI REST API with Pydantic models, CORS, OpenAPI docs |
| `cli` | Python | CLI tool with argparse, rich output, config management |
| `pipeline` | Python | Data pipeline with transform stages, validation, sinks |
| `integration` | Python | Third-party connector (Slack, GitHub, Notion) |
| `sdk` | Python | Client library with retries, auth, pagination |
| `webhook` | Python | Webhook receiver with HMAC verification, retry queue |
| `rust_lib` | Rust | Library crate with error types, tests, Cargo.toml |
| `go_service` | Go | Microservice with handlers, middleware, graceful shutdown |
| `react_app` | TypeScript | React/Next.js component with hooks, CSS, accessibility |
| `terraform` | HCL | IaC module with variables, outputs, remote state |
| `workflow` | YAML | GitHub Actions CI/CD workflow |
| `extension` | TypeScript | VS Code extension with package.json, tsconfig |
| `docker` | Dockerfile | Dockerfile + docker-compose.yml |
| `skill` | Vitalis .sl | Native JIT-compiled hot-path function |
| `full_project` | Python | Multi-file production project scaffold with tests & Docker |
| `lean4_proof` | Lean 4 | Formal mathematical proof & invariant specification (kernel trust level zero) |

### Scoring Pipeline

```
LLM Generation (4 models)
        ↓
Vitalis Heuristic Scoring (sub-µs, native Rust)
  • Line count, import density, error handling, complexity
        ↓
LLM Semantic Scoring (Gemini, cheapest model)
  • Correctness, completeness, security, quality, production-readiness
        ↓
Final Score = 40% LLM + 60% Heuristic
  (We trust math over LLM self-evaluation)
        ↓
Winner saved + auto-deployed with config files
```

### Auto-Deployment

Every artifact type gets full deployment wiring:

| Type | Generated Files |
|------|----------------|
| `mcp_server` | `server.py`, `mcp.json` (Cursor), `vscode-mcp-snippet.json`, `README.md` |
| `api` | `main.py`, `requirements.txt`, `Dockerfile`, `docker-compose.yml`, `.env.example` |
| `cli` | `tool.py`, `pyproject.toml`, `run.sh` |
| `agent` | `agent.py`, `requirements.txt`, `run.sh`, `agent.service` (systemd) |
| `rust_lib` | `src/lib.rs`, `Cargo.toml` |
| `go_service` | `main.go`, `go.mod`, `Makefile`, `Dockerfile` |
| `react_app` | `Component.tsx`, `package.json` |
| `terraform` | `main.tf`, `backend.tf`, `terraform.tfvars.example` |
| `full_project` | Multi-file tree parsed from `# === FILE: path ===` markers + `README.md` |
| `lean4_proof` | `Proof.lean`, `lakefile.lean`, `lean-toolchain`, `README.md` (kernel trust level zero) |

---

## 🧬 Evolution Engine

Not a basic genetic algorithm. This is research-grade evolutionary computation powered by native Rust hotpaths and **KLS Stochastic Localization**.

### Selection Algorithms

| Algorithm | Purpose |
|-----------|---------|
| **KLS Stochastic Localization Tilt Selection** | Continuous measure-tilting (`stochastic_localization_select`) over isotropic 64D n-gram embeddings with dimension-free $O(1)$ KLS/Poincaré spectral mixing (Song & Zhang 2026) |
| **Multi-Trajectory Dead-End Pruning** | Eliminates stagnant lineages lagging the Pareto front and supports human-director trajectory steering (`director_hook`) |
| **Boltzmann (Softmax) Selection** | Temperature-controlled exploration/exploitation. T→0 = greedy, T→∞ = random |
| **Bayesian UCB1** | Multi-armed bandit — try under-explored solutions more |
| **Elite Passthrough** | Top N individuals survive unchanged |
| **Quantum-Inspired Annealing** | Probabilistically accept worse solutions to escape local optima |

### Crossover Operators

| Operator | What It Does |
|----------|-------------|
| **Uniform Crossover** | For each line, randomly pick from parent A or B |
| **Single-Point Crossover** | Swap tails at a random body line |
| **AST-Aware Crossover** | Swap entire brace-depth blocks between parents (prevents syntax breaks) |

### Mutation Operators

| Operator | What It Does |
|----------|-------------|
| **Swap Lines** | Swap two adjacent body lines |
| **Insert Guard** | Add an early-return guard clause |
| **Change Constant** | Alter a numeric literal by a Lévy-flight step |
| **Add Comment** | Inject a descriptive comment (drives novelty score) |
| **Rename Variable** | Rename a variable for code distance |

### The 6 Fitness Dimensions

| Dimension | Weight | Source |
|---|---|---|
| **Correctness** | 30% | Test case pass rate |
| **Performance** | 25% | Relative execution speed, algorithmic complexity |
| **Code Quality** | 15% | Structure, naming, documentation, type hints |
| **Robustness** | 15% | Error handling, input validation, edge cases |
| **Efficiency** | 10% | Memory patterns, allocations, streaming |
| **Novelty** | 5% | Code distance from population (prevents convergence) |

---

## 🔒 The 7 Compiler Gates

Every submission passes through 7 gates before being scored:

```
Source → LEX → PARSE → TYPE CHECK → LINT → CAPABILITY → COMPILE → EXECUTE
          ↓      ↓         ↓          ↓        ↓          ↓         ↓
        Reject  Reject   Reject    Score    Reject     Reject    Score
```

If any gate fails, the submission is eliminated. The compiler is the impartial judge — it doesn't care which LLM wrote the code.

---

## 🧠 Three-Tier Memory

```
┌──────────────────────────────────────────┐
│  Tier 1: WORKING MEMORY (in-RAM)         │
│  Per-session, cosine dedup via Vitalis    │
│  Max 30 entries, importance-weighted      │
├──────────────────────────────────────────┤
│  Tier 2: EPISODIC MEMORY (JSON on disk)  │
│  EMA importance decay, 500 entry limit    │
│  Automatic eviction of low-importance     │
├──────────────────────────────────────────┤
│  Tier 3: SEMANTIC (Skills + Instructions)│
│  Injected into system prompts            │
│  Boltzmann-selected based on query match │
└──────────────────────────────────────────┘
```

**Skills** are context-aware prompt injections. When you ask about debugging, the debugging skill activates and enriches the system prompt. Skills have fitness scores that update via adaptive fitness scoring.

**Instructions** are standing orders (e.g., "Be concise", "Use type hints") that persist across sessions.

---

## 🛡️ Self-Improvement Engine

The Forge can modify its own source code:

```
User instruction → LLM generates line-range patches
                          ↓
                    JSON repair layer
                          ↓
                    AST syntax validation (Python)
                          ↓
              ┌─── Fitness Gate ───┐
              │  Baseline score    │
              │  Mutant score      │
              │  Regression? BLOCK │
              │  Below floor? BLOCK│
              └────────────────────┘
                          ↓
                    Auto-backup (.bak)
                          ↓
                    Overwrite + hot-swap
```

**Safety layers:**
1. JSON repair (fix truncated LLM output)
2. AST dry-run before overwrite
3. 6-dimensional fitness scoring — **no regressions allowed**
4. Quality floor (30/100 minimum)
5. Auto-backup before every write
6. Hot-swap only when patching the server itself

---

## 🔐 Security

The Forge's HTTP server can spend money, read/write files, and — if you opt in —
run shell commands. It's hardened as follows:

| Control | Behavior |
|---|---|
| **Auth** | Every `/api/*` route (except `/api/health`) requires an `X-Forge-Key` header (or `Authorization: Bearer <key>`). Set `FORGE_API_KEY` yourself, or let the server auto-generate one into `.forge_key` on first run (git-ignored). |
| **Bind address** | Defaults to `127.0.0.1` (loopback-only). Set `FORGE_BIND_HOST=0.0.0.0` only if you deliberately want LAN/remote access. |
| **CORS** | `Access-Control-Allow-Origin` is only echoed back for `localhost`/`127.0.0.1` origins — no wildcard for arbitrary sites. |
| **Shell execution** | The cowork agent loop's `<execute_powershell>` tags and GUI keystroke automation are **disabled by default**. Enable with `FORGE_ALLOW_SHELL_EXEC=true`, and even then every command is checked against the governance `PolicyEngine` before it runs. |
| **Path jailing** | Self-improve patch targets and generated-artifact deploys are resolved and confined to the project root — no writing outside the repo. |
| **Secret files** | `/api/analyze-file` refuses to read files matching common credential patterns (`.env`, `.pem`, `id_rsa`, `.aws/credentials`, etc.). |
| **Budget gate** | Every LLM-calling endpoint checks the cost tracker first and returns `402` once `FORGE_BUDGET_USD` is exhausted, instead of spending past the cap. |
| **Fitness gate (fail-closed)** | If the self-improvement sandbox can't evaluate a patch, the patch is rejected rather than applied. |
| **Governed deploys** | Every artifact from the Agent Factory is checked by the `PolicyEngine` (AST-based dangerous-call detection, not just substring matching) before `deployer.py` will compile and run it. |

**Local-only tool, not a public service.** The Forge is designed to run on your
own machine for your own use. Don't put it on the public internet — the auth
key is a shared secret, not a full identity/authorization system, and features
like self-improvement and shell exec are inherently high-privilege.

---

## 🔗 Governance & Provenance

### SHA-256 Provenance Chain

Every action is recorded in a tamper-evident, hash-chained ledger:

```python
entry = ProvenanceEntry(
    timestamp=time.time(),
    event_type="factory_complete",       # submission, compilation, mutation, promotion...
    entity_id="run_a1b2c3d4",
    actor="factory",
    data={"winner_provider": "claude", "score": 87.2},
    parent_hash="previous_entry_sha256",
    entry_hash="sha256(timestamp|type|id|actor|data|parent)",
)
```

Modify any entry → all subsequent hashes invalidate → tamper detected.

### Policy Engine

| Policy | Enforcement |
|--------|-------------|
| No file system access | Compile-time capability check |
| No network access | Compile-time capability check |
| No process execution | Compile-time capability check |
| Budget enforcement | Halt all calls when budget exhausted |
| Type safety | Type-check must pass before JIT |
| Timeout enforcement | Kill execution exceeding limit |
| Regression prevention | Champion must beat current best |
| Novelty threshold | Reject <10% code distance |

### Circuit Breaker

Protects against cascading API failures:
- **Closed** → normal operation
- **Open** → blocks all calls after N consecutive failures
- **Half-open** → allows one test call after cooldown

---

## 💰 Budget & Cost Tracking

Every API call is traced with:

| Metric | Tracked |
|--------|---------|
| Input/output tokens | Per request |
| Cost (USD) | Per request, per provider |
| Latency | Per request (ms) |
| EMA spike detection | Alert on anomalous costs |
| Per-provider breakdown | Who's expensive, who's cheap |
| Budget enforcement | Hard cap with remaining balance |
| Optimization hints | "Switch to Gemini for 3x savings" |

```python
tracker = get_tracker(BudgetConfig(max_budget_usd=50.0))
# Every call auto-records. Dashboard shows real-time spend.
```

---

## 🖥️ Live Dashboard

The Forge ships with a full interactive dashboard at `http://localhost:8777`:

![Chat View with Model Badges](docs/screenshots/forge-chat-view.png)

| Tab | Features |
|-----|----------|
| **Chat** | Multi-model chat with vendor badges (DIRECT/OPENROUTER/LOCAL) |
| **Cowork** | Desktop co-work agent with native OS hooks |
| **Research** | Fan query to multiple models, consensus synthesis |
| **Build** | Agent Factory — 4 models compete, leaderboard scoring |
| **Compile** | Vitalis .sl code compilation & execution |
| **Dashboard** | KPIs, Compute & Platform panel, Vendor Routing matrix |
| **Orchestrate** | Multi-step complex task execution |
| **Evolve** | Self-improvement engine with fitness gating |
| **Trace** | Execution traces + Human-in-the-Loop approvals |
| **Antigravity** | IDE export inbox |

### Dashboard Highlights

- **6 KPI Cards**: Total Cost, Tokens, Requests, Active Vendors, GPU Count, Vitalis Version
- **Compute & Platform Panel**: Detected GPU (name, VRAM bar), OS badge, CPU cores, RAM, compute mode selector
- **Vendor Routing Matrix**: Shows which vendors are ACTIVE/INACTIVE with IDE export targets
- **Real-time telemetry**: CPU%, RAM%, GPU% with VRAM utilization in the top bar

---

## 🐍 Python SDK

```python
from forge import Arena, ArenaConfig, Challenge

# Define a challenge
challenge = Challenge(
    name="Fibonacci",
    description="Compute the nth Fibonacci number",
    function_signature="fn fib(n: i64) -> i64",
)

# Create arena
arena = Arena(config=ArenaConfig(max_generations=50))
arena.register_provider("claude", my_claude_api)
arena.register_provider("gpt", my_gpt_api)

# Run tournament
tournament = arena.run(challenge)

# Get the champion
print(f"Winner: {tournament.champion.fitness.total}")
print(tournament.champion.source_code)
```

### Multi-Agent Research

```python
from forge import multi_agent_research, consensus

# Ask all models the same question
results = multi_agent_research("Best Rust error handling patterns")
# → {"claude": "...", "gpt": "...", "gemini": "...", "deepseek": "..."}

# Or get a synthesized consensus
result = consensus("Compare actor model vs CSP for Go concurrency")
# → {"individual": {...}, "consensus": "merged answer", "cost_usd": 0.003}
```

### Smart Router

```python
from forge import auto_route

# Automatically picks cheapest model that can handle the task
answer = auto_route("What's 2+2?")           # → Gemini Flash (cheapest)
answer = auto_route("Design a payment API")   # → Claude (premium)
```

---

## 🔧 Model Registry & Multi-Vendor Routing

October 2026 frontier and open-weight model matrix:

| Name | Model ID | Tier | Routing |
|------|----------|------|--------|
| `claude-fable` | `anthropic/claude-fable-5-1` | Ultra / Elite | Direct → OpenRouter fallback |
| `claude-mythos` | `anthropic/claude-mythos-5` | Ultra / Elite | Direct → OpenRouter fallback |
| `claude-opus` | `anthropic/claude-opus-5-5` | Ultra / Elite | Direct → OpenRouter fallback |
| `claude` | `anthropic/claude-sonnet-5-5` | Premium | Direct → OpenRouter fallback |
| `gpt` | `openai/gpt-6-astra` | Premium | Direct → OpenRouter fallback |
| `gpt-sol` | `openai/gpt-6.1-sol` | Premium | Direct → OpenRouter fallback |
| `gemini` | `google/gemini-4-argon` | Premium | Direct → OpenRouter fallback |
| `gemini-pro` | `google/gemini-3.8-pro` | Premium | Direct → OpenRouter fallback |
| `grok` | `x-ai/grok-4.7` | Premium | Direct (`XAI_API_KEY`) → OpenRouter fallback |
| `deepseek-r1` | `deepseek/deepseek-r1` | Premium | Direct → OpenRouter fallback |
| `o3` | `openai/o3` | Premium | Direct → OpenRouter fallback |
| `o3-mini` | `openai/o3-mini` | Premium | Direct → OpenRouter fallback |
| `claude-haiku` | `anthropic/claude-haiku-5-5` | Fast / Economy | Direct → OpenRouter fallback |
| `gpt-mini` | `openai/gpt-5` | Fast / Economy | Direct → OpenRouter fallback |
| `gpt-nano` | `openai/o3-mini` | Fast / Economy | Direct → OpenRouter fallback |
| `gemini-lite` | `google/gemini-3.8-flash` | Fast / Economy | Direct → OpenRouter fallback |
| `deepseek` | `deepseek/deepseek-chat` | Fast / Economy | Direct → OpenRouter fallback |
| `llama-3.3` | `meta-llama/llama-3.3-70b-instruct` | Fast / Economy | OpenRouter / Ollama |
| `qwen-local` | `qwen2.5-coder:7b` | Local | Ollama (GPU/CPU/Split) |
| `llama-local` | `llama3.2:latest` | Local | Ollama (GPU/CPU/Split) |
| `codellama` | `codellama:7b` | Local | Ollama (GPU/CPU/Split) |
| `mistral-local` | `mistral:latest` | Local | Ollama (GPU/CPU/Split) |
| `phi-local` | `phi3:mini` | Local | Ollama (GPU/CPU/Split) |

> **Note on reasoning & frontier models:** direct Anthropic calls to the Claude 5.x family omit sampling parameters (`temperature` is rejected with a 400 on these models) — steering is prompt-only. Direct OpenAI calls to `o1`/`o3`/`o4` reasoning models automatically send `max_completion_tokens` and omit `temperature`.

### Smart Routing

The Forge uses a **smart routing** strategy:

1. **Direct vendor key present?** → Call vendor API directly (lowest latency)
2. **No direct key?** → Fall back to OpenRouter (universal relay)
3. **Local model?** → Route to Ollama with hardware-aware `num_gpu`

```
Anthropic key → api.anthropic.com (direct, ~200ms)
No key         → openrouter.ai/api (relay, ~400ms)
qwen-local     → localhost:11434 (Ollama, GPU/CPU)
```

---

## 🖥 Compute & Hardware

The Forge auto-detects available hardware for local inference:

| Platform | GPU Detection | RAM Detection |
|----------|--------------|---------------|
| **Windows** | `nvidia-smi` (NVIDIA) | `wmic` / `psutil` |
| **Linux** | `nvidia-smi` (NVIDIA), `rocm-smi` (AMD) | `psutil` |
| **macOS** | Apple Silicon (unified memory) | `psutil` |

### Compute Modes (`FORGE_COMPUTE`)

| Mode | Behavior | Use Case |
|------|----------|----------|
| `auto` | Detect GPU, fallback to CPU | Default — works everywhere |
| `gpu` | Force all layers on GPU | Dedicated GPU machines |
| `cpu` | Force CPU-only (`num_gpu=0`) | No GPU, 16GB+ RAM |
| `split` | Split layers across GPU+CPU | Limited VRAM (4-6GB) |

The dashboard's **Compute & Platform** panel shows detected hardware in real-time:
- GPU name, VRAM total/free with usage bar
- Platform badge (🪟 Windows / 🐧 Linux / 🍎 macOS)
- CPU cores, system RAM with capacity bar
- Active compute mode selector visualization

---

## 📊 Statistical Rigor

The Forge doesn't use vibes. Every comparison uses proper statistics:

- **Welford's algorithm** for numerically stable online mean/variance
- **95% confidence intervals** via Student's t distribution
- **Welch's t-test** for comparing two candidates with unequal variance
- **Cohen's d** effect size measurement
- **MAD-based outlier detection** (modified Z-score)
- **Minimum 30 runs** before declaring significance
- **Pareto front** computation for multi-objective optimization

---

## 📁 Project Structure

```
the-forge/
├── forge/
│   ├── __init__.py           # Package exports (v2.4.0)
│   ├── models.py             # Data models (Challenge, Submission, FitnessScore, etc.)
│   ├── compiler.py           # Vitalis JIT + CLI + sandboxed pure-Python .sl interpreter (7 gates)
│   ├── benchmark.py          # Welford stats, Student's t 95% CI, Welch's t-test, MAD outliers
│   ├── evolution.py          # Crossover, mutation, Boltzmann/UCB selection, quantum annealing
│   ├── arena.py              # Multi-LLM tournament orchestrator with provenance & test runner
│   ├── factory.py            # Agent Factory (17 artifact types, 8 languages, auto-deploy)
│   ├── deployer.py           # Policy-governed auto-deployment wiring for all 17 artifact types
│   ├── fitness_engine.py     # 6-dimensional polyglot code scoring (Python/TS/Rust/Go/HCL/YAML/Docker/.sl)
│   ├── providers.py          # Smart-routed Direct Vendor + OpenRouter + Ollama LLM providers
│   ├── budget.py             # Thread-safe cost tracking, pre-update EMA spike detection
│   ├── governance.py         # SHA-256 provenance chain, 10-rule AST policy engine, circuit breaker
│   ├── memory.py             # Thread-safe 3-tier memory (working/episodic/semantic)
│   ├── marketplace.py        # Portable skill & artifact marketplace registry
│   ├── skills.py             # Cryptographic Skill DNA certification from compilation
│   ├── tracer.py             # Bounded execution traces + HITL approval gates
│   ├── replay.py             # Deterministic tournament replay & A/B testing (`run_ab_test`)
│   └── vitalis_ffi.py        # Vitalis Rust FFI bindings (234K LOC of bindings)
├── tests/
│   ├── test_forge_comprehensive.py # Full 11-part end-to-end verification suite
│   └── test_forge.py         # Test runner entry point
├── dashboard/
│   └── index.html            # Full interactive dashboard (single-file, zero external JS deps)
├── challenges/
│   └── sort_integers.json    # Example challenge definition
├── forge_server.py           # ThreadingHTTPServer API server (2,100+ lines)
├── forge_cli.py              # Full CLI entry point (9 subcommands)
├── forge_desktop.py          # Native Windows desktop tray & Explorer context menu bridge
├── forge_mcp.py              # MCP server interface (13 tools over JSON-RPC 2.0 stdio)
├── launch.ps1                # Windows PowerShell launcher
├── requirements.txt          # Minimal dependencies
└── README.md
```

---

## 🔌 API Reference

### REST Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/chat` | Send message to any model |
| `POST` | `/api/research` | Fan query to selected models |
| `POST` | `/api/consensus` | All models + synthesis |
| `POST` | `/api/compile` | Compile .sl code via Vitalis |
| `POST` | `/api/build` | Agent Factory — build any artifact |
| `POST` | `/api/deploy` | Deploy a factory result |
| `POST` | `/api/orchestrate` | Multi-step complex task execution |
| `POST` | `/api/score` | Score code with fitness engine |
| `POST` | `/api/self-improve` | Self-improvement patching |
| `POST` | `/api/cowork` | Desktop co-work agent |
| `POST` | `/api/quick-chat` | Stateless single-shot chat |
| `POST` | `/api/analyze-file` | AI code review of local file |
| `POST` | `/api/export` | Export to IDE bridge (multi-target) |
| `POST` | `/api/native` | Native OS bridge (explorer/IDE/terminal) |
| `POST` | `/api/transcribe` | Local Whisper voice-to-text transcription |
| `POST` | `/api/hitl/resolve` | Approve or reject a pending Human-in-the-Loop request |
| `GET` | `/api/health` | System health + active vendors (public) |
| `GET` | `/api/auth-bootstrap` | Loopback-only API key bootstrap for local dashboard |
| `GET` | `/api/models` | Available models + pricing + vendor badges |
| `GET` | `/api/budget` | Cost & token report |
| `GET` | `/api/provenance` | Governance audit trail |
| `GET` | `/api/memory` | Memory system stats |
| `GET` | `/api/traces` | Execution traces with step durations |
| `GET` | `/api/hitl/pending` | Pending Human-in-the-Loop approval gates |
| `GET` | `/api/system` | Real-time CPU, RAM, and GPU telemetry |
| `GET` | `/api/artifact-types` | Supported Agent Factory artifact types & languages |
| `GET` | `/api/marketplace` | Published skills & artifacts in the marketplace |
| `GET` | `/api/ag-inbox` | Antigravity IDE inbox items |
| `GET` | `/api/vendor-health` | Vendor connection status |
| `GET` | `/api/compute` | Hardware detection (GPUs, CPU, RAM) |
| `GET` | `/api/ide-targets` | Configured IDE export targets |

### MCP Tools (`forge_mcp.py` — 13 Tools over JSON-RPC 2.0 `stdio`)

| Tool | Description |
|------|-------------|
| `vitalis_score` | 6-dimensional polyglot code fitness evaluation (`0-100` + grade `A+` to `F`) |
| `forge_compile` | Compile & execute `.sl` code through the 7-gate Vitalis pipeline |
| `forge_benchmark` | Benchmark `.sl` code across $N$ runs with Welford stats & 95% Student's $t$ CI |
| `forge_build` | Multi-LLM Agent Factory competition across 17 artifact types |
| `forge_orchestrate` | Architect + multi-model competitive challenge generation & evolution |
| `forge_research` | Multi-agent parallel research query |
| `forge_consensus` | Multi-agent query + authoritative synthesis |
| `forge_chat` | Cost-tracked chat with any configured cloud or local model |
| `forge_budget` | Live spend, token counters, per-provider breakdown, and optimization hints |
| `forge_market_search` | Search certified skills and artifacts in the Forge Marketplace |
| `forge_market_publish` | Publish a code artifact or skill with SHA-256 integrity hashing |
| `forge_provenance` | Inspect and verify the SHA-256 governance provenance chain |
| `forge_provider_status` | Inspect active LLM vendors and hardware compute capabilities |

---

## 🗺 Roadmap

- [x] Core engine (compiler, benchmark, evolution, arena)
- [x] CLI with demo mode
- [x] Vitalis JIT integration with native Rust hotpaths
- [x] Real LLM providers via OpenRouter (Claude, GPT, Gemini, DeepSeek)
- [x] **Multi-vendor smart routing** (direct Anthropic/OpenAI/Google/DeepSeek/xAI + OpenRouter fallback)
- [x] **Cross-platform compute detection** (NVIDIA, AMD ROCm, Apple Silicon, CPU-only)
- [x] **IDE-agnostic export bridge** (VS Code, Cursor, Windsurf, Antigravity, clipboard)
- [x] Budget & cost tracking with EMA spike detection
- [x] Enterprise governance (provenance chain, policy engine, circuit breaker)
- [x] Agent Factory (17 artifact types, 8 languages)
- [x] Auto-deployment wiring for all artifact types
- [x] Three-tier memory engine (working/episodic/semantic)
- [x] Self-improvement engine with fitness gating
- [x] Interactive dashboard with 10+ tabs
- [x] Native desktop bridge (File Explorer, VS Code, PowerShell)
- [x] Polyglot fitness engine (Python, Rust, Go, TypeScript, HCL, YAML, Dockerfile, Vitalis `.sl`)
- [x] Local model support via Ollama (GPU/CPU/split compute modes)
- [x] MCP server (13 tools, smart-routed, stdout-isolated JSON-RPC 2.0)
- [x] Deterministic tournament replay & A/B testing (`create_replay_config`, `run_replay`, `run_ab_test`)
- [x] **KLS Stochastic Localization Tilt Selection, Poincaré Spectral Diagnostics & Lean 4 Proof Factory (`v2.5.0`)**
- [ ] SQLite evolution ledger
- [ ] Multi-user collaboration mode
- [ ] WebSocket real-time dashboard updates

---

## 📄 License

MIT License — see [LICENSE](LICENSE) for details.

## 🔧 Recent Changes (v2.5.0 — KLS Stochastic Localization, Multi-Trajectory Pruning & Lean 4 Proof Factory)

- **KLS Stochastic Localization Tilt Selection (`forge/evolution.py`)** — Added `StochasticLocalizationState` and `stochastic_localization_select()` implementing Eldan / Song–Zhang (2026, `arXiv:2610.01447`) continuous measure-tilting over isotropically preconditioned 64D code embeddings with quadratic confinement and standardized advantage weighting.
- **KLS Isoperimetric & Poincaré Spectral Diagnostics (`forge/benchmark.py`)** — Added `kls_spectral_diagnostics()` computing empirical fitness variance $\mathrm{Var}_\mu(f)$, discrete Dirichlet gradient energy $\mathbb{E}_\mu[\|\nabla_{\mathcal{G}} f\|^2]$, the Poincaré ratio $\hat{C}_{\text{Poincaré}}$ (`KLS500` bound verification $\le 500$), and Silverman KDE median hyperplane cut conductance $\hat{\psi}_{\text{KLS}}$.
- **Multi-Trajectory Dead-End Pruning & Human-Director Steering (`forge/arena.py`)** — Added `_prune_dead_end_trajectories()` and `director_hook` in `Arena` to prune stagnant lineages and focus population evaluations on high-gradient trajectories. Verified in a 10-seed A/B benchmark: **+6.38 mean population fitness gain** (`92.31` vs `85.93`), **59.5% variance reduction**, Welch's $t = 4.59$ ($p < 0.001$), and Cohen's $d = 2.0527$.
- **18th Artifact Type: Lean 4 Formal Proof & Kernel Verification (`forge/factory.py`, `forge/deployer.py`, `forge/fitness_engine.py`)** — Added `lean4_proof` (`Proof.lean`, `lakefile.lean`, `lean-toolchain`) and a dedicated Lean 4 fitness scorer that enforces zero `sorry`/`admit` axioms (`SORRY_AXIOM_DETECTED`) and verifies `#print axioms` kernel-trust-level-zero structure.
- **v2.4.0 Foundation** — Sandboxed pure-Python `.sl` lexer/parser/type-checker/interpreter fallback, AST alias-resolving `PolicyEngine`, SHA-256 parent-link tamper detection, and stdout-isolated JSON-RPC 2.0 MCP server.

---

<div align="center">

**Built with 🔥 by [ModernOps888](https://github.com/ModernOps888)**

*Where code is forged through competition, refined by evolution, and hardened by compilation.*

</div>
历史前置条件说明(补充参考)

Python 3.12+;至少一个厂商 API Key(OpenRouter、Anthropic、OpenAI、Google 或 DeepSeek),费用由厂商计费、具体价格待核验;可选 Ollama 本地推理与 Vitalis v60 编译后端;境外 API 依赖与国内网络可达性待核验;MCP 客户端配置方式待核验。

项目来源与清单版权许可

https://github.com/ModernOps888/the-forge

整理来源:https://github.com/slavakurilyak/awesome-ai-agents

清单版权与许可:

MIT License

Copyright (c) 2024 Slava Kurilyak

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.