ares

module
v0.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2026 License: Apache-2.0

README

           _____  ______  _____ 
     /\   |  __ \|  ____|/ ____|
    /  \  | |__) | |__  | (___  
   / /\ \ |  _  /|  __|  \___ \ 
  / ____ \| | \ \| |____ ____) |
 /_/    \_\_|  \_\______|_____/ 

ARES (Adaptive Resilient Evolution System) — A Self-Healing, Self-Evolving Runtime for Autonomous Agents

Go-based multi-agent framework with DAG workflow orchestration, genetic algorithm self-evolution, memory distillation, inter-agent protocol (AHP), and chaos engineering — built for production-grade agent orchestration.

Unlike static agent frameworks, ARES treats agent behavior as an evolvable genome: strategies are mutated, crossed over, and selected across generations based on real execution evidence. The system heals from failures via checkpoint recovery, ages out stale strategies, and continuously improves through closed-loop evolution.

Architecture

Architecture

graph TB
    User["User Request"] --> Bootstrap

    subgraph api ["API Layer (api/core/)"]
        Bootstrap["Bootstrap Factory"]
        Interfaces["AgentService / Runtime / Evolution / Arena / MemoryService / LLMService / WorkflowService"]
    end

    Bootstrap --> RT
    Bootstrap --> EvoSvc
    Bootstrap --> ArenaSvc
    Bootstrap --> MemMgr

    subgraph runtime ["Runtime Layer"]
        RT["Runtime Manager"]
        RT -->|"manages lifecycle"| Leader
        RT -->|"replays"| ES["EventStore"]
        RT -->|"restores"| MM["MemoryStore"]
        RT -->|"module=runtime"| LOG["Structured Logger"]
    end

    subgraph agents ["Agent System"]
        direction TB
        Leader["Leader Agent"]
        SubA["Sub Agent A"]
        SubB["Sub Agent B"]
        SubC["Sub Agent C"]
        Leader -->|"AHP Protocol"| SubA
        Leader -->|"AHP Protocol"| SubB
        Leader -->|"AHP Protocol"| SubC
        Supervisor["Supervisor"]
        Leader -.->|"Checkpoint Recovery"| Supervisor
    end

    subgraph workflow ["Workflow Engine"]
        MutableDAG["MutableDAG"]
        DynamicExec["DynamicExecutor"]
        PluginBus["PluginBus"]
        MutableDAG --> DynamicExec
        DynamicExec --> PluginBus
        DynamicExec --> TopoSort["Topological Sort"]
        DynamicExec --> CycleDetect["Cycle Detection"]
    end

    subgraph llm ["LLM Layer"]
        Adapters["Output Adapters"]
        Templates["Prompt Templates"]
        Parser["Function Call Parser"]
    end

    subgraph mem ["Memory Manager"]
        MemMgr["Memory Manager"]
        Session["Session Memory"]
        Task["Task Memory"]
        Distilled["Distilled Memory"]
        Session --> Pipeline["Distillation Pipeline"]
        Task --> Pipeline
        Pipeline --> Distilled
    end

    subgraph evo ["Evolution Engine"]
        EvoSvc["Evolution Service"]
        Pop["GA Population"]
        Score["Scoring Pipeline"]
        EvidAgg["Evidence Aggregator"]
        Promo["Promotion Logic"]
        Report["Evolution Report"]
        Cross["Crossover"]
        Mut["Mutation"]
        EvoSvc --> Pop
        Pop --> Score
        Score --> Cross
        Cross --> Mut
        Mut --> Pop
        Score -->|"per-generation"| EvidAgg
        EvidAgg -->|"evidence"| Promo
        Promo -->|"after all gens"| Report
        ExpStore["Experience Store"]
        Norm["Normalizer"]
        OutcomeRec["Outcome Recorder"]
        ToolCollect["Tool Call Collector"]
        OutcomeRec --> Norm
        ToolCollect --> Norm
        Norm --> ExpStore
        ExpStore --> EvidAgg
    end

    subgraph hitl ["Human-in-the-Loop"]
        IH["Interrupt Handler"]
        IS["Interrupt Store"]
        AW["Approval Workflow"]
        IH --> IS
        IH --> AW
    end

    subgraph stor ["Storage Layer"]
        VS["VectorStore Interface"]
        PG[("PostgreSQL + pgvector")]
        MEM[("In-Memory")]
        QD[("Qdrant")]
        SQL[("SQLite + sqlite-vec")]
        CUSTOM[("Your Backend")]
        Cache["Cache"]
        CB["Circuit Breaker"]
        VS --> PG
        VS --> MEM
        VS --> QD
        VS --> SQL
        VS --> CUSTOM
        PG --> Cache
        Cache --> CB
    end

    subgraph tools ["Tool System"]
        Registry["Tool Registry"]
        MCP["MCP Manager"]
        MCP_Ext["MCP Servers"]
        Registry --> MCP
        MCP -->|"stdio/SSE"| MCP_Ext
    end

    subgraph obs ["Observability"]
        Dashboard["Web Dashboard"]
        Flight["Flight Recorder"]
        Genealogy["Agent Genealogy"]
    end

    subgraph cb ["Callbacks"]
        Handler["Handler Registry"]
        Events["Lifecycle Events"]
    end

    subgraph arena ["Chaos Engineering"]
        ArenaSvc["Arena Service"]
        FI["Fault Injector"]
        RS["Resilience Scoring"]
        SM["Survival Mode"]
        ArenaSvc --> FI
        FI --> RS
        RS --> SM
    end

    EmbedSvc["Embedding Service"]
    ReportFile["Report File"]

    evo -->|"stores results"| Distilled
    evo -->|"uses"| Score
    Report -->|"persists to"| ReportFile

    Leader --> MutableDAG
    Leader --> Session
    Leader --> Registry
    Leader --> Adapters
    Leader --> cb
    Leader --> IH
    Session --> VS
    Registry --> VS
    VS -.->|"embeds via"| EmbedSvc

    obs -.->|"monitor"| RT
    obs -.->|"monitor"| Leader
    obs -.->|"monitor"| MutableDAG
    arena -.->|"stress test"| RT
    arena -.->|"stress test"| Leader

