Skip to content

会话管理

会话(Session)是 OpenClaw 中消息上下文的基本单元。每个对话都发生在一个会话中,会话决定了 AI 的记忆范围、工具权限和行为配置。

会话模型

会话类型

类型说明工具权限
main1:1 私聊会话在宿主机上直接执行工具
group群组/频道会话可选 Docker 沙箱隔离
channel按通道隔离继承通道配置

会话 Key

Source: src/gateway/session-utils.ts

会话通过 sessionKey 唯一标识,key 由通道类型和账户 ID 派生:

typescript
// src/config/sessions.ts (simplified)
function deriveSessionKey(channel: string, accountId: string): string {
  return `${channel}:${normalizeAccountId(accountId)}`;
}

function normalizeAccountId(accountId: string): string {
  // Normalize E164 phone numbers, WhatsApp JIDs, etc.
}

会话存储

Source: src/config/sessions.ts

会话状态持久化到文件系统:

typescript
// src/config/sessions.ts (simplified)
function resolveStorePath(sessionKey: string): string {
  // ~/.openclaw/sessions/{sessionKey}/
}

function loadSessionStore(sessionKey: string): SessionStore {
  // Load from file system
}

function saveSessionStore(sessionKey: string, store: SessionStore): void {
  // Persist to file system
}

存储位置:~/.openclaw/sessions/{sessionKey}/

会话补丁

Source: src/gateway/sessions-patch.ts

通过 sessions.patch 方法可以动态修改会话配置:

可补丁的属性包括:

属性类型说明
modelstringAI 模型选择
thinkingLevelstring思考级别(on/off/stream)
sandboxModeboolean沙箱模式
queueModestring消息队列模式
activationModestring激活方式(mention/always)

会话解析

Source: src/gateway/sessions-resolve.ts

当消息到达时,Gateway 需要解析出目标会话:

typescript
// src/gateway/sessions-resolve.ts (simplified)
function resolveSession(
  channel: string,
  chatType: "direct" | "group" | "channel",
  accountId: string
): ResolvedSession {
  // 1. Derive session key
  const sessionKey = deriveSessionKey(channel, accountId);

  // 2. Check if session exists
  // 3. Apply channel defaults
  // 4. Merge per-session overrides

  return { sessionKey, config };
}

激活模式

不同场景下 AI 是否响应消息由激活模式控制:

模式说明典型场景
always响应所有消息1:1 私聊
mention仅在被 @ 时响应群组聊天
command仅响应命令频道

文件系统会话工具

Source: src/gateway/session-utils.fs.ts

会话文件系统操作包括转录(transcript)管理和镜像持久化:

typescript
// src/gateway/session-utils.fs.ts (simplified)
// Session transcript persistence
// Mirrored transcript management
// Session cleanup and maintenance

会话类型定义

Source: src/gateway/session-utils.types.ts

typescript
// src/gateway/session-utils.types.ts (simplified)
interface SessionConfig {
  model?: string;
  thinkingLevel?: "on" | "off" | "stream";
  sandboxMode?: boolean;
  queueMode?: "fifo" | "fanout";
  activationMode?: "always" | "mention" | "command";
  // ...
}

小结

  • 会话通过 sessionKey 唯一标识,key 由通道 + 账户 ID 派生
  • 三种会话类型:main(1:1)、group(群组)、channel(通道级)
  • 会话状态持久化到 ~/.openclaw/sessions/ 目录
  • 支持通过 sessions.patch 动态修改配置(模型、思考级别、沙箱等)
  • 激活模式控制 AI 是否响应:always / mention / command

下一章:配置系统

OpenClaw 源码学习教程