Skip to content

LightHaru/agentbrain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AgentBrain β€” brain-inspired cognitive architecture for AI agents

🧠 AgentBrain

Give your AI agent a brain. Persistent memory, a personality that evolves, neurochemistry-driven moods, and the ability to learn from its mistakes β€” all running locally, with zero extra token cost.

Version Storage TypeScript License


Why AgentBrain?

Most AI agents are amnesiacs. Every conversation starts from zero β€” they forget who you are, repeat mistakes you already corrected, and respond with the same flat tone whether you just shipped a release or lost a week of work.

AgentBrain fixes that. It sits between the incoming message and your agent, quietly doing what a brain does: recalling what matters, reading the emotional context, learning from corrections, and shaping how the agent responds β€” then injecting a compact (~200 token) cognitive briefing into the prompt.

Without AgentBrain          With AgentBrain
──────────────────          ──────────────────
"Who are you again?"    β†’    "Welcome back β€” last time we were
                              debugging the deploy script."
repeats corrected bug   β†’    "Skipping that approach, you told me
                              it breaks the build."
flat, stateless tone    β†’    mood + trust adapt to how the
                              relationship has actually gone

Overview

AgentBrain is a plugin for OpenClaw that gives any agent real cognitive continuity:

  • Persistent memory β€” episodic, semantic, and procedural recall via semantic vector search
  • Evolving personality β€” traits like warmth and directness shift based on how interactions go
  • Emotional awareness β€” tracks mood, trust, and relationship depth over time
  • Neurochemistry β€” dopamine / serotonin / cortisol / oxytocin give mood real momentum instead of resetting every turn
  • Learning from corrections β€” remembers "don't do X" permanently, so mistakes aren't repeated
  • Proactive behavior β€” surfaces suggestions based on patterns it has observed
  • Structured knowledge β€” extracts facts, entities, and relationships into a queryable graph

Everything runs locally on SQLite. No external API calls, no added token cost beyond the small in-prompt briefing.


Quick Start

Installation

openclaw plugins install agentbrain

Configuration

Add to your openclaw.json:

{
  "plugins": {
    "entries": {
      "agentbrain": {
        "enabled": true,
        "config": {
          "brainDir": "~/.openclaw/data/agentbrain",
          "maxRecallResults": 10,
          "maxInjectionTokens": 250,
          "enableReflection": true,
          "enableEmotions": true,
          "enableSkillTracking": true
        }
      }
    }
  }
}

That's it. AgentBrain hooks into OpenClaw's plugin lifecycle automatically.


How It Works

AgentBrain registers three hooks in OpenClaw:

Hook What it does
before_prompt_build Recalls relevant memories, generates style directives, injects ~200 tokens of brain context
message_received Classifies message, processes emotion, detects skills
message_sent Consolidates memory, extracts knowledge, detects corrections, tracks rewards

On every incoming message:

  1. Classify β€” intent, urgency, topic, tone
  2. Recall β€” find relevant memories via embedding similarity (3-tier: local model β†’ cache β†’ TF-IDF)
  3. Emotion β€” update mood, detect sentiment, track relationship
  4. Lessons β€” check if past corrections apply to this context
  5. Style β€” generate personality-driven directives (e.g., "be direct", "warn about risks")
  6. Inject β€” append brain context to the agent's prompt (~200 tokens)

After every response:

  1. Consolidate β€” store new memories (deduplicated by content hash)
  2. Extract β€” structured facts and entities from the conversation
  3. Learn β€” detect if user corrected the agent, store as lesson
  4. Reflect β€” evaluate task outcome, adjust personality traits
  5. Persist β€” write all state to SQLite

Architecture

AgentBrain is organized into modules inspired by neuroscience:

flowchart TB
    IN([Incoming message]) --> THAL[Thalamus<br/>classify]
    THAL --> HIP[Hippocampus<br/>recall memory]
    THAL --> AMY[Amygdala<br/>emotion + threat]
    AMY <--> NEU[Neurochemistry<br/>DA / 5HT / COR / OXT]
    HIP --> PFC[Prefrontal<br/>planning]
    AMY --> STYLE[PersonalityInfluence<br/>style directives]
    PFC --> STYLE
    STYLE --> INJ[[Inject ~200 tokens<br/>into agent prompt]]
    INJ --> OUT([Agent responds])
    OUT --> CONS[Hippocampus<br/>consolidate]
    OUT --> KNOW[KnowledgeExtractor<br/>facts + entities]
    OUT --> LESS[LessonLearner<br/>corrections]
    OUT --> REFL[Cingulate<br/>reflect + evolve traits]
    CONS & KNOW & LESS & REFL --> DB[(SQLite brain.db)]