Plugin System Architecture

graph TB
    subgraph executor ["Workflow Engine"]
        DEX["DynamicExecutor"]
        DAG["MutableDAG"]
    end

    subgraph plugins ["PluginBus & Plugins"]
        PB["PluginBus"]
        EB["EventBus"]
        WH["WorkflowHook"]
        REG["Plugin Registry"]
        CAP["Capability Index"]

        subgraph builtins ["Built-in Plugins"]
            OBS["ObserverPlugin"]
            CP["CheckpointPlugin"]
            TP["ToolPlugin"]
            RP["RouterPlugin<br/>(ExpressionRouter / MemoryRouter / EvolutionRouter)"]
            LP["LoopPlugin"]
            REC["RecoveryPlugin"]
            IP["InterruptPlugin"]
        end
    end

    subgraph storage ["Plugin Storage"]
        ES[("EventStore")]
        CKPT[("CheckpointStore")]
        COL["ExecutionCollector"]
    end

    subgraph discovery ["Discovery & Routing"]
        ADV["MemoryPlugin.AdviseRoute"]
        EVO["EvolutionPlugin.Recommend"]
    end

    DEX -->|"BeforeStep / AfterStep"| WH
    DEX -->|"flush checkpoints"| CP
    DEX -->|"PluginsByCap"| CAP
    REG --> builtins
    PB --> REG
    PB --> EB
    PB --> WH
    EB -->|"subscribe"| OBS
    OBS -->|"persist"| ES
    CP -->|"save to"| CKPT
    CP -->|"collect data"| COL
    RP -->|"Route(ctx, state)"| DEX
    LP -->|"ShouldContinue"| DEX
    REC -->|"ShouldRecover"| DEX
    RP -.->|"optional"| ADV
    RP -.->|"optional"| EVO

    style DEX fill:#4a6fa5,color:#fff
    style PB fill:#2e7d32,color:#fff
    style EB fill:#2e7d32,color:#fff
    style WH fill:#2e7d32,color:#fff
    style ES fill:#6a1b9a,color:#fff
    style CKPT fill:#6a1b9a,color:#fff

The PluginBus sits between the DynamicExecutor and all plugins. The executor calls BeforeStep/AfterStep hooks on every step boundary; hooks dispatch with configurable timeout and automatic panic recovery. EventBus enables pub/sub decoupling — plugins emit events without knowing who consumes them. Capability Index allows loose‑coupling lookup (PluginsByCap) so the executor never depends on concrete plugin types.

Data Flow

Request Lifecycle
sequenceDiagram
    participant U as User
    participant RT as Runtime
    participant L as Leader Agent
    participant SA as Sub Agents
    participant T as Tools / MCP
    participant LLM as LLM
    participant M as Memory Store

    U->>RT: 1. Request
    RT->>L: 2. Dispatch
    L->>L: 3. Plan (DAG)
    L->>SA: 4. AHP Tasks
    SA->>LLM: 5. LLM Call
    SA->>T: 6. Tool/MCP Call
    T-->>SA: 7. Tool Result
    LLM-->>SA: 8. LLM Response
    SA-->>L: 9. Aggregate
    L-->>RT: 10. Response
    RT-->>U: 11. Final Response
    L->>M: 12. Store Experiences

Request routed through Runtime → Leader plan with DAG → Sub Agents execute (LLM + Tools) → results aggregated and returned.

Memory Distillation Pipeline
flowchart LR
    A["Extract"] --> B["Classify"]
    B --> C["Score"]
    C --> D["Denoise"]
    D --> E["Conflict Resolution"]
    E --> F["Capacity Cap"]
    F --> Distilled[("Distilled Memory")]

6-step pipeline: extract experiences from raw interactions, classify by type, score relevance, filter noise, resolve conflicts with existing memories, and enforce capacity limits.

AHP Protocol

Custom Agent Hosting Protocol handling inter-agent communication with heartbeat monitoring, dead-letter queue (DLQ), and progress tracking. All protocol operations benchmark under 1 us.

Leader Failover

Checkpoint-based recovery. Supervisor detects leader failure, recovers stale tasks from last checkpoint, and reassigns work to available sub-agents.

Key Features

DAG Workflow Engine

  • MutableDAG: runtime graph mutation (add/remove nodes and edges) all under 1 us
  • DynamicExecutor: executes DAG with topological sort
  • Incremental cycle detection on edge insertion
  • Hot reload and runtime mutation without stopping execution

Memory System

  • Session memory: short-term conversation context
  • Task memory: per-task working memory
  • Distilled memory: long-term compressed knowledge via 6-step pipeline (errgroup-based concurrent embedding)
  • Multi-language experience extraction with Chinese keyword detection and importance scoring
  • Content-hash deduplication for idempotent memory storage
  • pgvector-backed semantic search

Storage Layer

  • Pluggable vector store interface — swap PostgreSQL for Qdrant, Milvus, SQLite, or your own backend
  • Built-in implementations: PostgreSQL + pgvector (production), in-memory (dev/test)
  • Repository pattern abstraction
  • Built-in cache layer + circuit breaker for fault tolerance
  • Idempotent DDL migrations, safe for repeated execution
  • See Custom Vector Store Guide

