@@ -0,0 +1,390 @@
1+/**
2+ * Persisted session-message types and parsing/validation helpers.
3+ *
4+ * @module
5+ */
6+
7+import type {
8+ AssistantMessage,
9+ Message,
10+ ToolResultMessage,
11+ UserMessage,
12+} from "@mariozechner/pi-ai";
13+import { collapseWhitespaceToNull, joinTextBlocks } from "./text.ts";
14+import type { TodoItem } from "./tools.ts";
15+
16+/** Rich-text format hints supported by persisted UI info messages. */
17+export type UiInfoFormat = "markdown";
18+
19+/** A persisted UI-only info message shown in the conversation log. */
20+export interface UiInfoMessage {
21+ /** Identifies this as an internal UI message. */
22+ role: "ui";
23+ /** UI message category for rendering and future behavior. */
24+ kind: "info";
25+ /** Display text shown in the conversation log. */
26+ content: string;
27+ /** Optional rich-text format hint for the content. */
28+ format?: UiInfoFormat;
29+ /** Unix timestamp in milliseconds. */
30+ timestamp: number;
31+}
32+
33+/** A persisted UI-only todo snapshot shown in the conversation log. */
34+export interface UiTodoMessage {
35+ /** Identifies this as an internal UI message. */
36+ role: "ui";
37+ /** UI message category for rendering and future behavior. */
38+ kind: "todo";
39+ /** Todo snapshot rendered in the conversation pane. */
40+ todos: TodoItem[];
41+ /** Unix timestamp in milliseconds. */
42+ timestamp: number;
43+}
44+
45+/** A persisted UI-only message shown in the conversation log. */
46+export type UiMessage = UiInfoMessage | UiTodoMessage;
47+
48+/** Any message persisted in session history. */
49+export type PersistedMessage = Message | UiMessage;
50+
51+const EMPTY_ASSISTANT_USAGE: AssistantMessage["usage"] = {
52+ input: 0,
53+ output: 0,
54+ cacheRead: 0,
55+ cacheWrite: 0,
56+ totalTokens: 0,
57+ cost: {
58+ input: 0,
59+ output: 0,
60+ cacheRead: 0,
61+ cacheWrite: 0,
62+ total: 0,
63+ },
64+};
65+
66+function getMultipartUserPreview(
67+ content: Extract<Message, { role: "user" }>["content"],
68+): string | null {
69+ if (typeof content === "string") {
70+ return collapseWhitespaceToNull(content);
71+ }
72+
73+ return collapseWhitespaceToNull(joinTextBlocks(content));
74+}
75+
76+function toRecord(value: unknown): Record<string, unknown> | null {
77+ return typeof value === "object" && value !== null && !Array.isArray(value)
78+ ? (value as Record<string, unknown>)
79+ : null;
80+}
81+
82+function readFiniteNumber(
83+ record: Record<string, unknown>,
84+ key: string,
85+): number | null {
86+ const value = record[key];
87+ return typeof value === "number" && Number.isFinite(value) ? value : null;
88+}
89+
90+function isTextContentBlock(
91+ value: unknown,
92+): value is { type: "text"; text: string } {
93+ const record = toRecord(value);
94+ return record?.type === "text" && typeof record.text === "string";
95+}
96+
97+function isImageContentBlock(
98+ value: unknown,
99+): value is { type: "image"; data: string; mimeType: string } {
100+ const record = toRecord(value);
101+ return (
102+ record?.type === "image" &&
103+ typeof record.data === "string" &&
104+ typeof record.mimeType === "string"
105+ );
106+}
107+
108+function isThinkingContentBlock(
109+ value: unknown,
110+): value is Extract<AssistantMessage["content"][number], { type: "thinking" }> {
111+ const record = toRecord(value);
112+ return record?.type === "thinking" && typeof record.thinking === "string";
113+}
114+
115+function isToolCallContentBlock(
116+ value: unknown,
117+): value is Extract<AssistantMessage["content"][number], { type: "toolCall" }> {
118+ const record = toRecord(value);
119+ return (
120+ record?.type === "toolCall" &&
121+ typeof record.id === "string" &&
122+ typeof record.name === "string" &&
123+ toRecord(record.arguments) !== null
124+ );
125+}
126+
127+function isAssistantUsage(value: unknown): value is AssistantMessage["usage"] {
128+ const usageRecord = toRecord(value);
129+ const costRecord = toRecord(usageRecord?.cost);
130+ return (
131+ usageRecord !== null &&
132+ costRecord !== null &&
133+ readFiniteNumber(usageRecord, "input") !== null &&
134+ readFiniteNumber(usageRecord, "output") !== null &&
135+ readFiniteNumber(usageRecord, "cacheRead") !== null &&
136+ readFiniteNumber(usageRecord, "cacheWrite") !== null &&
137+ readFiniteNumber(usageRecord, "totalTokens") !== null &&
138+ readFiniteNumber(costRecord, "input") !== null &&
139+ readFiniteNumber(costRecord, "output") !== null &&
140+ readFiniteNumber(costRecord, "cacheRead") !== null &&
141+ readFiniteNumber(costRecord, "cacheWrite") !== null &&
142+ readFiniteNumber(costRecord, "total") !== null
143+ );
144+}
145+
146+function isStopReason(value: unknown): value is AssistantMessage["stopReason"] {
147+ return (
148+ value === "stop" ||
149+ value === "length" ||
150+ value === "toolUse" ||
151+ value === "error" ||
152+ value === "aborted"
153+ );
154+}
155+
156+function isUserMessageRecord(value: unknown): value is UserMessage {
157+ const record = toRecord(value);
158+ if (!record || record.role !== "user") {
159+ return false;
160+ }
161+
162+ return (
163+ readFiniteNumber(record, "timestamp") !== null &&
164+ (typeof record.content === "string" ||
165+ (Array.isArray(record.content) &&
166+ record.content.every(
167+ (block) => isTextContentBlock(block) || isImageContentBlock(block),
168+ )))
169+ );
170+}
171+
172+function parseAssistantMessageRecord(value: unknown): AssistantMessage | null {
173+ const record = toRecord(value);
174+ if (!record || record.role !== "assistant") {
175+ return null;
176+ }
177+
178+ const timestamp = readFiniteNumber(record, "timestamp");
179+ if (
180+ !Array.isArray(record.content) ||
181+ !record.content.every(
182+ (block) =>
183+ isTextContentBlock(block) ||
184+ isThinkingContentBlock(block) ||
185+ isToolCallContentBlock(block),
186+ ) ||
187+ typeof record.api !== "string" ||
188+ typeof record.provider !== "string" ||
189+ typeof record.model !== "string" ||
190+ !isStopReason(record.stopReason) ||
191+ (record.errorMessage !== undefined &&
192+ typeof record.errorMessage !== "string") ||
193+ timestamp === null
194+ ) {
195+ return null;
196+ }
197+
198+ return {
199+ role: "assistant",
200+ content: record.content,
201+ api: record.api,
202+ provider: record.provider,
203+ model: record.model,
204+ usage: isAssistantUsage(record.usage)
205+ ? record.usage
206+ : structuredClone(EMPTY_ASSISTANT_USAGE),
207+ stopReason: record.stopReason,
208+ ...(typeof record.errorMessage === "string"
209+ ? { errorMessage: record.errorMessage }
210+ : {}),
211+ timestamp,
212+ };
213+}
214+
215+function isToolResultMessageRecord(value: unknown): value is ToolResultMessage {
216+ const record = toRecord(value);
217+ if (!record || record.role !== "toolResult") {
218+ return false;
219+ }
220+
221+ return (
222+ typeof record.toolCallId === "string" &&
223+ typeof record.toolName === "string" &&
224+ typeof record.isError === "boolean" &&
225+ Array.isArray(record.content) &&
226+ record.content.every(
227+ (block) => isTextContentBlock(block) || isImageContentBlock(block),
228+ ) &&
229+ readFiniteNumber(record, "timestamp") !== null
230+ );
231+}
232+
233+function isUiMessageRecord(value: unknown): value is UiMessage {
234+ const record = toRecord(value);
235+ if (!record || record.role !== "ui") {
236+ return false;
237+ }
238+
239+ const timestamp = readFiniteNumber(record, "timestamp");
240+ if (timestamp === null) {
241+ return false;
242+ }
243+
244+ if (record.kind === "info") {
245+ return (
246+ typeof record.content === "string" &&
247+ (record.format === undefined || record.format === "markdown")
248+ );
249+ }
250+
251+ return (
252+ record.kind === "todo" &&
253+ Array.isArray(record.todos) &&
254+ record.todos.every(
255+ (todo) =>
256+ typeof todo === "object" &&
257+ todo !== null &&
258+ typeof (todo as { content?: unknown }).content === "string" &&
259+ ((todo as { status?: unknown }).status === "pending" ||
260+ (todo as { status?: unknown }).status === "in_progress" ||
261+ (todo as { status?: unknown }).status === "completed"),
262+ )
263+ );
264+}
265+
266+/**
267+ * Parse one persisted message row from SQLite JSON.
268+ *
269+ * Invalid or unsupported rows return `null` so callers can skip corrupt data
270+ * without crashing session loading.
271+ *
272+ * @param data - Raw JSON-serialized message row.
273+ * @returns The validated persisted message, or `null` when invalid.
274+ */
275+export function parsePersistedMessage(data: string): PersistedMessage | null {
276+ let parsed: unknown;
277+ try {
278+ parsed = JSON.parse(data) as unknown;
279+ } catch {
280+ return null;
281+ }
282+
283+ if (
284+ isUserMessageRecord(parsed) ||
285+ isToolResultMessageRecord(parsed) ||
286+ isUiMessageRecord(parsed)
287+ ) {
288+ return parsed;
289+ }
290+
291+ return parseAssistantMessageRecord(parsed);
292+}
293+
294+/**
295+ * Read the first-user preview cached by the session-list query.
296+ *
297+ * @param messageData - Raw JSON from the first conversational message row.
298+ * @returns A collapsed single-line preview, or `null` when unavailable.
299+ */
300+export function readFirstUserPreview(
301+ messageData: string | null,
302+): string | null {
303+ if (!messageData) {
304+ return null;
305+ }
306+
307+ const message = parsePersistedMessage(messageData);
308+ if (!message || message.role !== "user") {
309+ return null;
310+ }
311+
312+ return getMultipartUserPreview(message.content);
313+}
314+
315+/**
316+ * Check whether a persisted message is a UI-only message.
317+ *
318+ * @param message - Message to inspect.
319+ * @returns `true` when the message is a {@link UiMessage}.
320+ */
321+export function isUiMessage(message: PersistedMessage): message is UiMessage {
322+ return message.role === "ui";
323+}
324+
325+/**
326+ * Return an assistant message's usage when the persisted shape is valid.
327+ *
328+ * Session rows are treated as untrusted at runtime because older builds or
329+ * external tooling may have stored assistant messages without a `usage`
330+ * payload. Invalid or missing usage is ignored instead of crashing session
331+ * loading or stats calculations.
332+ *
333+ * @param message - Message to inspect.
334+ * @returns The assistant usage payload, or `null` when it is missing/invalid.
335+ */
336+export function getAssistantUsage(
337+ message: PersistedMessage | Message,
338+): AssistantMessage["usage"] | null {
339+ if (message.role !== "assistant") {
340+ return null;
341+ }
342+
343+ const messageRecord = toRecord(message);
344+ const usageRecord = toRecord(messageRecord?.usage);
345+ const costRecord = toRecord(usageRecord?.cost);
346+ if (!usageRecord || !costRecord) {
347+ return null;
348+ }
349+
350+ const input = readFiniteNumber(usageRecord, "input");
351+ const output = readFiniteNumber(usageRecord, "output");
352+ const cacheRead = readFiniteNumber(usageRecord, "cacheRead");
353+ const cacheWrite = readFiniteNumber(usageRecord, "cacheWrite");
354+ const totalTokens = readFiniteNumber(usageRecord, "totalTokens");
355+ const costInput = readFiniteNumber(costRecord, "input");
356+ const costOutput = readFiniteNumber(costRecord, "output");
357+ const costCacheRead = readFiniteNumber(costRecord, "cacheRead");
358+ const costCacheWrite = readFiniteNumber(costRecord, "cacheWrite");
359+ const costTotal = readFiniteNumber(costRecord, "total");
360+
361+ if (
362+ input === null ||
363+ output === null ||
364+ cacheRead === null ||
365+ cacheWrite === null ||
366+ totalTokens === null ||
367+ costInput === null ||
368+ costOutput === null ||
369+ costCacheRead === null ||
370+ costCacheWrite === null ||
371+ costTotal === null
372+ ) {
373+ return null;
374+ }
375+
376+ return {
377+ input,
378+ output,
379+ cacheRead,
380+ cacheWrite,
381+ totalTokens,
382+ cost: {
383+ input: costInput,
384+ output: costOutput,
385+ cacheRead: costCacheRead,
386+ cacheWrite: costCacheWrite,
387+ total: costTotal,
388+ },
389+ };
390+}