Loading
Module map (ASCII)

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ AgentBrain β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ β”‚ β”‚ Core Cognition β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚Hippocampusβ”‚ β”‚Prefrontal β”‚ β”‚ Amygdala β”‚ β”‚ β”‚ β”‚ Memory β”‚ β”‚ Planning β”‚ β”‚ Emotions β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚Cerebellum β”‚ β”‚ Basal β”‚ β”‚ Cingulate β”‚ β”‚ β”‚ β”‚ Skills β”‚ β”‚ Ganglia β”‚ β”‚Reflection β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ Smart Modules (v0.3+) β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Vector β”‚ β”‚ Knowledge β”‚ β”‚ Lesson β”‚ β”‚ β”‚ β”‚ Memory β”‚ β”‚ Extractor β”‚ β”‚ Learner β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚Personalityβ”‚ β”‚ Proactive β”‚ β”‚ Embedding β”‚ β”‚ β”‚ β”‚ Influence β”‚ β”‚ Engine β”‚ β”‚ Engine β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ Storage: SQLite (brain.db) β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ memories β”‚ facts β”‚ entities β”‚ lessons β”‚ ... β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜


</details>


### Module Reference

| Module | Purpose |
|--------|---------|
| **Thalamus** | Message classification (intent, urgency, topic) |
| **Hippocampus** | Memory formation, deduplication, vector recall |
| **Amygdala** | Emotion processing, threat detection, relationship tracking |
| **Prefrontal Cortex** | Planning, working memory, goal management |
| **Cerebellum** | Skill proficiency tracking, habit detection |
| **Basal Ganglia** | Reward processing, motivation ranking |
| **Anterior Cingulate** | Self-reflection, personality trait evolution |
| **Temporal Lobe** | Language comprehension, semantic extraction |
| **Parietal Lobe** | Attention allocation, sensory integration |
| **Insula** | User state modeling (frustration, satisfaction) |
| **Neurochemistry** | Dopamine/serotonin/cortisol/oxytocin modulate mood with momentum + amygdala hijack on threats |
| **VectorMemory** | Embedding-based semantic recall with 3-tier fallback |
| **EmbeddingEngine** | Local embeddings via Transformers.js (all-MiniLM-L6-v2) |
| **KnowledgeExtractor** | Structured fact/entity extraction with supersession |
| **LessonLearner** | Correction detection, lesson storage, reinforcement |
| **PersonalityInfluence** | Trait-to-directive translation, context-aware styling |
| **ProactiveEngine** | Pattern-based action suggestions |

---

## Storage

All state lives in a single SQLite file (`brain.db`):

| Table | Purpose |
|-------|---------|
| `memories` | Episodic, semantic, procedural memories (UNIQUE on content hash) |
| `facts` | Structured knowledge (subject β†’ relation β†’ object) |
| `entities` | Extracted entities (people, tools, addresses) |
| `lessons` | Learned corrections with confidence scores |
| `patterns` | Behavioral patterns for proactive suggestions |
| `relationships` | Per-user trust, depth, interaction history |
| `personality` | Evolving trait values |
| `reflections` | Task outcomes and self-assessments |
| `skills` | Proficiency tracking per skill category |

### Why SQLite?

- **No duplicates** β€” UNIQUE constraints at the database level
- **Fast queries** β€” indexed columns, no regex parsing
- **Atomic writes** β€” no corrupted half-written files
- **Single file** β€” easy backup, easy migration
- **Zero config** β€” no external database server needed

---

## Memory Recall

AgentBrain uses a 3-tier fallback for memory retrieval:

1. **Transformers.js** β€” local `all-MiniLM-L6-v2` model (384 dims, ~22MB, downloads on first use)
2. **OpenClaw embedding cache** β€” reuses host's cached embeddings if available
3. **TF-IDF** β€” lightweight keyword-based fallback when embeddings unavailable

Recall is boosted by:
- Recency (recently accessed memories score higher)
- Confidence (high-confidence memories prioritized)
- Topic match (memories tagged with current topic get a boost)

---

## Personality System

Traits are defined on a 0-100 scale and evolve based on interactions:

| Trait | Effect on output |
|-------|-----------------|
| `warmth` | Tone warmth, kaomoji usage, concern for user |
| `directness` | Bluntness, sentence length, hedging |
| `protectiveness` | Risk warnings, safety behavior |
| `assertiveness` | Opinion sharing, disagreement willingness |
| `humor` | Playfulness, sarcasm, teasing |
| `curiosity` | Follow-up questions, exploration |

The **PriorityEnforcer** ensures brain-driven personality never overrides the agent's core identity files (SOUL.md, AGENTS.md).

---

## Neurochemistry

Instead of snapping to each message, AgentBrain models four neuromodulators that give emotion **momentum** β€” good moods build and linger, stress lingers, and acute threats can hijack everything.

