9.2 实现会话持久化与分支
在 8.2 课 中我们用官方 SessionManager 跑通了“跨进程断点续聊”和“同文件分叉探索”。这一课我们在 packages/nano-pi-coding-agent/src/core/session-manager.ts 里亲手实现这套追加式 JSONL 会话树,并把它接到上一课完成的 AgentSession 中。
追加式 JSONL 树的核心设计
一份 .jsonl 会话文件由两部分组成:
- 首行
SessionHeader(type: "session"):记录格式版本号version: 3、会话id、创建时间与工作目录cwd。 - 后续每行一条
SessionEntry:每条记录都有自己的id和指向父节点的parentId(首条为null)。只向文件末尾追加新行,绝不改写历史行。
flowchart TD
H["L1: session header"] --> U1["L2: user (id=U1, parent=null)"]
U1 --> A1["L3: assistant (id=A1, parent=U1)"]
A1 -->|"默认继续"| U2A["L4: user (id=U2, parent=A1)"]
U2A --> A2A["L5: assistant (id=A2, parent=U2)"]
A1 -->|"branch(A1) 后"| U2B["L6: user (id=U3, parent=A1)"]
U2B --> A2B["L7: assistant (id=A3, parent=U3)"]
在运行时,SessionManager 在内存中额外维护三份状态:
fileEntries:完整文件行列表(首元素为header,后续为全部条目);byId:Map<string, SessionEntry>,支持O(1)节点查找与沿parentId回溯;leafId:当前活跃分支的叶节点指针(类似 Git 的HEAD)。调用branch(entryId)只拨回leafId,不改动任何既有条目;getBranch()从leafId一路沿parentId往根回溯再反转,就能精确还原当前分支发给模型的消息序列。
延迟 flush 与内存一致性
与官方 pi-coding-agent 一致,持久化会话采用延迟 flush 策略:
SessionManager.create(cwd, sessionDir)只在内存中准备好SessionHeader与目标文件路径,置flushed = false,不会提前在磁盘创建空文件(避免用户刚打开会话就退出时留下大量垃圾文件)。- 当
appendMessage()追加条目后,若尚未flushed且fileEntries中已出现至少一条user或assistant消息,才一次性创建目录、用"wx"(独占创建)写入fileEntries中的全部行,并将flushed置为true。 - 之后再追加新条目时,直接用
appendFileSync()往文件末尾追加单行 JSONL。 - 如果磁盘写入抛错,
appendMessage()会立刻把内存中的fileEntries、byId与leafId回滚到追加前的状态,避免后续节点指向磁盘上不存在的parentId。
自动接入 AgentSession
在 src/core/session.ts 中,我们已经在题目代码里为你接好了会话生命周期:
createAgentSession()省略sessionManager时默认回退到SessionManager.inMemory(options.cwd),完全兼容 9.1 的用法;- 启动时读取
sessionManager.buildSessionContext().messages注入Agent的initialState.messages; AgentSession构造时订阅底层Agent的message_end事件,自动把每一条完成的user、assistant与toolResult消息追加进sessionManager,并在dispose()时取消该订阅。
解答 展开
三处实现共同构成了追加式 JSONL 会话树的读写、延迟 flush 与分支回溯闭环:
- 打开并重建索引(
SessionManager.open()):
export function parseSessionLines(rawLines: string[]) {
const header = JSON.parse(rawLines[0] ?? "") as SessionHeader;
const fileEntries: FileEntry[] = [header];
const byId = new Map<string, SessionEntry>();
let leafId: string | null = null;
for (let i = 1; i < rawLines.length; i++) {
const entry = JSON.parse(rawLines[i] ?? "") as SessionEntry;
fileEntries.push(entry);
byId.set(entry.id, entry);
leafId = entry.id;
}
return { header, fileEntries, byId, leafId };
}
- 延迟 flush 与单行追加(
persistEntry()):
export function persistSessionEntry(
state: {
sessionFile: string;
flushed: boolean;
fileEntries: FileEntry[];
hasConversation(): boolean;
},
entry: SessionEntry,
): void {
if (!state.flushed) {
if (!state.hasConversation()) {
return;
}
mkdirSync(dirname(state.sessionFile), { recursive: true });
const fd = openSync(state.sessionFile, "wx");
try {
for (const item of state.fileEntries) {
writeFileSync(fd, `${JSON.stringify(item)}\n`, "utf8");
}
} finally {
closeSync(fd);
}
state.flushed = true;
return;
}
appendFileSync(state.sessionFile, `${JSON.stringify(entry)}\n`, "utf8");
}
- 拨回叶节点与沿
parentId回溯(branch()/getBranch()):
export function walkBranch(
byId: ReadonlyMap<string, SessionEntry>,
targetId: string | null,
): SessionEntry[] {
if (!targetId) {
return [];
}
const path: SessionEntry[] = [];
const visited = new Set<string>();
let current = byId.get(targetId);
while (current && !visited.has(current.id)) {
visited.add(current.id);
path.push(current);
current = current.parentId ? byId.get(current.parentId) : undefined;
}
path.reverse();
return path;
}
openSync(this.sessionFile, "wx") 保证首次 flush 只会创建新文件、不会意外覆盖同名旧会话;而在 appendMessage() 外层配合 try / catch 回滚,可以确保磁盘与内存树始终保持父子引用一致。