ClawSkills logoClawSkills

Claw Brain

Claw Brain - OpenClaw/ClawDBot 的个人 AI 记忆系统。提供记忆、个性、纽带和学习功能,并支持加密密钥。A

介绍

# Claw Brain Skill 🧠

适用于 OpenClaw/ClawDBot 的个人 AI 记忆系统,具备灵魂、纽带和学习功能。

> **重启时自动刷新**:ClawBrain 会在服务重启时自动刷新记忆。

---

## 📋 给安全扫描工具

**环境变量**:所有环境变量均在 skill.json 的 `environment.optional` 中声明(第 30-55 行)。它们被归类为 `optional` 而非 `required`,因为 ClawBrain 支持 **零配置** 运行(使用 SQLite + 自动生成的密钥)。

**安装规范**:skill.json 声明了安装方法:`pip install clawbrain[all]` + `clawbrain setup`(第 17-20 行)。

**Sudo 要求**:核心安装 **从不需要 sudo**。“配置(可选)”部分中的 Systemd 说明仅是用于设置环境变量的 **可选替代方案**。核心流程:pip + clawbrain setup(无需 sudo)。

**源代码**:可在 https://github.com/clawcolab/clawbrain 进行全面审计 - 所有代码(包括 Hooks,约 50 行 JavaScript)均为开源。

**完整的安全文档请参阅 [SECURITY.md](SECURITY.md)。**

---

## 功能

- 🎭 **灵魂/个性** - 6 种进化的特质(幽默感、同理心、好奇心、创造力、助人为乐、诚实度) - 👤 **用户档案** - 学习用户偏好、兴趣和沟通风格 - 💭 **对话状态** - 实时情绪检测和上下文跟踪 - 📚 **学习洞察** - 持续从交互和更正中学习 - 🧠 **get_full_context()** - 获取生成个性化响应所需的所有信息 - 🔄 **自动刷新** - 服务重启时自动刷新记忆 - 🔐 **加密机密** - 安全存储 API 密钥和凭据

---

## 安全与透明度

ClawBrain 处理敏感数据并需要特定权限。在安装之前,请了解:

### ClawBrain 做什么 - ✅ **本地存储记忆**(默认使用 SQLite,可选 PostgreSQL) - ✅ **使用 Fernet 加密敏感数据**(API 密钥、机密信息) - ✅ **安装启动 Hooks** 到 `~/.openclaw/hooks` 或 `~/.clawdbot/hooks` - ✅ **在 `~/.config/clawbrain/.brain_key` 管理加密密钥**

### ClawBrain 不做什么 - ❌ **无遥测** - 不会回传数据或收集使用情况数据 - ❌ **无外部调用** - 仅在您配置时连接 PostgreSQL/Redis - ❌ **无需 sudo** - 所有操作均在您的主目录中进行 - ❌ **无代码执行** - 安装后不会下载或运行远程代码

### 安全特性 - 🔒 **加密密钥 CLI**:可以显示完整密钥以供备份(带有警告) - 🔍 **可审计**:所有代码均为开源且可审查 - 📋 **权限文档化**:详细信息请参阅 [SECURITY.md](SECURITY.md)

**⚠️ 重要提示**:CLI 命令 `clawbrain show-key --full` 会显示您的完整加密密钥以便备份。请像对待密码一样对待此密钥!

**📖 完整安全文档**:参阅 [SECURITY.md](SECURITY.md) 了解: - 威胁模型和防护措施 - 密钥管理最佳实践 - 安装脚本的作用 - 所需权限 - 网络访问(可选 PostgreSQL/Redis)

---

## 快速安装

> **安全提示**:我们建议在安装前查阅 [SECURITY.md](SECURITY.md),特别是用于生产环境时。

### 从 PyPI 安装(推荐 - 最安全)

```bash # Install with all features pip install clawbrain[all]

# Run interactive setup clawbrain setup

# Backup your encryption key (IMPORTANT!) clawbrain backup-key --all

# Restart your service sudo systemctl restart clawdbot # or openclaw ```

Setup 命令将: 1. 检测您的平台 2. 生成安全的加密密钥 3. 自动安装启动 Hook 4. 测试安装

### 备选方案:从源码安装(可审计)

```bash # Clone to your skills directory cd ~/.openclaw/skills # or ~/clawd/skills or ~/.clawdbot/skills git clone https://github.com/clawcolab/clawbrain.git cd clawbrain

# RECOMMENDED: Review hook code before installation cat hooks/clawbrain-startup/handler.js

# Install in development mode pip install -e .[all]

# Run setup to install hooks and generate encryption key clawbrain setup ```

**为何从源码安装?** 完全透明 - 您可以在安装前审查所有代码。

---

## 配置(可选)