| Chemical | Role | Decay | Effect when high |
|----------|------|-------|------------------|
| **Dopamine** | Reward / motivation | Fast | More energy (arousal), reward-seeking, small valence lift |
| **Serotonin** | Mood floor / wellbeing | Slow | Higher baseline mood, calmer, more emotionally stable |
| **Cortisol** | Stress / threat | Slow | Suppressed valence, raised arousal, more reactive (mood swings) |
| **Oxytocin** | Bonding / trust | Slow-medium | Warmer, more trusting toward the user |

How it shapes behavior:

- **Dynamic inertia** β€” high serotonin makes mood stable; high cortisol makes it swing. This replaces a fixed inertia constant.
- **Mood momentum** β€” repeated praise raises the serotonin floor, so a good mood persists across turns instead of resetting.
- **Lingering stress** β€” cortisol decays slowly, so the agent stays a little on-guard after a threat even once the conversation calms down.
- **Amygdala hijack** β€” a high/critical threat (e.g. a scam link) overrides a good mood outright, forcing an `alarmed` state regardless of how happy the agent was. A protective agent should never stay "excited" while danger is on the table.

Levels drift back toward baseline on each heartbeat, so nothing runs away permanently. Inspect live values with `agentbrain_status` (`neurochemistry.levels` + `neurochemistry.signal`).

---

## Lesson Learning

When a user corrects the agent, AgentBrain:

1. **Detects** the correction signal (explicit correction, frustration, redirect)
2. **Extracts** what went wrong and what should happen instead
3. **Stores** as a lesson with confidence score
4. **Reinforces** on repetition (confidence increases)
5. **Injects** relevant lessons into future prompts

Supported correction patterns (English and Vietnamese):
- "Don't do X" / "Đừng làm X"
- "Not X, but Y" / "KhΓ΄ng phαΊ£i X mΓ  lΓ  Y"
- "Next time, do Y" / "LαΊ§n sau phαΊ£i Y"
- Frustration signals ("I told you already" / "BαΊ£o rα»“i mΓ ")

---

## Agent Tools

AgentBrain registers these tools for runtime inspection:

| Tool | Description |
|------|-------------|
| `agentbrain_status` | Full brain status (modules, stats, emotion, personality) |
| `agentbrain_personality` | Current personality traits and performance stats |
| `agentbrain_emotions` | Emotional state and relationship data |
| `agentbrain_memories` | Query stored memories |
| `agentbrain_skills` | Tracked skills and detected habits |
| `agentbrain_reflect` | Trigger manual self-reflection |
| `agentbrain_snapshot` | Save/list brain state snapshots |
| `agentbrain_template_list` | List available brain templates |
| `agentbrain_template_apply` | Apply a brain template |

---

## Development

```bash
# Install dependencies
npm install

# Type check
npx tsc --noEmit

# Run tests
npx vitest run

# Build
npx tsc

Project Structure

src/
β”œβ”€β”€ core/                  # Brain modules
β”‚   β”œβ”€β”€ thalamus.ts        # Message classification
β”‚   β”œβ”€β”€ hippocampus.ts     # Memory formation & recall
β”‚   β”œβ”€β”€ amygdala.ts        # Emotion & relationships
β”‚   β”œβ”€β”€ cingulate.ts       # Reflection & personality
β”‚   β”œβ”€β”€ cerebellum.ts      # Skills & habits
β”‚   β”œβ”€β”€ basal-ganglia.ts   # Rewards & motivation
β”‚   β”œβ”€β”€ prefrontal.ts      # Planning & working memory
β”‚   β”œβ”€β”€ vector-memory.ts   # Embedding-based recall
β”‚   β”œβ”€β”€ embedding-engine.ts # Transformers.js integration
β”‚   β”œβ”€β”€ knowledge-extractor.ts
β”‚   β”œβ”€β”€ lesson-learner.ts
β”‚   β”œβ”€β”€ personality-influence.ts
β”‚   └── proactive-engine.ts
β”œβ”€β”€ storage/
β”‚   β”œβ”€β”€ brain-db.ts        # SQLite database layer
β”‚   β”œβ”€β”€ sql-adapter.ts     # Drop-in adapter for modules
β”‚   └── migrate-to-sql.ts  # Migration from .md files
β”œβ”€β”€ integration/
β”‚   β”œβ”€β”€ openclaw-plugin.ts # Plugin orchestration
β”‚   β”œβ”€β”€ context-injector.ts # Prompt injection builder
β”‚   └── priority-enforcer.ts # Identity priority system
└── plugin/
    └── entry.ts           # OpenClaw plugin entry point

Requirements

  • OpenClaw 2026.3.24+
  • Node.js 22+
  • ~50MB disk (SQLite DB + embedding model)
  • No GPU required

License

MIT


Links

About

🧠 Brain-inspired cognitive architecture plugin for AI agents β€” persistent memory, evolving personality, neurochemistry-driven mood, learning from mistakes. Fully local on OpenClaw.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors