xonecas.io
64875
Mc

mini-coder / commit 786c3ed

feat: add session persistence and modernize toolchain

- session.ts: SQLite schema, CRUD, turn numbering, undo, fork, stats
  with full JSDoc on all exports, interfaces, and fields
- session.test.ts: 20 tests against real in-memory bun:sqlite (no mocks)
- Add @mariozechner/pi-ai dependency
- Modernize toolchain config (cel-tui style):
  - biome: lint + organize imports only (formatter disabled)
  - prettier: owns all formatting (no conflicts with biome)
  - lefthook: 4 separate silent steps (check, format, test, typecheck)
  - package.json: split check/format/fix scripts
  - .prettierignore: simplified
- AGENTS.md: document bunx over npx, accurate script descriptions

xonecas2026-04-04 786c3ed7a0fcc6b797a9d744a312a7c8c6cff6e5 parent 2a33a2a

7 files changed

.prettierignore+2−6
@@ -1,7 +1,3 @@
1-node_modules/
2-dist/
3-*.db
4-*.db-shm
5-*.db-wal
1+node_modules
2+dist
63 bun.lock
7-package-lock.json
AGENTS.md+3−3
@@ -7,9 +7,9 @@
77
88 ## Repo
99
10-- Runtime: Bun. Use `bun run` for scripts, `bun test` for tests, `bun install` for deps.
11-- `bun run check` runs the pre-commit checks (prettier, typecheck, biome lint).
12-- `bun run format` fixes formatting.
10+- Runtime: Bun. Use `bun run` for scripts, `bun test` for tests, `bun install` for deps, `bunx` instead of `npx`.
11+- `bun run check` runs biome (lint + format + organize imports). `bun run format` checks prettier. `bun run typecheck` runs tsc. `bun test` runs tests. The lefthook pre-commit runs all four.
12+- `bun run check:fix` and `bun run format:fix` auto-fix issues.
1313 - App data directory: `~/.config/mini-coder/`.
1414 - Key dependency source code for reference:
1515 - pi-ai: `~/src/pi-mono/packages/ai/` — LLM provider SDK. See `src/types.ts` for core types, `src/stream.ts` for streaming API, `src/utils/oauth/` for OAuth, `src/providers/faux.ts` for test provider.
biome.json+7−45
@@ -1,60 +1,22 @@
11 {
2- "$schema": "https://biomejs.dev/schemas/2.4.6/schema.json",
3- "vcs": {
4- "enabled": true,
5- "clientKind": "git",
6- "useIgnoreFile": true
7- },
8- "formatter": {
9- "enabled": false
10- },
2+ "$schema": "https://biomejs.dev/schemas/2.4.10/schema.json",
113 "assist": {
12- "enabled": true,
134 "actions": {
145 "source": {
156 "organizeImports": "on"
167 }
178 }
189 },
10+ "formatter": {
11+ "enabled": false
12+ },
1913 "linter": {
2014 "enabled": true,
21- "domains": {
22- "test": "all"
23- },
2415 "rules": {
25- "recommended": true,
26- "style": {
27- "noNonNullAssertion": "error",
28- "noParameterAssign": "error",
29- "noShoutyConstants": "error",
30- "noEnum": "error",
31- "noNestedTernary": "error",
32- "useConst": "error",
33- "useCollapsedIf": "error",
34- "useThrowNewError": "error",
35- "useThrowOnlyError": "error",
36- "useNumberNamespace": "error",
37- "useAtIndex": "error"
38- },
39- "complexity": {
40- "noUselessCatch": "error",
41- "noUselessStringConcat": "error",
42- "noForEach": "error"
43- },
44- "suspicious": {
45- "noDebugger": "error",
46- "noExplicitAny": "error",
47- "noConsole": "off",
48- "noEvolvingTypes": "error"
49- },
50- "correctness": {
51- "noUnusedVariables": "error",
52- "noUnusedImports": "error",
53- "noUndeclaredVariables": "error"
54- }
16+ "recommended": true
5517 }
5618 },
57- "javascript": {
58- "globals": ["Bun", "Timer"]
19+ "files": {
20+ "includes": ["src/**/*.ts"]
5921 }
6022 }
lefthook.yml+8−1
@@ -1,4 +1,11 @@
11 pre-commit:
2+ parallel: false
23 commands:
34 check:
4- run: bun run check
5+ run: bun run --silent check
6+ format:
7+ run: bun run --silent format -- --log-level warn
8+ test:
9+ run: bun test --only-failures
10+ typecheck:
11+ run: bun run --silent typecheck
package.json+7−4
@@ -10,13 +10,16 @@
1010 "scripts": {
1111 "prepare": "lefthook install",
1212 "dev": "bun run src/index.ts",
13- "format": "prettier --write --log-level warn .",
14- "check": "bun run prettier -c . && bun run typecheck && bun run lint",
13+ "check": "biome check src",
14+ "check:fix": "biome check --write src",
15+ "format": "prettier --check .",
16+ "format:fix": "prettier --write .",
1517 "typecheck": "tsc --noEmit",
16- "lint": "biome check src",
1718 "test": "bun test"
1819 },
19- "dependencies": {},
20+ "dependencies": {
21+ "@mariozechner/pi-ai": "^0.65.0"
22+ },
2023 "devDependencies": {
2124 "@biomejs/biome": "^2.4.6",
2225 "@types/bun": "latest",
src/session.test.ts+381−0
@@ -0,0 +1,381 @@
1+import { describe, expect, test } from "bun:test";
2+import type {
3+ AssistantMessage,
4+ Message,
5+ ToolResultMessage,
6+ UserMessage,
7+} from "@mariozechner/pi-ai";
8+import {
9+ appendMessage,
10+ computeStats,
11+ createSession,
12+ deleteSession,
13+ forkSession,
14+ getSession,
15+ listSessions,
16+ loadMessages,
17+ openDatabase,
18+ undoLastTurn,
19+} from "./session.ts";
20+
21+// ---------------------------------------------------------------------------
22+// Helpers
23+// ---------------------------------------------------------------------------
24+
25+function makeUser(text: string): UserMessage {
26+ return { role: "user", content: text, timestamp: Date.now() };
27+}
28+
29+function makeAssistant(
30+ text: string,
31+ usage?: Partial<AssistantMessage["usage"]>,
32+): AssistantMessage {
33+ const defaultUsage: AssistantMessage["usage"] = {
34+ input: 100,
35+ output: 50,
36+ cacheRead: 0,
37+ cacheWrite: 0,
38+ totalTokens: 150,
39+ cost: {
40+ input: 0.001,
41+ output: 0.002,
42+ cacheRead: 0,
43+ cacheWrite: 0,
44+ total: 0.003,
45+ },
46+ };
47+ return {
48+ role: "assistant",
49+ content: [{ type: "text", text }],
50+ api: "anthropic-messages",
51+ provider: "anthropic",
52+ model: "claude-sonnet-4-20250514",
53+ usage: { ...defaultUsage, ...usage },
54+ stopReason: "stop",
55+ timestamp: Date.now(),
56+ };
57+}
58+
59+function makeToolResult(toolCallId: string, text: string): ToolResultMessage {
60+ return {
61+ role: "toolResult",
62+ toolCallId,
63+ toolName: "shell",
64+ content: [{ type: "text", text }],
65+ isError: false,
66+ timestamp: Date.now(),
67+ };
68+}
69+
70+// ---------------------------------------------------------------------------
71+// Tests
72+// ---------------------------------------------------------------------------
73+
74+describe("session persistence", () => {
75+ test("openDatabase returns a usable database", () => {
76+ const db = openDatabase(":memory:");
77+ expect(db).toBeDefined();
78+ db.close();
79+ });
80+
81+ test("createSession inserts a session record", () => {
82+ const db = openDatabase(":memory:");
83+ const session = createSession(db, {
84+ cwd: "/tmp/test",
85+ model: "anthropic/claude-sonnet-4-20250514",
86+ effort: "medium",
87+ });
88+ expect(session.id).toBeString();
89+ expect(session.cwd).toBe("/tmp/test");
90+ expect(session.model).toBe("anthropic/claude-sonnet-4-20250514");
91+ expect(session.effort).toBe("medium");
92+ expect(session.forkedFrom).toBeNull();
93+ expect(session.createdAt).toBeNumber();
94+ expect(session.updatedAt).toBe(session.createdAt);
95+ db.close();
96+ });
97+
98+ test("getSession retrieves a session by id", () => {
99+ const db = openDatabase(":memory:");
100+ const created = createSession(db, { cwd: "/tmp/test" });
101+ const loaded = getSession(db, created.id);
102+ expect(loaded).not.toBeNull();
103+ expect(loaded?.id).toBe(created.id);
104+ expect(loaded?.cwd).toBe("/tmp/test");
105+ db.close();
106+ });
107+
108+ test("getSession returns null for unknown id", () => {
109+ const db = openDatabase(":memory:");
110+ expect(getSession(db, "nonexistent")).toBeNull();
111+ db.close();
112+ });
113+
114+ test("listSessions returns sessions scoped to CWD, ordered by updated_at desc", () => {
115+ const db = openDatabase(":memory:");
116+ const s1 = createSession(db, { cwd: "/tmp/a" });
117+ const s2 = createSession(db, { cwd: "/tmp/a" });
118+ createSession(db, { cwd: "/tmp/b" }); // different cwd
119+
120+ // Touch s1 so it becomes more recent
121+ appendMessage(db, s1.id, makeUser("hello"));
122+
123+ const list = listSessions(db, "/tmp/a");
124+ expect(list).toHaveLength(2);
125+ // s1 was updated more recently (message appended)
126+ expect(list[0]?.id).toBe(s1.id);
127+ expect(list[1]?.id).toBe(s2.id);
128+ db.close();
129+ });
130+
131+ test("deleteSession removes session and cascades to messages", () => {
132+ const db = openDatabase(":memory:");
133+ const session = createSession(db, { cwd: "/tmp/test" });
134+ appendMessage(db, session.id, makeUser("hello"));
135+ deleteSession(db, session.id);
136+ expect(getSession(db, session.id)).toBeNull();
137+ expect(loadMessages(db, session.id)).toEqual([]);
138+ db.close();
139+ });
140+});
141+
142+describe("message persistence and turn numbering", () => {
143+ test("first user message gets turn 1", () => {
144+ const db = openDatabase(":memory:");
145+ const session = createSession(db, { cwd: "/tmp/test" });
146+ const turn = appendMessage(db, session.id, makeUser("hello"));
147+ expect(turn).toBe(1);
148+ db.close();
149+ });
150+
151+ test("subsequent messages in same loop share the turn", () => {
152+ const db = openDatabase(":memory:");
153+ const session = createSession(db, { cwd: "/tmp/test" });
154+
155+ const t1 = appendMessage(db, session.id, makeUser("do stuff"));
156+ expect(t1).toBe(1);
157+
158+ // Assistant response and tool results share the same turn
159+ const t2 = appendMessage(db, session.id, makeAssistant("on it"), t1);
160+ expect(t2).toBe(1);
161+
162+ const t3 = appendMessage(db, session.id, makeToolResult("tc1", "done"), t1);
163+ expect(t3).toBe(1);
164+ db.close();
165+ });
166+
167+ test("next user message increments the turn", () => {
168+ const db = openDatabase(":memory:");
169+ const session = createSession(db, { cwd: "/tmp/test" });
170+
171+ const t1 = appendMessage(db, session.id, makeUser("first"));
172+ appendMessage(db, session.id, makeAssistant("reply"), t1);
173+
174+ const t2 = appendMessage(db, session.id, makeUser("second"));
175+ expect(t2).toBe(2);
176+ db.close();
177+ });
178+
179+ test("loadMessages returns all messages in insertion order", () => {
180+ const db = openDatabase(":memory:");
181+ const session = createSession(db, { cwd: "/tmp/test" });
182+
183+ const t1 = appendMessage(db, session.id, makeUser("hello"));
184+ appendMessage(db, session.id, makeAssistant("hi"), t1);
185+
186+ const msgs = loadMessages(db, session.id);
187+ expect(msgs).toHaveLength(2);
188+ expect(msgs[0]?.role).toBe("user");
189+ expect(msgs[1]?.role).toBe("assistant");
190+ db.close();
191+ });
192+
193+ test("appendMessage updates session updated_at", () => {
194+ const db = openDatabase(":memory:");
195+ const session = createSession(db, { cwd: "/tmp/test" });
196+ const before = session.updatedAt;
197+
198+ // Small delay to ensure timestamp differs
199+ const msg = makeUser("hello");
200+ msg.timestamp = before + 100;
201+ appendMessage(db, session.id, msg);
202+
203+ const updated = getSession(db, session.id);
204+ expect(updated).not.toBeNull();
205+ expect(updated?.updatedAt).toBeGreaterThanOrEqual(before);
206+ db.close();
207+ });
208+});
209+
210+describe("undo", () => {
211+ test("undoLastTurn removes the highest turn", () => {
212+ const db = openDatabase(":memory:");
213+ const session = createSession(db, { cwd: "/tmp/test" });
214+
215+ const t1 = appendMessage(db, session.id, makeUser("first"));
216+ appendMessage(db, session.id, makeAssistant("reply1"), t1);
217+
218+ const t2 = appendMessage(db, session.id, makeUser("second"));
219+ appendMessage(db, session.id, makeAssistant("reply2"), t2);
220+
221+ const removed = undoLastTurn(db, session.id);
222+ expect(removed).toBe(true);
223+
224+ const msgs = loadMessages(db, session.id);
225+ expect(msgs).toHaveLength(2);
226+ expect((msgs[0] as UserMessage).content).toBe("first");
227+ expect(
228+ (
229+ (msgs[1] as AssistantMessage).content[0] as {
230+ type: "text";
231+ text: string;
232+ }
233+ ).text,
234+ ).toBe("reply1");
235+ db.close();
236+ });
237+
238+ test("undoLastTurn removes all messages in the turn (user + assistant + tool results)", () => {
239+ const db = openDatabase(":memory:");
240+ const session = createSession(db, { cwd: "/tmp/test" });
241+
242+ const t1 = appendMessage(db, session.id, makeUser("do it"));
243+ appendMessage(db, session.id, makeAssistant("calling tool"), t1);
244+ appendMessage(db, session.id, makeToolResult("tc1", "result"), t1);
245+ appendMessage(db, session.id, makeAssistant("done"), t1);
246+
247+ const removed = undoLastTurn(db, session.id);
248+ expect(removed).toBe(true);
249+
250+ const msgs = loadMessages(db, session.id);
251+ expect(msgs).toHaveLength(0);
252+ db.close();
253+ });
254+
255+ test("undoLastTurn returns false on empty session", () => {
256+ const db = openDatabase(":memory:");
257+ const session = createSession(db, { cwd: "/tmp/test" });
258+ const removed = undoLastTurn(db, session.id);
259+ expect(removed).toBe(false);
260+ db.close();
261+ });
262+});
263+
264+describe("fork", () => {
265+ test("forkSession copies all messages to a new session", () => {
266+ const db = openDatabase(":memory:");
267+ const original = createSession(db, {
268+ cwd: "/tmp/test",
269+ model: "m",
270+ effort: "high",
271+ });
272+
273+ const t1 = appendMessage(db, original.id, makeUser("hello"));
274+ appendMessage(db, original.id, makeAssistant("hi"), t1);
275+
276+ const forked = forkSession(db, original.id);
277+ expect(forked.id).not.toBe(original.id);
278+ expect(forked.cwd).toBe(original.cwd);
279+ expect(forked.model).toBe(original.model);
280+ expect(forked.effort).toBe(original.effort);
281+ expect(forked.forkedFrom).toBe(original.id);
282+
283+ const forkedMsgs = loadMessages(db, forked.id);
284+ expect(forkedMsgs).toHaveLength(2);
285+ expect(forkedMsgs[0]?.role).toBe("user");
286+ expect(forkedMsgs[1]?.role).toBe("assistant");
287+ db.close();
288+ });
289+
290+ test("fork preserves turn numbers", () => {
291+ const db = openDatabase(":memory:");
292+ const original = createSession(db, { cwd: "/tmp/test" });
293+
294+ const t1 = appendMessage(db, original.id, makeUser("one"));
295+ appendMessage(db, original.id, makeAssistant("r1"), t1);
296+ const t2 = appendMessage(db, original.id, makeUser("two"));
297+ appendMessage(db, original.id, makeAssistant("r2"), t2);
298+
299+ const forked = forkSession(db, original.id);
300+
301+ // Appending a new user message to the fork should get turn 3
302+ const t3 = appendMessage(db, forked.id, makeUser("three"));
303+ expect(t3).toBe(3);
304+ db.close();
305+ });
306+
307+ test("fork does not affect the original session", () => {
308+ const db = openDatabase(":memory:");
309+ const original = createSession(db, { cwd: "/tmp/test" });
310+
311+ const t1 = appendMessage(db, original.id, makeUser("hello"));
312+ appendMessage(db, original.id, makeAssistant("hi"), t1);
313+
314+ const forked = forkSession(db, original.id);
315+ appendMessage(db, forked.id, makeUser("diverging"));
316+
317+ const originalMsgs = loadMessages(db, original.id);
318+ expect(originalMsgs).toHaveLength(2);
319+
320+ const forkedMsgs = loadMessages(db, forked.id);
321+ expect(forkedMsgs).toHaveLength(3);
322+ db.close();
323+ });
324+});
325+
326+describe("cumulative stats", () => {
327+ test("computeStats sums usage from assistant messages", () => {
328+ const messages: Message[] = [
329+ makeUser("hello"),
330+ makeAssistant("hi", {
331+ input: 100,
332+ output: 50,
333+ totalTokens: 150,
334+ cost: {
335+ input: 0.001,
336+ output: 0.002,
337+ cacheRead: 0,
338+ cacheWrite: 0,
339+ total: 0.003,
340+ },
341+ }),
342+ makeUser("do more"),
343+ makeAssistant("done", {
344+ input: 200,
345+ output: 100,
346+ totalTokens: 300,
347+ cost: {
348+ input: 0.002,
349+ output: 0.004,
350+ cacheRead: 0,
351+ cacheWrite: 0,
352+ total: 0.006,
353+ },
354+ }),
355+ ];
356+
357+ const stats = computeStats(messages);
358+ expect(stats.totalInput).toBe(300);
359+ expect(stats.totalOutput).toBe(150);
360+ expect(stats.totalCost).toBeCloseTo(0.009);
361+ });
362+
363+ test("computeStats returns zeros for empty history", () => {
364+ const stats = computeStats([]);
365+ expect(stats.totalInput).toBe(0);
366+ expect(stats.totalOutput).toBe(0);
367+ expect(stats.totalCost).toBe(0);
368+ });
369+
370+ test("computeStats ignores non-assistant messages", () => {
371+ const messages: Message[] = [
372+ makeUser("hello"),
373+ makeToolResult("tc1", "result"),
374+ ];
375+
376+ const stats = computeStats(messages);
377+ expect(stats.totalInput).toBe(0);
378+ expect(stats.totalOutput).toBe(0);
379+ expect(stats.totalCost).toBe(0);
380+ });
381+});
src/session.ts+406−0
@@ -0,0 +1,406 @@
1+/**
2+ * Session persistence layer.
3+ *
4+ * Stores sessions and their message histories in a single SQLite database
5+ * via `bun:sqlite`. Messages are stored as JSON-serialized pi-ai {@link Message}
6+ * objects grouped by turn number. Cumulative token/cost stats are computed
7+ * from the message history rather than stored separately.
8+ *
9+ * @module
10+ */
11+
12+import { Database } from "bun:sqlite";
13+import type { AssistantMessage, Message } from "@mariozechner/pi-ai";
14+
15+// ---------------------------------------------------------------------------
16+// Types
17+// ---------------------------------------------------------------------------
18+
19+/**
20+ * A persisted session record.
21+ *
22+ * Represents a single conversation scoped to a working directory.
23+ * The `model` and `effort` fields reflect the values at session creation —
24+ * the user may switch models mid-session via `/model`, but the session
25+ * record is not updated (individual assistant messages carry their own model).
26+ */
27+export interface Session {
28+ /** Unique session identifier (UUID). */
29+ id: string;
30+ /** Working directory the session is scoped to. */
31+ cwd: string;
32+ /** Provider/model string at creation time, e.g. `"anthropic/claude-sonnet-4-20250514"`. */
33+ model: string | null;
34+ /** Thinking effort level at creation time. */
35+ effort: string | null;
36+ /** ID of the session this was forked from, or `null` if original. */
37+ forkedFrom: string | null;
38+ /** Unix timestamp in milliseconds when the session was created. */
39+ createdAt: number;
40+ /** Unix timestamp in milliseconds, updated on each new message. */
41+ updatedAt: number;
42+}
43+
44+/**
45+ * Cumulative token and cost statistics for a session.
46+ *
47+ * Computed by summing `usage` fields from all {@link AssistantMessage}s
48+ * in the session's history. Not stored — derived on load and maintained
49+ * in-memory during the session.
50+ */
51+export interface SessionStats {
52+ /** Total input tokens across all assistant messages. */
53+ totalInput: number;
54+ /** Total output tokens across all assistant messages. */
55+ totalOutput: number;
56+ /** Total cost in dollars across all assistant messages. */
57+ totalCost: number;
58+}
59+
60+/** Options for creating a new session. */
61+interface CreateSessionOpts {
62+ /** Working directory to scope the session to. */
63+ cwd: string;
64+ /** Provider/model identifier, e.g. `"anthropic/claude-sonnet-4-20250514"`. */
65+ model?: string;
66+ /** Thinking effort level, e.g. `"medium"`. */
67+ effort?: string;
68+}
69+
70+// ---------------------------------------------------------------------------
71+// Internal row types (map directly to SQLite column names)
72+// ---------------------------------------------------------------------------
73+
74+/** Row shape returned by `SELECT * FROM sessions`. */
75+type SessionRow = {
76+ id: string;
77+ cwd: string;
78+ model: string | null;
79+ effort: string | null;
80+ forked_from: string | null;
81+ created_at: number;
82+ updated_at: number;
83+};
84+
85+/** Row shape for `SELECT MAX(turn)` queries. */
86+type MaxTurnRow = { max_turn: number | null };
87+
88+/** Row shape for `SELECT data` queries. */
89+type DataRow = { data: string };
90+
91+// ---------------------------------------------------------------------------
92+// SQL
93+// ---------------------------------------------------------------------------
94+
95+const SQL = {
96+ listSessions: "SELECT * FROM sessions WHERE cwd = ? ORDER BY updated_at DESC",
97+ maxTurn: "SELECT MAX(turn) as max_turn FROM messages WHERE session_id = ?",
98+ loadMessages: "SELECT data FROM messages WHERE session_id = ? ORDER BY id",
99+} as const;
100+
101+const SCHEMA = `
102+CREATE TABLE IF NOT EXISTS sessions (
103+ id TEXT PRIMARY KEY,
104+ cwd TEXT NOT NULL,
105+ model TEXT,
106+ effort TEXT,
107+ forked_from TEXT,
108+ created_at INTEGER NOT NULL,
109+ updated_at INTEGER NOT NULL
110+);
111+
112+CREATE INDEX IF NOT EXISTS idx_sessions_cwd ON sessions(cwd);
113+
114+CREATE TABLE IF NOT EXISTS messages (
115+ id INTEGER PRIMARY KEY AUTOINCREMENT,
116+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
117+ turn INTEGER NOT NULL,
118+ data TEXT NOT NULL,
119+ created_at INTEGER NOT NULL
120+);
121+
122+CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, turn);
123+`;
124+
125+// ---------------------------------------------------------------------------
126+// Database
127+// ---------------------------------------------------------------------------
128+
129+/**
130+ * Open (or create) the SQLite database and ensure the schema exists.
131+ *
132+ * Enables WAL journal mode for concurrent read performance and foreign
133+ * keys for cascade deletes. Pass `":memory:"` for an in-memory database
134+ * (useful in tests).
135+ *
136+ * @param path - File path for the database, or `":memory:"` for in-memory.
137+ * @returns An open {@link Database} handle. The caller is responsible for
138+ * closing it when done.
139+ *
140+ * @example
141+ * ```ts
142+ * const db = openDatabase("~/.config/mini-coder/mini-coder.db");
143+ * // ... use db ...
144+ * db.close();
145+ * ```
146+ */
147+export function openDatabase(path: string): Database {
148+ const db = new Database(path);
149+ db.run("PRAGMA journal_mode = WAL");
150+ db.run("PRAGMA foreign_keys = ON");
151+ db.exec(SCHEMA);
152+ return db;
153+}
154+
155+// ---------------------------------------------------------------------------
156+// Session CRUD
157+// ---------------------------------------------------------------------------
158+
159+function generateId(): string {
160+ return crypto.randomUUID();
161+}
162+
163+/**
164+ * Create a new session record.
165+ *
166+ * @param db - Open database handle.
167+ * @param opts - Session options (cwd is required; model and effort are optional).
168+ * @returns The newly created {@link Session}.
169+ */
170+export function createSession(db: Database, opts: CreateSessionOpts): Session {
171+ const id = generateId();
172+ const now = Date.now();
173+ db.run(
174+ "INSERT INTO sessions (id, cwd, model, effort, forked_from, created_at, updated_at) VALUES (?, ?, ?, ?, NULL, ?, ?)",
175+ [id, opts.cwd, opts.model ?? null, opts.effort ?? null, now, now],
176+ );
177+ return {
178+ id,
179+ cwd: opts.cwd,
180+ model: opts.model ?? null,
181+ effort: opts.effort ?? null,
182+ forkedFrom: null,
183+ createdAt: now,
184+ updatedAt: now,
185+ };
186+}
187+
188+/**
189+ * Retrieve a session by its ID.
190+ *
191+ * @param db - Open database handle.
192+ * @param id - The session UUID.
193+ * @returns The {@link Session}, or `null` if not found.
194+ */
195+export function getSession(db: Database, id: string): Session | null {
196+ const row = db
197+ .query<SessionRow, [string]>("SELECT * FROM sessions WHERE id = ?")
198+ .get(id);
199+ if (!row) return null;
200+ return {
201+ id: row.id,
202+ cwd: row.cwd,
203+ model: row.model,
204+ effort: row.effort,
205+ forkedFrom: row.forked_from,
206+ createdAt: row.created_at,
207+ updatedAt: row.updated_at,
208+ };
209+}
210+
211+/**
212+ * List sessions for a working directory, most recently updated first.
213+ *
214+ * @param db - Open database handle.
215+ * @param cwd - Working directory to filter by.
216+ * @returns An array of {@link Session} records ordered by `updatedAt` descending.
217+ */
218+export function listSessions(db: Database, cwd: string): Session[] {
219+ const rows = db.query<SessionRow, [string]>(SQL.listSessions).all(cwd);
220+ return rows.map((row) => ({
221+ id: row.id,
222+ cwd: row.cwd,
223+ model: row.model,
224+ effort: row.effort,
225+ forkedFrom: row.forked_from,
226+ createdAt: row.created_at,
227+ updatedAt: row.updated_at,
228+ }));
229+}
230+
231+/**
232+ * Delete a session and all its messages (via foreign key cascade).
233+ *
234+ * @param db - Open database handle.
235+ * @param id - The session UUID to delete.
236+ */
237+export function deleteSession(db: Database, id: string): void {
238+ db.run("DELETE FROM sessions WHERE id = ?", [id]);
239+}
240+
241+// ---------------------------------------------------------------------------
242+// Messages
243+// ---------------------------------------------------------------------------
244+
245+/**
246+ * Append a message to a session's history.
247+ *
248+ * Turn numbering rules:
249+ * - When `turn` is **omitted**, a new turn is started with `MAX(turn) + 1`
250+ * (or `1` for the first message). This is used for user messages.
251+ * - When `turn` is **provided**, the message joins that existing turn.
252+ * This is used for assistant and tool-result messages that belong to
253+ * the same agent loop as the initiating user message.
254+ *
255+ * Also updates the session's `updatedAt` timestamp.
256+ *
257+ * @param db - Open database handle.
258+ * @param sessionId - The session to append to.
259+ * @param message - A pi-ai {@link Message} (UserMessage, AssistantMessage, or ToolResultMessage).
260+ * @param turn - Explicit turn number to join. Omit to start a new turn.
261+ * @returns The turn number the message was stored with.
262+ */
263+export function appendMessage(
264+ db: Database,
265+ sessionId: string,
266+ message: Message,
267+ turn?: number,
268+): number {
269+ const now = Date.now();
270+
271+ let effectiveTurn: number;
272+ if (turn !== undefined) {
273+ effectiveTurn = turn;
274+ } else {
275+ const row = db.query<MaxTurnRow, [string]>(SQL.maxTurn).get(sessionId);
276+ effectiveTurn = (row?.max_turn ?? 0) + 1;
277+ }
278+
279+ db.run(
280+ "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
281+ [sessionId, effectiveTurn, JSON.stringify(message), now],
282+ );
283+ db.run("UPDATE sessions SET updated_at = ? WHERE id = ?", [now, sessionId]);
284+
285+ return effectiveTurn;
286+}
287+
288+/**
289+ * Load all messages for a session in insertion order.
290+ *
291+ * Messages are deserialized from their JSON representation back into
292+ * pi-ai {@link Message} objects. The ordering matches the original
293+ * append order (by autoincrement `id`), preserving the conversation flow.
294+ *
295+ * @param db - Open database handle.
296+ * @param sessionId - The session to load messages for.
297+ * @returns An array of {@link Message} objects, empty if the session has
298+ * no messages or does not exist.
299+ */
300+export function loadMessages(db: Database, sessionId: string): Message[] {
301+ const rows = db.query<DataRow, [string]>(SQL.loadMessages).all(sessionId);
302+ return rows.map((row) => JSON.parse(row.data) as Message);
303+}
304+
305+// ---------------------------------------------------------------------------
306+// Undo
307+// ---------------------------------------------------------------------------
308+
309+/**
310+ * Remove the last turn from a session's history.
311+ *
312+ * Deletes **all** messages with the highest turn number — the user message
313+ * and every assistant/tool-result message that followed in the same agent
314+ * loop. This is a context-only operation; filesystem changes are not reverted.
315+ *
316+ * @param db - Open database handle.
317+ * @param sessionId - The session to undo in.
318+ * @returns `true` if a turn was removed, `false` if the session had no messages.
319+ */
320+export function undoLastTurn(db: Database, sessionId: string): boolean {
321+ const row = db.query<MaxTurnRow, [string]>(SQL.maxTurn).get(sessionId);
322+ if (!row?.max_turn) return false;
323+
324+ db.run("DELETE FROM messages WHERE session_id = ? AND turn = ?", [
325+ sessionId,
326+ row.max_turn,
327+ ]);
328+ return true;
329+}
330+
331+// ---------------------------------------------------------------------------
332+// Fork
333+// ---------------------------------------------------------------------------
334+
335+/**
336+ * Fork a session into a new independent copy.
337+ *
338+ * Creates a new session with the same `cwd`, `model`, and `effort` as the
339+ * source, then copies all messages preserving their turn numbers. The new
340+ * session's `forkedFrom` field points back to the source. The original
341+ * session is not modified.
342+ *
343+ * @param db - Open database handle.
344+ * @param sourceId - The session to fork from.
345+ * @returns The newly created {@link Session}.
346+ * @throws If the source session does not exist.
347+ */
348+export function forkSession(db: Database, sourceId: string): Session {
349+ const source = getSession(db, sourceId);
350+ if (!source) throw new Error(`Session not found: ${sourceId}`);
351+
352+ const id = generateId();
353+ const now = Date.now();
354+
355+ db.run(
356+ "INSERT INTO sessions (id, cwd, model, effort, forked_from, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
357+ [id, source.cwd, source.model, source.effort, sourceId, now, now],
358+ );
359+
360+ db.run(
361+ "INSERT INTO messages (session_id, turn, data, created_at) SELECT ?, turn, data, created_at FROM messages WHERE session_id = ? ORDER BY id",
362+ [id, sourceId],
363+ );
364+
365+ return {
366+ id,
367+ cwd: source.cwd,
368+ model: source.model,
369+ effort: source.effort,
370+ forkedFrom: sourceId,
371+ createdAt: now,
372+ updatedAt: now,
373+ };
374+}
375+
376+// ---------------------------------------------------------------------------
377+// Stats
378+// ---------------------------------------------------------------------------
379+
380+/**
381+ * Compute cumulative token and cost statistics from a message history.
382+ *
383+ * Iterates over the messages, summing `usage` fields from assistant messages
384+ * only (user and tool-result messages do not carry usage data). This is
385+ * designed to be called once on session load, with the result maintained
386+ * in-memory via a running accumulator during the session.
387+ *
388+ * @param messages - The full message history for a session.
389+ * @returns Aggregated {@link SessionStats}.
390+ */
391+export function computeStats(messages: Message[]): SessionStats {
392+ let totalInput = 0;
393+ let totalOutput = 0;
394+ let totalCost = 0;
395+
396+ for (const msg of messages) {
397+ if (msg.role === "assistant") {
398+ const am = msg as AssistantMessage;
399+ totalInput += am.usage.input;
400+ totalOutput += am.usage.output;
401+ totalCost += am.usage.cost.total;
402+ }
403+ }
404+
405+ return { totalInput, totalOutput, totalCost };
406+}