8.2 持久化会话与分叉探索

上一课我们在 createAgentSession() 中传的是 SessionManager.inMemory(cwd)——进程一退出,对话上下文就消失了。真实编程场景里,我们既希望关掉终端明天能接着聊,又经常在尝试方案 A 走不通时,回到几轮之前改走方案 B,同时还不想弄丢方案 A 的记录。

@earendil-works/pi-coding-agent 的 SessionManager 用一种极简而优雅的存储格式同时解决了这两个问题:追加式 JSONL 树。

为什么是追加式 JSONL 树,而不是普通 JSON 数组?

每一份会话文件都是一个 .jsonl 文件(每行一条独立 JSON):

flowchart LR
    H["session header"] --> M1["第 1 轮(公共背景,leafId = A)"]
    M1 --> M2A["主线第 2 轮(Redis,parent = A)"]
    M1 --> M2B["新分支第 2 轮(SQLite,parent = A)"]

当 createAgentSession() 启动时,SessionManager.buildSessionContext() 会从当前 leafId 一路沿 parentId 往根回溯,只把当前分支路径上的消息发给模型——因此新分支既继承了公共第 1 轮背景,又完全不会看到被切走的旧分支(Redis)消息。

解答 展开 收起
GitHub 代码对比

在 examples/hello-pi-coding-agent/persistence/session-store.ts 中,使用 SessionManager.create()、SessionManager.open() 与 sessionManager.branch() 实现落盘、恢复与同文件分叉:

import { SessionManager } from "@earendil-works/pi-coding-agent";

export function openOrBranchManager(
	sessionFile: string,
	branchFromId?: string,
): SessionManager {
	const manager = SessionManager.open(sessionFile);
	if (branchFromId) {
		manager.branch(branchFromId);
	}
	return manager;
}

实现要点:

  • 必须在 createAgentSession() 之前调用 branch():createAgentSession() 初始化底层 Agent 的消息列表时会读取 sessionManager.buildSessionContext(),提前把 leafId 拨回目标历史节点,才能让新会话只携带公共祖先路径上的上下文。
  • 只追加、不删改:分叉后的新消息直接追加在同一个 .jsonl 文件末尾,仅把 parentId 指向公共节点;旧分支的所有条目依然完整保留,随时可以通过再次 branch() 切回。