xonecas.io
64875
Mc

mini-coder / commit a723083

refactor: clean up implementation patterns

xonecas2026-04-17 a723083b8919d574e3127e260687c07687f0fd59 parent 55b494c

17 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+1−0
@@ -90,6 +90,7 @@
9090 - UI/info messages may live in the persisted log and in `state.messages`, but they must stay marked as UI-only (`role: "ui"`, `turn = NULL`) and always be filtered out of model context.
9191 - Prompt context has explicit reload boundaries: AGENTS.md content, discovered skills, and plugin prompt suffixes are stable within a session and should refresh only at boundaries like `/new` or CWD change.
9292 - Tool safety truncation and UI `/verbose` preview are separate layers. Do not conflate them.
93+- Avoid accretive growth. When a file starts absorbing unrelated behavior, split it at a real seam instead of appending more helpers. Prefer explicit state ownership over module globals, shared helpers over copy-modify text/state logic, and typed boundaries over `Record<string, unknown>` plus downstream casts.
9394 - The plugin API is still in spec-alignment cleanup. Current repo reality is `tools` plus `toolHandlers`; treat that as temporary, not settled design.
9495 - Before 1.0, prefer correct/simple semantics over speculative compatibility shims, but call out intentional breaking changes.
9596 - TUI changes need real terminal validation in `tmux`; passing tests is not enough.
TODO.md+9−0
@@ -5,6 +5,15 @@ Don't keep completed items bloating the file, remove them before committing.
55 Keep the file structured and minimal.
66 The spec.md and code are the sources of truth, not this file, don't assume anything because it's documented here.
77
8+## Implementation-pattern cleanup plan
9+
10+- [x] Extract narrow shared helpers for repeated text-shaping/state-reset logic instead of copy-modify variants (`src/session.ts`, `src/ui.ts`, `src/ui/commands.ts`, `src/ui/status.ts`)
11+- [x] Reduce weakly-typed tool wiring by moving built-in tool argument validation/coercion to typed boundaries instead of `Record<string, unknown>` casts in dispatch (`src/index.ts`, `src/tools.ts`, `src/agent.ts`)
12+- [x] Move session-state reload/reset sequences behind focused helpers so command flows stop manually reassigning `messages`/`stats`/`contextTokens` in multiple places (`src/index.ts`, `src/ui/commands.ts`, `src/submit.ts`)
13+- [x] Replace module-global UI streaming/runtime state with explicit controller/runtime state objects where practical, starting with the streaming agent tail and related render/reset hooks (`src/ui.ts`, `src/ui/agent.ts`, `src/ui/conversation.ts`)
14+- [x] Split oversized mixed-concern modules along existing seams without changing behavior: shell command normalization/capture helpers, persisted-message parsing helpers, and UI runtime helpers (`src/tools.ts`, `src/session.ts`, `src/ui.ts`)
15+- [x] Verify the cleanup with targeted tests first, then full repo checks, and only mark this section complete after diff review (`src/*.test.ts`, `src/ui/*.test.ts`)
16+
817 ## Forge comparison follow-ups (high-value gaps, highest priority first)
918
1019 - [x] Add first-class todo tools plus prompt/UI integration so the agent can track and complete work explicitly instead of relying only on a `/tmp` file (`src/tools.ts`, `src/agent.ts`, `src/prompt.ts`, `src/ui/conversation.ts`)
src/index.test.ts+46−0
@@ -6,6 +6,7 @@ import { pathToFileURL } from "node:url";
66 import type { Model } from "@mariozechner/pi-ai";
77 import {
88 type AppState,
9+ buildToolList,
910 didOAuthCredentialsChange,
1011 discoverCustomProviders,
1112 getAvailableModels,
@@ -454,6 +455,51 @@ test("discoverCustomProviders skips providers that collide with built-in names",
454455 expect(result.warnings[0]).toContain("built-in");
455456 });
456457
458+// ---------------------------------------------------------------------------
459+// buildToolList
460+// ---------------------------------------------------------------------------
461+
462+test("buildToolList uses validated built-in handlers and gates readImage by model input", () => {
463+ const state = createTestState();
464+ try {
465+ const model: Model<string> = {
466+ id: "test-model",
467+ name: "test-model",
468+ api: "openai-completions",
469+ provider: "test-provider",
470+ baseUrl: "http://localhost:1234/v1",
471+ reasoning: false,
472+ input: ["text"],
473+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
474+ contextWindow: 8192,
475+ maxTokens: 4096,
476+ };
477+ state.model = model;
478+
479+ const textOnlyTools = buildToolList(state);
480+
481+ expect(textOnlyTools.tools.map((tool) => tool.name)).toEqual([
482+ "edit",
483+ "shell",
484+ "todoWrite",
485+ "todoRead",
486+ ]);
487+ expect(textOnlyTools.toolHandlers.has("readImage")).toBe(false);
488+ expect(() =>
489+ textOnlyTools.toolHandlers.get("todoWrite")!({}, state.cwd),
490+ ).toThrow(/Validation failed for tool "todoWrite"/);
491+
492+ state.model = { ...model, input: ["text", "image"] };
493+
494+ const visionTools = buildToolList(state);
495+
496+ expect(visionTools.tools.map((tool) => tool.name)).toContain("readImage");
497+ expect(visionTools.toolHandlers.has("readImage")).toBe(true);
498+ } finally {
499+ state.db.close();
500+ }
501+});
502+
457503 // ---------------------------------------------------------------------------
458504 // getAvailableModels with custom models
459505 // ---------------------------------------------------------------------------
src/index.ts+21−55
@@ -50,8 +50,7 @@ import {
5050 } from "./prompt.ts";
5151 import {
5252 appendMessage,
53- computeContextTokens,
54- computeStats,
53+ createConversationSnapshot,
5554 createSession,
5655 filterModelMessages,
5756 type loadMessages,
@@ -69,14 +68,14 @@ import {
6968 import { discoverSkills, type Skill } from "./skills.ts";
7069 import { DEFAULT_THEME, mergeThemes, type Theme } from "./theme.ts";
7170 import {
71+ createTodoReadToolHandler,
72+ createTodoWriteToolHandler,
7273 editTool,
73- executeEdit,
74- executeReadImage,
75- executeShell,
76- executeTodoRead,
77- executeTodoWrite,
74+ editToolHandler,
7875 readImageTool,
76+ readImageToolHandler,
7977 shellTool,
78+ shellToolHandler,
8079 todoReadTool,
8180 todoWriteTool,
8281 } from "./tools.ts";
@@ -359,26 +358,6 @@ function selectModel(
359358 // Tool wiring
360359 // ---------------------------------------------------------------------------
361360
362-/** Built-in tool handlers keyed by tool name. */
363-const BUILTIN_HANDLERS: Record<string, ToolHandler> = {
364- edit: (args, cwd) =>
365- executeEdit(
366- {
367- path: args.path as string,
368- oldText: args.oldText as string,
369- newText: args.newText as string,
370- },
371- cwd,
372- ),
373- shell: (args, cwd, signal, onUpdate) =>
374- executeShell({ command: args.command as string }, cwd, {
375- ...(signal ? { signal } : {}),
376- ...(onUpdate ? { onUpdate } : {}),
377- }),
378- readImage: (args, cwd) =>
379- executeReadImage({ path: args.path as string }, cwd),
380-};
381-
382361 /**
383362 * Build tool definitions and handler map for the current model.
384363 *
@@ -392,30 +371,16 @@ function buildTools(
392371 ): { tools: Tool[]; toolHandlers: Map<string, ToolHandler> } {
393372 const tools: Tool[] = [editTool, shellTool, todoWriteTool, todoReadTool];
394373 const toolHandlers = new Map<string, ToolHandler>([
395- [editTool.name, BUILTIN_HANDLERS.edit!],
396- [shellTool.name, BUILTIN_HANDLERS.shell!],
397- [
398- todoWriteTool.name,
399- (args) =>
400- executeTodoWrite(
401- {
402- todos: Array.isArray(args.todos)
403- ? (args.todos as Array<{
404- content: string;
405- status: "pending" | "in_progress" | "completed" | "cancelled";
406- }>)
407- : [],
408- },
409- messages,
410- ),
411- ],
412- [todoReadTool.name, () => executeTodoRead(messages)],
374+ [editTool.name, editToolHandler],
375+ [shellTool.name, shellToolHandler],
376+ [todoWriteTool.name, createTodoWriteToolHandler(messages)],
377+ [todoReadTool.name, createTodoReadToolHandler(messages)],
413378 ]);
414379
415380 // Conditionally register readImage for vision-capable models
416381 if (model.input.includes("image")) {
417382 tools.push(readImageTool);
418- toolHandlers.set(readImageTool.name, BUILTIN_HANDLERS.readImage!);
383+ toolHandlers.set(readImageTool.name, readImageToolHandler);
419384 }
420385
421386 // Add plugin tools
@@ -635,21 +600,22 @@ export async function init(): Promise<AppState> {
635600 // Open database. Sessions are created lazily on the first user message.
636601 const db = openDatabase(DB_PATH);
637602 const effort = startup.effort;
638- const messages: ReturnType<typeof loadMessages> = [];
639- const stats = computeStats(messages);
640- const contextTokens = computeContextTokens(messages);
641- const promptContext = await loadPromptContext(filterModelMessages(messages), {
642- cwd,
643- });
603+ const conversation = createConversationSnapshot();
604+ const promptContext = await loadPromptContext(
605+ filterModelMessages(conversation.messages),
606+ {
607+ cwd,
608+ },
609+ );
644610
645611 return {
646612 db,
647613 session: null,
648614 model,
649615 effort,
650- messages,
651- stats,
652- contextTokens,
616+ messages: conversation.messages,
617+ stats: conversation.stats,
618+ contextTokens: conversation.contextTokens,
653619 agentsMd: promptContext.agentsMd,
654620 skills: promptContext.skills,
655621 plugins: promptContext.plugins,
src/session-message.ts+390−0
@@ -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+}
src/session.test.ts+67−0
@@ -11,10 +11,13 @@ import type {
1111 import {
1212 addMessageToContextTokens,
1313 addMessageToStats,
14+ appendConversationMessage,
1415 appendMessage,
1516 appendPromptHistory,
17+ clearConversationState,
1618 computeContextTokens,
1719 computeStats,
20+ createConversationSnapshot,
1821 createSession,
1922 createUiMessage,
2023 createUiTodoMessage,
@@ -26,6 +29,7 @@ import {
2629 listSessions,
2730 loadMessages,
2831 openDatabase,
32+ replaceConversationState,
2933 truncatePromptHistory,
3034 truncateSessions,
3135 undoLastTurn,
@@ -708,6 +712,69 @@ describe("cumulative stats", () => {
708712 expect(stats.totalCost).toBe(0);
709713 });
710714
715+ test("createConversationSnapshot and replaceConversationState derive state from history", () => {
716+ const messages = [
717+ makeUser("hello"),
718+ makeAssistant("reply", {
719+ input: 120,
720+ output: 60,
721+ totalTokens: 180,
722+ cost: {
723+ input: 0.001,
724+ output: 0.002,
725+ cacheRead: 0,
726+ cacheWrite: 0,
727+ total: 0.003,
728+ },
729+ }),
730+ makeUiMessage("ignored in model context"),
731+ ];
732+ const snapshot = createConversationSnapshot(messages);
733+ const state = createConversationSnapshot();
734+
735+ expect(snapshot.messages).toBe(messages);
736+ expect(snapshot.stats).toEqual(computeStats(messages));
737+ expect(snapshot.contextTokens).toBe(computeContextTokens(messages));
738+
739+ replaceConversationState(state, messages);
740+
741+ expect(state).toEqual(snapshot);
742+ });
743+
744+ test("appendConversationMessage and clearConversationState keep derived state in sync", () => {
745+ const user = makeUser("hello world");
746+ const assistant = makeAssistant("done", {
747+ input: 150,
748+ output: 25,
749+ totalTokens: 175,
750+ cost: {
751+ input: 0.001,
752+ output: 0.001,
753+ cacheRead: 0,
754+ cacheWrite: 0,
755+ total: 0.002,
756+ },
757+ });
758+ const ui = makeUiMessage("note");
759+ const state = createConversationSnapshot();
760+
761+ appendConversationMessage(state, user);
762+ appendConversationMessage(state, assistant);
763+ appendConversationMessage(state, ui);
764+
765+ expect(state.messages).toEqual([user, assistant, ui]);
766+ expect(state.stats).toEqual(computeStats(state.messages));
767+ expect(state.contextTokens).toBe(computeContextTokens(state.messages));
768+
769+ clearConversationState(state);
770+
771+ expect(state).toEqual({
772+ messages: [],
773+ stats: { totalInput: 0, totalOutput: 0, totalCost: 0 },
774+ contextTokens: 0,
775+ });
776+ });
777+
711778 test("filterModelMessages excludes UI messages", () => {
712779 const ui = makeUiMessage("Help output");
713780 const todoUi = makeUiTodoMessage();
src/session.ts+102−396
@@ -10,14 +10,29 @@
1010 */
1111
1212 import { Database } from "bun:sqlite";
13-import type {
14- AssistantMessage,
15- Message,
16- ToolResultMessage,
17- UserMessage,
18-} from "@mariozechner/pi-ai";
13+import type { AssistantMessage, Message } from "@mariozechner/pi-ai";
14+import {
15+ getAssistantUsage,
16+ isUiMessage,
17+ type PersistedMessage,
18+ parsePersistedMessage,
19+ readFirstUserPreview,
20+ type UiInfoFormat,
21+ type UiInfoMessage,
22+ type UiMessage,
23+ type UiTodoMessage,
24+} from "./session-message.ts";
1925 import type { TodoItem } from "./tools.ts";
2026
27+export type {
28+ PersistedMessage,
29+ UiInfoFormat,
30+ UiInfoMessage,
31+ UiMessage,
32+ UiTodoMessage,
33+};
34+export { getAssistantUsage };
35+
2136 // ---------------------------------------------------------------------------
2237 // Types
2338 // ---------------------------------------------------------------------------
@@ -95,41 +110,6 @@ interface AppendPromptHistoryOpts {
95110 sessionId?: string;
96111 }
97112
98-/** Rich-text format hints supported by persisted UI info messages. */
99-export type UiInfoFormat = "markdown";
100-
101-/** A persisted UI-only info message shown in the conversation log. */
102-export interface UiInfoMessage {
103- /** Identifies this as an internal UI message. */
104- role: "ui";
105- /** UI message category for rendering and future behavior. */
106- kind: "info";
107- /** Display text shown in the conversation log. */
108- content: string;
109- /** Optional rich-text format hint for the content. */
110- format?: UiInfoFormat;
111- /** Unix timestamp in milliseconds. */
112- timestamp: number;
113-}
114-
115-/** A persisted UI-only todo snapshot shown in the conversation log. */
116-export interface UiTodoMessage {
117- /** Identifies this as an internal UI message. */
118- role: "ui";
119- /** UI message category for rendering and future behavior. */
120- kind: "todo";
121- /** Todo snapshot rendered in the conversation pane. */
122- todos: TodoItem[];
123- /** Unix timestamp in milliseconds. */
124- timestamp: number;
125-}
126-
127-/** A persisted UI-only message shown in the conversation log. */
128-export type UiMessage = UiInfoMessage | UiTodoMessage;
129-
130-/** Any message persisted in session history. */
131-export type PersistedMessage = Message | UiMessage;
132-
133113 /** Options for creating a new session. */
134114 interface CreateSessionOpts {
135115 /** Working directory to scope the session to. */
@@ -166,21 +146,6 @@ type MaxTurnRow = { max_turn: number | null };
166146 /** Row shape for `SELECT data` queries. */
167147 type DataRow = { data: string };
168148
169-const EMPTY_ASSISTANT_USAGE: AssistantMessage["usage"] = {
170- input: 0,
171- output: 0,
172- cacheRead: 0,
173- cacheWrite: 0,
174- totalTokens: 0,
175- cost: {
176- input: 0,
177- output: 0,
178- cacheRead: 0,
179- cacheWrite: 0,
180- total: 0,
181- },
182-};
183-
184149 const SQLITE_BUSY_TIMEOUT_MS = 1_000;
185150
186151 /** Row shape returned by `SELECT * FROM prompt_history`. */
@@ -338,240 +303,6 @@ export function getSession(db: Database, id: string): Session | null {
338303 };
339304 }
340305
341-/** Collapse preview text into a single readable line. */
342-function collapsePreviewText(text: string): string | null {
343- const collapsed = text.replace(/\s+/g, " ").trim();
344- return collapsed.length > 0 ? collapsed : null;
345-}
346-
347-function getMultipartUserPreview(
348- content: Extract<Message, { role: "user" }>["content"],
349-): string | null {
350- if (typeof content === "string") {
351- return collapsePreviewText(content);
352- }
353-
354- const text = content
355- .filter(
356- (block): block is Extract<(typeof content)[number], { type: "text" }> => {
357- return block.type === "text";
358- },
359- )
360- .map((block) => block.text)
361- .join(" ");
362-
363- return collapsePreviewText(text);
364-}
365-
366-function isTextContentBlock(
367- value: unknown,
368-): value is { type: "text"; text: string } {
369- const record = toRecord(value);
370- return record?.type === "text" && typeof record.text === "string";
371-}
372-
373-function isImageContentBlock(
374- value: unknown,
375-): value is { type: "image"; data: string; mimeType: string } {
376- const record = toRecord(value);
377- return (
378- record?.type === "image" &&
379- typeof record.data === "string" &&
380- typeof record.mimeType === "string"
381- );
382-}
383-
384-function isThinkingContentBlock(
385- value: unknown,
386-): value is Extract<AssistantMessage["content"][number], { type: "thinking" }> {
387- const record = toRecord(value);
388- return record?.type === "thinking" && typeof record.thinking === "string";
389-}
390-
391-function isToolCallContentBlock(
392- value: unknown,
393-): value is Extract<AssistantMessage["content"][number], { type: "toolCall" }> {
394- const record = toRecord(value);
395- return (
396- record?.type === "toolCall" &&
397- typeof record.id === "string" &&
398- typeof record.name === "string" &&
399- toRecord(record.arguments) !== null
400- );
401-}
402-
403-function isAssistantUsage(value: unknown): value is AssistantMessage["usage"] {
404- const usageRecord = toRecord(value);
405- const costRecord = toRecord(usageRecord?.cost);
406- return (
407- usageRecord !== null &&
408- costRecord !== null &&
409- readFiniteNumber(usageRecord, "input") !== null &&
410- readFiniteNumber(usageRecord, "output") !== null &&
411- readFiniteNumber(usageRecord, "cacheRead") !== null &&
412- readFiniteNumber(usageRecord, "cacheWrite") !== null &&
413- readFiniteNumber(usageRecord, "totalTokens") !== null &&
414- readFiniteNumber(costRecord, "input") !== null &&
415- readFiniteNumber(costRecord, "output") !== null &&
416- readFiniteNumber(costRecord, "cacheRead") !== null &&
417- readFiniteNumber(costRecord, "cacheWrite") !== null &&
418- readFiniteNumber(costRecord, "total") !== null
419- );
420-}
421-
422-function isStopReason(value: unknown): value is AssistantMessage["stopReason"] {
423- return (
424- value === "stop" ||
425- value === "length" ||
426- value === "toolUse" ||
427- value === "error" ||
428- value === "aborted"
429- );
430-}
431-
432-function isUserMessageRecord(value: unknown): value is UserMessage {
433- const record = toRecord(value);
434- if (!record || record.role !== "user") {
435- return false;
436- }
437-
438- return (
439- readFiniteNumber(record, "timestamp") !== null &&
440- (typeof record.content === "string" ||
441- (Array.isArray(record.content) &&
442- record.content.every(
443- (block) => isTextContentBlock(block) || isImageContentBlock(block),
444- )))
445- );
446-}
447-
448-function parseAssistantMessageRecord(value: unknown): AssistantMessage | null {
449- const record = toRecord(value);
450- if (!record || record.role !== "assistant") {
451- return null;
452- }
453-
454- const timestamp = readFiniteNumber(record, "timestamp");
455- if (
456- !Array.isArray(record.content) ||
457- !record.content.every(
458- (block) =>
459- isTextContentBlock(block) ||
460- isThinkingContentBlock(block) ||
461- isToolCallContentBlock(block),
462- ) ||
463- typeof record.api !== "string" ||
464- typeof record.provider !== "string" ||
465- typeof record.model !== "string" ||
466- !isStopReason(record.stopReason) ||
467- (record.errorMessage !== undefined &&
468- typeof record.errorMessage !== "string") ||
469- timestamp === null
470- ) {
471- return null;
472- }
473-
474- return {
475- role: "assistant",
476- content: record.content,
477- api: record.api,
478- provider: record.provider,
479- model: record.model,
480- usage: isAssistantUsage(record.usage)
481- ? record.usage
482- : structuredClone(EMPTY_ASSISTANT_USAGE),
483- stopReason: record.stopReason,
484- ...(typeof record.errorMessage === "string"
485- ? { errorMessage: record.errorMessage }
486- : {}),
487- timestamp,
488- };
489-}
490-
491-function isToolResultMessageRecord(value: unknown): value is ToolResultMessage {
492- const record = toRecord(value);
493- if (!record || record.role !== "toolResult") {
494- return false;
495- }
496-
497- return (
498- typeof record.toolCallId === "string" &&
499- typeof record.toolName === "string" &&
500- typeof record.isError === "boolean" &&
501- Array.isArray(record.content) &&
502- record.content.every(
503- (block) => isTextContentBlock(block) || isImageContentBlock(block),
504- ) &&
505- readFiniteNumber(record, "timestamp") !== null
506- );
507-}
508-
509-function isUiMessageRecord(value: unknown): value is UiMessage {
510- const record = toRecord(value);
511- if (!record || record.role !== "ui") {
512- return false;
513- }
514-
515- const timestamp = readFiniteNumber(record, "timestamp");
516- if (timestamp === null) {
517- return false;
518- }
519-
520- if (record.kind === "info") {
521- return (
522- typeof record.content === "string" &&
523- (record.format === undefined || record.format === "markdown")
524- );
525- }
526-
527- return (
528- record.kind === "todo" &&
529- Array.isArray(record.todos) &&
530- record.todos.every(
531- (todo) =>
532- typeof todo === "object" &&
533- todo !== null &&
534- typeof (todo as { content?: unknown }).content === "string" &&
535- ((todo as { status?: unknown }).status === "pending" ||
536- (todo as { status?: unknown }).status === "in_progress" ||
537- (todo as { status?: unknown }).status === "completed"),
538- )
539- );
540-}
541-
542-function parsePersistedMessage(data: string): PersistedMessage | null {
543- let parsed: unknown;
544- try {
Cut short: this commit's diff is over 1000 lines.
src/submit.ts+3−25
Cut short: this commit's diff is over 1000 lines.
src/text.ts+71−0
Cut short: this commit's diff is over 1000 lines.
src/tool-common.ts+91−0
Cut short: this commit's diff is over 1000 lines.
src/tool-shell.ts+869−0
Cut short: this commit's diff is over 1000 lines.
src/tools.test.ts+39−0
Cut short: this commit's diff is over 1000 lines.
src/tools.ts+162−995
Cut short: this commit's diff is over 1000 lines.
src/ui.ts+17−97
Cut short: this commit's diff is over 1000 lines.
src/ui/agent.ts+100−105
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.ts+13−39
Cut short: this commit's diff is over 1000 lines.
src/ui/runtime.ts+66−0
Cut short: this commit's diff is over 1000 lines.