> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zerone.run/llms.txt
> Use this file to discover all available pages before exploring further.

# Sessions

> 持久化、恢复、分叉和压缩 Agent 会话。

# 管理 Session

Agent 默认持久化 Session（`persistSession` 默认 `true`）。创建时传入 `sessionId` 可指定 ID，使用 `resume` 恢复已有会话，或使用 `continue: true` 继续最近一次会话。

## Session 选项

| 选项                  | 类型        | 默认值     | 说明                           |
| ------------------- | --------- | ------- | ---------------------------- |
| `sessionId`         | `string`  | 自动生成    | 显式 Session ID                |
| `resume`            | `string`  | —       | 按 ID 恢复 Session              |
| `continue`          | `boolean` | `false` | 继续最近一次 Session               |
| `persistSession`    | `boolean` | `true`  | 将 Session 持久化到磁盘             |
| `maxSessionQueries` | `number`  | —       | 纳入 LLM 上下文的最大查询数；更早的查询触发减半压缩 |

## 常用操作

| API                         | 用途                     |
| --------------------------- | ---------------------- |
| `listSessions()`            | 列出持久化 Session          |
| `forkSession(id)`           | 从已有 Session 分叉         |
| `agent.clear()`             | 重置当前会话                 |
| `agent.getMessageHistory()` | 读取 engine 的持久历史（压缩后视图） |
| `agent.getMessageLog()`     | 读取所有已发出消息的追加式审计日志      |

## 压缩历史

上下文增长时调用 `agent.compact()`；流式版本 `agent.compactStream()` 会发出 `compact` 事件并持久化 Session。两个独立选项控制最近尾部保留多少：

| 选项                     | 默认值 | 含义                                           |
| ---------------------- | --- | -------------------------------------------- |
| `protectedQueries`     | `4` | 逐字保留的最近用户查询数（头部摘要、尾部保留）                      |
| `toolProtectedQueries` | `2` | 尾部中保留**完整** `tool_result` 内容的查询数；更早的尾部结果会被清空 |

将 `toolProtectedQueries` 设为不小于尾部大小可完全禁用 tool result 裁剪。省略参数时保留历史默认值（逐字保留 4 个查询，其中最近 2 个保留完整 tool result）。

不经过 Agent 时，`compactSessionStream(opts)` / `compactSession(opts)` 可按 `sessionId` 直接压缩持久化 Session，并原子化写入消息、摘要与 token 计数；宿主持有自定义存储时则使用 `compactMessagesStream()` / `compactMessages()`，并将返回的 `messages` 与 `state` 一起持久化。完整的压缩入口与行为变化见 [API Reference](/zh/sdk/api-reference)。

<Warning>跨请求并发访问同一 Session 时，宿主应用负责加锁。</Warning>
