核心概念关系概览
OpenClaw 的核心概念围绕 Gateway(控制平面) 与 Agent Runtime(代理运行时) 协同工作展开。Gateway 负责会话、路由、插件与协议;Agent Runtime 执行对话循环、调用模型与工具,并管理内存与上下文。会话(Sessions)是消息与状态的载体,内存(Memory)提供持久知识,压缩(Compaction)与修剪(Pruning)维持上下文在模型限制内。消息(Messages)经去重、防抖、队列(Queue)后进入代理循环,流式(Streaming)返回结果。插件(Plugins)通过 TypeBox 定义的协议扩展通道、工具、内存与模型提供者。Presence 监控实例状态,多代理(Multi-Agent)与子代理工具扩展能力。
graph TB
subgraph "客户端/通道"
CLI[CLI]
UI[Control UI]
TUI[TUI]
CH[Channels: WhatsApp/Telegram/Discord/...]
end
subgraph "Gateway 控制平面"
GW[Gateway Server]
SM[Session Manager]
PL[Plugin Loader]
PR[Presence]
SC[Schema (TypeBox)]
end
subgraph "Agent Runtime"
AR[PiEmbeddedRunner]
SP[System Prompt Builder]
MEM[Memory Search]
TR[Tool Registry / Sandbox]
end
subgraph "会话与持久化"
SS[Session Store (sessions.json)]
TRX[Transcript (.jsonl)]
WS[Workspace (memory files)]
end
subgraph "模型与流"
MP[Model Providers]
STR[Streaming]
end
CLI -->|WebSocket| GW
UI -->|WebSocket| GW
TUI -->|WebSocket| GW
CH -->|消息| GW
GW --> SM
GW --> PL
GW --> PR
GW --> SC
GW -->|路由| AR
AR --> SP
AR --> MEM
AR --> TR
AR -->|请求| MP
MP -->|响应| STR
STR -->|流回| GW
GW -->|流回| CH
SM --> SS
SM --> TRX
MEM --> WS
PL -->|插件| CH
PL -->|插件| TR
PL -->|插件| MEM
PL -->|插件| MP
关键关系说明
1. Gateway 与 Agent Runtime
- Gateway 通过 WebSocket 接收来自 CLI、Control UI、TUI 与各类通道的消息,并按会话键(sessionKey)路由到 Agent Runtime 执行 1 。
- Agent Runtime(PiEmbeddedRunner)执行代理循环:加载会话、构建系统提示、查询内存、调用模型、执行工具、流式返回结果 2 。
2. 会话(Sessions)与持久化
- 会话由 Gateway 的 Session Manager 管理,按
session.dmScope与群组/通道划分键,存储在sessions.json与.jsonl转录中 3 。 - 会话支持修剪(Pruning,内存中清理旧工具结果)与压缩(Compaction,持久化摘要)以维持上下文在模型限制内 4 。
3. 内存(Memory)与压缩(Compaction)
- 内存是工作区中的 Markdown 文件(每日日志与 MEMORY.md),由内存插件(默认 memory-core)提供搜索 5 。
- 在接近压缩阈值时,系统触发“预压缩内存刷新”静默轮次,提醒模型将持久信息写入磁盘 6 。
4. 消息(Messages)与队列(Queue)
5. 插件(Plugins)与 TypeBox 协议
- 插件通过扫描
package.json的openclaw.extensions字段加载,注册到通道/工具/内存/提供者插槽 1 。 - TypeBox 定义 Gateway 协议的请求/响应/事件模式,生成运行时验证器与 Swift 模型 9 。
6. 流式(Streaming)与模型提供者(Model Providers)
7. Presence 与多客户端
- Presence 由 Gateway 维护,来自 WS 连接与系统事件信标,用于 UI 显示实例状态 12 。
Notes
- 以上关系基于 OpenClaw 文档的“Key Concepts”相关页面,包括架构、代理循环、会话、内存、压缩、消息、队列、Presence、TypeBox 与插件等 13 。
- 具体配置与实现细节请参考对应概念文档(如
docs/concepts/session.md、docs/concepts/compaction.md等)。 - 若需深入代码实现,可查看
src/gateway/server.ts、src/agents/piembeddedrunner.ts与src/plugins/loader.ts等文件(未在本文引用中展开)。
Wiki pages you might want to explore: - Overview (openclaw/openclaw)
Citations
File: docs/start/hubs.md (L32-60)
## Core concepts
- [Architecture](/concepts/architecture)
- [Network hub](/network)
- [Agent runtime](/concepts/agent)
- [Agent workspace](/concepts/agent-workspace)
- [Memory](/concepts/memory)
- [Agent loop](/concepts/agent-loop)
- [Streaming + chunking](/concepts/streaming)
- [Multi-agent routing](/concepts/multi-agent)
- [Compaction](/concepts/compaction)
- [Sessions](/concepts/session)
- [Sessions (alias)](/concepts/sessions)
- [Session pruning](/concepts/session-pruning)
- [Session tools](/concepts/session-tool)
- [Queue](/concepts/queue)
- [Slash commands](/tools/slash-commands)
- [RPC adapters](/reference/rpc)
- [TypeBox schemas](/concepts/typebox)
- [Timezone handling](/concepts/timezone)
- [Presence](/concepts/presence)
- [Discovery + transports](/gateway/discovery)
- [Bonjour](/gateway/bonjour)
- [Channel routing](/concepts/channel-routing)
- [Groups](/concepts/groups)
- [Group messages](/concepts/group-messages)
- [Model failover](/concepts/model-failover)
- [OAuth](/concepts/oauth)
File: docs/concepts/agent-loop.md (L31-40)
- enforces timeout -> aborts run if exceeded
- returns payloads + usage metadata
4) `subscribeEmbeddedPiSession` bridges pi-agent-core events to OpenClaw `agent` stream:
- tool events => `stream: "tool"`
- assistant deltas => `stream: "assistant"`
- lifecycle events => `stream: "lifecycle"` (`phase: "start" | "end" | "error"`)
5) `agent.wait` uses `waitForAgentJob`:
- waits for **lifecycle end/error** for `runId`
- returns `{ status: ok|error|timeout, startedAt, endedAt, error? }`
File: docs/concepts/agent-loop.md (L41-45)
## Queueing + concurrency
- Runs are serialized per session key (session lane) and optionally through a global lane.
- This prevents tool/session races and keeps session history consistent.
- Messaging channels can choose queue modes (collect/steer/followup) that feed this lane system.
See [Command Queue](/concepts/queue).
File: docs/concepts/session.md (L8-16)
OpenClaw treats **one direct-chat session per agent** as primary. Direct chats collapse to `agent:<agentId>:<mainKey>` (default `main`), while group/channel chats get their own keys. `session.mainKey` is honored.
Use `session.dmScope` to control how **direct messages** are grouped:
- `main` (default): all DMs share the main session for continuity.
- `per-peer`: isolate by sender id across channels.
- `per-channel-peer`: isolate by channel + sender (recommended for multi-user inboxes).
- `per-account-channel-peer`: isolate by account + channel + sender (recommended for multi-account inboxes).
Use `session.identityLinks` to map provider-prefixed peer ids to a canonical identity so the same person shares a DM session across channels when using `per-peer`, `per-channel-peer`, or `per-account-channel-peer`.
File: docs/concepts/compaction.md (L9-16)
Every model has a **context window** (max tokens it can see). Long-running chats accumulate messages and tool results; once the window is tight, OpenClaw **compacts** older history to stay within limits.
## What compaction is
Compaction **summarizes older conversation** into a compact summary entry and keeps recent messages intact. The summary is stored in the session history, so future requests use:
- The compaction summary
- Recent messages after the compaction point
Compaction **persists** in the session’s JSONL history.
File: docs/concepts/memory.md (L9-14)
OpenClaw memory is **plain Markdown in the agent workspace**. The files are the
source of truth; the model only "remembers" what gets written to disk.
Memory search tools are provided by the active memory plugin (default:
`memory-core`). Disable memory plugins with `plugins.slots.memory = "none"`.
File: docs/concepts/memory.md (L37-43)
## Automatic memory flush (pre-compaction ping)
When a session is **close to auto-compaction**, OpenClaw triggers a **silent,
agentic turn** that reminds the model to write durable memory **before** the
context is compacted. The default prompts explicitly say the model *may reply*,
but usually `NO_REPLY` is the correct response so the user never sees this turn.
File: docs/concepts/messages.md (L32-45)
Channels can redeliver the same message after reconnects. OpenClaw keeps a
short-lived cache keyed by channel/account/peer/session/message id so duplicate
deliveries do not trigger another agent run.
## Inbound debouncing
Rapid consecutive messages from the **same sender** can be batched into a single
agent turn via `messages.inbound`. Debouncing is scoped per channel + conversation
and uses the most recent message for reply threading/IDs.
Config (global default + per-channel overrides):
```json5
{
messages: {
File: docs/concepts/messages.md (L113-120)
## Streaming, chunking, and batching
Block streaming sends partial replies as the model produces text blocks.
Chunking respects channel text limits and avoids splitting fenced code.
Key settings:
- `agents.defaults.blockStreamingDefault` (`on|off`, default off)
- `agents.defaults.blockStreamingBreak` (`text_end|message_end`)
File: docs/concepts/typebox.md (L54-62)
## Where the schemas live
- Source: `src/gateway/protocol/schema.ts`
- Runtime validators (AJV): `src/gateway/protocol/index.ts`
- Server handshake + method dispatch: `src/gateway/server.ts`
- Node client: `src/gateway/client.ts`
- Generated JSON Schema: `dist/protocol.schema.json`
- Generated Swift models: `apps/macos/Sources/OpenClawProtocol/GatewayModels.swift`
File: docs/concepts/presence.md (L31-44)
## Producers (where presence comes from)
Presence entries are produced by multiple sources and **merged**.
### 1) Gateway self entry
The Gateway always seeds a “self” entry at startup so UIs show the gateway host
even before any clients connect.
### 2) WebSocket connect
Every WS client begins with a `connect` request. On successful handshake the
Gateway upserts a presence entry for that connection.