pal-code 0.0.9 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/SYSTEM.md +3 -3
- package/bin/pal-code.js +37 -11
- package/package.json +7 -14
- package/packages/cli/README.md +2 -2
- package/packages/cli/src/commands/ext.ts +1 -1
- package/packages/cli/src/commands.ts +1 -1
- package/packages/cli/src/components/render-history.ts +2 -2
- package/packages/cli/src/config.ts +2 -2
- package/packages/cli/src/index.ts +7 -7
- package/packages/cli/src/overlays/key-input.ts +1 -1
- package/packages/cli/src/overlays/model-picker.ts +2 -2
- package/packages/cli/src/overlays/session-picker.ts +1 -1
- package/packages/cli/src/overlays/wizard.ts +1 -1
- package/packages/cli/src/state.ts +2 -2
- package/packages/cli/src/turn.ts +14 -9
- package/packages/cli/src/utils/permissions.ts +3 -3
- package/packages/core/src/agent/events.ts +0 -36
- package/packages/core/src/agent/fallback.ts +0 -344
- package/packages/core/src/agent/index.ts +0 -35
- package/packages/core/src/agent/roles.ts +0 -188
- package/packages/core/src/agent/run.ts +0 -713
- package/packages/core/src/agent/scope.ts +0 -34
- package/packages/core/src/agent/todos.ts +0 -66
- package/packages/core/src/compaction.ts +0 -243
- package/packages/core/src/config.ts +0 -387
- package/packages/core/src/extensions.ts +0 -178
- package/packages/core/src/index.ts +0 -157
- package/packages/core/src/logger.ts +0 -54
- package/packages/core/src/provider/auth.ts +0 -153
- package/packages/core/src/provider/complete.ts +0 -63
- package/packages/core/src/provider/index.ts +0 -6
- package/packages/core/src/provider/openrouter.ts +0 -304
- package/packages/core/src/provider/pick-model.ts +0 -43
- package/packages/core/src/provider/registry.ts +0 -222
- package/packages/core/src/provider/types.ts +0 -61
- package/packages/core/src/repo-map.ts +0 -177
- package/packages/core/src/session/index.ts +0 -2
- package/packages/core/src/session/store.ts +0 -677
- package/packages/core/src/session/types.ts +0 -72
- package/packages/core/src/snapshots.ts +0 -107
- package/packages/core/src/tools/definitions.ts +0 -365
- package/packages/core/src/tools/executor.ts +0 -1363
- package/packages/core/src/tools/index.ts +0 -5
- package/packages/core/src/tools/search.ts +0 -201
- package/scripts/postinstall.js +0 -121
- package/scripts/preinstall.js +0 -51
|
@@ -1,677 +0,0 @@
|
|
|
1
|
-
import {Database} from 'bun:sqlite';
|
|
2
|
-
import {mkdirSync} from 'node:fs';
|
|
3
|
-
import {homedir} from 'node:os';
|
|
4
|
-
import {dirname, join} from 'node:path';
|
|
5
|
-
import {randomUUID} from 'node:crypto';
|
|
6
|
-
import type {ConversationMessage as Message} from '../agent/run.js';
|
|
7
|
-
import type {
|
|
8
|
-
CompactionRecord,
|
|
9
|
-
MessageMeta,
|
|
10
|
-
Session,
|
|
11
|
-
SessionTokenomics,
|
|
12
|
-
StoredMessage,
|
|
13
|
-
} from './types.js';
|
|
14
|
-
|
|
15
|
-
const EMPTY_TOKENOMICS: SessionTokenomics = {
|
|
16
|
-
inputTokens: 0,
|
|
17
|
-
outputTokens: 0,
|
|
18
|
-
cachedTokens: 0,
|
|
19
|
-
cost: 0,
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Current on-disk schema version (PRAGMA user_version).
|
|
24
|
-
*
|
|
25
|
-
* v2 repairs `sessions.messages_backup`, which `RENAME COLUMN` left `NOT NULL`
|
|
26
|
-
* and so rejected every future INSERT — see `relaxMessagesBackup`.
|
|
27
|
-
*/
|
|
28
|
-
const SCHEMA_VERSION = 2;
|
|
29
|
-
|
|
30
|
-
/** Row shape of the `sessions` table. */
|
|
31
|
-
interface SessionRow {
|
|
32
|
-
id: string;
|
|
33
|
-
title: string | null;
|
|
34
|
-
input_tokens: number;
|
|
35
|
-
output_tokens: number;
|
|
36
|
-
cached_tokens: number;
|
|
37
|
-
cost: number;
|
|
38
|
-
created_at: number;
|
|
39
|
-
updated_at: number;
|
|
40
|
-
compacted_upto_seq: number;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** Row shape of the `messages` table. */
|
|
44
|
-
interface MessageRow {
|
|
45
|
-
id: string;
|
|
46
|
-
session_id: string;
|
|
47
|
-
seq: number;
|
|
48
|
-
role: string;
|
|
49
|
-
content: string;
|
|
50
|
-
tool_calls: string | null;
|
|
51
|
-
tool_call_id: string | null;
|
|
52
|
-
tool_name: string | null;
|
|
53
|
-
tool_status: string | null;
|
|
54
|
-
agent_role: string | null;
|
|
55
|
-
created_at: number;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Row shape of the `session_compactions` table. */
|
|
59
|
-
interface CompactionRow {
|
|
60
|
-
id: string;
|
|
61
|
-
session_id: string;
|
|
62
|
-
from_seq: number;
|
|
63
|
-
to_seq: number;
|
|
64
|
-
summary: string;
|
|
65
|
-
created_at: number;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* SQLite-backed session persistence.
|
|
70
|
-
*
|
|
71
|
-
* Storage is **normalized and append-only**: a session is a row in `sessions`,
|
|
72
|
-
* its history is one row per message in `messages`, and compaction is an
|
|
73
|
-
* additive event in `session_compactions`. Nothing rewrites or deletes message
|
|
74
|
-
* rows during normal operation, so the full transcript is always available for
|
|
75
|
-
* the UI to repaint while the model is fed only the tail after
|
|
76
|
-
* `sessions.compacted_upto_seq`.
|
|
77
|
-
*
|
|
78
|
-
* Uses Bun's built-in SQLite driver (`bun:sqlite`) for zero-dependency local
|
|
79
|
-
* storage.
|
|
80
|
-
*
|
|
81
|
-
* @example
|
|
82
|
-
* ```ts
|
|
83
|
-
* const store = new SessionStore();
|
|
84
|
-
* store.init();
|
|
85
|
-
* const session = store.create([{role: 'user', content: 'hi'}]);
|
|
86
|
-
* ```
|
|
87
|
-
*/
|
|
88
|
-
export class SessionStore {
|
|
89
|
-
private readonly db: Database;
|
|
90
|
-
private readonly dbPath: string;
|
|
91
|
-
|
|
92
|
-
constructor({dbPath}: {dbPath?: string} = {}) {
|
|
93
|
-
this.dbPath = dbPath ?? join(homedir(), '.pal', 'sessions.db');
|
|
94
|
-
|
|
95
|
-
// Ensure the parent directory exists before opening the database.
|
|
96
|
-
mkdirSync(dirname(this.dbPath), {recursive: true});
|
|
97
|
-
|
|
98
|
-
this.db = new Database(this.dbPath);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// -----------------------------------------------------------------------
|
|
102
|
-
// Lifecycle
|
|
103
|
-
// -----------------------------------------------------------------------
|
|
104
|
-
|
|
105
|
-
/** Create the schema if needed and run any pending migrations. */
|
|
106
|
-
init(): void {
|
|
107
|
-
// `sessions` is created WITHOUT the legacy `messages` column. Existing
|
|
108
|
-
// databases keep their old table; the migration step below gets rid of the
|
|
109
|
-
// column by renaming it.
|
|
110
|
-
this.db.exec(`
|
|
111
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
112
|
-
id TEXT PRIMARY KEY,
|
|
113
|
-
title TEXT,
|
|
114
|
-
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
115
|
-
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
116
|
-
cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
117
|
-
cost REAL NOT NULL DEFAULT 0,
|
|
118
|
-
created_at INTEGER NOT NULL,
|
|
119
|
-
updated_at INTEGER NOT NULL,
|
|
120
|
-
compacted_upto_seq INTEGER NOT NULL DEFAULT 0
|
|
121
|
-
);
|
|
122
|
-
|
|
123
|
-
CREATE TABLE IF NOT EXISTS messages (
|
|
124
|
-
id TEXT PRIMARY KEY,
|
|
125
|
-
session_id TEXT NOT NULL,
|
|
126
|
-
seq INTEGER NOT NULL,
|
|
127
|
-
role TEXT NOT NULL,
|
|
128
|
-
content TEXT NOT NULL,
|
|
129
|
-
tool_calls TEXT,
|
|
130
|
-
tool_call_id TEXT,
|
|
131
|
-
tool_name TEXT,
|
|
132
|
-
tool_status TEXT,
|
|
133
|
-
agent_role TEXT,
|
|
134
|
-
created_at INTEGER NOT NULL,
|
|
135
|
-
UNIQUE(session_id, seq)
|
|
136
|
-
);
|
|
137
|
-
CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(session_id, seq);
|
|
138
|
-
|
|
139
|
-
CREATE TABLE IF NOT EXISTS session_compactions (
|
|
140
|
-
id TEXT PRIMARY KEY,
|
|
141
|
-
session_id TEXT NOT NULL,
|
|
142
|
-
from_seq INTEGER NOT NULL,
|
|
143
|
-
to_seq INTEGER NOT NULL,
|
|
144
|
-
summary TEXT NOT NULL,
|
|
145
|
-
created_at INTEGER NOT NULL
|
|
146
|
-
);
|
|
147
|
-
CREATE INDEX IF NOT EXISTS idx_compactions_session ON session_compactions(session_id, to_seq);
|
|
148
|
-
`);
|
|
149
|
-
|
|
150
|
-
this.migrate();
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* Bring an existing database up to the current schema version.
|
|
155
|
-
*
|
|
156
|
-
* Runs inside a single transaction so a crash can't leave half the sessions
|
|
157
|
-
* exploded into rows. The legacy `messages` JSON column is renamed rather than
|
|
158
|
-
* dropped (some SQLite builds lack DROP COLUMN, and keeping it makes the
|
|
159
|
-
* migration auditable).
|
|
160
|
-
*/
|
|
161
|
-
private migrate(): void {
|
|
162
|
-
const version = (
|
|
163
|
-
this.db.query<{user_version: number}, []>('PRAGMA user_version').get() ?? {user_version: 0}
|
|
164
|
-
).user_version;
|
|
165
|
-
|
|
166
|
-
if (version >= SCHEMA_VERSION) return;
|
|
167
|
-
|
|
168
|
-
const columns = this.sessionColumns();
|
|
169
|
-
|
|
170
|
-
const hasLegacyMessages = columns.includes('messages');
|
|
171
|
-
|
|
172
|
-
const run = this.db.transaction(() => {
|
|
173
|
-
if (version < 1 && hasLegacyMessages) {
|
|
174
|
-
// Ensure additive columns from older schemas exist before copying.
|
|
175
|
-
for (const col of ['input_tokens', 'output_tokens', 'cached_tokens', 'cost']) {
|
|
176
|
-
if (!columns.includes(col)) {
|
|
177
|
-
const type = col === 'cost' ? 'REAL' : 'INTEGER';
|
|
178
|
-
this.db.exec(`ALTER TABLE sessions ADD COLUMN ${col} ${type} NOT NULL DEFAULT 0`);
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
if (!columns.includes('compacted_upto_seq')) {
|
|
182
|
-
this.db.exec(
|
|
183
|
-
'ALTER TABLE sessions ADD COLUMN compacted_upto_seq INTEGER NOT NULL DEFAULT 0',
|
|
184
|
-
);
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
const legacy = this.db
|
|
188
|
-
.query<{id: string; messages: string}, []>('SELECT id, messages FROM sessions')
|
|
189
|
-
.all();
|
|
190
|
-
|
|
191
|
-
for (const row of legacy) {
|
|
192
|
-
let parsed: unknown;
|
|
193
|
-
try {
|
|
194
|
-
parsed = JSON.parse(row.messages);
|
|
195
|
-
} catch {
|
|
196
|
-
console.warn(`sessions: skipping malformed history for session ${row.id}`);
|
|
197
|
-
continue;
|
|
198
|
-
}
|
|
199
|
-
if (!Array.isArray(parsed)) {
|
|
200
|
-
console.warn(`sessions: skipping non-array history for session ${row.id}`);
|
|
201
|
-
continue;
|
|
202
|
-
}
|
|
203
|
-
this.insertMessages(row.id, parsed as Message[], undefined, Date.now());
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Keep the old blob around for audit; drop it in a later release.
|
|
207
|
-
this.db.exec('ALTER TABLE sessions RENAME COLUMN messages TO messages_backup');
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// v1 → v2: relax the constraint the rename above carried over.
|
|
211
|
-
if (version < 2) this.relaxMessagesBackup();
|
|
212
|
-
|
|
213
|
-
this.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
|
|
214
|
-
});
|
|
215
|
-
|
|
216
|
-
run();
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
/** Names of the columns currently present on `sessions`. */
|
|
220
|
-
private sessionColumns(): string[] {
|
|
221
|
-
return this.db
|
|
222
|
-
.query<{name: string}, []>('PRAGMA table_info(sessions)')
|
|
223
|
-
.all()
|
|
224
|
-
.map((c) => c.name);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Drop the legacy `NOT NULL` from `sessions.messages_backup`.
|
|
229
|
-
*
|
|
230
|
-
* SQLite's `RENAME COLUMN` carries a column's constraints with it, so the
|
|
231
|
-
* renamed legacy blob kept its `NOT NULL` — and then rejected every
|
|
232
|
-
* `INSERT INTO sessions` that didn't mention it, with:
|
|
233
|
-
*
|
|
234
|
-
* NOT NULL constraint failed: sessions.messages_backup
|
|
235
|
-
*
|
|
236
|
-
* That broke session creation outright on any database migrated from the
|
|
237
|
-
* JSON-blob schema. SQLite cannot ALTER a column's constraints, so the table
|
|
238
|
-
* is rebuilt with the column nullable; the audit blob itself is preserved.
|
|
239
|
-
*
|
|
240
|
-
* `messages`/`session_compactions` declare no foreign key back to `sessions`,
|
|
241
|
-
* so dropping and recreating it leaves every message row untouched.
|
|
242
|
-
*/
|
|
243
|
-
private relaxMessagesBackup(): void {
|
|
244
|
-
const backup = this.db
|
|
245
|
-
.query<{name: string; notnull: number}, []>('PRAGMA table_info(sessions)')
|
|
246
|
-
.all()
|
|
247
|
-
.find((c) => c.name === 'messages_backup');
|
|
248
|
-
|
|
249
|
-
// Nothing to do when the column is absent (fresh DB) or already nullable.
|
|
250
|
-
if (!backup || backup.notnull === 0) return;
|
|
251
|
-
|
|
252
|
-
this.db.exec(`
|
|
253
|
-
CREATE TABLE sessions_rebuilt (
|
|
254
|
-
id TEXT PRIMARY KEY,
|
|
255
|
-
title TEXT,
|
|
256
|
-
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
257
|
-
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
258
|
-
cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
259
|
-
cost REAL NOT NULL DEFAULT 0,
|
|
260
|
-
created_at INTEGER NOT NULL,
|
|
261
|
-
updated_at INTEGER NOT NULL,
|
|
262
|
-
compacted_upto_seq INTEGER NOT NULL DEFAULT 0,
|
|
263
|
-
messages_backup TEXT
|
|
264
|
-
);
|
|
265
|
-
|
|
266
|
-
INSERT INTO sessions_rebuilt (
|
|
267
|
-
id, title, input_tokens, output_tokens, cached_tokens, cost,
|
|
268
|
-
created_at, updated_at, compacted_upto_seq, messages_backup
|
|
269
|
-
)
|
|
270
|
-
SELECT
|
|
271
|
-
id, title, input_tokens, output_tokens, cached_tokens, cost,
|
|
272
|
-
created_at, updated_at, compacted_upto_seq, messages_backup
|
|
273
|
-
FROM sessions;
|
|
274
|
-
|
|
275
|
-
DROP TABLE sessions;
|
|
276
|
-
ALTER TABLE sessions_rebuilt RENAME TO sessions;
|
|
277
|
-
`);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// -----------------------------------------------------------------------
|
|
281
|
-
// Sessions
|
|
282
|
-
// -----------------------------------------------------------------------
|
|
283
|
-
|
|
284
|
-
/** Persist a brand-new session and return it with its generated ID. */
|
|
285
|
-
create(
|
|
286
|
-
messages: Message[],
|
|
287
|
-
title?: string,
|
|
288
|
-
tokenomics?: SessionTokenomics,
|
|
289
|
-
meta?: MessageMeta[],
|
|
290
|
-
): Session {
|
|
291
|
-
const now = Date.now();
|
|
292
|
-
const tok = tokenomics ?? {...EMPTY_TOKENOMICS};
|
|
293
|
-
const id = randomUUID();
|
|
294
|
-
|
|
295
|
-
this.db.run(
|
|
296
|
-
'INSERT INTO sessions (id, title, input_tokens, output_tokens, cached_tokens, cost, created_at, updated_at, compacted_upto_seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)',
|
|
297
|
-
[id, title ?? null, tok.inputTokens, tok.outputTokens, tok.cachedTokens, tok.cost, now, now],
|
|
298
|
-
);
|
|
299
|
-
|
|
300
|
-
if (messages.length > 0) {
|
|
301
|
-
this.appendMessages(id, messages, meta);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
return {
|
|
305
|
-
id,
|
|
306
|
-
title,
|
|
307
|
-
messages,
|
|
308
|
-
createdAt: now,
|
|
309
|
-
updatedAt: now,
|
|
310
|
-
tokenomics: tok,
|
|
311
|
-
compactedUptoSeq: 0,
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
/**
|
|
316
|
-
* Reconcile a session's history and tokenomics.
|
|
317
|
-
*
|
|
318
|
-
* Kept for callers that still hand over the whole in-memory array. Under
|
|
319
|
-
* append-only storage this only inserts messages beyond what is already
|
|
320
|
-
* stored — it never rewrites or removes rows — so it is safe to call after
|
|
321
|
-
* every turn.
|
|
322
|
-
*/
|
|
323
|
-
update(
|
|
324
|
-
id: string,
|
|
325
|
-
messages: Message[],
|
|
326
|
-
tokenomics?: SessionTokenomics,
|
|
327
|
-
meta?: MessageMeta[],
|
|
328
|
-
): void {
|
|
329
|
-
const existing = this.db
|
|
330
|
-
.query<{n: number}, [string]>('SELECT COUNT(*) AS n FROM messages WHERE session_id = ?')
|
|
331
|
-
.get(id)?.n ?? 0;
|
|
332
|
-
|
|
333
|
-
if (messages.length > existing) {
|
|
334
|
-
// Derive metadata over the WHOLE conversation (not just the delta) so a
|
|
335
|
-
// tool result appended in this batch can still resolve the name from an
|
|
336
|
-
// assistant tool-call stored in an earlier batch. Caller-supplied meta
|
|
337
|
-
// (e.g. agent role) takes precedence via the store's merge below.
|
|
338
|
-
const allMeta = meta ?? deriveMessageMeta(messages);
|
|
339
|
-
this.appendMessages(id, messages.slice(existing), allMeta.slice(existing));
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
const tok = tokenomics;
|
|
343
|
-
if (tok) {
|
|
344
|
-
this.db.run(
|
|
345
|
-
'UPDATE sessions SET input_tokens = ?, output_tokens = ?, cached_tokens = ?, cost = ?, updated_at = ? WHERE id = ?',
|
|
346
|
-
[tok.inputTokens, tok.outputTokens, tok.cachedTokens, tok.cost, Date.now(), id],
|
|
347
|
-
);
|
|
348
|
-
} else {
|
|
349
|
-
this.db.run('UPDATE sessions SET updated_at = ? WHERE id = ?', [Date.now(), id]);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
/** Fetch a session by ID, or `null` if it doesn't exist. */
|
|
354
|
-
get(id: string): Session | null {
|
|
355
|
-
const row = this.db
|
|
356
|
-
.query<SessionRow, [string]>('SELECT * FROM sessions WHERE id = ?')
|
|
357
|
-
.get(id);
|
|
358
|
-
if (!row) return null;
|
|
359
|
-
|
|
360
|
-
const messages = this.getMessages(id).map(rowToMessage);
|
|
361
|
-
return {
|
|
362
|
-
id: row.id,
|
|
363
|
-
title: row.title ?? undefined,
|
|
364
|
-
messages,
|
|
365
|
-
createdAt: row.created_at,
|
|
366
|
-
updatedAt: row.updated_at,
|
|
367
|
-
tokenomics: {
|
|
368
|
-
inputTokens: row.input_tokens ?? 0,
|
|
369
|
-
outputTokens: row.output_tokens ?? 0,
|
|
370
|
-
cachedTokens: row.cached_tokens ?? 0,
|
|
371
|
-
cost: row.cost ?? 0,
|
|
372
|
-
},
|
|
373
|
-
compactedUptoSeq: row.compacted_upto_seq ?? 0,
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
/** List all sessions ordered by most-recently-updated first. */
|
|
378
|
-
list(): Session[] {
|
|
379
|
-
const rows = this.db
|
|
380
|
-
.query<SessionRow, []>('SELECT * FROM sessions ORDER BY updated_at DESC')
|
|
381
|
-
.all();
|
|
382
|
-
|
|
383
|
-
return rows.map((row) => ({
|
|
384
|
-
id: row.id,
|
|
385
|
-
title: row.title ?? undefined,
|
|
386
|
-
messages: this.getMessages(row.id).map(rowToMessage),
|
|
387
|
-
createdAt: row.created_at,
|
|
388
|
-
updatedAt: row.updated_at,
|
|
389
|
-
tokenomics: {
|
|
390
|
-
inputTokens: row.input_tokens ?? 0,
|
|
391
|
-
outputTokens: row.output_tokens ?? 0,
|
|
392
|
-
cachedTokens: row.cached_tokens ?? 0,
|
|
393
|
-
cost: row.cost ?? 0,
|
|
394
|
-
},
|
|
395
|
-
compactedUptoSeq: row.compacted_upto_seq ?? 0,
|
|
396
|
-
}));
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
/** Permanently delete a session and everything attached to it. */
|
|
400
|
-
delete(id: string): void {
|
|
401
|
-
const run = this.db.transaction(() => {
|
|
402
|
-
this.db.run('DELETE FROM messages WHERE session_id = ?', [id]);
|
|
403
|
-
this.db.run('DELETE FROM session_compactions WHERE session_id = ?', [id]);
|
|
404
|
-
this.db.run('DELETE FROM sessions WHERE id = ?', [id]);
|
|
405
|
-
});
|
|
406
|
-
run();
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/** Update a session's title without touching its history. */
|
|
410
|
-
updateTitle(id: string, title: string): void {
|
|
411
|
-
this.db.run('UPDATE sessions SET title = ?, updated_at = ? WHERE id = ?', [title, Date.now(), id]);
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
// -----------------------------------------------------------------------
|
|
415
|
-
// Messages
|
|
416
|
-
// -----------------------------------------------------------------------
|
|
417
|
-
|
|
418
|
-
/**
|
|
419
|
-
* Append messages to a session.
|
|
420
|
-
*
|
|
421
|
-
* The sequence is allocated ONCE per batch inside a single transaction, so
|
|
422
|
-
* ordering can't race and can't interleave with a concurrent append.
|
|
423
|
-
*/
|
|
424
|
-
appendMessages(sessionId: string, msgs: Message[], meta?: MessageMeta[]): number {
|
|
425
|
-
if (msgs.length === 0) return 0;
|
|
426
|
-
const now = Date.now();
|
|
427
|
-
let inserted = 0;
|
|
428
|
-
const run = this.db.transaction(() => {
|
|
429
|
-
inserted = this.insertMessages(sessionId, msgs, meta, now);
|
|
430
|
-
this.db.run('UPDATE sessions SET updated_at = ? WHERE id = ?', [now, sessionId]);
|
|
431
|
-
});
|
|
432
|
-
run();
|
|
433
|
-
return inserted;
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
/** Append a single message. */
|
|
437
|
-
appendMessage(sessionId: string, msg: Message, meta?: MessageMeta): number {
|
|
438
|
-
return this.appendMessages(sessionId, [msg], meta ? [meta] : undefined);
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
/**
|
|
442
|
-
* Shared insert routine. Assumes it is already inside a transaction when
|
|
443
|
-
* called from `appendMessages`; the migration calls it directly inside its own.
|
|
444
|
-
*/
|
|
445
|
-
private insertMessages(
|
|
446
|
-
sessionId: string,
|
|
447
|
-
msgs: Message[],
|
|
448
|
-
meta: MessageMeta[] | undefined,
|
|
449
|
-
createdAt: number,
|
|
450
|
-
): number {
|
|
451
|
-
const next =
|
|
452
|
-
(this.db
|
|
453
|
-
.query<{n: number | null}, [string]>(
|
|
454
|
-
'SELECT MAX(seq) AS n FROM messages WHERE session_id = ?',
|
|
455
|
-
)
|
|
456
|
-
.get(sessionId)?.n ?? 0) + 1;
|
|
457
|
-
|
|
458
|
-
let seq = next;
|
|
459
|
-
let count = 0;
|
|
460
|
-
// When the caller doesn't supply metadata, derive it from the messages
|
|
461
|
-
// themselves (tool names/status) so repaint has what it needs.
|
|
462
|
-
const derivedMeta = meta === undefined ? deriveMessageMeta(msgs) : [];
|
|
463
|
-
for (let i = 0; i < msgs.length; i++) {
|
|
464
|
-
const m = msgs[i];
|
|
465
|
-
const meta_i = meta?.[i] ?? (meta === undefined ? derivedMeta[i] : undefined);
|
|
466
|
-
const toolCalls =
|
|
467
|
-
m.role === 'assistant' && m.toolCalls?.length ? JSON.stringify(m.toolCalls) : null;
|
|
468
|
-
const toolCallId = m.role === 'tool' ? m.tool_call_id : null;
|
|
469
|
-
|
|
470
|
-
this.db.run(
|
|
471
|
-
'INSERT INTO messages (id, session_id, seq, role, content, tool_calls, tool_call_id, tool_name, tool_status, agent_role, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
|
472
|
-
[
|
|
473
|
-
randomUUID(),
|
|
474
|
-
sessionId,
|
|
475
|
-
seq,
|
|
476
|
-
m.role,
|
|
477
|
-
m.content,
|
|
478
|
-
toolCalls,
|
|
479
|
-
toolCallId,
|
|
480
|
-
meta_i?.toolName ?? null,
|
|
481
|
-
meta_i?.toolStatus ?? null,
|
|
482
|
-
meta_i?.agentRole ?? null,
|
|
483
|
-
createdAt,
|
|
484
|
-
],
|
|
485
|
-
);
|
|
486
|
-
seq++;
|
|
487
|
-
count++;
|
|
488
|
-
}
|
|
489
|
-
return count;
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
/** Load a session's message rows in seq order. */
|
|
493
|
-
getMessages(sessionId: string): StoredMessage[] {
|
|
494
|
-
const rows = this.db
|
|
495
|
-
.query<MessageRow, [string]>(
|
|
496
|
-
'SELECT * FROM messages WHERE session_id = ? ORDER BY seq ASC',
|
|
497
|
-
)
|
|
498
|
-
.all(sessionId);
|
|
499
|
-
|
|
500
|
-
return rows.map((r) => ({
|
|
501
|
-
id: r.id,
|
|
502
|
-
sessionId: r.session_id,
|
|
503
|
-
seq: r.seq,
|
|
504
|
-
role: r.role,
|
|
505
|
-
content: r.content,
|
|
506
|
-
toolCalls: r.tool_calls ? (JSON.parse(r.tool_calls) as StoredMessage['toolCalls']) : undefined,
|
|
507
|
-
toolCallId: r.tool_call_id ?? undefined,
|
|
508
|
-
meta: {
|
|
509
|
-
toolName: r.tool_name ?? undefined,
|
|
510
|
-
toolStatus: (r.tool_status as MessageMeta['toolStatus']) ?? undefined,
|
|
511
|
-
agentRole: r.agent_role ?? undefined,
|
|
512
|
-
},
|
|
513
|
-
createdAt: r.created_at,
|
|
514
|
-
}));
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
/**
|
|
518
|
-
* Drop every message from `seq` onward.
|
|
519
|
-
*
|
|
520
|
-
* This is a genuinely destructive recovery primitive (used when a turn errors
|
|
521
|
-
* out and must be rolled back). Normal turns never call it. If the removed
|
|
522
|
-
* range overlapped the compaction mark, the mark is reset to 0 so the model
|
|
523
|
-
* view can't point past the end of history.
|
|
524
|
-
*/
|
|
525
|
-
deleteMessagesFrom(sessionId: string, seq: number): number {
|
|
526
|
-
const removed =
|
|
527
|
-
this.db
|
|
528
|
-
.query<{n: number}, [string, number]>(
|
|
529
|
-
'SELECT COUNT(*) AS n FROM messages WHERE session_id = ? AND seq >= ?',
|
|
530
|
-
)
|
|
531
|
-
.get(sessionId, seq)?.n ?? 0;
|
|
532
|
-
|
|
533
|
-
const run = this.db.transaction(() => {
|
|
534
|
-
this.db.run('DELETE FROM messages WHERE session_id = ? AND seq >= ?', [sessionId, seq]);
|
|
535
|
-
this.db.run(
|
|
536
|
-
'UPDATE sessions SET compacted_upto_seq = 0, updated_at = ? WHERE id = ? AND compacted_upto_seq >= ?',
|
|
537
|
-
[Date.now(), sessionId, seq],
|
|
538
|
-
);
|
|
539
|
-
});
|
|
540
|
-
run();
|
|
541
|
-
|
|
542
|
-
return removed;
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
// -----------------------------------------------------------------------
|
|
546
|
-
// Compaction
|
|
547
|
-
// -----------------------------------------------------------------------
|
|
548
|
-
|
|
549
|
-
/**
|
|
550
|
-
* Record that `[fromSeq, toSeq]` was summarized, and raise the session's
|
|
551
|
-
* high-water mark. Messages themselves are never touched.
|
|
552
|
-
*/
|
|
553
|
-
recordCompaction(
|
|
554
|
-
sessionId: string,
|
|
555
|
-
fromSeq: number,
|
|
556
|
-
toSeq: number,
|
|
557
|
-
summary: string,
|
|
558
|
-
): CompactionRecord {
|
|
559
|
-
const now = Date.now();
|
|
560
|
-
const record: CompactionRecord = {
|
|
561
|
-
id: randomUUID(),
|
|
562
|
-
sessionId,
|
|
563
|
-
fromSeq,
|
|
564
|
-
toSeq,
|
|
565
|
-
summary,
|
|
566
|
-
createdAt: now,
|
|
567
|
-
};
|
|
568
|
-
|
|
569
|
-
const run = this.db.transaction(() => {
|
|
570
|
-
this.db.run(
|
|
571
|
-
'INSERT INTO session_compactions (id, session_id, from_seq, to_seq, summary, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
|
572
|
-
[record.id, sessionId, fromSeq, toSeq, summary, now],
|
|
573
|
-
);
|
|
574
|
-
this.db.run(
|
|
575
|
-
'UPDATE sessions SET compacted_upto_seq = MAX(compacted_upto_seq, ?), updated_at = ? WHERE id = ?',
|
|
576
|
-
[toSeq, now, sessionId],
|
|
577
|
-
);
|
|
578
|
-
});
|
|
579
|
-
run();
|
|
580
|
-
|
|
581
|
-
return record;
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
/** All compaction checkpoints for a session, oldest first. */
|
|
585
|
-
getCompactions(sessionId: string): CompactionRecord[] {
|
|
586
|
-
const rows = this.db
|
|
587
|
-
.query<CompactionRow, [string]>(
|
|
588
|
-
'SELECT * FROM session_compactions WHERE session_id = ? ORDER BY to_seq ASC',
|
|
589
|
-
)
|
|
590
|
-
.all(sessionId);
|
|
591
|
-
|
|
592
|
-
return rows.map(rowToCompaction);
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
/** The most recent compaction checkpoint, or `null`. */
|
|
596
|
-
getLatestCompaction(sessionId: string): CompactionRecord | null {
|
|
597
|
-
const row = this.db
|
|
598
|
-
.query<CompactionRow, [string]>(
|
|
599
|
-
'SELECT * FROM session_compactions WHERE session_id = ? ORDER BY to_seq DESC LIMIT 1',
|
|
600
|
-
)
|
|
601
|
-
.get(sessionId);
|
|
602
|
-
return row ? rowToCompaction(row) : null;
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
/** Highest seq already folded into a summary (0 = nothing compacted). */
|
|
606
|
-
getCompactedUpto(sessionId: string): number {
|
|
607
|
-
return (
|
|
608
|
-
this.db
|
|
609
|
-
.query<{n: number | null}, [string]>(
|
|
610
|
-
'SELECT compacted_upto_seq AS n FROM sessions WHERE id = ?',
|
|
611
|
-
)
|
|
612
|
-
.get(sessionId)?.n ?? 0
|
|
613
|
-
);
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// -----------------------------------------------------------------------
|
|
617
|
-
// Cleanup
|
|
618
|
-
// -----------------------------------------------------------------------
|
|
619
|
-
|
|
620
|
-
/** Close the underlying database connection. */
|
|
621
|
-
close(): void {
|
|
622
|
-
this.db.close();
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
// ---------------------------------------------------------------------------
|
|
627
|
-
// Helpers
|
|
628
|
-
// ---------------------------------------------------------------------------
|
|
629
|
-
|
|
630
|
-
function rowToCompaction(row: CompactionRow): CompactionRecord {
|
|
631
|
-
return {
|
|
632
|
-
id: row.id,
|
|
633
|
-
sessionId: row.session_id,
|
|
634
|
-
fromSeq: row.from_seq,
|
|
635
|
-
toSeq: row.to_seq,
|
|
636
|
-
summary: row.summary,
|
|
637
|
-
createdAt: row.created_at,
|
|
638
|
-
};
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
/** Convert a stored row back into the in-memory conversation message shape. */
|
|
642
|
-
function rowToMessage(row: StoredMessage): Message {
|
|
643
|
-
if (row.role === 'tool') {
|
|
644
|
-
return {role: 'tool', tool_call_id: row.toolCallId ?? '', content: row.content};
|
|
645
|
-
}
|
|
646
|
-
if (row.role === 'assistant') {
|
|
647
|
-
return row.toolCalls?.length
|
|
648
|
-
? {role: 'assistant', content: row.content, toolCalls: row.toolCalls}
|
|
649
|
-
: {role: 'assistant', content: row.content};
|
|
650
|
-
}
|
|
651
|
-
return {role: 'user', content: row.content};
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
/**
|
|
655
|
-
* Derive per-message UI metadata from a conversation.
|
|
656
|
-
*
|
|
657
|
-
* `tool_name` isn't carried on the tool result itself — it lives on the
|
|
658
|
-
* assistant `toolCalls` that requested it — so we correlate by call id. Call
|
|
659
|
-
* this at persist time so a resumed session can repaint tool blocks with their
|
|
660
|
-
* real names and status. Status is inferred from the conventional `Error:`
|
|
661
|
-
* prefix the tool executor uses; unknown results default to `ok`.
|
|
662
|
-
*/
|
|
663
|
-
export function deriveMessageMeta(messages: readonly Message[]): MessageMeta[] {
|
|
664
|
-
const nameByCallId = new Map<string, string>();
|
|
665
|
-
return messages.map((m) => {
|
|
666
|
-
if (m.role === 'assistant' && m.toolCalls?.length) {
|
|
667
|
-
for (const tc of m.toolCalls) nameByCallId.set(tc.id, tc.name);
|
|
668
|
-
return {};
|
|
669
|
-
}
|
|
670
|
-
if (m.role === 'tool') {
|
|
671
|
-
const name = nameByCallId.get(m.tool_call_id);
|
|
672
|
-
const isError = /^\s*error[:\s]/i.test(m.content ?? '');
|
|
673
|
-
return {toolName: name, toolStatus: isError ? 'error' : 'ok'};
|
|
674
|
-
}
|
|
675
|
-
return {};
|
|
676
|
-
});
|
|
677
|
-
}
|