Skip to content

会话与上下文

会话是什么

OpenClaw 为每个对话维护一个会话(Session),包含:

  • 完整的对话历史(存储为 JSONL 文件)
  • 会话状态(当前模型、指令等)
  • Token 使用计数

所有会话状态由 Gateway 管理,不在客户端本地存储。

会话键(Session Key)

每个会话由一个 sessionKey 标识。私信(DM)默认使用主会话键 agent:<agentId>:main;群组/频道会话使用独立的键。

dmScope:控制私信如何分组

session.dmScope 控制私信会话的隔离粒度:

行为
main(默认)所有私信共享主会话(适合单用户)
per-peer按发送者 ID 隔离(跨渠道同一人共享)
per-channel-peer按渠道+发送者 ID 隔离(推荐多用户场景
per-account-channel-peer按账号+渠道+发送者 ID 隔离(推荐多账号场景)

安全警告:如果多个用户可以私信你的 Bot,强烈建议启用 dmScope: "per-channel-peer"。默认的 main 模式下所有用户共享同一上下文,可能导致隐私信息泄露。

json5
{
  session: {
    dmScope: "per-channel-peer",
  },
}

状态存储位置

  • 会话索引~/.openclaw/agents/<agentId>/sessions/sessions.json
  • 对话历史~/.openclaw/agents/<agentId>/sessions/<SessionId>.jsonl
  • Telegram 话题会话:.../<SessionId>-topic-<threadId>.jsonl

会话索引是一个 sessionKey → { sessionId, updatedAt, ... } 的映射。删除条目是安全的,按需重新创建。

会话重置

自动重置

json5
{
  session: {
    reset: {
      mode: "daily",   // off | daily | idle
      atHour: 4,       // 每天凌晨 4 点重置
      idleMinutes: 120, // 闲置 2 小时后重置
    },
  },
}

手动重置触发词

json5
{
  session: {
    resetTriggers: ["/new", "/reset"],
  },
}

用户发送 /new/reset 即可立即开始新会话。

按渠道不同重置策略

json5
{
  session: {
    resetByChannel: {
      discord: { mode: "idle", idleMinutes: 10080 }, // Discord 闲置 7 天
    },
  },
}

上下文压缩(Compaction)

当会话接近模型的上下文长度限制时,OpenClaw 自动进行上下文压缩

  1. 触发一个静默的 Agent 轮次,提示模型写入持久记忆
  2. 压缩(截断)历史对话,保留最近内容
  3. 继续正常对话

相关配置:

json5
{
  agents: {
    defaults: {
      compaction: {
        reserveTokensFloor: 20000,
        memoryFlush: {
          enabled: true,
        },
      },
    },
  },
}

线程绑定(Discord 专有)

Discord 支持将频道 thread 绑定到特定会话:

json5
{
  session: {
    threadBindings: {
      enabled: true,
      idleHours: 24,    // thread 闲置多久后解绑
      maxAgeHours: 0,   // 0 = 不限最大时长
    },
  },
}

相关 slash 命令:/focus(绑定 thread)、/unfocus(解绑)

会话维护(自动清理)

防止会话文件无限增长:

json5
{
  session: {
    maintenance: {
      mode: "prune",       // warn | prune
      pruneAfter: "30d",   // 超过 30 天的会话
      maxEntries: 500,     // 最多保留 500 个会话
      rotateBytes: "10mb", // JSONL 文件超过 10MB 时轮转
      maxDiskBytes: "500mb",
    },
  },
}

发送策略(sendPolicy)

控制 Agent 是否允许主动向特定渠道发送消息:

json5
{
  session: {
    sendPolicy: {
      default: "allow",
      rules: [
        { action: "deny", match: { channel: "discord", chatType: "group" } },
      ],
    },
  },
}

跨渠道身份链接

如果同一个人通过多个渠道联系你,用 identityLinks 合并他们的 DM 会话:

json5
{
  session: {
    identityLinks: [
      {
        canonical: "whatsapp:+15551234567",
        aliases: ["telegram:123456789", "discord:user:987654321"],
      },
    ],
  },
}