凌晨1点45分,我在想一个问题:如果Agent的记忆是一块黑板,那会话管理就是决定什么时候擦黑板、什么时候保留板书。
OpenClaw的会话管理系统决定了Agent如何在多轮交互中保持上下文、管理状态和协调任务。良好的会话管理是构建可靠Agent的基础——它决定了Agent是"健忘症患者"还是"过目不忘的天才"。
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Created │ → │ Active │ → │ Suspended│
└──────────┘ └──────────┘ └──────────┘
↓ ↓
┌──────────┐ ┌──────────┐
│ Blocked │ │ Archived │
└──────────┘ └──────────┘
↓
┌──────────┐
│ Closed │
└──────────┘
| 状态 | 说明 | 恢复方式 |
|---|---|---|
| Created | 刚创建,等待首次交互 | 自动激活 |
| Active | 正常运行中 | - |
| Suspended | 暂停,等待外部输入 | 收到消息自动恢复 |
| Blocked | 等待审批 | 审批通过/拒绝 |
| Archived | 已归档,只读 | 手动恢复 |
| Closed | 已关闭 | 无法恢复 |
import { SessionManager } from 'openclaw';
// 创建会话管理器
const sessionManager = new SessionManager({
storage: './sessions', // 会话存储路径
maxSessions: 100, // 最大并发会话
defaultTTL: 3600000, // 默认1小时超时
autoSave: true // 自动保存
});
// 创建新会话
const session = await sessionManager.create({
agentId: 'my-agent',
userId: 'user_123',
metadata: {
title: '代码审查任务',
priority: 'high'
}
});
console.log(session.id); // "sess_abc123def"
// 发送消息到会话
const response = await session.send('请帮我审查这段代码');
console.log(response.text);
console.log(response.tokenUsage); // { input: 500, output: 200 }
// 获取会话历史
const history = await session.getHistory();
console.log(history.messages.length); // 2 (用户+助手)
// 持久化配置
const sessionManager = new SessionManager({
storage: {
type: 'sqlite', // 存储类型
path: './data/sessions.db',
encrypt: true, // 加密存储
encryptionKey: process.env.SESSION_KEY
},
// 会话保留策略
retention: {
active: 'indefinite', // 活跃会话永久保留
archived: '30d', // 归档会话30天
closed: '7d', // 关闭会话7天
cleanup: 'daily' // 每天清理
}
});
// 恢复之前的会话
const restored = await sessionManager.restore('sess_abc123def');
console.log(restored.metadata); // { title: '代码审查任务' }
console.log(restored.history.length); // 恢复完整历史
// 多会话管理
const coordinator = new SessionCoordinator({
sessionManager,
// 会话路由规则
routing: {
byTopic: true, // 按话题路由
byPriority: true, // 按优先级排序
maxParallel: 3 // 最多3个并行会话
},
// 会话间通信
interSession: {
enabled: true,
sharedContext: true, // 共享上下文
contextTTL: 300000 // 共享上下文5分钟
}
});
// 创建任务组
const taskGroup = await coordinator.createGroup({
name: '产品发布准备',
sessions: [
{ title: '文案撰写', agent: 'writer' },
{ title: '代码审查', agent: 'reviewer' },
{ title: '测试验证', agent: 'tester' }
]
});
// 查看任务组状态
const status = await taskGroup.getStatus();
// {
// total: 3,
// completed: 1,
// inProgress: 1,
// pending: 1
// }
// 创建会话分支(探索不同方案)
const branch = await session.branch({
name: '方案B探索',
message: '如果用方案B重新处理呢?'
});
// 两个分支独立运行
const resultA = await session.send('继续方案A');
const resultB = await branch.send('继续方案B');
// 合并分支
const merged = await session.merge(branch, {
strategy: 'best', // 选择最佳结果
criteria: 'token_efficiency'
});
// 定义会话模板
const templates = {
codeReview: {
systemPrompt: '你是一个资深代码审查员...',
tools: ['file_read', 'git_diff', 'lint_check'],
maxTurns: 20,
autoSummarize: true
},
customerSupport: {
systemPrompt: '你是一个友好的客服代表...',
tools: ['knowledge_search', 'ticket_create'],
escalation: true,
sentiment: 'monitor'
}
};
// 使用模板创建会话
const session = await sessionManager.createFromTemplate(
'codeReview',
{ repo: 'my-project', pr: 123 }
);