Agent System

  • Leader/Sub agent architecture
  • AHP protocol for structured communication (heartbeat, DLQ, progress)
  • Leader failover with checkpoint recovery
  • Parallel task execution with configurable concurrency
  • Agent resurrection plugin with pluggable health checking

Runtime Layer

  • Agent lifecycle management: register, start, stop, restart, restore
  • Automatic crash detection and resurrection via AgentFactory
  • Two recovery dimensions: EventStore (operational) + MemoryStore (cognitive)
  • Health monitoring with heartbeat and status-based checks
  • Structured concurrency via errgroup with graceful shutdown

Event Sourcing

  • EventStore interface with optimistic concurrency control
  • MemoryEventStore for dev/test, PostgresEventStore for production
  • 17 event types covering agent lifecycle, tasks, sessions, workflows, failover
  • Pub/sub via Subscribe with filtered event channels
  • DLQ auto-retry with configurable retry budgets

Human-in-the-Loop

  • Pause workflow steps for human approval before execution
  • InterruptConfig on any step, InterruptHandler for blocking approval
  • InterruptStore for crash recovery of pending approvals
  • Approval workflows and review gates

Tool System

  • Dynamic tool registration and discovery
  • Capability matching between agents and tools
  • Parameter validation with schema support
  • Pre/post execution lifecycle hooks

MCP Integration

  • Model Context Protocol client with JSON-RPC 2.0 messaging
  • Stdio and SSE transport support
  • Tool schema management and connection lifecycle

Observability

  • Web Dashboard: real-time monitoring with WebSocket streaming
  • Flight Recorder: timeline tracking, decision logging, diagnostics engine
  • Agent Genealogy: lineage tracking with graph export (DOT/JSON)
  • Event Bridge: system state streaming to dashboard

Chaos Engineering

  • Arena framework for fault injection testing
  • Fault types: process_kill, network_partition, latency_spike, kill_orchestrator
  • Resilience scoring with configurable metrics
  • Survival mode for continuous chaos testing

LLM Tool Calling

  • Multi-provider output adapters (OpenAI, Ollama, OpenRouter)
  • Prompt template engine with Go template syntax
  • Function calling extraction and validation
  • Schema-based parameter validation
  • Streaming output parser

Extensibility

  • Event-driven callbacks system with typed contexts
  • Event auto-compaction with retention policies
  • Pluggable health checking for agent resurrection

Autonomous Evolution (Genetic Algorithm)

  • Multi-generation population-based evolution with selection, crossover, and mutation
  • Strategy mutation engine with deterministic reproducibility (seed-controlled)
  • Arena regression testing with Welch's t-test statistical significance
  • Dream cycle orchestration: trigger → mutate → evaluate → adopt → record lineage
  • Bandit feedback loop for continuous experience quality optimization
  • Event-driven callback system for LLM/Tool/Agent lifecycle hooks
  • Wired high-level API: NewWiredEvolutionSystem for one-call component wiring
  • Elite preservation and adaptive survival rate across generations
  • Post-run evolution report generation: winner score, generation trajectory, scorer cost summary, lineage concentration, and promotion summary persisted to file
  • Evidence aggregation and promotion evaluation pipeline: per-generation evidence collection with success rate, latency, error rate, confidence; promotion state/reason computed for champion/candidate decisions
  • AfterRun hook for finalization: one-shot evidence collection, promotion evaluation, report generation, and file persistence

Plugin System

  • PluginBus: centralized plugin registry and lifecycle manager. Thread-safe Start/Stop with reverse-order shutdown, duplicate detection, and started-state guards.
  • EventBus: typed event pub/sub interface. Emit is non-blocking — drops events on full subscriber buffers. Subscribe supports filtering by stream ID, event type, and time range.
  • WorkflowHook: synchronous interceptor interface (BeforeStep / AfterStep) invoked by DynamicExecutor at every step boundary. Each dispatch has configurable timeout and automatic panic recovery with structured PluginError wrapping.
  • Capability-based discovery: PluginsByCap(CapCheckpoint) returns a copy of all plugins advertising that capability. Enables loose coupling between the workflow engine and plugins — the executor never depends on concrete plugin types.

Built-in Plugins

Plugin Capability Role
ObserverPlugin observer Subscribes to workflow lifecycle events (workflow.started/completed/failed, step.started/completed/failed, checkpoint.saved) and persists them to EventStore
CheckpointPlugin checkpoint Saves deep-copy execution snapshots at step boundaries. Configurable flush interval. 22-field schema covering step states, variables, route/tool/memory/interrupt/error/loop history, and scoring signals
ToolPlugin tool Validates and records tool invocations via ExecutionCollector
ExpressionRouter router Rule-based router: FromStepID → ToStepID with predicate condition. First-match semantics
MemoryRouter router Queries MemoryPlugin.AdviseRoute first, falls back to expression rules
EvolutionRouter router Queries EvolutionPlugin.Recommend first, falls back to expression rules
LoopPlugin loop Controlled execution loops with MaxIterations, UntilCondition, and SubStepIDs
BasicRecoveryPlugin recovery Allowlist-based step failure recovery decisions
InterruptPlugin — Records HITL interrupt lifecycle events via collector
ArenaPlugin — Fault injection for robustness testing (plugin_panic, plugin_timeout, plugin_error, bus_stop)

