docs: add self-evolution documentation and fix SOUL.md persistence
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- Create 01-identity-evolution.md: Identity system architecture (SOUL.md, USER.md, change proposals, version management) - Create 04-heartbeat-engine.md: Proactive behavior system (heartbeat config, alerts, proactivity levels) - Create 06-context-compaction.md: Context compression system (token management, summarization, information retention) - Update ZCLAW_AGENT_INTELLIGENCE_EVOLUTION.md: Add Phase 5 self-evolution UX roadmap - Fix AgentOnboardingWizard: Persist SOUL.md and USER.md after agent creation - Fix llm-service: Add Tauri kernel mode detection for memory system LLM calls - Fix kernel: Kernel config takes priority over agent's persisted model Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
220
docs/features/02-intelligence-layer/01-identity-evolution.md
Normal file
220
docs/features/02-intelligence-layer/01-identity-evolution.md
Normal file
@@ -0,0 +1,220 @@
|
||||
# 身份演化系统 (Identity Evolution)
|
||||
|
||||
> **成熟度**: L4 - 生产
|
||||
> **最后更新**: 2026-03-24
|
||||
> **负责人**: Intelligence Layer Team
|
||||
|
||||
## 概述
|
||||
|
||||
身份演化系统是 ZCLAW 自我进化能力的核心,让 Agent 能够:
|
||||
1. **定义人格** - 通过 SOUL.md 定义核心特质
|
||||
2. **演化人格** - 基于对话反思自动改进
|
||||
3. **版本管理** - 跟踪人格变更历史,支持回滚
|
||||
|
||||
---
|
||||
|
||||
## 核心概念
|
||||
|
||||
### 身份文件 (Identity Files)
|
||||
|
||||
每个 Agent 有三个核心身份文件:
|
||||
|
||||
| 文件 | 用途 | 示例内容 |
|
||||
|------|------|----------|
|
||||
| `soul` (SOUL.md) | Agent 人格定义 | 核心特质、沟通风格、专业领域 |
|
||||
| `instructions` | 行为指令集 | 执行规则、约束条件 |
|
||||
| `user_profile` (USER.md) | 用户画像 | 用户偏好、角色、场景 |
|
||||
|
||||
### 身份变更提案 (Identity Change Proposal)
|
||||
|
||||
```typescript
|
||||
interface IdentityChangeProposal {
|
||||
id: string;
|
||||
agent_id: string;
|
||||
file: 'soul' | 'instructions' | 'user_profile';
|
||||
current_content: string;
|
||||
proposed_content: string;
|
||||
diff: string; // Unified diff
|
||||
reason: string; // AI 生成的变更原因
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
created_at: string;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 技术实现
|
||||
|
||||
### 核心文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `desktop/src/lib/intelligence-client.ts` | 前端身份 API 客户端 |
|
||||
| `desktop/src/lib/intelligence-backend.ts` | 身份管理后端实现 |
|
||||
| `desktop/src/lib/personality-presets.ts` | 人格预设和 SOUL.md 生成 |
|
||||
| `desktop/src/components/AgentOnboardingWizard.tsx` | 引导向导,创建时持久化 SOUL.md |
|
||||
|
||||
### API 接口
|
||||
|
||||
```typescript
|
||||
// intelligence-client.ts
|
||||
identity: {
|
||||
// 获取 Agent 的所有身份文件
|
||||
get(agentId: string): Promise<IdentityFiles>;
|
||||
|
||||
// 读取单个文件内容
|
||||
readFile(agentId: string, file: string): Promise<string>;
|
||||
|
||||
// 更新文件内容(自动创建快照)
|
||||
updateFile(agentId: string, file: string, content: string): Promise<void>;
|
||||
|
||||
// 构建完整的人格 Prompt
|
||||
buildPrompt(agentId: string, memoryContext?: string): Promise<string>;
|
||||
|
||||
// 变更提案
|
||||
proposeChange(proposal: Omit<IdentityChangeProposal, 'id' | 'status' | 'created_at'>): Promise<IdentityChangeProposal>;
|
||||
getProposals(): Promise<IdentityChangeProposal[]>;
|
||||
approveProposal(proposalId: string): Promise<IdentityFiles>;
|
||||
rejectProposal(proposalId: string): Promise<void>;
|
||||
|
||||
// 版本管理
|
||||
getSnapshots(agentId: string, limit?: number): Promise<IdentitySnapshot[]>;
|
||||
restoreSnapshot(agentId: string, snapshotId: string): Promise<IdentityFiles>;
|
||||
}
|
||||
```
|
||||
|
||||
### SOUL.md 生成
|
||||
|
||||
```typescript
|
||||
// personality-presets.ts
|
||||
export function generateSoulContent(config: {
|
||||
agentName: string;
|
||||
emoji?: string;
|
||||
personality?: string; // professional | friendly | creative | concise
|
||||
scenarios?: string[]; // coding, writing, product, data, design...
|
||||
communicationStyle?: string;
|
||||
}): string;
|
||||
```
|
||||
|
||||
生成的 SOUL.md 包含:
|
||||
- 核心特质(基于人格预设)
|
||||
- 沟通风格
|
||||
- 专业领域
|
||||
- 边界约束
|
||||
- 语气设定
|
||||
|
||||
---
|
||||
|
||||
## 数据流
|
||||
|
||||
### 创建时持久化
|
||||
|
||||
```
|
||||
AgentOnboardingWizard
|
||||
│
|
||||
├── createClone() → 创建 Agent
|
||||
│
|
||||
├── generateSoulContent() → 生成 SOUL.md
|
||||
│
|
||||
├── generateUserContent() → 生成 USER.md
|
||||
│
|
||||
└── identity.updateFile() → 持久化到存储
|
||||
```
|
||||
|
||||
### 演化流程
|
||||
|
||||
```
|
||||
对话历史
|
||||
│
|
||||
▼
|
||||
反思引擎 (Reflection Engine)
|
||||
│
|
||||
├── 分析对话模式
|
||||
│
|
||||
├── 识别人格改进点
|
||||
│
|
||||
▼
|
||||
identity.proposeChange() → 创建变更提案
|
||||
│
|
||||
▼
|
||||
用户审批 UI
|
||||
│
|
||||
├── approveProposal() → 应用变更
|
||||
│ │
|
||||
│ └── 创建快照
|
||||
│
|
||||
└── rejectProposal() → 丢弃提案
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 人格预设
|
||||
|
||||
| ID | 名称 | 特质 |
|
||||
|----|------|------|
|
||||
| `professional` | 专业严谨 | 严谨分析、准确执行、专业术语、结构化输出 |
|
||||
| `friendly` | 友好亲切 | 热情回应、通俗易懂、主动关怀、耐心解答 |
|
||||
| `creative` | 创意灵活 | 创新思维、多角度探索、灵活应变、突破常规 |
|
||||
| `concise` | 简洁高效 | 直击要点、快速响应、高效执行、精炼表达 |
|
||||
|
||||
---
|
||||
|
||||
## 使用场景
|
||||
|
||||
### 场景 1:首次创建 Agent
|
||||
|
||||
1. 用户通过 AgentOnboardingWizard 创建 Agent
|
||||
2. 选择人格预设和使用场景
|
||||
3. 系统自动生成 SOUL.md 和 USER.md
|
||||
4. 持久化到身份存储
|
||||
|
||||
### 场景 2:基于反思的人格演化
|
||||
|
||||
1. Agent 进行多轮对话
|
||||
2. 反思引擎分析对话模式
|
||||
3. 发现用户偏好(如"不要那么啰嗦")
|
||||
4. 生成人格变更提案
|
||||
5. 用户审批后更新 SOUL.md
|
||||
|
||||
### 场景 3:回滚到之前版本
|
||||
|
||||
1. 用户觉得新人格不合适
|
||||
2. 查看演化历史
|
||||
3. 选择之前的快照
|
||||
4. 一键恢复
|
||||
|
||||
---
|
||||
|
||||
## 集成点
|
||||
|
||||
| 组件 | 集成方式 |
|
||||
|------|----------|
|
||||
| **RightPanel** | 显示身份文件内容、变更提案 |
|
||||
| **ReflectionEngine** | 触发人格变更提案 |
|
||||
| **AutonomyManager** | 审批自主级别下的自动变更 |
|
||||
| **ChatStore** | 使用 `buildPrompt()` 构建系统提示 |
|
||||
|
||||
---
|
||||
|
||||
## 限制与未来改进
|
||||
|
||||
### 当前限制
|
||||
|
||||
1. **前端回滚 UI 未实现** - `getSnapshots()` 和 `restoreSnapshot()` API 存在但无 UI
|
||||
2. **变更提案通知缺失** - 提案创建后无主动通知用户
|
||||
3. **Tauri 模式下文件存储** - 当前使用内存存储,重启后丢失
|
||||
|
||||
### 未来改进
|
||||
|
||||
1. **文件系统持久化** - 将身份文件写入 `~/.zclaw/agents/{agentId}/`
|
||||
2. **变更提案通知** - 添加桌面通知或消息提示
|
||||
3. **人格版本对比** - 可视化 diff 显示变更内容
|
||||
4. **多人格切换** - 支持同一 Agent 保存多套人格配置
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [00-agent-memory.md](./00-agent-memory.md) - 记忆系统
|
||||
- [03-reflection-engine.md](./03-reflection-engine.md) - 反思引擎
|
||||
- [05-autonomy-manager.md](./05-autonomy-manager.md) - 自主授权
|
||||
274
docs/features/02-intelligence-layer/04-heartbeat-engine.md
Normal file
274
docs/features/02-intelligence-layer/04-heartbeat-engine.md
Normal file
@@ -0,0 +1,274 @@
|
||||
# 心跳巡检引擎 (Heartbeat Engine)
|
||||
|
||||
> **成熟度**: L4 - 生产
|
||||
> **最后更新**: 2026-03-24
|
||||
> **负责人**: Intelligence Layer Team
|
||||
|
||||
## 概述
|
||||
|
||||
心跳巡检引擎是 ZCLAW 主动行为的核心,定期执行检查任务:
|
||||
1. **主动巡检** - 定期检查系统状态、待办事项
|
||||
2. **智能提醒** - 根据上下文生成提醒
|
||||
3. **自主触发** - 在自主级别下自动执行操作
|
||||
|
||||
---
|
||||
|
||||
## 核心概念
|
||||
|
||||
### 心跳配置 (HeartbeatConfig)
|
||||
|
||||
```typescript
|
||||
interface HeartbeatConfig {
|
||||
enabled: boolean; // 是否启用心跳
|
||||
interval_minutes: number; // 心跳间隔(分钟)
|
||||
quiet_hours_start: string | null; // 静默时段开始(如 "22:00")
|
||||
quiet_hours_end: string | null; // 静默时段结束(如 "08:00")
|
||||
notify_channel: 'ui' | 'desktop' | 'all'; // 通知渠道
|
||||
proactivity_level: 'silent' | 'light' | 'standard' | 'autonomous'; // 主动级别
|
||||
max_alerts_per_tick: number; // 每次心跳最大提醒数
|
||||
}
|
||||
```
|
||||
|
||||
### 心跳提醒 (HeartbeatAlert)
|
||||
|
||||
```typescript
|
||||
interface HeartbeatAlert {
|
||||
title: string; // 提醒标题
|
||||
content: string; // 提醒内容
|
||||
urgency: 'low' | 'medium' | 'high'; // 紧急程度
|
||||
source: string; // 来源模块
|
||||
timestamp: string; // 时间戳
|
||||
}
|
||||
```
|
||||
|
||||
### 心跳结果 (HeartbeatResult)
|
||||
|
||||
```typescript
|
||||
interface HeartbeatResult {
|
||||
status: 'ok' | 'alert'; // 状态
|
||||
alerts: HeartbeatAlert[]; // 提醒列表
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 主动级别
|
||||
|
||||
| 级别 | 行为 |
|
||||
|------|------|
|
||||
| `silent` | 仅记录日志,不发送通知 |
|
||||
| `light` | 发送 UI 内通知 |
|
||||
| `standard` | 发送桌面通知 |
|
||||
| `autonomous` | 自主执行操作(需用户授权) |
|
||||
|
||||
---
|
||||
|
||||
## 技术实现
|
||||
|
||||
### 核心文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `desktop/src/lib/intelligence-backend.ts` | 心跳后端实现 |
|
||||
| `desktop/src/domains/intelligence/store.ts` | 状态管理 |
|
||||
| `desktop/src/domains/intelligence/types.ts` | 类型定义 |
|
||||
|
||||
### Store 接口
|
||||
|
||||
```typescript
|
||||
interface IntelligenceStore {
|
||||
// 状态
|
||||
heartbeatConfig: HeartbeatConfig | null;
|
||||
heartbeatHistory: HeartbeatResult[];
|
||||
isHeartbeatRunning: boolean;
|
||||
|
||||
// 操作
|
||||
initHeartbeat(agentId: string, config?: HeartbeatConfig): Promise<void>;
|
||||
startHeartbeat(agentId: string): Promise<void>;
|
||||
stopHeartbeat(agentId: string): Promise<void>;
|
||||
tickHeartbeat(agentId: string): Promise<HeartbeatResult>;
|
||||
}
|
||||
```
|
||||
|
||||
### 后端实现
|
||||
|
||||
```typescript
|
||||
// intelligence-backend.ts
|
||||
export const heartbeat = {
|
||||
config: {
|
||||
get: async (agentId: string): Promise<HeartbeatConfig> => {...},
|
||||
update: async (agentId: string, config: Partial<HeartbeatConfig>): Promise<HeartbeatConfig> => {...},
|
||||
},
|
||||
|
||||
start: async (agentId: string): Promise<void> => {...},
|
||||
stop: async (agentId: string): Promise<void> => {...},
|
||||
tick: async (agentId: string): Promise<HeartbeatResult> => {...},
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 心跳巡检任务
|
||||
|
||||
每次心跳 `tick` 执行以下检查:
|
||||
|
||||
### 1. 任务检查
|
||||
- 检查是否有待办任务 (type=task)
|
||||
- 检查任务是否到期
|
||||
- 生成任务提醒
|
||||
|
||||
### 2. 上下文检查
|
||||
- 检查对话历史长度
|
||||
- 触发上下文压缩建议
|
||||
- 检查记忆提取机会
|
||||
|
||||
### 3. 反思检查
|
||||
- 检查距离上次反思的对话数
|
||||
- 触发反思引擎
|
||||
- 生成人格变更提案
|
||||
|
||||
### 4. 系统检查
|
||||
- 检查 Gateway 连接状态
|
||||
- 检查 API 配额
|
||||
- 检查更新可用性
|
||||
|
||||
---
|
||||
|
||||
## 使用场景
|
||||
|
||||
### 场景 1:定时任务提醒
|
||||
|
||||
```
|
||||
心跳 tick (每 30 分钟)
|
||||
│
|
||||
├── 检查任务记忆
|
||||
│
|
||||
├── 发现到期任务:"明天 10 点提醒我开会"
|
||||
│
|
||||
└── 生成 HeartbeatAlert
|
||||
title: "任务提醒"
|
||||
content: "10:00 有会议"
|
||||
urgency: "medium"
|
||||
```
|
||||
|
||||
### 场景 2:反思触发
|
||||
|
||||
```
|
||||
心跳 tick
|
||||
│
|
||||
├── 检查对话数 >= 10
|
||||
│
|
||||
├── 距离上次反思 > 1 小时
|
||||
│
|
||||
└── 触发 ReflectionEngine.reflect()
|
||||
│
|
||||
└── 生成人格变更提案
|
||||
```
|
||||
|
||||
### 场景 3:自主级别下的自动操作
|
||||
|
||||
```
|
||||
心跳 tick (autonomous 级别)
|
||||
│
|
||||
├── 检查用户授权
|
||||
│
|
||||
├── 发现可自动执行的任务
|
||||
│
|
||||
└── 执行操作(如:整理记忆、压缩上下文)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 与其他组件的集成
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Heartbeat Engine │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Memory Store │◀────│ 任务检查 │ │
|
||||
│ └──────────────┘ └──────────────┘ │
|
||||
│ │ │ │
|
||||
│ │ ▼ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Reflection │◀────│ 反思触发 │ │
|
||||
│ │ Engine │ └──────────────┘ │
|
||||
│ └──────────────┘ │
|
||||
│ │ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ Identity Evolution │ │
|
||||
│ │ (人格变更提案) │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 配置示例
|
||||
|
||||
### 开发者模式
|
||||
```typescript
|
||||
{
|
||||
enabled: true,
|
||||
interval_minutes: 5,
|
||||
quiet_hours_start: null,
|
||||
quiet_hours_end: null,
|
||||
notify_channel: 'ui',
|
||||
proactivity_level: 'light',
|
||||
max_alerts_per_tick: 3
|
||||
}
|
||||
```
|
||||
|
||||
### 生产模式
|
||||
```typescript
|
||||
{
|
||||
enabled: true,
|
||||
interval_minutes: 30,
|
||||
quiet_hours_start: "22:00",
|
||||
quiet_hours_end: "08:00",
|
||||
notify_channel: 'all',
|
||||
proactivity_level: 'standard',
|
||||
max_alerts_per_tick: 5
|
||||
}
|
||||
```
|
||||
|
||||
### 自主模式
|
||||
```typescript
|
||||
{
|
||||
enabled: true,
|
||||
interval_minutes: 15,
|
||||
quiet_hours_start: "23:00",
|
||||
quiet_hours_end: "07:00",
|
||||
notify_channel: 'desktop',
|
||||
proactivity_level: 'autonomous',
|
||||
max_alerts_per_tick: 10
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 限制与未来改进
|
||||
|
||||
### 当前限制
|
||||
|
||||
1. **前端定时器依赖** - 心跳依赖页面打开,后台时不运行
|
||||
2. **无持久化调度** - 重启后心跳不自动恢复
|
||||
3. **静默时段实现不完整** - 时区处理可能有问题
|
||||
|
||||
### 未来改进
|
||||
|
||||
1. **后台心跳** - 使用 Service Worker 或 Tauri 后台任务
|
||||
2. **智能间隔调整** - 根据用户活跃度动态调整间隔
|
||||
3. **云端同步** - 多设备心跳状态同步
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [03-reflection-engine.md](./03-reflection-engine.md) - 反思引擎
|
||||
- [05-autonomy-manager.md](./05-autonomy-manager.md) - 自主授权
|
||||
- [01-identity-evolution.md](./01-identity-evolution.md) - 身份演化
|
||||
383
docs/features/02-intelligence-layer/06-context-compaction.md
Normal file
383
docs/features/02-intelligence-layer/06-context-compaction.md
Normal file
@@ -0,0 +1,383 @@
|
||||
# 上下文压缩系统 (Context Compaction)
|
||||
|
||||
> **成熟度**: L4 - 生产
|
||||
> **最后更新**: 2026-03-24
|
||||
> **负责人**: Intelligence Layer Team
|
||||
|
||||
## 概述
|
||||
|
||||
上下文压缩系统解决了无限对话长度的核心挑战:
|
||||
1. **Token 限制管理** - 监控对话长度,防止超出模型限制
|
||||
2. **智能摘要** - 将历史对话压缩为简洁摘要
|
||||
3. **信息保留** - 确保关键决策、偏好、上下文不丢失
|
||||
4. **无感知压缩** - 用户无需手动管理对话历史
|
||||
|
||||
---
|
||||
|
||||
## 核心概念
|
||||
|
||||
### 压缩配置 (CompactionConfig)
|
||||
|
||||
```typescript
|
||||
interface CompactionConfig {
|
||||
soft_threshold_tokens: number; // 软阈值(触发压缩建议)
|
||||
hard_threshold_tokens: number; // 硬阈值(强制压缩)
|
||||
reserve_tokens: number; // 为响应预留的 token
|
||||
memory_flush_enabled: boolean; // 是否在压缩前刷新记忆
|
||||
keep_recent_messages: number; // 保留的最近消息数
|
||||
summary_max_tokens: number; // 摘要最大 token 数
|
||||
use_llm: boolean; // 是否使用 LLM 生成摘要
|
||||
llm_fallback_to_rules: boolean; // LLM 失败时回退到规则
|
||||
}
|
||||
```
|
||||
|
||||
### 压缩检查 (CompactionCheck)
|
||||
|
||||
```typescript
|
||||
interface CompactionCheck {
|
||||
should_compact: boolean; // 是否需要压缩
|
||||
current_tokens: number; // 当前 token 数
|
||||
threshold: number; // 触发阈值
|
||||
urgency: 'none' | 'soft' | 'hard'; // 紧急程度
|
||||
}
|
||||
```
|
||||
|
||||
### 压缩结果 (CompactionResult)
|
||||
|
||||
```typescript
|
||||
interface CompactionResult {
|
||||
compacted_messages: CompactableMessage[]; // 压缩后的消息列表
|
||||
summary: string; // 生成的摘要
|
||||
original_count: number; // 原始消息数
|
||||
retained_count: number; // 保留消息数
|
||||
flushed_memories: number; // 刷新的记忆数
|
||||
tokens_before_compaction: number; // 压缩前 token
|
||||
tokens_after_compaction: number; // 压缩后 token
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 压缩流程
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Context Compaction │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────┐ │
|
||||
│ │ 新消息到达 │ │
|
||||
│ └──────┬───────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────┐ soft_threshold ┌─────────┐ │
|
||||
│ │ Token 计算 │─────────────────────────▶│ 建议压缩 │ │
|
||||
│ └──────┬───────┘ └─────────┘ │
|
||||
│ │ │
|
||||
│ │ hard_threshold │
|
||||
│ ▼ │
|
||||
│ ┌──────────────┐ │
|
||||
│ │ 强制压缩 │ │
|
||||
│ └──────┬───────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 1. 保留最近 N 条消息 │ │
|
||||
│ │ 2. 对旧消息生成摘要 │ │
|
||||
│ │ 3. 可选:提取记忆到 Memory Store │ │
|
||||
│ │ 4. 替换旧消息为摘要 │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────┐ │
|
||||
│ │ 压缩完成 │ │
|
||||
│ └──────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Token 估算算法
|
||||
|
||||
### CJK + 英文混合估算
|
||||
|
||||
```rust
|
||||
// Rust 实现 (compactor.rs)
|
||||
pub fn estimate_tokens(text: &str) -> usize {
|
||||
let mut tokens: f64 = 0.0;
|
||||
for char in text.chars() {
|
||||
let code = char as u32;
|
||||
if code >= 0x4E00 && code <= 0x9FFF {
|
||||
// CJK 基本汉字 → 1.5 tokens
|
||||
tokens += 1.5;
|
||||
} else if code >= 0x3400 && code <= 0x4DBF {
|
||||
// CJK 扩展 A → 1.5 tokens
|
||||
tokens += 1.5;
|
||||
} else if code >= 0x3000 && code <= 0x303F {
|
||||
// CJK 标点 → 1.0 token
|
||||
tokens += 1.0;
|
||||
} else if char == ' ' || char == '\n' || char == '\t' {
|
||||
// 空白字符 → 0.25 token
|
||||
tokens += 0.25;
|
||||
} else {
|
||||
// ASCII 字符 → ~0.3 token (4 chars ≈ 1 token)
|
||||
tokens += 0.3;
|
||||
}
|
||||
}
|
||||
tokens.ceil() as usize
|
||||
}
|
||||
```
|
||||
|
||||
**设计原则**:宁可高估,不可低估。高估会提前触发压缩,但不会导致 API 错误。
|
||||
|
||||
---
|
||||
|
||||
## 摘要生成
|
||||
|
||||
### 规则摘要(当前实现)
|
||||
|
||||
```rust
|
||||
fn generate_summary(&self, messages: &[CompactableMessage]) -> String {
|
||||
let mut sections: Vec<String> = vec!["[以下是之前对话的摘要]".to_string()];
|
||||
|
||||
// 1. 提取讨论主题
|
||||
let topics = extract_topics(user_messages);
|
||||
sections.push(format!("讨论主题: {}", topics.join("; ")));
|
||||
|
||||
// 2. 提取关键结论
|
||||
let conclusions = extract_conclusions(assistant_messages);
|
||||
sections.push(format!("关键结论:\n- {}", conclusions.join("\n- ")));
|
||||
|
||||
// 3. 提取技术上下文(代码片段等)
|
||||
let tech_context = extract_technical_context(messages);
|
||||
sections.push(format!("技术上下文: {}", tech_context.join(", ")));
|
||||
|
||||
// 4. 统计信息
|
||||
sections.push(format!("(已压缩 {} 条消息)", messages.len()));
|
||||
|
||||
sections.join("\n")
|
||||
}
|
||||
```
|
||||
|
||||
### 摘要示例
|
||||
|
||||
```
|
||||
[以下是之前对话的摘要]
|
||||
讨论主题: 如何在 Rust 中实现异步 HTTP 服务器; 性能优化建议
|
||||
关键结论:
|
||||
- 使用 tokio::run 作为异步运行时
|
||||
- 考虑使用连接池减少开销
|
||||
- 建议启用 HTTP/2 支持提升性能
|
||||
技术上下文: 代码片段 (rust), 代码片段 (toml)
|
||||
(已压缩 24 条消息,其中用户 12 条,助手 12 条)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 技术实现
|
||||
|
||||
### 核心文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `desktop/src-tauri/src/intelligence/compactor.rs` | Rust 压缩核心实现 |
|
||||
| `desktop/src/lib/intelligence-backend.ts` | TypeScript API 封装 |
|
||||
| `desktop/src/domains/intelligence/store.ts` | 状态管理 |
|
||||
|
||||
### Tauri Commands
|
||||
|
||||
```rust
|
||||
#[tauri::command]
|
||||
pub fn compactor_estimate_tokens(text: String) -> usize;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn compactor_estimate_messages_tokens(messages: Vec<CompactableMessage>) -> usize;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn compactor_check_threshold(
|
||||
messages: Vec<CompactableMessage>,
|
||||
config: Option<CompactionConfig>,
|
||||
) -> CompactionCheck;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn compactor_compact(
|
||||
messages: Vec<CompactableMessage>,
|
||||
agent_id: String,
|
||||
conversation_id: Option<String>,
|
||||
config: Option<CompactionConfig>,
|
||||
) -> CompactionResult;
|
||||
```
|
||||
|
||||
### 前端 API
|
||||
|
||||
```typescript
|
||||
// intelligence-backend.ts
|
||||
export const compactor = {
|
||||
estimateTokens(text: string): Promise<number>;
|
||||
estimateMessagesTokens(messages: CompactableMessage[]): Promise<number>;
|
||||
checkThreshold(messages: CompactableMessage[], config?: CompactionConfig): Promise<CompactionCheck>;
|
||||
compact(messages: CompactableMessage[], agentId: string, conversationId?: string, config?: CompactionConfig): Promise<CompactionResult>;
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 使用场景
|
||||
|
||||
### 场景 1:自动压缩
|
||||
|
||||
```typescript
|
||||
// 在发送消息前检查
|
||||
const check = await intelligence.compactor.checkThreshold(messages);
|
||||
|
||||
if (check.urgency === 'hard') {
|
||||
// 强制压缩
|
||||
const result = await intelligence.compactor.compact(messages, agentId);
|
||||
setMessages(result.compacted_messages);
|
||||
console.log(`压缩完成: ${result.tokens_before_compaction} → ${result.tokens_after_compaction} tokens`);
|
||||
} else if (check.urgency === 'soft') {
|
||||
// 建议用户压缩或等待
|
||||
showCompactionSuggestion();
|
||||
}
|
||||
```
|
||||
|
||||
### 场景 2:手动压缩
|
||||
|
||||
```typescript
|
||||
// 用户主动触发压缩
|
||||
const result = await intelligence.compactor.compact(
|
||||
messages,
|
||||
agentId,
|
||||
conversationId,
|
||||
{
|
||||
soft_threshold_tokens: 12000,
|
||||
keep_recent_messages: 10,
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### 场景 3:压缩 + 记忆提取
|
||||
|
||||
```typescript
|
||||
// 压缩前先提取记忆
|
||||
if (config.memory_flush_enabled) {
|
||||
const memories = await extractMemoriesFromOldMessages(oldMessages);
|
||||
for (const memory of memories) {
|
||||
await intelligence.memory.store(memory);
|
||||
}
|
||||
}
|
||||
|
||||
// 然后执行压缩
|
||||
const result = await intelligence.compactor.compact(messages, agentId);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 与其他组件的集成
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Context Compactor │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ ChatStore │────▶│ Token 检查 │ │
|
||||
│ └──────────────┘ └──────────────┘ │
|
||||
│ │ │ │
|
||||
│ │ ▼ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Memory Store │◀────│ 记忆提取 │ │
|
||||
│ └──────────────┘ └──────────────┘ │
|
||||
│ │ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 摘要生成 │ │
|
||||
│ │ - 规则提取(当前) │ │
|
||||
│ │ - LLM 摘要(可选) │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────┐ │
|
||||
│ │ 压缩后消息 │ │
|
||||
│ └──────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 配置示例
|
||||
|
||||
### 开发模式(频繁压缩测试)
|
||||
|
||||
```typescript
|
||||
{
|
||||
soft_threshold_tokens: 5000,
|
||||
hard_threshold_tokens: 8000,
|
||||
reserve_tokens: 2000,
|
||||
memory_flush_enabled: true,
|
||||
keep_recent_messages: 4,
|
||||
summary_max_tokens: 400,
|
||||
use_llm: false,
|
||||
llm_fallback_to_rules: true,
|
||||
}
|
||||
```
|
||||
|
||||
### 生产模式(较长上下文)
|
||||
|
||||
```typescript
|
||||
{
|
||||
soft_threshold_tokens: 15000,
|
||||
hard_threshold_tokens: 20000,
|
||||
reserve_tokens: 4000,
|
||||
memory_flush_enabled: true,
|
||||
keep_recent_messages: 6,
|
||||
summary_max_tokens: 800,
|
||||
use_llm: false,
|
||||
llm_fallback_to_rules: true,
|
||||
}
|
||||
```
|
||||
|
||||
### 大上下文模式(32K 模型)
|
||||
|
||||
```typescript
|
||||
{
|
||||
soft_threshold_tokens: 25000,
|
||||
hard_threshold_tokens: 30000,
|
||||
reserve_tokens: 6000,
|
||||
memory_flush_enabled: true,
|
||||
keep_recent_messages: 10,
|
||||
summary_max_tokens: 1200,
|
||||
use_llm: true, // 启用 LLM 摘要
|
||||
llm_fallback_to_rules: true,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 限制与未来改进
|
||||
|
||||
### 当前限制
|
||||
|
||||
1. **规则摘要质量有限** - 无法理解复杂语义,可能丢失重要细节
|
||||
2. **无增量压缩** - 每次都重新处理所有旧消息
|
||||
3. **无压缩预览** - 用户无法在压缩前预览摘要内容
|
||||
4. **LLM 摘要未实现** - `use_llm: true` 配置存在但未实际使用
|
||||
|
||||
### 未来改进
|
||||
|
||||
1. **LLM 增强摘要** - 使用轻量模型生成高质量摘要
|
||||
2. **增量压缩** - 只处理新增的消息,保留之前的摘要
|
||||
3. **压缩预览** - 显示摘要内容,允许用户编辑
|
||||
4. **智能保留** - 基于重要性的消息保留策略
|
||||
5. **压缩历史** - 保存压缩记录,支持回溯
|
||||
|
||||
---
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [00-agent-memory.md](./00-agent-memory.md) - 记忆系统
|
||||
- [03-reflection-engine.md](./03-reflection-engine.md) - 反思引擎
|
||||
- [04-heartbeat-engine.md](./04-heartbeat-engine.md) - 心跳巡检
|
||||
Reference in New Issue
Block a user