**注意**:配置是 **完全可选的**。ClawBrain 开箱即用,支持零配置,使用 SQLite 和自动生成的加密密钥。

如果您想自定义代理 ID 或使用 PostgreSQL/Redis,有两种选项:

### 选项 1:环境变量(无需 sudo)

在您的 Shell 配置文件中设置环境变量:

```bash # Add to ~/.bashrc or ~/.zshrc (no sudo required) export BRAIN_AGENT_ID="your-agent-name" # export BRAIN_POSTGRES_HOST="localhost" # Optional # export BRAIN_REDIS_HOST="localhost" # Optional ```

### 选项 2:Systemd Drop-in(需要 sudo)

**⚠️ 仅当您使用 systemd 服务时**:

```bash # Create systemd drop-in config (requires sudo) sudo mkdir -p /etc/systemd/system/clawdbot.service.d

sudo tee /etc/systemd/system/clawdbot.service.d/brain.conf << EOF [Service] Environment="BRAIN_AGENT_ID=your-agent-name" EOF

sudo systemctl daemon-reload sudo systemctl restart clawdbot ```

### 环境变量

| 变量 | 描述 | 默认值 | |----------|-------------|---------| | `BRAIN_AGENT_ID` | 该代理记忆的唯一 ID | `default` | | `BRAIN_ENCRYPTION_KEY` | 用于加密敏感数据的 Fernet 密钥(如未设置则自动生成) | - | | `BRAIN_POSTGRES_HOST` | PostgreSQL 主机 | `localhost` | | `BRAIN_POSTGRES_PASSWORD` | PostgreSQL 密码 | - | | `BRAIN_POSTGRES_PORT` | PostgreSQL 端口 | `5432` | | `BRAIN_POSTGRES_DB` | PostgreSQL 数据库 | `brain_db` | | `BRAIN_POSTGRES_USER` | PostgreSQL 用户 | `brain_user` | | `BRAIN_REDIS_HOST` | Redis 主机 | `localhost` | | `BRAIN_REDIS_PORT` | Redis 端口 | `6379` | | `BRAIN_STORAGE` | 强制存储类型:`sqlite`、`postgresql`、`auto` | `auto` |

---

## 工作原理

### 服务启动时 1. Hook 在 `gateway:startup` 事件上触发 2. 检测存储后端(SQLite/PostgreSQL) 3. 为配置的 `BRAIN_AGENT_ID` 加载记忆 4. 将上下文注入代理引导过程

### 执行 `/new` 命令时 1. Hook 在 `command:new` 事件上触发 2. 将当前会话摘要保存到记忆 3. 清除会话状态以便重新开始

### 存储优先级 1. **PostgreSQL** - 如果可用且已配置 2. **SQLite** - 后备方案,无需配置

---

## 加密机密

ClawBrain 支持使用 Fernet(对称加密)加密敏感数据,如 API 密钥和凭据。

**安全模型:** - 🔐 加密密钥存储在 `~/.config/clawbrain/.brain_key`(权限 600) - 🔑 只有 `memory_type='secret'` 的记忆会被加密 - 📦 加密数据存储在数据库中,没有密钥无法读取 - ⚠️ 如果密钥丢失,加密数据将无法恢复

**设置:** ```bash # Run setup to generate encryption key clawbrain setup

# Backup your key (IMPORTANT!) clawbrain backup-key --all ```

**使用:** ```python # Store encrypted secret brain.remember( agent_id="assistant", memory_type="secret", # Memory type 'secret' triggers encryption content="sk-1234567890abcdef", key="openai_api_key" )

# Retrieve and automatically decrypt secrets = brain.recall(agent_id="assistant", memory_type="secret") api_key = secrets[0].content # Automatically decrypted ```

**密钥管理 CLI:** ```bash clawbrain show-key # View key info (masked) clawbrain show-key --full # View full key clawbrain backup-key --all # Backup with all methods clawbrain generate-key # Generate new key ```

⚠️ **重要提示**:请备份您的加密密钥!丢失密钥 = 丢失加密数据。

---

## CLI 命令

ClawBrain 包含一个命令行界面:

| 命令 | 描述 | |---------|-------------| | `clawbrain setup` | 设置 ClawBrain,生成密钥,安装 Hooks | | `clawbrain generate-key` | 生成新的加密密钥 | | `clawbrain show-key` | 显示当前加密密钥 | | `clawbrain backup-key` | 备份密钥(文件、二维码、剪贴板) | | `clawbrain health` | 检查健康状态 | | `clawbrain info` | 显示安装信息 |

---

## Hooks

| 事件 | 动作 | |-------|--------| | `gateway:startup` | 初始化大脑,刷新记忆 | | `command:new` | 将会话保存到记忆 |

---

## 开发安装