ExecutionCollector

  • Thread-safe data aggregator collecting route decisions, tool calls, memory hits, interrupts, and errors during workflow execution
  • Export() produces serializable maps; MergeInto() copies into ExperienceCheckpoint
  • Consumed by CheckpointPlugin, memory distillation pipeline, and evolution engine scoring

ExperienceCheckpoint — full execution snapshot:

{
  "schema_version": 1,
  "execution_id": "...",
  "workflow_id": "...",
  "workflow_version": "...",
  "state_version": 1,
  "status": "running",
  "step_states": [...],
  "variables": {...},
  "output_store": {...},
  "route_history": [...],
  "tool_history": [...],
  "memory_hits": [...],
  "interrupt_history": [...],
  "loop_history": [...],
  "error_history": [...],
  "scoring_signals": [...],
  "created_at": "..."
}

Enables complete execution state restore for leader failover and step-level recovery.

Benchmark Highlights

116 benchmarks total. 5675 tests pass with -race across 130 packages.

Platform: darwin/arm64, Apple M3 Max, Go 1.26.4

Category Count Hot (< 1 us) Normal (1-100 us) Cold (> 100 us)
Eval 5 2 2 1
Distillation 10 0 9 1
Tools/Core 9 4 5 0
Errors 4 3 1 0
Events 6 0 5 1
Handler 3 1 1 1
Evolution 6 0 1 5
Evolution/Genome 30+ 0 20+ 10+
Total 116 10 43 20

Selected hot-path results:

Operation ns/op allocs/op
ExactMatchEvaluator 3.07 0
ToolUsageEvaluator 28.49 0
ToolExecution 14.69 0
ConvertEvent 4.87 0
ParameterValidation 7.22 0
Wrap (error) 0.27 0
WrapMultipleWraps 0.59 0
ResultCreation (Success) 0.27 0
ResultCreation (Error) 0.28 0
ConflictDetection 1027 0
DreamCycle_SingleRun 224 4

10 of 116 benchmarks run under 1 us. Zero-allocation paths for evaluation, tool execution, result creation, error wrapping, and parameter validation.

Full benchmark report: benchmarks/benchmark_report.md

Quick Start

Prerequisites

  • Go 1.26+
  • PostgreSQL 15+ with pgvector (optional, for persistence)
  • Docker (optional, for database)

1. Set API Key

export OPENROUTER_API_KEY="your-api-key"

2. Start Database (Optional)

# One-click restart with migration (optionally import a doc)
./scripts/docker/restart.sh
./scripts/docker/restart.sh --save examples/knowledge-base/README.md

# Or manually:
docker run -d \
  --name ares-db \
  -e POSTGRES_PASSWORD=postgres \
  -e POSTGRES_DB=goagent \
  -p 5433:5432 \
  pgvector/pgvector:pg15

3. Run Examples

# Quick start (bootstrap API)
go run examples/quickstart/main.go

# Graph workflow demos
go run examples/graph_demo/basic/basic_example.go
go run examples/graph_demo/conditional/conditional_example.go
go run examples/graph_demo/scheduler/scheduler_example.go
go run examples/graph_demo/recovery/recovery_example.go

# Advanced patterns
go run examples/advanced/mutable_dag/main.go
go run examples/advanced/dynamic_executor/main.go
go run examples/advanced/leader_failover/main.go
go run examples/advanced/agent_resurrection/main.go

# Multi-agent collaboration
cd examples/travel && go run main.go

# Knowledge base Q&A (requires database)
cd examples/knowledge-base && go run main.go --chat

# Chaos engineering
cd examples/mcp-dashboard && go run main.go

# Quantitative trading
cd examples/quant-trading && go run . --ticker AAPL

# Autonomous evolution (genetic algorithm)
cd examples/autonomous-evolution && go run main.go

4. Run Tests

go test ./...                      # All tests
go test -race ./...                # With race detector
go test -bench=. ./...             # Benchmarks

5. Use the API

ARES provides abstract interfaces in api/core/ and a bootstrap factory in api/bootstrap/:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/Timwood0x10/ares/api/bootstrap"
)

func main() {
    ctx := context.Background()

    // Create ARES instance with all modules wired.
    ares, err := bootstrap.New(ctx, bootstrap.DefaultConfig())
    if err != nil {
        log.Fatal(err)
    }
    defer ares.Stop()

    // Start runtime (manages agent lifecycles).
    if err := ares.Start(ctx); err != nil {
        log.Fatal(err)
    }

    // Run genetic algorithm evolution.
    result, err := ares.RunEvolution(ctx, 10)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Best score: %.2f\n", result.BestStrategy.Score)

    // Execute chaos engineering action.
    res := ares.ExecuteArenaAction(ctx, arena.Action{
        Type:     arena.ActionKillAgent,
        TargetID: "worker-1",
    })
    fmt.Printf("Chaos result: %v\n", res.Success)
}

Available interfaces in api/core/:

  • AgentService — Agent CRUD + task execution
  • Runtime — Agent lifecycle management
  • WorkflowService — DAG workflow orchestration
  • MemoryService — Memory management + distillation
  • LLMService — LLM provider abstraction
  • RetrievalService — Vector retrieval
  • Evolution — Genetic algorithm evolution
  • DreamCycle — Autonomous self-evolution
  • Arena — Chaos engineering (fault injection + resilience scoring)
  • ContextCleaner — Context window management

Project Structure

