用本章的程序读一个会话文件
把本章的会话读取器对着一个真实的 JSONL 文件运行,看清头、id/parentId 树,以及那两种时间戳格式。
一个 Pi 会话是一个 JSONL 文件:一行一个 JSON 对象,session 头在最前,然后是由 id 和 parentId 链接起来的条目。这种格式是第 5、6、23、24 章那些会话论断的共同来源——它们引用它的声明,而不是重新定义它——所以一个能跑的读取器是看清它们全都意味着什么的最直接方式。下面是第 27 章自己的读取程序,在 1.0.4 上,原样复现。
运行本章的读取器
read-session.ts 走的是文件,不是分支,对每一种已知的条目类型打印一行。它是本章的 example:,完整给出:
import { readFileSync } from "fs";
const lines = readFileSync(process.argv[2] ?? "session.jsonl", "utf8").trim().split("\n");
for (const line of lines) {
const entry = JSON.parse(line);
switch (entry.type) {
case "session":
console.log(`Session v${entry.version ?? 1}: ${entry.id}`);
break;
case "message":
console.log(`[${entry.id}] ${entry.message.role}: ${JSON.stringify(entry.message.content)}`);
break;
case "compaction":
console.log(`[${entry.id}] Compaction: ${entry.tokensBefore} tokens summarized`);
break;
case "branch_summary":
console.log(`[${entry.id}] Branch from ${entry.fromId}`);
break;
case "usage":
console.log(`[${entry.id}] Usage (${entry.kind}): ${entry.usage.totalTokens} tokens`);
break;
case "custom":
console.log(`[${entry.id}] Custom (${entry.customType}): ${JSON.stringify(entry.data)}`);
break;
case "custom_message":
console.log(`[${entry.id}] Extension message (${entry.customType}): ${entry.content}`);
break;
case "label":
console.log(`[${entry.id}] Label "${entry.label}" on ${entry.targetId}`);
break;
case "model_change":
console.log(`[${entry.id}] Model: ${entry.provider}/${entry.modelId}`);
break;
case "thinking_level_change":
console.log(`[${entry.id}] Thinking: ${entry.thinkingLevel}`);
break;
}
}把 node read-session.ts <session.jsonl>(裸的 session.jsonl 是默认值)对着一个符合下面格式的文件运行。
这个文件是什么形状
读取器依赖的两个事实,在真实文件上被断言。第一行是一个带 "version": 3 而没有 parentId 的 session 头——元数据,不是树的一部分。而同一个文件里有两种时间戳格式:条目的 timestamp 是 ISO("2026-10-01T09:00:01.000Z"),而嵌套的 message.timestamp 是 Unix 毫秒(1733234401000);同一个瞬间,两种格式。
它据此读取的那份声明
每一个非头条目都携带那些基础字段;这份声明是第 5、6、23、24 章交叉引用的东西:
export interface SessionEntryBase {
type: string;
id: string; // Usually an 8-char hex ID; may fall back to a full UUID
parentId: string | null; // null for a root entry
timestamp: string; // ISO timestamp
}机制与局限
有文档记载: JSONL 容器、头在最前的规则,以及那些基础条目字段,来自锁定的 session-format.md 和这份声明。已观察:entries.test.ts 用一个 faux provider 构建一个持久化的会话,然后用 Node 把这个读取器原样对着真实文件运行,并断言头在最前的形状、v3 版本、树链接、两种时间戳格式,以及读取器自己的输出行(Session v3:、user:、assistant:、Model: faux/)。
这个读取器展示的是被存储的条目,而不是一次请求所包含的东西:压缩选出一个范围,而 context_edit 改写条目——第 23 章和第 5 章拥有那些机制;本页不重新推导它们。这个示例从不运行模型:它的主题是记录一次运行的那个文件格式。
完整源码与测试 。
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.