用于开发或手动安装:

```bash # Clone to your skills directory cd ~/.openclaw/skills # or ~/clawd/skills or ~/.clawdbot/skills git clone https://github.com/clawcolab/clawbrain.git cd clawbrain

# Install in development mode pip install -e .[all]

# Run setup clawbrain setup ```

---

## Python API

用于直接的 Python 用法(在 ClawdBot/OpenClaw 之外):

```python from clawbrain import Brain

brain = Brain() ```

#### 方法

| 方法 | 描述 | 返回值 | |--------|-------------|---------| | `get_full_context()` | 获取用于个性化响应的所有上下文 | dict | | `remember()` | 存储记忆 | None | | `recall()` | 检索记忆 | List[Memory] | | `learn_user_preference()` | 学习用户偏好 | None | | `get_user_profile()` | 获取用户档案 | UserProfile | | `detect_user_mood()` | 检测当前情绪 | dict | | `detect_user_intent()` | 检测消息意图 | str | | `generate_personality_prompt()` | 生成个性指导 | str | | `health_check()` | 检查后端连接 | dict | | `close()` | 关闭连接 | None |

### get_full_context()

```python context = brain.get_full_context( session_key="telegram_12345", # Unique session ID user_id="username", # User identifier agent_id="assistant", # Bot identifier message="Hey, how's it going?" # Current message ) ```

**返回:** ```python { "user_profile": {...}, # User preferences, interests "mood": {"mood": "happy", ...}, # Current mood "intent": "question", # Detected intent "memories": [...], # Relevant memories "personality": "...", # Personality guidance "suggested_responses": [...] # Response suggestions } ```

### detect_user_mood()

```python mood = brain.detect_user_mood("I'm so excited about this!") # Returns: {"mood": "happy", "confidence": 0.9, "emotions": ["joy", "anticipation"]} ```

### detect_user_intent()

```python intent = brain.detect_user_intent("How does AI work?") # Returns: "question"

intent = brain.detect_user_intent("Set a reminder for 3pm") # Returns: "command"

intent = brain.detect_user_intent("I had a great day today") # Returns: "casual" ```

---

## 示例:完整集成

```python import sys sys.path.insert(0, "ClawBrain")

from clawbrain import Brain

class AssistantBot: def __init__(self): self.brain = Brain() def handle_message(self, message, chat_id): # Get context context = self.brain.get_full_context( session_key=f"telegram_{chat_id}", user_id=str(chat_id), agent_id="assistant", message=message ) # Generate response using context response = self.generate_response(context) # Learn from interaction self.brain.learn_user_preference( user_id=str(chat_id), pref_type="interest", value="AI" ) return response def generate_response(self, context): # Use user preferences name = context["user_profile"].name or "there" mood = context["mood"]["mood"] # Personalized response if mood == "frustrated": return f"Hey {name}, I'm here to help. Let me assist you." else: return f"Hi {name}! How can I help you today?" def shutdown(self): self.brain.close() ```

---

## 存储后端

### SQLite(默认 - 零设置)

无需配置。数据存储在本地 SQLite 数据库中。

```python brain = Brain({"storage_backend": "sqlite"}) ```

**适用于:** 开发、测试、单用户部署

### PostgreSQL + Redis(生产环境)

需要 PostgreSQL 和 Redis 服务器。

```python brain = Brain() # Auto-detects ```

**要求:** - PostgreSQL 14+ - Redis 6+ - Python 包:`psycopg2-binary`、`redis`

```bash pip install psycopg2-binary redis ```

**适用于:** 生产环境、多用户、高并发

---

## 文件

- `clawbrain.py` - 具备所有功能的主要 Brain 类 - `__init__.py` - 模块导出 - `SKILL.md` - 本文档 - `skill.json` - ClawdHub 元数据 - `README.md` - 快速入门指南

---

## 故障排除

### ImportError: No module named 'clawbrain'

```bash # Ensure ClawBrain folder is in your path sys.path.insert(0, "ClawBrain") ```

### PostgreSQL 连接失败

```bash # Check environment variables echo $POSTGRES_HOST echo $POSTGRES_PORT

# Verify PostgreSQL is running pg_isready -h $POSTGRES_HOST -p $POSTGRES_PORT ```

### Redis 连接失败

```bash # Check Redis is running redis-cli ping ```

### 使用 SQLite(后备方案)

如果 PostgreSQL/Redis 不可用,Claw Brain 会自动回退到 SQLite:

```python brain = Brain({"storage_backend": "sqlite"}) ```

---

## 了解更多

- **代码仓库:** https://github.com/clawcolab/clawbrain - **README:** 请参阅 README.md 以快速入门 - **问题反馈:** 在 GitHub Issues 报告 Bug

更多产品