import { createReadStream } from "node:fs"; import { readdir } from "node:fs/promises"; import { join } from "node:path"; import { createInterface } from "node:readline"; import { Type, type Static } from "typebox"; import { Check } from "typebox/value"; export interface TranscriptItem { id: string; kind: "user" | "assistant" | "note" | "summary"; label: string; timestamp: string; text: string; tools: string[]; /** Image `data:` URLs. */ images?: string[]; /** IDs of hidden entries, such as tool results, that follow this item. */ anchors: string[]; /** Parent entry ID when the item does not continue the previous entry. */ branch?: string; } export interface Transcript { id: string; cwd?: string; name?: string; /** IDs of hidden entries before the first item. */ anchors: string[]; items: TranscriptItem[]; } const MAX_TOOL_LINE = 200; const IMAGE_TYPE = /^image\/(?:png|jpeg|gif|webp)$/; function toolLine(text: string): string { const line = text.replace(/\s+/g, " "); return line.length > MAX_TOOL_LINE ? `${line.slice(0, MAX_TOOL_LINE - 1)}…` : line; } const Content = Type.Union([ Type.String(), Type.Array( Type.Object({ type: Type.String(), text: Type.Optional(Type.String()), name: Type.Optional(Type.String()), arguments: Type.Optional(Type.Record(Type.String(), Type.Unknown())), data: Type.Optional(Type.String()), mimeType: Type.Optional(Type.String()), }), ), ]); const Base = { id: Type.String(), parentId: Type.Union([Type.String(), Type.Null()]), timestamp: Type.String(), }; const Header = Type.Object({ type: Type.Literal("session"), id: Type.String(), cwd: Type.Optional(Type.String()), parentSession: Type.Optional(Type.String()), }); const EntryBase = Type.Object(Base); const MessageEntry = Type.Object({ ...Base, type: Type.Literal("message"), message: Type.Object({ role: Type.String(), content: Type.Optional(Content), command: Type.Optional(Type.String()), model: Type.Optional(Type.String()), errorMessage: Type.Optional(Type.String()), }), }); const SummaryEntry = Type.Object({ ...Base, type: Type.Union([Type.Literal("compaction"), Type.Literal("branch_summary")]), summary: Type.String(), }); const CustomMessageEntry = Type.Object({ ...Base, type: Type.Literal("custom_message"), customType: Type.String(), content: Content, display: Type.Literal(true), }); const InfoEntry = Type.Object({ ...Base, type: Type.Literal("session_info"), name: Type.String(), }); async function readHeader(file: string): Promise | undefined> { const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity }); try { for await (const line of lines) { const header: unknown = JSON.parse(line); return Check(Header, header) ? header : undefined; } } catch { return undefined; } finally { lines.close(); } return undefined; } /** IDs of a session and the sessions it was forked from, nearest first. */ export async function sessionLineage(id: string, parent?: string): Promise { const ids = [id]; for (let file = parent; file;) { const header = await readHeader(file); if (!header || ids.includes(header.id)) { break; } ids.push(header.id); file = header.parentSession; } return ids; } /** Finds a top-level session file by the ID in its `_.jsonl` name. */ export async function findSessionFile(directory: string, id: string): Promise { const suffix = `_${id}.jsonl`; const projects = await readdir(directory, { withFileTypes: true }).catch(() => []); for (const project of projects) { if (project.isDirectory()) { const names = await readdir(join(directory, project.name)).catch(() => []); const name = names.find( (candidate) => candidate.slice(candidate.indexOf("_")) === suffix, ); if (name) { return join(directory, project.name, name); } } } return undefined; } function contentParts( content: Static = "", ): Pick { if (Check(Type.String(), content)) { return { text: content, tools: [] }; } const text: string[] = []; const tools: string[] = []; const images: string[] = []; for (const part of content) { if (part.type === "text" && part.text) { text.push(part.text); } else if (part.type === "image") { if (part.data && IMAGE_TYPE.test(part.mimeType ?? "")) { images.push(`data:${part.mimeType};base64,${part.data}`); } else { text.push("[image]"); } } else if (part.type === "toolCall" && part.name) { const args = Object.entries(part.arguments ?? {}).map( ([key, value]) => `${key}=${Check(Type.String(), value) ? value : JSON.stringify(value)}`, ); tools.push(toolLine([part.name, ...args].join(" "))); } } return { text: text.join("\n\n"), tools, images }; } type Visible = Pick; function visible(entry: Static): Visible | undefined { if (Check(MessageEntry, entry)) { const { role, content, command, model, errorMessage } = entry.message; const parts = contentParts(content); if (role === "user") { return { kind: "user", label: "User", ...parts }; } if (role === "assistant") { const text = errorMessage ? `${parts.text}\n\n**Error:** ${errorMessage}` : parts.text; return text.trim() || parts.tools.length ? { kind: "assistant", label: model ? `Assistant · ${model}` : "Assistant", text, tools: parts.tools, } : undefined; } if (role === "bashExecution" && command) { return { kind: "note", label: "User bash", text: "", tools: [toolLine(command)] }; } return undefined; } if (Check(SummaryEntry, entry)) { return { kind: "summary", label: entry.type === "compaction" ? "Compaction summary" : "Branch summary", text: entry.summary, tools: [], }; } if (Check(CustomMessageEntry, entry)) { return { kind: "note", label: entry.customType, ...contentParts(entry.content), }; } return undefined; } // TODO: Render with Pi's HTML session export when Pi exposes it in its public API. /** * Reads the user-facing messages of a session file in file order. Reading is streamed so that * large sessions do not block Pi. Tool results, thinking, and extension state are omitted. */ export async function readTranscript(file: string): Promise { const transcript: Transcript = { id: "", anchors: [], items: [] }; const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity }); let previous: string | null = null; let branch: string | undefined; for await (const line of lines) { let entry: unknown; try { entry = JSON.parse(line); } catch { continue; } if (Check(Header, entry)) { transcript.id = entry.id; transcript.cwd = entry.cwd; continue; } if (!Check(EntryBase, entry)) { continue; } if (entry.parentId !== previous && entry.parentId !== null) { branch = entry.parentId; } previous = entry.id; if (Check(InfoEntry, entry)) { transcript.name = entry.name; } const item = visible(entry); if (item) { transcript.items.push({ ...item, id: entry.id, timestamp: entry.timestamp, anchors: [], branch, }); branch = undefined; } else { (transcript.items.at(-1)?.anchors ?? transcript.anchors).push(entry.id); } } return transcript; }