ares/
├── api/                  # Public API layer (interfaces only, no implementations)
│   ├── core/             # Abstract interfaces: AgentService, Runtime, Evolution, Arena, etc.
│   ├── errors/           # Unified error types
│   ├── client/           # Go client SDK
│   ├── handler/          # HTTP handlers (thin delegation)
│   ├── router/           # Route registration
│   └── bootstrap/        # Factory — wires all modules into ARES container
├── internal/
│   ├── agents/           # Leader/Sub agent system
│   ├── ares_runtime/     # Runtime lifecycle + PluginBus (+ 10 built-in plugins)
│   ├── ares_events/      # EventStore interface, MemoryEventStore, event types
│   ├── ares_memory/      # Memory system + distillation pipeline
│   ├── ares_evolution/   # Genetic algorithm evolution system (genome, mutation, scoring)
│   ├── ares_arena/       # Chaos engineering / fault injection
│   ├── ares_flight/      # Flight recorder (timeline / genealogy / diagnostics)
│   ├── ares_mcp/         # MCP client (stdio / SSE transport)
│   ├── ares_callbacks/   # Event-driven lifecycle callbacks
│   ├── ares_observability/ # OpenTelemetry + Prometheus
│   ├── ares_eval/        # Agent evaluation framework
│   ├── ares_quant/       # Quantitative trading toolkit
│   ├── ares_config/      # Configuration loading + validation
│   ├── ares_ratelimit/   # Rate limiting
│   ├── ares_shutdown/    # Graceful shutdown orchestration
│   ├── ares_security/    # Input sanitization
│   ├── ares_experience/  # Experience store + feedback service
│   ├── ares_protocol/    # AHP inter-agent protocol
│   ├── ares_ctxutil/     # Context utilities
│   ├── ares_bootstrap/   # Module wiring factory
│   ├── workflow/engine/  # DAG workflow engine (DynamicExecutor + PluginBus)
│   ├── workflow/graph/   # Graph executor + checkpoint resume
│   ├── workflow/graphservice/ # RPC graph service
│   ├── storage/          # VectorStore interface + implementations (PG, memory, Qdrant, SQLite)
│   ├── storage/postgres/ # PostgreSQL adapter + migrations + repositories
│   ├── storage/memory/   # In-memory vector store
│   ├── llm/              # LLM client + output parsers
│   ├── llmservice/       # LLM service abstraction
│   ├── memoryservice/    # Memory service abstraction
│   ├── retrievalservice/ # Retrieval service abstraction
│   ├── llm/output/       # Output adapters (OpenAI, Ollama, OpenRouter)
│   ├── monitoring/       # Web dashboard + SSE + metrics
│   ├── dashboard/        # Dashboard API + WebSocket hub + orchestrator
│   ├── discovery/        # MCP server discovery (file, binary)
│   ├── logger/           # Module-scoped structured logging
│   ├── tools/            # Tool registry (core, builtin, agent, resources)
│   ├── plugins/          # Runtime plugins (resurrection, etc.)
│   ├── errors/           # Unified error types
│   └── config/           # Global config
├── services/embedding/  # Embedding gateway (FastAPI + Ollama)
├── examples/            # Travel, knowledge-base, dashboard, quant, quickstart, ...
├── cmd/                 # CLI tools (arena, flight, migration, ...)
├── docs/                # Architecture, features, guides (EN + ZH)
├── scripts/             # Docker, CI, setup scripts
└── benchmarks/          # Benchmark reports and logs

Configuration

Configuration is YAML-based. Key sections:

llm:
  provider: openrouter
  api_key: "${OPENROUTER_API_KEY}"
  model: meta-llama/llama-3.1-8b-instruct
  timeout: 60

agents:
  leader:
    id: leader-main
    max_steps: 10
    max_parallel_tasks: 4
  sub:
    - id: agent-a
      type: research
      max_retries: 3
      timeout: 30

storage:
  type: postgres
  host: localhost
  port: 5433
  database: goagent
  pgvector:
    enabled: true
    dimension: 1024

memory:
  enabled: true
  enable_distillation: true
  distillation_threshold: 3

See examples/travel/config.yaml for a complete example.

Performance

Key benchmark results (Apple M3 Max, Go 1.26):

Operation Throughput Latency Allocs Note
Tool Execution 68M ops/s 14.8 ns 0 Interface dispatch
Result Creation 3.7B ops/s 0.27 ns 0 Compiler inlined
Parameter Validation 135M ops/s 7.4 ns 0 Struct comparison
Event Append 1.9M ops/s 530 ns 7
Subscribe (100 subs) 7.7K ops/s 130 μs 600 alloc ↓33% allocs
GA Evolve (1 gen) 3.3M ops/s 305 ns 7 Population=20
GA Stats (pop=1000) 23 runs/s 43.3 ms 12 ↓38% via DiversitySampleSize sampling
FitnessSharing (pop=500) 136 runs/s 7.4 ms 506 alloc ↓44% allocs via Reservoir Sampling
GA RealWorld (100 gen) 98 runs/s 10.2 ms 57K Population=20
CloneStrategy (5 params) 4.5M ops/s 220 ns 3
Stream Handle 260K ops/s 3.9 μs 69

See Full Benchmark Report for detailed results across all modules.

Tech Stack

Component Technology
Language Go 1.26+
Database PostgreSQL 15+ with pgvector (pluggable: Qdrant, Milvus, SQLite, or custom)
Protocol Custom AHP (Agent Hosting Protocol)
Embedding FastAPI + Ollama/SentenceTransformers
Cache Redis
Concurrency errgroup, sync

Documentation

LICENSE

Apache 2.0

Directories

