9.2 实现会话持久化与分支

在 8.2 课 中我们用官方 SessionManager 跑通了“跨进程断点续聊”和“同文件分叉探索”。这一课我们在 packages/nano-pi-coding-agent/src/core/session-manager.ts 里亲手实现这套追加式 JSONL 会话树,并把它接到上一课完成的 AgentSession 中。

追加式 JSONL 树的核心设计

一份 .jsonl 会话文件由两部分组成:

  1. 首行 SessionHeader(type: "session"):记录格式版本号 version: 3、会话 id、创建时间与工作目录 cwd。
  2. 后续每行一条 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 在内存中额外维护三份状态:

延迟 flush 与内存一致性

与官方 pi-coding-agent 一致,持久化会话采用延迟 flush 策略:

自动接入 AgentSession

在 src/core/session.ts 中,我们已经在题目代码里为你接好了会话生命周期:

解答 展开 收起
GitHub 代码对比

三处实现共同构成了追加式 JSONL 会话树的读写、延迟 flush 与分支回溯闭环:

  1. 打开并重建索引(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 };
}
  1. 延迟 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");
}
  1. 拨回叶节点与沿 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 回滚,可以确保磁盘与内存树始终保持父子引用一致。