export interface TranscriptResult { text: string; messageCount: number; } type TranscriptRole = "user" | "assistant"; interface MessageEntryLike { type?: unknown; message?: { role?: unknown; content?: unknown; }; } export function formatTranscript( entries: readonly unknown[], ): TranscriptResult { const sections: string[] = []; let messageCount = 0; for (const entry of entries) { const message = getCopyableMessage(entry); if (!message) continue; const body = formatContent(message.content); if (!body.trim()) continue; sections.push(`${roleLabel(message.role)}:\n${body}`); messageCount += 1; } return { text: sections.join("\n\n"), messageCount, }; } function getCopyableMessage( entry: unknown, ): { role: TranscriptRole; content: unknown } | undefined { const maybeEntry = entry as MessageEntryLike; if (maybeEntry?.type !== "message") return undefined; const role = maybeEntry.message?.role; if (role !== "user" && role !== "assistant") return undefined; return { role, content: maybeEntry.message?.content, }; } function roleLabel(role: TranscriptRole): string { return role === "user" ? "User" : "Assistant"; } function formatContent(content: unknown): string { if (typeof content === "string") return content; if (!Array.isArray(content)) return ""; return content .map(formatContentBlock) .filter((line): line is string => line !== undefined && line.length > 0) .join("\n"); } function formatContentBlock(block: unknown): string | undefined { if (!block || typeof block !== "object") return undefined; const typedBlock = block as { type?: unknown; text?: unknown; mimeType?: unknown; mediaType?: unknown; source?: { mediaType?: unknown }; }; if (typedBlock.type === "text" && typeof typedBlock.text === "string") { return typedBlock.text; } if (typedBlock.type === "image") { return `[image: ${getImageMimeType(typedBlock)}]`; } // Skip thinking, tool calls, and unknown blocks. return undefined; } function getImageMimeType(block: { mimeType?: unknown; mediaType?: unknown; source?: { mediaType?: unknown }; }): string { const mimeType = block.mimeType ?? block.mediaType ?? block.source?.mediaType; return typeof mimeType === "string" && mimeType.length > 0 ? mimeType : "unknown"; }