Path Synopsis
api
bootstrap
Package bootstrap provides factory functions for creating ARES modules.
Package bootstrap provides factory functions for creating ARES modules.
client
Package client provides a library-style entry point for embedding GoAgent into other Go applications.
Package client provides a library-style entry point for embedding GoAgent into other Go applications.
core
Package core provides core abstractions for agent operations.
Package core provides core abstractions for agent operations.
discovery
Package discovery provides the public API for service discovery.
Package discovery provides the public API for service discovery.
errors
Package errors provides unified error definitions for API layer.
Package errors provides unified error definitions for API layer.
handler
Package handler provides HTTP handlers for the GoAgent API.
Package handler provides HTTP handlers for the GoAgent API.
mcp
Package mcp provides the public API for MCP (Model Context Protocol) integration.
Package mcp provides the public API for MCP (Model Context Protocol) integration.
router
Package router provides HTTP routing for the GoAgent API.
Package router provides HTTP routing for the GoAgent API.
service/runtime
Package ares_runtime provides a high-level API for agent lifecycle management.
Package ares_runtime provides a high-level API for agent lifecycle management.
service/workflow
Package workflow provides workflow orchestration service implementation.
Package workflow provides workflow orchestration service implementation.
tools
Package tools provides the public API for tool registration and execution.
Package tools provides the public API for tool registration and execution.
cmd
arena command
Command arena provides the Chaos Engineering Arena CLI.
Command arena provides the Chaos Engineering Arena CLI.
check_rls command
create_distilled_table command
Package main creates the distilled_memories table (also included in full migrate).
Package main creates the distilled_memories table (also included in full migrate).
flight command
Command flight provides the Agent Flight Recorder CLI.
Command flight provides the Agent Flight Recorder CLI.
mcp-null command
Command ares_mcp-null provides a minimal MCP server for demos that don't need external MCP tools.
Command ares_mcp-null provides a minimal MCP server for demos that don't need external MCP tools.
migrate_db command
Package main creates and migrates the production ares database.
Package main creates and migrates the production ares database.
monitor-demo command
monitor-live command
monitor-live: Real agent monitoring with LLM + MCP tools.
monitor-live: Real agent monitoring with LLM + MCP tools.
setup_test_db command
Package main creates and migrates the test database.
Package main creates and migrates the test database.
examples
advanced/agent_resurrection command
Package main demonstrates generic agent resurrection using the plugin.
Package main demonstrates generic agent resurrection using the plugin.
advanced/dynamic_executor command
Package main demonstrates DynamicExecutor API and ApplyMode configuration.
Package main demonstrates DynamicExecutor API and ApplyMode configuration.
advanced/full_lifecycle command
Package main demonstrates the complete agent lifecycle with Runtime, EventStore, MemoryManager, and MutableDAG workflow modification.
Package main demonstrates the complete agent lifecycle with Runtime, EventStore, MemoryManager, and MutableDAG workflow modification.
advanced/leader_failover command
Package main demonstrates Leader Failover using the Runtime with checkpoint-based recovery.
Package main demonstrates Leader Failover using the Runtime with checkpoint-based recovery.
advanced/mutable_dag command
Package main demonstrates MutableDAG with runtime node/edge mutations.
Package main demonstrates MutableDAG with runtime node/edge mutations.
advanced/runtime_resurrection command
Package main demonstrates Runtime-managed agent resurrection with full state recovery.
Package main demonstrates Runtime-managed agent resurrection with full state recovery.
autonomous-evolution command
Package main demonstrates ares Autonomous Evolution (Dream Mode v1) workflow.
Package main demonstrates ares Autonomous Evolution (Dream Mode v1) workflow.
custom-store command
custom-store demonstrates implementing a custom ServiceStore for persistent service discovery (SQLite, Postgres, etc.).
custom-store demonstrates implementing a custom ServiceStore for persistent service discovery (SQLite, Postgres, etc.).
discovery command
discovery demonstrates the Service Discovery Engine.
discovery demonstrates the Service Discovery Engine.
end-to-end command
external-tools command
external-tools demonstrates how external projects use the ares public API.
external-tools demonstrates how external projects use the ares public API.
finetune command
graph_demo/agent command
Package main demonstrates agent integration with graphservice.
Package main demonstrates agent integration with graphservice.
graph_demo/applymode command
Package main compares ApplyAtCheckpoint vs ApplyImmediate in DynamicExecutor, demonstrating the ares_runtime plugin system via PluginBus with ObserverPlugin.
Package main compares ApplyAtCheckpoint vs ApplyImmediate in DynamicExecutor, demonstrating the ares_runtime plugin system via PluginBus with ObserverPlugin.
graph_demo/basic command
Package main demonstrates basic graph usage.
Package main demonstrates basic graph usage.
graph_demo/conditional command
Package main demonstrates conditional branching in graphs.
Package main demonstrates conditional branching in graphs.
graph_demo/integration command
Package main demonstrates a real-world integration example using the graph system with the full ares_runtime plugin stack.
Package main demonstrates a real-world integration example using the graph system with the full ares_runtime plugin stack.
graph_demo/recovery command
Package main demonstrates node-level recovery via StepRecoveryHandler combined with the full ares_runtime plugin stack: CheckpointPlugin for crash recovery, ObserverPlugin for event logging, and ToolPlugin for tool-call recording — all wired through a single PluginBus.
Package main demonstrates node-level recovery via StepRecoveryHandler combined with the full ares_runtime plugin stack: CheckpointPlugin for crash recovery, ObserverPlugin for event logging, and ToolPlugin for tool-call recording — all wired through a single PluginBus.
graph_demo/replace_node command
Package main demonstrates MutableDAG.ReplaceNode for dynamic step replacement.
Package main demonstrates MutableDAG.ReplaceNode for dynamic step replacement.
graph_demo/scheduler command
Package main demonstrates different scheduling strategies.
Package main demonstrates different scheduling strategies.
graph_demo/subscribe command
Package main demonstrates subscribing to GraphEventHub for graph mutation events.
Package main demonstrates subscribing to GraphEventHub for graph mutation events.
knowledge-base command
mcp-dashboard command
package main — ares Chaos Engineering Demo.
package main — ares Chaos Engineering Demo.
mcp-registry command
mcp-registry demonstrates MCP service discovery and lifecycle management.
mcp-registry demonstrates MCP service discovery and lifecycle management.
mcp-server command
Command ares_mcp-server provides an example MCP server demonstrating tool, resource, and prompt registration with ares MCP SDK.
Command ares_mcp-server provides an example MCP server demonstrating tool, resource, and prompt registration with ares MCP SDK.
quant-trading command
Package main — signal generation bridge between research layer and simulation.
Package main — signal generation bridge between research layer and simulation.
quant-trading/agents
Package agents provides prompts for the quant trading demo agents.
Package agents provides prompts for the quant trading demo agents.
quant-trading/memory
Package memory provides cross-stock decision memory.
Package memory provides cross-stock decision memory.
quant-trading/workflow
Package workflow provides the Bull/Bear debate loop for quant analysis.
Package workflow provides the Bull/Bear debate loop for quant analysis.
quickstart command
Package main demonstrates ARES quick start using the bootstrap API.
Package main demonstrates ARES quick start using the bootstrap API.
travel command
internal
agents
Package agent provides error definitions for agent service.
Package agent provides error definitions for agent service.
api_impl
Package api provides the application-level entry point for ares.
Package api provides the application-level entry point for ares.
api_impl/agent
Package agent provides error definitions for agent operations.
Package agent provides error definitions for agent operations.
ares_arena
Package arena provides a chaos engineering layer that proves ares is a self-healing runtime.
Package arena provides a chaos engineering layer that proves ares is a self-healing runtime.
ares_bootstrap
package bootstrap provides startup wiring for MCP and Dashboard components.
package bootstrap provides startup wiring for MCP and Dashboard components.
ares_callbacks
Package callbacks provides lifecycle event hooks for LLM calls and agent execution.
Package callbacks provides lifecycle event hooks for LLM calls and agent execution.
ares_config
package config - provides configuration loading and validation for ares.
package config - provides configuration loading and validation for ares.
ares_ctxutil
Package ctxutil provides context utilities for tracing and lifecycle management.
Package ctxutil provides context utilities for tracing and lifecycle management.
ares_eval
Package eval provides LLM evaluation and benchmarking capabilities, including test suite execution, result reporting, and agent performance metrics.
Package eval provides LLM evaluation and benchmarking capabilities, including test suite execution, result reporting, and agent performance metrics.
ares_events
Package events defines event sourcing types and the event store interface.
Package events defines event sourcing types and the event store interface.
ares_evolution
Package evolution provides automatic experience extraction from flight recorder diagnostics.
Package evolution provides automatic experience extraction from flight recorder diagnostics.
ares_evolution/experience
Package experience provides evidence aggregation for the GA/Memory/Tool fusion system.
Package experience provides evidence aggregation for the GA/Memory/Tool fusion system.
ares_evolution/genome
Package genome provides genetic algorithm crossover (recombination) operators for combining two parent strategies into a child strategy.
Package genome provides genetic algorithm crossover (recombination) operators for combining two parent strategies into a child strategy.
ares_evolution/mutation
Package mutation provides strategy mutation engine for Dream Mode evolution.
Package mutation provides strategy mutation engine for Dream Mode evolution.
ares_evolution/promotion
Package promotion provides strategy promotion and demotion logic.
Package promotion provides strategy promotion and demotion logic.
ares_evolution/scheduler
Package scheduler provides idle-time evolution triggers for autonomous evolution.
Package scheduler provides idle-time evolution triggers for autonomous evolution.
ares_evolution/scoring
Package scoring provides cost-controlled scoring infrastructure for the evolution system, including strategy hashing, score caching, and tiered scorer pipelines.
Package scoring provides cost-controlled scoring infrastructure for the evolution system, including strategy hashing, score caching, and tiered scorer pipelines.
ares_evolution/service
Package evolution provides error definitions for the evolution service.
Package evolution provides error definitions for the evolution service.
ares_experience
Package experience provides experience conflict resolution service.
Package experience provides experience conflict resolution service.
ares_experience/service
Package experience provides experience conflict resolution service.
Package experience provides experience conflict resolution service.
ares_flight
Package flight provides runtime intelligence for ares agents.
Package flight provides runtime intelligence for ares agents.
ares_mcp
package mcp - provides MCP (Model Context Protocol) client integration for ares.
package mcp - provides MCP (Model Context Protocol) client integration for ares.
ares_memory
Package memory provides unified memory management for the StyleAgent framework.
Package memory provides unified memory management for the StyleAgent framework.
ares_memory/distillation
Package distillation provides memory distillation functionality for agent experience extraction.
Package distillation provides memory distillation functionality for agent experience extraction.
ares_memory/embedding
Package embedding provides canonical embedding types and a unified pipeline for generating vector embeddings across memory distillation, storage, and retrieval.
Package embedding provides canonical embedding types and a unified pipeline for generating vector embeddings across memory distillation, storage, and retrieval.
ares_memory/push
Package push provides active knowledge recommendation to strategies.
Package push provides active knowledge recommendation to strategies.
ares_memory/report
Package report provides human-readable evolution report generation.
Package report provides human-readable evolution report generation.
ares_memory/retrieval_api
Package retrieval provides error definitions for retrieval operations.
Package retrieval provides error definitions for retrieval operations.
ares_memory/service
Package memory provides API abstractions for memory distillation operations.
Package memory provides API abstractions for memory distillation operations.
ares_quant
Package ares_quant provides MCP-compatible tools for quantitative trading analysis.
Package ares_quant provides MCP-compatible tools for quantitative trading analysis.
ares_quant/dataflow
Package dataflow provides anti-hallucination infrastructure for market data, including symbol normalization, vendor routing, data validation, and verified snapshot construction.
Package dataflow provides anti-hallucination infrastructure for market data, including symbol normalization, vendor routing, data validation, and verified snapshot construction.
ares_quant/errors
Package errors provides shared sentinel errors for ares_quant sub-packages.
Package errors provides shared sentinel errors for ares_quant sub-packages.
ares_quant/indicators
Package indicators provides technical analysis computations.
Package indicators provides technical analysis computations.
ares_quant/market
Package market provides market data types and internal data source clients for quantitative trading.
Package market provides market data types and internal data source clients for quantitative trading.
ares_quant/marketmaking
Package marketmaking provides the core domain model for market-making operations.
Package marketmaking provides the core domain model for market-making operations.
ares_quant/marketmaking_api
Package marketmaking provides a domain-level facade for market-making and quantitative trading operations.
Package marketmaking provides a domain-level facade for market-making and quantitative trading operations.
ares_quant/portfolio
Package portfolio provides backtesting and portfolio simulation for quantitative trading strategies.
Package portfolio provides backtesting and portfolio simulation for quantitative trading strategies.
ares_quant/research
Package research provides the structured research pipeline for quantitative stock analysis, including state management, typed schemas, graph execution, and markdown rendering of research outputs.
Package research provides the structured research pipeline for quantitative stock analysis, including state management, typed schemas, graph execution, and markdown rendering of research outputs.
ares_quant/research/agents
Package agents provides prompt building, agent interfaces, and execution infrastructure for the quantitative research pipeline.
Package agents provides prompt building, agent interfaces, and execution infrastructure for the quantitative research pipeline.
ares_quant/store
Package store provides persistent storage for quant trading data.
Package store provides persistent storage for quant trading data.
ares_runtime
Package runtime defines the plugin contract for extending workflow execution.
Package runtime defines the plugin contract for extending workflow execution.
dashboard
package dashboard — unified API v2.
package dashboard — unified API v2.
discovery
Package discovery provides a pluggable service discovery engine.
Package discovery provides a pluggable service discovery engine.
discovery/providers
Package providers implements DiscoveryProvider for various sources.
Package providers implements DiscoveryProvider for various sources.
llm
Package llm provides LLM client functionality for various providers.
Package llm provides LLM client functionality for various providers.
llmservice
Package llm provides error definitions for LLM service.
Package llm provides error definitions for LLM service.
logger
Package logger provides module-scoped structured logging helpers.
Package logger provides module-scoped structured logging helpers.
memoryservice
Package memory provides error definitions for memory service.
Package memory provides error definitions for memory service.
monitoring
Package monitoring provides the ARES Console monitoring plugin.
Package monitoring provides the ARES Console monitoring plugin.
monitoring/adapter
Package adapter provides adapters between the monitoring plugin and external subsystems such as the runtime manager and orchestrator.
Package adapter provides adapters between the monitoring plugin and external subsystems such as the runtime manager and orchestrator.
monitoring/dag
Package dag provides the node interaction engine for ARES Console.
Package dag provides the node interaction engine for ARES Console.
monitoring/data
Package data provides state aggregation for the ARES Console monitoring plugin.
Package data provides state aggregation for the ARES Console monitoring plugin.
monitoring/eventutil
Package eventutil provides shared helpers for extracting typed values from ares_events.Event payloads.
Package eventutil provides shared helpers for extracting typed values from ares_events.Event payloads.
monitoring/tabs
Package tabs implements component-level tabs for the ARES Console monitoring plugin.
Package tabs implements component-level tabs for the ARES Console monitoring plugin.
plugins/resurrection
Package resurrection provides a pluggable agent resurrection plugin.
Package resurrection provides a pluggable agent resurrection plugin.
retrievalservice
Package retrieval provides error definitions for retrieval service.
Package retrieval provides error definitions for retrieval service.
storage
package storage defines the vector storage interface.
package storage defines the vector storage interface.
storage/memory
package memory provides an in-memory vector store implementation.
package memory provides an in-memory vector store implementation.
storage/postgres
Package postgres provides PostgreSQL database operations for the storage system.
Package postgres provides PostgreSQL database operations for the storage system.
storage/postgres/adapters
Package adapters provides format conversion layer for storage operations.
Package adapters provides format conversion layer for storage operations.
storage/postgres/embedding
nolint: errcheck // Operations may ignore return values
nolint: errcheck // Operations may ignore return values
storage/postgres/models
Package models defines data structures for the storage system.
Package models defines data structures for the storage system.
storage/postgres/repositories
Package repositories provides data access layer for storage system.
Package repositories provides data access layer for storage system.
storage/postgres/services
Package services provides retrieval services for the storage system.
Package services provides retrieval services for the storage system.
truncate
Package truncate provides rune-safe string truncation utilities.
Package truncate provides rune-safe string truncation utilities.
workflow/engine
package engine - Human-in-the-loop (HITL) support for pausing and resuming workflow execution.
package engine - Human-in-the-loop (HITL) support for pausing and resuming workflow execution.
workflow/graphservice
Package graph provides YAML configuration parsing for graph workflows.
Package graph provides YAML configuration parsing for graph workflows.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL