@qlairoslabs/acp-client 0.7.3 → 0.8.0

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.
Files changed (58) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +474 -19
  3. package/package.json +6 -1
  4. package/src/agent-adapter-registry.ts +66 -0
  5. package/src/agent-conversation-continuation.ts +121 -0
  6. package/src/agent-conversation-contracts.ts +279 -0
  7. package/src/agent-conversation-errors.ts +31 -0
  8. package/src/agent-conversation-owner.ts +55 -0
  9. package/src/agent-conversation-presentation.ts +217 -0
  10. package/src/agent-conversation-queue.ts +44 -0
  11. package/src/agent-conversation.ts +41 -0
  12. package/src/agent-ids.ts +50 -0
  13. package/src/agent-session.ts +1022 -682
  14. package/src/agent.ts +1175 -0
  15. package/src/audit/config.ts +186 -0
  16. package/src/audit/contracts.ts +59 -0
  17. package/src/audit/index.ts +50 -0
  18. package/src/audit/projection.ts +125 -0
  19. package/src/audit/reader.ts +371 -0
  20. package/src/audit/runtime.ts +1060 -0
  21. package/src/checkpointing/config.ts +91 -0
  22. package/src/checkpointing/contracts.ts +45 -0
  23. package/src/checkpointing/coordinator.ts +100 -0
  24. package/src/checkpointing/ids.ts +5 -0
  25. package/src/checkpointing/index.ts +6 -0
  26. package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
  27. package/src/checkpointing/recovery.ts +114 -0
  28. package/src/checkpointing/strategy.ts +139 -0
  29. package/src/controller.ts +37 -5
  30. package/src/identity.ts +62 -0
  31. package/src/index.ts +121 -0
  32. package/src/internal-inference/config.ts +68 -0
  33. package/src/internal-inference/contracts.ts +218 -0
  34. package/src/internal-inference/coordination/handles.ts +133 -0
  35. package/src/internal-inference/coordination/manager.ts +487 -0
  36. package/src/internal-inference/ids.ts +10 -0
  37. package/src/internal-inference/index.ts +10 -0
  38. package/src/internal-inference/persistence/records.ts +132 -0
  39. package/src/internal-inference/persistence/repository.ts +35 -0
  40. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  41. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  42. package/src/internal-inference/strategy/registry.ts +42 -0
  43. package/src/metering/engine.ts +47 -0
  44. package/src/metering/record.ts +4 -1
  45. package/src/observation/contracts.ts +10 -0
  46. package/src/observation/index.ts +8 -0
  47. package/src/observation/subscription-hub.ts +43 -0
  48. package/src/persistence/activity-projection.ts +26 -12
  49. package/src/persistence/backend.ts +774 -0
  50. package/src/persistence/index.ts +99 -0
  51. package/src/persistence/managed-creation.ts +18 -2
  52. package/src/persistence/managed-load.ts +19 -5
  53. package/src/persistence/managed-open-progress.ts +54 -0
  54. package/src/persistence/presentation.ts +3 -0
  55. package/src/persistence/sqlite-backend.ts +1927 -0
  56. package/src/persistence/sqlite-conversation-records.ts +425 -0
  57. package/src/persistence/sqlite-owner-lock.ts +106 -0
  58. package/src/persistence/sqlite-schema.ts +561 -0
@@ -0,0 +1,1927 @@
1
+ import { Database, type Changes } from "bun:sqlite";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, realpath } from "node:fs/promises";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import {
6
+ createAgentSessionId,
7
+ isAgentConversationId,
8
+ isAgentSessionId,
9
+ type AgentConversationId,
10
+ type AgentSessionId,
11
+ } from "../agent-ids.ts";
12
+ import {
13
+ IMPLICIT_USER_PARTICIPANT_ID,
14
+ PersistenceCapabilityError,
15
+ PersistenceConflictError,
16
+ isConversationRecordKind,
17
+ normalizeParticipantRef,
18
+ type AgentConversationSummary,
19
+ type AgentAuditState,
20
+ type AgentMeteringCommitInput,
21
+ type AgentPersistenceIdentity,
22
+ type AuditOutboxItem,
23
+ type AuditOutboxBacklog,
24
+ type AuditOutboxPersistence,
25
+ type ConversationCheckpointPersistence,
26
+ type ConversationListOptions,
27
+ type ConversationMessagePersistence,
28
+ type ConversationPage,
29
+ type ConversationPersistence,
30
+ type ConversationRecord,
31
+ type ConversationRecordPage,
32
+ type ConversationRecordPersistence,
33
+ type ConversationRuntimeCheckpoint,
34
+ type CreateAgentConversationInput,
35
+ type IdentityMemoryObservation,
36
+ type IdentityPersistence,
37
+ type IdentityProjectionState,
38
+ type MessageListOptions,
39
+ type MessagePage,
40
+ type MessageRecord,
41
+ type MeteringCommitInput,
42
+ type MeteringPersistence,
43
+ type MeteringRecordListOptions,
44
+ type MeteringRecordPage,
45
+ type NewConversationRecord,
46
+ type NewAuditOutboxItem,
47
+ type NewIdentityMemoryObservation,
48
+ type ParticipantRef,
49
+ type PersistedIdentitySnapshot,
50
+ type PersistenceBackend,
51
+ type PersistenceCapabilities,
52
+ type PersistenceExtension,
53
+ type PersistenceExtensionCatalog,
54
+ type PersistenceExtensionRegistration,
55
+ type PersistenceJsonPrimitive,
56
+ type PersistenceJsonValue,
57
+ type PersistenceScope,
58
+ type PersistedConversationMeteringState,
59
+ type PersistedAgentMeteringState,
60
+ type ProviderSessionPersistence,
61
+ type ProviderSessionRecord,
62
+ type RecordListOptions,
63
+ type SearchMatch,
64
+ type SearchPersistence,
65
+ type SearchQuery,
66
+ } from "./backend.ts";
67
+ import type { OperationMeteringRecord } from "../metering/record.ts";
68
+ import type { AgentSessionMeteringState } from "../metering/state.ts";
69
+ import { installSqliteFts, migrateSqliteAgentSchema } from "./sqlite-schema.ts";
70
+ import { SqliteInternalInferenceRepository } from "../internal-inference/persistence/sqlite-repository.ts";
71
+ import type { InternalInferenceRepository } from "../internal-inference/persistence/repository.ts";
72
+ import type { ConversationRecoveryCheckpointRepository } from "../checkpointing/contracts.ts";
73
+ import { SqliteConversationRecoveryCheckpointRepository } from "../checkpointing/persistence/sqlite-repository.ts";
74
+ import {
75
+ hydrateConversationRecords,
76
+ insertConversationRecordDetail,
77
+ operationIdFromRecord,
78
+ sameConversationRecord,
79
+ type ConversationRecordRow,
80
+ } from "./sqlite-conversation-records.ts";
81
+ import { SqliteOwnerLock, SqliteOwnerLockConflictError } from "./sqlite-owner-lock.ts";
82
+ import { canonicalizeJson } from "./integrity.ts";
83
+
84
+ type SqlValue = string | number | bigint | boolean | Uint8Array | null;
85
+ type WriteRunner = <T>(work: () => T) => Promise<T>;
86
+
87
+ interface ConversationRow {
88
+ agent_conversation_id: string;
89
+ agent_session_id: string;
90
+ title: string | null;
91
+ created_at: string;
92
+ updated_at: string;
93
+ latest_sequence: number;
94
+ deleted_at: string | null;
95
+ metadata: string | null;
96
+ }
97
+
98
+ interface IdentityRow {
99
+ agent_session_id: string;
100
+ created_at: string;
101
+ updated_at: string;
102
+ metadata: string | null;
103
+ }
104
+
105
+ export interface SqliteAgentPersistenceConfig {
106
+ readonly path: string;
107
+ /** Required to create with a chosen identity; omitted reuses an existing identity or mints one. */
108
+ readonly agentSessionId?: AgentSessionId;
109
+ readonly metadata?: string;
110
+ readonly busyTimeoutMs?: number;
111
+ readonly extensions?: readonly PersistenceExtension[];
112
+ /** Escape hatch for vendor-patched SQLite builds whose version string is not recognized. */
113
+ readonly allowUnsafeWalVersion?: boolean;
114
+ }
115
+
116
+ export class AgentDatabaseInUseError extends Error {
117
+ readonly path: string;
118
+
119
+ constructor(path: string, options?: ErrorOptions) {
120
+ super(`agent database already has an active runtime owner: ${path}`, options);
121
+ this.name = "AgentDatabaseInUseError";
122
+ this.path = path;
123
+ }
124
+ }
125
+
126
+ /** One caller-located SQLite database containing exactly one agent and its conversations. */
127
+ export class SqliteAgentPersistence implements PersistenceBackend {
128
+ readonly path: string;
129
+ readonly identityRecord: AgentPersistenceIdentity;
130
+ readonly capabilities: PersistenceCapabilities;
131
+
132
+ readonly conversations: ConversationPersistence;
133
+ readonly records: ConversationRecordPersistence;
134
+ readonly messages: ConversationMessagePersistence;
135
+ readonly checkpoints: ConversationCheckpointPersistence;
136
+ readonly providerSessions: ProviderSessionPersistence;
137
+ readonly metering: MeteringPersistence;
138
+ readonly internalInferences: InternalInferenceRepository;
139
+ readonly recoveryCheckpoints: ConversationRecoveryCheckpointRepository;
140
+ readonly identity: IdentityPersistence;
141
+ readonly search?: SearchPersistence;
142
+ readonly auditOutbox: AuditOutboxPersistence;
143
+ readonly extensions: PersistenceExtensionCatalog;
144
+
145
+ private readonly database: Database;
146
+ private readonly installedExtensions: PersistenceExtension[] = [];
147
+ private writeTail: Promise<void> = Promise.resolve();
148
+ private closed = false;
149
+
150
+ private constructor(
151
+ path: string,
152
+ database: Database,
153
+ identityRecord: AgentPersistenceIdentity,
154
+ fullTextSearch: boolean,
155
+ private readonly ownerLock?: SqliteOwnerLock,
156
+ ) {
157
+ this.path = path;
158
+ this.database = database;
159
+ this.identityRecord = identityRecord;
160
+ this.capabilities = Object.freeze({
161
+ transactions: true as const,
162
+ fullTextSearch,
163
+ identity: true,
164
+ auditOutbox: true,
165
+ extensions: true,
166
+ vectorSearch: false,
167
+ metering: true,
168
+ });
169
+ const scope = this.createScope((work) => this.autoWrite(work), (records) => this.notifyRecordsCommitted(records));
170
+ this.conversations = scope.conversations;
171
+ this.records = scope.records;
172
+ this.messages = scope.messages;
173
+ this.checkpoints = scope.checkpoints;
174
+ this.providerSessions = scope.providerSessions;
175
+ this.metering = scope.metering;
176
+ this.internalInferences = scope.internalInferences!;
177
+ this.recoveryCheckpoints = scope.recoveryCheckpoints!;
178
+ this.identity = scope.identity!;
179
+ this.search = fullTextSearch ? new SqliteSearchPersistence(database) : undefined;
180
+ this.auditOutbox = scope.auditOutbox!;
181
+ this.extensions = scope.extensions!;
182
+ }
183
+
184
+ static async open(config: SqliteAgentPersistenceConfig): Promise<SqliteAgentPersistence> {
185
+ if (config.agentSessionId !== undefined && !isAgentSessionId(config.agentSessionId)) {
186
+ throw new Error(`invalid agent session id for SQLite persistence: ${config.agentSessionId}`);
187
+ }
188
+ if (!config.path.trim()) throw new Error("SQLite persistence path cannot be blank");
189
+ const path = config.path === ":memory:" ? config.path : await canonicalSqlitePath(config.path);
190
+ let ownerLock: SqliteOwnerLock | undefined;
191
+ if (path !== ":memory:") {
192
+ try {
193
+ ownerLock = await SqliteOwnerLock.acquire(path, `${path}.agent-owner.sqlite`);
194
+ } catch (error) {
195
+ if (error instanceof SqliteOwnerLockConflictError) {
196
+ throw new AgentDatabaseInUseError(path, { cause: error });
197
+ }
198
+ throw error;
199
+ }
200
+ }
201
+
202
+ let database: Database;
203
+ try {
204
+ database = new Database(path, { create: true, readwrite: true, strict: true });
205
+ } catch (error) {
206
+ ownerLock?.close();
207
+ throw error;
208
+ }
209
+ try {
210
+ const busyTimeoutMs = boundedInteger(config.busyTimeoutMs ?? 5_000, 1, 60_000, "busyTimeoutMs");
211
+ database.exec("PRAGMA foreign_keys = ON");
212
+ database.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}`);
213
+ const version = String(
214
+ database.query<{ version: string }, []>("SELECT sqlite_version() AS version").get()?.version ?? "",
215
+ );
216
+ if (!config.allowUnsafeWalVersion && !hasSafeConcurrentWal(version)) {
217
+ throw new Error(
218
+ `SQLite ${version || "unknown"} lacks a recognized concurrent-WAL fix; require 3.51.3+, 3.50.7, or 3.44.6`,
219
+ );
220
+ }
221
+ if (path !== ":memory:") {
222
+ const mode = database.query<{ journal_mode: string }, []>("PRAGMA journal_mode = WAL").get();
223
+ if (mode?.journal_mode?.toLowerCase() !== "wal") {
224
+ throw new Error(`SQLite persistence could not enable WAL mode at ${path}`);
225
+ }
226
+ }
227
+ database.exec("PRAGMA synchronous = NORMAL");
228
+ migrateSqliteAgentSchema(database);
229
+ const fullTextSearch = installSqliteFts(database);
230
+ const existingIdentity = database.query<{ agent_session_id: string }, []>(
231
+ "SELECT agent_session_id FROM agent_identity WHERE singleton = 1",
232
+ ).get();
233
+ const agentSessionId = config.agentSessionId
234
+ ?? (existingIdentity?.agent_session_id as AgentSessionId | undefined)
235
+ ?? createAgentSessionId();
236
+ const identityRecord = initializeAgentIdentity(database, agentSessionId, config.metadata);
237
+ const backend = new SqliteAgentPersistence(path, database, identityRecord, fullTextSearch, ownerLock);
238
+ for (const extension of config.extensions ?? []) await backend.installExtension(extension);
239
+ return backend;
240
+ } catch (error) {
241
+ try {
242
+ database.close();
243
+ } finally {
244
+ ownerLock?.close();
245
+ }
246
+ throw error;
247
+ }
248
+ }
249
+
250
+ async transaction<T>(work: (transaction: PersistenceScope) => T | Promise<T>): Promise<T> {
251
+ this.assertOpen();
252
+ return await this.enqueueWrite(async () => {
253
+ const committed: ConversationRecord[] = [];
254
+ this.database.exec("BEGIN IMMEDIATE");
255
+ try {
256
+ const scope = this.createScope(async (operation) => operation(), (records) => {
257
+ committed.push(...records);
258
+ });
259
+ const result = await work(scope);
260
+ this.database.exec("COMMIT");
261
+ await this.notifyRecordsCommitted(committed);
262
+ return result;
263
+ } catch (error) {
264
+ if (this.database.inTransaction) this.database.exec("ROLLBACK");
265
+ throw error;
266
+ }
267
+ });
268
+ }
269
+
270
+ async close(): Promise<void> {
271
+ if (this.closed) return;
272
+ await this.writeTail;
273
+ this.closed = true;
274
+ try {
275
+ // sqlite3_close_v2 safely finalizes Bun's cached prepared statements.
276
+ this.database.close();
277
+ } finally {
278
+ this.ownerLock?.close();
279
+ }
280
+ }
281
+
282
+ private createScope(
283
+ runWrite: WriteRunner,
284
+ onAppended: (records: readonly ConversationRecord[]) => void | Promise<void>,
285
+ ): PersistenceScope {
286
+ return Object.freeze({
287
+ conversations: new SqliteConversationPersistence(this.database, this.identityRecord.agentSessionId, runWrite),
288
+ records: new SqliteConversationRecordPersistence(
289
+ this.database,
290
+ this.identityRecord.agentSessionId,
291
+ runWrite,
292
+ onAppended,
293
+ ),
294
+ messages: new SqliteConversationMessagePersistence(this.database),
295
+ checkpoints: new SqliteCheckpointPersistence(this.database, runWrite),
296
+ providerSessions: new SqliteProviderSessionPersistence(this.database, runWrite),
297
+ metering: new SqliteMeteringPersistence(this.database, runWrite),
298
+ internalInferences: new SqliteInternalInferenceRepository(this.database, runWrite),
299
+ recoveryCheckpoints: new SqliteConversationRecoveryCheckpointRepository(this.database, runWrite),
300
+ identity: new SqliteIdentityPersistence(
301
+ this.database,
302
+ this.identityRecord.agentSessionId,
303
+ runWrite,
304
+ ),
305
+ ...(this.capabilities.fullTextSearch
306
+ ? { search: new SqliteSearchPersistence(this.database) }
307
+ : {}),
308
+ auditOutbox: new SqliteAuditOutboxPersistence(this.database, runWrite),
309
+ extensions: new SqliteExtensionCatalog(this.database),
310
+ });
311
+ }
312
+
313
+ private async installExtension(extension: PersistenceExtension): Promise<void> {
314
+ if (!/^[a-z][a-z0-9_.-]*$/i.test(extension.id)) {
315
+ throw new Error(`invalid persistence extension id: ${extension.id}`);
316
+ }
317
+ if (!Number.isSafeInteger(extension.version) || extension.version < 1) {
318
+ throw new Error(`invalid persistence extension version for ${extension.id}: ${extension.version}`);
319
+ }
320
+ if (this.installedExtensions.some((candidate) => candidate.id === extension.id)) {
321
+ throw new Error(`duplicate persistence extension: ${extension.id}`);
322
+ }
323
+
324
+ await this.transaction(async (scope) => {
325
+ const installed = await scope.extensions!.get(extension.id);
326
+ const installedVersion = installed?.schemaVersion ?? 0;
327
+ if (installedVersion > extension.version) {
328
+ throw new Error(
329
+ `persistence extension ${extension.id} schema ${installedVersion} is newer than ${extension.version}`,
330
+ );
331
+ }
332
+ if (installedVersion === extension.version) return;
333
+ await extension.migrate({
334
+ extensionId: extension.id,
335
+ installedVersion,
336
+ execute: async (sql, parameters = []) => {
337
+ runSql(this.database, sql, ...(parameters as SqlValue[]));
338
+ },
339
+ });
340
+ const now = new Date().toISOString();
341
+ runSql(this.database,
342
+ `INSERT INTO persistence_extensions(extension_id, schema_version, installed_at, updated_at)
343
+ VALUES (?, ?, ?, ?)
344
+ ON CONFLICT(extension_id) DO UPDATE SET
345
+ schema_version = excluded.schema_version,
346
+ updated_at = excluded.updated_at`,
347
+ extension.id,
348
+ extension.version,
349
+ installed?.installedAt ?? now,
350
+ now,
351
+ );
352
+ });
353
+ this.installedExtensions.push(extension);
354
+ }
355
+
356
+ private async notifyRecordsCommitted(records: readonly ConversationRecord[]): Promise<void> {
357
+ if (records.length === 0) return;
358
+ const owned = Object.freeze(records.map((record) => Object.freeze(structuredClone(record))));
359
+ for (const extension of this.installedExtensions) {
360
+ await extension.recordsCommitted?.(owned);
361
+ }
362
+ }
363
+
364
+ private async autoWrite<T>(work: () => T): Promise<T> {
365
+ this.assertOpen();
366
+ return await this.enqueueWrite(async () => {
367
+ this.database.exec("BEGIN IMMEDIATE");
368
+ try {
369
+ const result = work();
370
+ this.database.exec("COMMIT");
371
+ return result;
372
+ } catch (error) {
373
+ if (this.database.inTransaction) this.database.exec("ROLLBACK");
374
+ throw error;
375
+ }
376
+ });
377
+ }
378
+
379
+ private enqueueWrite<T>(work: () => Promise<T>): Promise<T> {
380
+ const result = this.writeTail.then(work, work);
381
+ this.writeTail = result.then(() => undefined, () => undefined);
382
+ return result;
383
+ }
384
+
385
+ private assertOpen(): void {
386
+ if (this.closed) throw new Error("SQLite persistence backend is closed");
387
+ }
388
+ }
389
+
390
+ class SqliteConversationPersistence implements ConversationPersistence {
391
+ constructor(
392
+ private readonly database: Database,
393
+ private readonly agentSessionId: AgentSessionId,
394
+ private readonly runWrite: WriteRunner,
395
+ ) {}
396
+
397
+ async create(input: CreateAgentConversationInput): Promise<AgentConversationSummary> {
398
+ if (input.agentSessionId !== this.agentSessionId) {
399
+ throw new Error("conversation agentSessionId does not match the SQLite agent database");
400
+ }
401
+ if (!isAgentConversationId(input.agentConversationId)) {
402
+ throw new Error(`invalid agent conversation id: ${input.agentConversationId}`);
403
+ }
404
+ return await this.runWrite(() => {
405
+ if (conversationRow(this.database, input.agentConversationId)) {
406
+ throw new PersistenceConflictError(`conversation already exists: ${input.agentConversationId}`);
407
+ }
408
+ const now = input.createdAt ?? new Date().toISOString();
409
+ assertInstant(now, "conversation createdAt");
410
+ runSql(this.database,
411
+ `INSERT INTO conversations(
412
+ agent_conversation_id, agent_session_id, title, created_at, updated_at, metadata
413
+ ) VALUES (?, ?, ?, ?, ?, ?)`,
414
+ input.agentConversationId,
415
+ input.agentSessionId,
416
+ input.title ?? null,
417
+ now,
418
+ now,
419
+ input.metadata ?? null,
420
+ );
421
+ const participants = input.participants?.length
422
+ ? input.participants
423
+ : [{ id: IMPLICIT_USER_PARTICIPANT_ID, kind: "user" as const }];
424
+ for (const participant of participants) {
425
+ ensureParticipantDirect(this.database, input.agentConversationId, participant, now);
426
+ }
427
+ return requireConversationSummary(this.database, input.agentConversationId);
428
+ });
429
+ }
430
+
431
+ async get(agentConversationId: AgentConversationId): Promise<AgentConversationSummary | null> {
432
+ const row = conversationRow(this.database, agentConversationId);
433
+ return row ? summaryFromRow(this.database, row) : null;
434
+ }
435
+
436
+ async list(options: ConversationListOptions = {}): Promise<ConversationPage> {
437
+ const limit = boundedInteger(options.limit ?? 50, 1, 500, "conversation limit");
438
+ const offset = decodeOffset(options.cursor);
439
+ const where: string[] = ["c.agent_session_id = ?"];
440
+ const parameters: SqlValue[] = [this.agentSessionId];
441
+ if (!options.includeDeleted) where.push("c.deleted_at IS NULL");
442
+ for (const participantId of options.participantIds ?? []) {
443
+ where.push(`EXISTS (
444
+ SELECT 1 FROM conversation_participants cp
445
+ WHERE cp.agent_conversation_id = c.agent_conversation_id
446
+ AND cp.participant_id = ?
447
+ )`);
448
+ parameters.push(participantId);
449
+ }
450
+ parameters.push(limit + 1, offset);
451
+ const rows = this.database.query<ConversationRow, SqlValue[]>(
452
+ `SELECT c.* FROM conversations c
453
+ WHERE ${where.join(" AND ")}
454
+ ORDER BY c.updated_at DESC, c.agent_conversation_id
455
+ LIMIT ? OFFSET ?`,
456
+ ).all(...parameters);
457
+ const hasMore = rows.length > limit;
458
+ const selected = rows.slice(0, limit).map((row) => summaryFromRow(this.database, row));
459
+ return Object.freeze({
460
+ conversations: Object.freeze(selected),
461
+ ...(hasMore ? { nextCursor: encodeOffset(offset + limit) } : {}),
462
+ });
463
+ }
464
+
465
+ async renameParticipant(
466
+ agentConversationId: AgentConversationId,
467
+ participantId: string,
468
+ name: string | undefined,
469
+ ): Promise<void> {
470
+ await this.runWrite(() => {
471
+ requireConversation(this.database, agentConversationId);
472
+ const linked = this.database.query<{ present: number }, [string, string]>(
473
+ `SELECT 1 AS present FROM conversation_participants
474
+ WHERE agent_conversation_id = ? AND participant_id = ?`,
475
+ ).get(agentConversationId, participantId);
476
+ if (!linked) throw new Error(`participant is not in conversation: ${participantId}`);
477
+ runSql(this.database,
478
+ "UPDATE participants SET name = ?, updated_at = ? WHERE participant_id = ?",
479
+ name?.trim() || null,
480
+ new Date().toISOString(),
481
+ participantId,
482
+ );
483
+ });
484
+ }
485
+
486
+ async ensureParticipant(
487
+ agentConversationId: AgentConversationId,
488
+ participant: ParticipantRef,
489
+ ): Promise<ParticipantRef> {
490
+ return await this.runWrite(() => ensureParticipantDirect(
491
+ this.database,
492
+ agentConversationId,
493
+ participant,
494
+ new Date().toISOString(),
495
+ ));
496
+ }
497
+
498
+ async delete(agentConversationId: AgentConversationId, deletedAt?: string): Promise<void> {
499
+ await this.runWrite(() => {
500
+ requireConversation(this.database, agentConversationId);
501
+ const at = deletedAt ?? new Date().toISOString();
502
+ assertInstant(at, "conversation deletedAt");
503
+ runSql(this.database,
504
+ "UPDATE conversations SET deleted_at = ?, updated_at = ? WHERE agent_conversation_id = ?",
505
+ at,
506
+ at,
507
+ agentConversationId,
508
+ );
509
+ });
510
+ }
511
+ }
512
+
513
+ class SqliteConversationRecordPersistence implements ConversationRecordPersistence {
514
+ constructor(
515
+ private readonly database: Database,
516
+ private readonly agentSessionId: AgentSessionId,
517
+ private readonly runWrite: WriteRunner,
518
+ private readonly onAppended: (records: readonly ConversationRecord[]) => void | Promise<void>,
519
+ ) {}
520
+
521
+ async append(record: NewConversationRecord): Promise<ConversationRecord> {
522
+ const records = await this.appendMany([record]);
523
+ return records[0]!;
524
+ }
525
+
526
+ async appendMany(records: readonly NewConversationRecord[]): Promise<readonly ConversationRecord[]> {
527
+ if (records.length === 0) return Object.freeze([]);
528
+ const appended = await this.runWrite(() => records.map((record) => this.appendDirect(record)));
529
+ await this.onAppended(appended);
530
+ return Object.freeze(appended);
531
+ }
532
+
533
+ async get(recordId: string): Promise<ConversationRecord | null> {
534
+ const row = this.database.query<ConversationRecordRow, [string]>(
535
+ "SELECT * FROM conversation_records WHERE record_id = ?",
536
+ ).get(recordId);
537
+ return row ? hydrateConversationRecords(this.database, [row])[0]! : null;
538
+ }
539
+
540
+ async list(
541
+ agentConversationId: AgentConversationId,
542
+ options: RecordListOptions = {},
543
+ ): Promise<ConversationRecordPage> {
544
+ requireConversation(this.database, agentConversationId);
545
+ const limit = boundedInteger(options.limit ?? 100, 1, 1_000, "record limit");
546
+ const offset = decodeOffset(options.cursor);
547
+ const where = ["agent_conversation_id = ?"];
548
+ const parameters: SqlValue[] = [agentConversationId];
549
+ if (options.afterSequence !== undefined) {
550
+ where.push("sequence > ?");
551
+ parameters.push(nonNegativeInteger(options.afterSequence, "afterSequence"));
552
+ }
553
+ if (options.throughSequence !== undefined) {
554
+ where.push("sequence <= ?");
555
+ parameters.push(nonNegativeInteger(options.throughSequence, "throughSequence"));
556
+ }
557
+ if (options.kinds?.length) {
558
+ for (const kind of options.kinds) {
559
+ if (!isConversationRecordKind(kind)) throw new Error(`unknown record kind: ${kind}`);
560
+ }
561
+ where.push(`kind IN (${options.kinds.map(() => "?").join(", ")})`);
562
+ parameters.push(...options.kinds);
563
+ }
564
+ parameters.push(limit + 1, offset);
565
+ const rows = this.database.query<ConversationRecordRow, SqlValue[]>(
566
+ `SELECT * FROM conversation_records
567
+ WHERE ${where.join(" AND ")}
568
+ ORDER BY sequence
569
+ LIMIT ? OFFSET ?`,
570
+ ).all(...parameters);
571
+ const hasMore = rows.length > limit;
572
+ return Object.freeze({
573
+ records: hydrateConversationRecords(this.database, rows.slice(0, limit)),
574
+ ...(hasMore ? { nextCursor: encodeOffset(offset + limit) } : {}),
575
+ });
576
+ }
577
+
578
+ private appendDirect(input: NewConversationRecord): ConversationRecord {
579
+ if (input.agentSessionId !== this.agentSessionId) {
580
+ throw new Error("record agentSessionId does not match the SQLite agent database");
581
+ }
582
+ if (!isConversationRecordKind(input.kind)) throw new Error(`unknown record kind: ${input.kind}`);
583
+ if (!input.recordId.trim()) throw new Error("recordId cannot be blank");
584
+ assertInstant(input.timestamp, "record timestamp");
585
+ requireConversation(this.database, input.agentConversationId);
586
+
587
+ const normalized = input.kind === "message" && input.role === "user" && !input.participantId
588
+ ? { ...input, participantId: IMPLICIT_USER_PARTICIPANT_ID }
589
+ : input;
590
+ if (normalized.kind === "message" && normalized.participantId) {
591
+ const known = this.database.query<{ kind: ParticipantRef["kind"]; name: string | null }, [string]>(
592
+ "SELECT kind, name FROM participants WHERE participant_id = ?",
593
+ ).get(normalized.participantId);
594
+ ensureParticipantDirect(this.database, normalized.agentConversationId, {
595
+ id: normalized.participantId,
596
+ kind: known?.kind ?? (normalized.role === "user" ? "user" : "agent"),
597
+ ...(known?.name ? { name: known.name } : {}),
598
+ }, normalized.timestamp);
599
+ }
600
+ const existing = this.database.query<ConversationRecordRow, [string]>(
601
+ "SELECT * FROM conversation_records WHERE record_id = ?",
602
+ ).get(normalized.recordId);
603
+ if (existing) {
604
+ const hydrated = hydrateConversationRecords(this.database, [existing])[0]!;
605
+ if (sameConversationRecord(hydrated, normalized)) {
606
+ return hydrated;
607
+ }
608
+ throw new PersistenceConflictError(`record id already exists with different content: ${normalized.recordId}`);
609
+ }
610
+
611
+ const next = this.database.query<{ sequence: number }, [string, string]>(
612
+ `UPDATE conversations
613
+ SET latest_sequence = latest_sequence + 1, updated_at = ?
614
+ WHERE agent_conversation_id = ? AND deleted_at IS NULL
615
+ RETURNING latest_sequence AS sequence`,
616
+ ).get(new Date().toISOString(), normalized.agentConversationId);
617
+ if (!next) throw new Error(`conversation is deleted: ${normalized.agentConversationId}`);
618
+ const inserted = this.database.query<{ row_id: number }, SqlValue[]>(
619
+ `INSERT INTO conversation_records(
620
+ record_id, agent_session_id, agent_conversation_id, sequence,
621
+ kind, timestamp, operation_id, metadata
622
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
623
+ RETURNING row_id`,
624
+ ).get(
625
+ normalized.recordId,
626
+ normalized.agentSessionId,
627
+ normalized.agentConversationId,
628
+ next.sequence,
629
+ normalized.kind,
630
+ normalized.timestamp,
631
+ operationIdFromRecord(normalized),
632
+ normalized.metadata ?? null,
633
+ );
634
+ if (!inserted) throw new Error(`could not persist conversation record: ${normalized.recordId}`);
635
+ insertConversationRecordDetail(this.database, Number(inserted.row_id), normalized);
636
+ return Object.freeze({ ...normalized, sequence: next.sequence }) as ConversationRecord;
637
+ }
638
+ }
639
+
640
+ class SqliteConversationMessagePersistence implements ConversationMessagePersistence {
641
+ constructor(private readonly database: Database) {}
642
+
643
+ async list(
644
+ agentConversationId: AgentConversationId,
645
+ options: MessageListOptions = {},
646
+ ): Promise<MessagePage> {
647
+ requireConversation(this.database, agentConversationId);
648
+ const limit = boundedInteger(options.limit ?? 100, 1, 1_000, "message limit");
649
+ const offset = decodeOffset(options.cursor);
650
+ const where = ["r.agent_conversation_id = ?", "r.kind = 'message'"];
651
+ const parameters: SqlValue[] = [agentConversationId];
652
+ if (options.afterSequence !== undefined) {
653
+ where.push("r.sequence > ?");
654
+ parameters.push(nonNegativeInteger(options.afterSequence, "afterSequence"));
655
+ }
656
+ if (options.throughSequence !== undefined) {
657
+ where.push("r.sequence <= ?");
658
+ parameters.push(nonNegativeInteger(options.throughSequence, "throughSequence"));
659
+ }
660
+ if (options.participantIds?.length) {
661
+ where.push(`m.participant_id IN (${options.participantIds.map(() => "?").join(", ")})`);
662
+ parameters.push(...options.participantIds);
663
+ }
664
+ parameters.push(limit + 1, offset);
665
+ const rows = this.database.query<ConversationRecordRow, SqlValue[]>(
666
+ `SELECT r.* FROM conversation_records r
667
+ JOIN conversation_messages m ON m.record_row_id = r.row_id
668
+ WHERE ${where.join(" AND ")}
669
+ ORDER BY r.sequence
670
+ LIMIT ? OFFSET ?`,
671
+ ).all(...parameters);
672
+ const hasMore = rows.length > limit;
673
+ return Object.freeze({
674
+ messages: hydrateConversationRecords(this.database, rows.slice(0, limit)) as readonly MessageRecord[],
675
+ ...(hasMore ? { nextCursor: encodeOffset(offset + limit) } : {}),
676
+ });
677
+ }
678
+ }
679
+
680
+ class SqliteCheckpointPersistence implements ConversationCheckpointPersistence {
681
+ constructor(private readonly database: Database, private readonly runWrite: WriteRunner) {}
682
+
683
+ async get(agentConversationId: AgentConversationId): Promise<ConversationRuntimeCheckpoint | null> {
684
+ const row = this.database.query<{
685
+ agent_conversation_id: string;
686
+ revision: number;
687
+ covered_sequence: number;
688
+ state_json: string;
689
+ updated_at: string;
690
+ }, [string]>("SELECT * FROM conversation_checkpoints WHERE agent_conversation_id = ?").get(agentConversationId);
691
+ return row ? Object.freeze({
692
+ agentConversationId: row.agent_conversation_id as AgentConversationId,
693
+ revision: Number(row.revision),
694
+ coveredSequence: Number(row.covered_sequence),
695
+ state: parseJson(row.state_json),
696
+ updatedAt: row.updated_at,
697
+ }) : null;
698
+ }
699
+
700
+ async put(
701
+ checkpoint: ConversationRuntimeCheckpoint,
702
+ expectedRevision?: number,
703
+ ): Promise<ConversationRuntimeCheckpoint> {
704
+ return await this.runWrite(() => {
705
+ requireConversation(this.database, checkpoint.agentConversationId);
706
+ const current = this.database.query<{ revision: number }, [string]>(
707
+ "SELECT revision FROM conversation_checkpoints WHERE agent_conversation_id = ?",
708
+ ).get(checkpoint.agentConversationId);
709
+ if (expectedRevision !== undefined && Number(current?.revision ?? 0) !== expectedRevision) {
710
+ throw new PersistenceConflictError(
711
+ `checkpoint revision mismatch: expected ${expectedRevision}, found ${Number(current?.revision ?? 0)}`,
712
+ );
713
+ }
714
+ if (current && checkpoint.revision <= Number(current.revision)) {
715
+ throw new PersistenceConflictError("checkpoint revision must increase");
716
+ }
717
+ runSql(this.database,
718
+ `INSERT INTO conversation_checkpoints(
719
+ agent_conversation_id, revision, covered_sequence, state_json, updated_at
720
+ ) VALUES (?, ?, ?, ?, ?)
721
+ ON CONFLICT(agent_conversation_id) DO UPDATE SET
722
+ revision = excluded.revision,
723
+ covered_sequence = excluded.covered_sequence,
724
+ state_json = excluded.state_json,
725
+ updated_at = excluded.updated_at`,
726
+ checkpoint.agentConversationId,
727
+ nonNegativeInteger(checkpoint.revision, "checkpoint revision"),
728
+ nonNegativeInteger(checkpoint.coveredSequence, "checkpoint coveredSequence"),
729
+ JSON.stringify(checkpoint.state),
730
+ checkpoint.updatedAt,
731
+ );
732
+ return Object.freeze(structuredClone(checkpoint));
733
+ });
734
+ }
735
+ }
736
+
737
+ class SqliteProviderSessionPersistence implements ProviderSessionPersistence {
738
+ constructor(private readonly database: Database, private readonly runWrite: WriteRunner) {}
739
+
740
+ async append(record: ProviderSessionRecord): Promise<void> {
741
+ await this.runWrite(() => {
742
+ requireConversation(this.database, record.agentConversationId);
743
+ const existing = this.database.query<{ present: number }, [string]>(
744
+ "SELECT 1 AS present FROM provider_sessions WHERE provider_session_record_id = ?",
745
+ ).get(record.providerSessionRecordId);
746
+ if (existing) return;
747
+ if (!record.deactivatedAt) {
748
+ runSql(this.database,
749
+ `UPDATE provider_sessions SET deactivated_at = ?
750
+ WHERE agent_conversation_id = ? AND deactivated_at IS NULL`,
751
+ record.activatedAt,
752
+ record.agentConversationId,
753
+ );
754
+ }
755
+ runSql(this.database,
756
+ `INSERT INTO provider_sessions(
757
+ provider_session_record_id, agent_conversation_id, internal_session_id,
758
+ adapter_id, mode, model, activated_at, deactivated_at, transition_id, metadata
759
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
760
+ record.providerSessionRecordId,
761
+ record.agentConversationId,
762
+ record.internalSessionId,
763
+ record.adapterId,
764
+ record.mode,
765
+ record.model ?? null,
766
+ record.activatedAt,
767
+ record.deactivatedAt ?? null,
768
+ record.transitionId ?? null,
769
+ record.metadata ?? null,
770
+ );
771
+ });
772
+ }
773
+
774
+ async list(agentConversationId: AgentConversationId): Promise<readonly ProviderSessionRecord[]> {
775
+ requireConversation(this.database, agentConversationId);
776
+ const rows = this.database.query<Record<string, unknown>, [string]>(
777
+ `SELECT * FROM provider_sessions
778
+ WHERE agent_conversation_id = ?
779
+ ORDER BY activated_at, provider_session_record_id`,
780
+ ).all(agentConversationId);
781
+ return Object.freeze(rows.map(providerSessionFromRow));
782
+ }
783
+
784
+ async active(agentConversationId: AgentConversationId): Promise<ProviderSessionRecord | null> {
785
+ requireConversation(this.database, agentConversationId);
786
+ const row = this.database.query<Record<string, unknown>, [string]>(
787
+ `SELECT * FROM provider_sessions
788
+ WHERE agent_conversation_id = ? AND deactivated_at IS NULL`,
789
+ ).get(agentConversationId);
790
+ return row ? providerSessionFromRow(row) : null;
791
+ }
792
+ }
793
+
794
+ class SqliteMeteringPersistence implements MeteringPersistence {
795
+ constructor(private readonly database: Database, private readonly runWrite: WriteRunner) {}
796
+
797
+ async commit(input: MeteringCommitInput): Promise<PersistedConversationMeteringState> {
798
+ return await this.runWrite(() => {
799
+ requireConversation(this.database, input.agentConversationId);
800
+ const operationId = nonblank(input.record.operationId, "metering operationId");
801
+ const existing = this.database.query<{ record_json: string | null }, [string, string]>(
802
+ `SELECT record_json FROM metering_records
803
+ WHERE agent_conversation_id = ? AND operation_id = ?`,
804
+ ).get(input.agentConversationId, operationId);
805
+ const serializedRecord = JSON.stringify(input.record);
806
+ if (existing) {
807
+ if (existing.record_json !== null && existing.record_json !== serializedRecord) {
808
+ throw new PersistenceConflictError(
809
+ `metering operation already exists with different content: ${operationId}`,
810
+ );
811
+ }
812
+ if (input.meteringRecords === "all" && existing.record_json === null) {
813
+ runSql(this.database,
814
+ `UPDATE metering_records SET record_json = ?
815
+ WHERE agent_conversation_id = ? AND operation_id = ?`,
816
+ serializedRecord,
817
+ input.agentConversationId,
818
+ operationId,
819
+ );
820
+ }
821
+ const current = readMeteringState(this.database, input.agentConversationId);
822
+ if (!current) {
823
+ throw new PersistenceConflictError(
824
+ `metering operation ${operationId} exists without restoration state`,
825
+ );
826
+ }
827
+ return current;
828
+ }
829
+
830
+ const current = readMeteringState(this.database, input.agentConversationId);
831
+ if (input.record.nextState.agentSessionId !== input.record.agentSessionId) {
832
+ throw new PersistenceConflictError("metering record and next state belong to different agents");
833
+ }
834
+ if (current && input.record.nextState.operationCount !== current.state.operationCount + 1) {
835
+ throw new PersistenceConflictError(
836
+ `metering operation count mismatch: expected ${current.state.operationCount + 1}, found ${input.record.nextState.operationCount}`,
837
+ );
838
+ }
839
+ if (!current && input.record.nextState.operationCount !== 1) {
840
+ throw new PersistenceConflictError(
841
+ `initial metering operation count must be 1, found ${input.record.nextState.operationCount}`,
842
+ );
843
+ }
844
+
845
+ runSql(this.database,
846
+ `INSERT INTO metering_records(
847
+ agent_conversation_id, operation_id, internal_session_id, adapter_id,
848
+ operation_kind, outcome, completed_at, record_json
849
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
850
+ input.agentConversationId,
851
+ operationId,
852
+ input.record.internalSessionId,
853
+ input.record.provider.adapterId,
854
+ input.record.operationKind,
855
+ input.record.outcome,
856
+ input.record.completedAt,
857
+ input.meteringRecords === "none" ? null : serializedRecord,
858
+ );
859
+
860
+ const revision = (current?.revision ?? 0) + 1;
861
+ const updatedAt = input.updatedAt ?? new Date().toISOString();
862
+ runSql(this.database,
863
+ `INSERT INTO conversation_metering_state(
864
+ agent_conversation_id, revision, state_json, updated_at
865
+ ) VALUES (?, ?, ?, ?)
866
+ ON CONFLICT(agent_conversation_id) DO UPDATE SET
867
+ revision = excluded.revision,
868
+ state_json = excluded.state_json,
869
+ updated_at = excluded.updated_at`,
870
+ input.agentConversationId,
871
+ revision,
872
+ JSON.stringify(input.record.nextState),
873
+ updatedAt,
874
+ );
875
+ if (typeof input.meteringRecords === "object") {
876
+ const retain = boundedInteger(
877
+ input.meteringRecords.retain,
878
+ 0,
879
+ 1_000_000,
880
+ "metering record retention",
881
+ );
882
+ runSql(this.database,
883
+ `UPDATE metering_records SET record_json = NULL
884
+ WHERE agent_conversation_id = ? AND operation_id NOT IN (
885
+ SELECT operation_id FROM metering_records
886
+ WHERE agent_conversation_id = ? AND record_json IS NOT NULL
887
+ ORDER BY completed_at DESC, operation_id DESC LIMIT ?
888
+ )`,
889
+ input.agentConversationId,
890
+ input.agentConversationId,
891
+ retain,
892
+ );
893
+ }
894
+ return Object.freeze({
895
+ agentConversationId: input.agentConversationId,
896
+ revision,
897
+ state: structuredClone(input.record.nextState),
898
+ updatedAt,
899
+ });
900
+ });
901
+ }
902
+
903
+ async state(agentConversationId: AgentConversationId): Promise<PersistedConversationMeteringState | null> {
904
+ requireConversation(this.database, agentConversationId);
905
+ return readMeteringState(this.database, agentConversationId);
906
+ }
907
+
908
+ async saveState(
909
+ agentConversationId: AgentConversationId,
910
+ state: AgentSessionMeteringState,
911
+ updatedAt = new Date().toISOString(),
912
+ ): Promise<PersistedConversationMeteringState> {
913
+ return await this.runWrite(() => {
914
+ requireConversation(this.database, agentConversationId);
915
+ const current = readMeteringState(this.database, agentConversationId);
916
+ const serialized = JSON.stringify(state);
917
+ if (current && JSON.stringify(current.state) === serialized) return current;
918
+ if (current && state.operationCount < current.state.operationCount) {
919
+ throw new PersistenceConflictError("metering state cannot move to an earlier operation count");
920
+ }
921
+ const revision = (current?.revision ?? 0) + 1;
922
+ runSql(this.database,
923
+ `INSERT INTO conversation_metering_state(
924
+ agent_conversation_id, revision, state_json, updated_at
925
+ ) VALUES (?, ?, ?, ?)
926
+ ON CONFLICT(agent_conversation_id) DO UPDATE SET
927
+ revision = excluded.revision,
928
+ state_json = excluded.state_json,
929
+ updated_at = excluded.updated_at`,
930
+ agentConversationId,
931
+ revision,
932
+ serialized,
933
+ updatedAt,
934
+ );
935
+ return Object.freeze({
936
+ agentConversationId,
937
+ revision,
938
+ state: structuredClone(state),
939
+ updatedAt,
940
+ });
941
+ });
942
+ }
943
+
944
+ async list(
945
+ agentConversationId: AgentConversationId,
946
+ options: MeteringRecordListOptions = {},
947
+ ): Promise<MeteringRecordPage> {
948
+ requireConversation(this.database, agentConversationId);
949
+ const limit = boundedInteger(options.limit ?? 100, 1, 1_000, "metering list limit");
950
+ const offset = decodeOffset(options.cursor);
951
+ const rows = this.database.query<{ record_json: string }, [string, number, number]>(
952
+ `SELECT record_json FROM metering_records
953
+ WHERE agent_conversation_id = ? AND record_json IS NOT NULL
954
+ ORDER BY completed_at, operation_id
955
+ LIMIT ? OFFSET ?`,
956
+ ).all(agentConversationId, limit + 1, offset);
957
+ const hasMore = rows.length > limit;
958
+ return Object.freeze({
959
+ records: Object.freeze(rows.slice(0, limit).map((row) => Object.freeze(
960
+ JSON.parse(row.record_json) as OperationMeteringRecord,
961
+ ))),
962
+ ...(hasMore ? { nextCursor: encodeOffset(offset + limit) } : {}),
963
+ });
964
+ }
965
+
966
+ async get(
967
+ agentConversationId: AgentConversationId,
968
+ operationId: string,
969
+ ): Promise<OperationMeteringRecord | null> {
970
+ requireConversation(this.database, agentConversationId);
971
+ const row = this.database.query<{ record_json: string | null }, [string, string]>(
972
+ `SELECT record_json FROM metering_records
973
+ WHERE agent_conversation_id = ? AND operation_id = ?`,
974
+ ).get(agentConversationId, nonblank(operationId, "metering operationId"));
975
+ return row?.record_json
976
+ ? Object.freeze(JSON.parse(row.record_json) as OperationMeteringRecord)
977
+ : null;
978
+ }
979
+
980
+ async commitAgent(input: AgentMeteringCommitInput): Promise<PersistedAgentMeteringState> {
981
+ return await this.runWrite(() => {
982
+ if (input.agentSessionId !== input.record.agentSessionId) {
983
+ throw new PersistenceConflictError("agent metering record belongs to another agent");
984
+ }
985
+ const operationId = nonblank(input.record.operationId, "metering operationId");
986
+ const existing = this.database.query<{ record_json: string | null }, [string, string]>(
987
+ `SELECT record_json FROM agent_metering_records
988
+ WHERE agent_session_id = ? AND operation_id = ?`,
989
+ ).get(input.agentSessionId, operationId);
990
+ const serializedRecord = JSON.stringify(input.record);
991
+ if (existing) {
992
+ if (existing.record_json !== null && existing.record_json !== serializedRecord) {
993
+ throw new PersistenceConflictError(
994
+ `agent metering operation already exists with different content: ${operationId}`,
995
+ );
996
+ }
997
+ if (input.meteringRecords === "all" && existing.record_json === null) {
998
+ runSql(this.database,
999
+ `UPDATE agent_metering_records SET record_json = ?
1000
+ WHERE agent_session_id = ? AND operation_id = ?`,
1001
+ serializedRecord, input.agentSessionId, operationId,
1002
+ );
1003
+ }
1004
+ const current = readAgentMeteringState(this.database, input.agentSessionId);
1005
+ if (!current) {
1006
+ throw new PersistenceConflictError(
1007
+ `agent metering operation ${operationId} exists without restoration state`,
1008
+ );
1009
+ }
1010
+ return current;
1011
+ }
1012
+
1013
+ const current = readAgentMeteringState(this.database, input.agentSessionId);
1014
+ const expectedCount = (current?.state.operationCount ?? 0) + 1;
1015
+ if (input.record.nextState.operationCount !== expectedCount) {
1016
+ throw new PersistenceConflictError(
1017
+ `agent metering operation count mismatch: expected ${expectedCount}, found ${input.record.nextState.operationCount}`,
1018
+ );
1019
+ }
1020
+ runSql(this.database,
1021
+ `INSERT INTO agent_metering_records(
1022
+ agent_session_id, operation_id, internal_session_id, adapter_id,
1023
+ operation_kind, outcome, completed_at, record_json
1024
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
1025
+ input.agentSessionId, operationId, input.record.internalSessionId,
1026
+ input.record.provider.adapterId, input.record.operationKind, input.record.outcome,
1027
+ input.record.completedAt, input.meteringRecords === "none" ? null : serializedRecord,
1028
+ );
1029
+ const revision = (current?.revision ?? 0) + 1;
1030
+ const updatedAt = input.updatedAt ?? new Date().toISOString();
1031
+ runSql(this.database,
1032
+ `INSERT INTO agent_metering_state(agent_session_id, revision, state_json, updated_at)
1033
+ VALUES (?, ?, ?, ?)
1034
+ ON CONFLICT(agent_session_id) DO UPDATE SET
1035
+ revision = excluded.revision,
1036
+ state_json = excluded.state_json,
1037
+ updated_at = excluded.updated_at`,
1038
+ input.agentSessionId, revision, JSON.stringify(input.record.nextState), updatedAt,
1039
+ );
1040
+ if (typeof input.meteringRecords === "object") {
1041
+ const retain = boundedInteger(input.meteringRecords.retain, 0, 1_000_000, "metering record retention");
1042
+ runSql(this.database,
1043
+ `UPDATE agent_metering_records SET record_json = NULL
1044
+ WHERE agent_session_id = ? AND operation_id NOT IN (
1045
+ SELECT operation_id FROM agent_metering_records
1046
+ WHERE agent_session_id = ? AND record_json IS NOT NULL
1047
+ ORDER BY completed_at DESC, operation_id DESC LIMIT ?
1048
+ )`,
1049
+ input.agentSessionId, input.agentSessionId, retain,
1050
+ );
1051
+ }
1052
+ return Object.freeze({
1053
+ agentSessionId: input.agentSessionId,
1054
+ revision,
1055
+ state: structuredClone(input.record.nextState),
1056
+ updatedAt,
1057
+ });
1058
+ });
1059
+ }
1060
+
1061
+ async agentState(agentSessionId: AgentSessionId): Promise<PersistedAgentMeteringState | null> {
1062
+ return readAgentMeteringState(this.database, agentSessionId);
1063
+ }
1064
+
1065
+ async listAgent(
1066
+ agentSessionId: AgentSessionId,
1067
+ options: MeteringRecordListOptions = {},
1068
+ ): Promise<MeteringRecordPage> {
1069
+ const limit = boundedInteger(options.limit ?? 100, 1, 1_000, "metering list limit");
1070
+ const offset = decodeOffset(options.cursor);
1071
+ const rows = this.database.query<{ record_json: string }, [string, number, number]>(
1072
+ `SELECT record_json FROM agent_metering_records
1073
+ WHERE agent_session_id = ? AND record_json IS NOT NULL
1074
+ ORDER BY completed_at, operation_id LIMIT ? OFFSET ?`,
1075
+ ).all(agentSessionId, limit + 1, offset);
1076
+ const hasMore = rows.length > limit;
1077
+ return Object.freeze({
1078
+ records: Object.freeze(rows.slice(0, limit).map((row) => Object.freeze(
1079
+ JSON.parse(row.record_json) as OperationMeteringRecord,
1080
+ ))),
1081
+ ...(hasMore ? { nextCursor: encodeOffset(offset + limit) } : {}),
1082
+ });
1083
+ }
1084
+
1085
+ async getAgent(
1086
+ agentSessionId: AgentSessionId,
1087
+ operationId: string,
1088
+ ): Promise<OperationMeteringRecord | null> {
1089
+ const row = this.database.query<{ record_json: string | null }, [string, string]>(
1090
+ `SELECT record_json FROM agent_metering_records
1091
+ WHERE agent_session_id = ? AND operation_id = ?`,
1092
+ ).get(agentSessionId, nonblank(operationId, "metering operationId"));
1093
+ return row?.record_json
1094
+ ? Object.freeze(JSON.parse(row.record_json) as OperationMeteringRecord)
1095
+ : null;
1096
+ }
1097
+ }
1098
+
1099
+ function readMeteringState(
1100
+ database: Database,
1101
+ agentConversationId: AgentConversationId,
1102
+ ): PersistedConversationMeteringState | null {
1103
+ const row = database.query<{
1104
+ agent_conversation_id: string;
1105
+ revision: number;
1106
+ state_json: string;
1107
+ updated_at: string;
1108
+ }, [string]>(
1109
+ "SELECT * FROM conversation_metering_state WHERE agent_conversation_id = ?",
1110
+ ).get(agentConversationId);
1111
+ return row ? Object.freeze({
1112
+ agentConversationId: row.agent_conversation_id as AgentConversationId,
1113
+ revision: Number(row.revision),
1114
+ state: Object.freeze(JSON.parse(row.state_json) as AgentSessionMeteringState),
1115
+ updatedAt: row.updated_at,
1116
+ }) : null;
1117
+ }
1118
+
1119
+ function readAgentMeteringState(
1120
+ database: Database,
1121
+ agentSessionId: AgentSessionId,
1122
+ ): PersistedAgentMeteringState | null {
1123
+ const row = database.query<{
1124
+ agent_session_id: string;
1125
+ revision: number;
1126
+ state_json: string;
1127
+ updated_at: string;
1128
+ }, [string]>("SELECT * FROM agent_metering_state WHERE agent_session_id = ?").get(agentSessionId);
1129
+ return row ? Object.freeze({
1130
+ agentSessionId: row.agent_session_id as AgentSessionId,
1131
+ revision: Number(row.revision),
1132
+ state: Object.freeze(JSON.parse(row.state_json) as AgentSessionMeteringState),
1133
+ updatedAt: row.updated_at,
1134
+ }) : null;
1135
+ }
1136
+
1137
+ class SqliteIdentityPersistence implements IdentityPersistence {
1138
+ constructor(
1139
+ private readonly database: Database,
1140
+ private readonly agentSessionId: AgentSessionId,
1141
+ private readonly runWrite: WriteRunner,
1142
+ ) {}
1143
+
1144
+ async append(
1145
+ observations: readonly NewIdentityMemoryObservation[],
1146
+ ): Promise<readonly IdentityMemoryObservation[]> {
1147
+ if (observations.length === 0) return Object.freeze([]);
1148
+ return await this.runWrite(() => Object.freeze(observations.map((observation) => {
1149
+ if (observation.agentSessionId !== this.agentSessionId) {
1150
+ throw new Error("identity observation belongs to another agent");
1151
+ }
1152
+ requireConversation(this.database, observation.sourceConversationId);
1153
+ const existing = this.database.query<Record<string, unknown>, [string]>(
1154
+ "SELECT * FROM identity_memories WHERE memory_id = ?",
1155
+ ).get(observation.memoryId);
1156
+ if (existing) {
1157
+ const persisted = identityMemoryFromRow(existing);
1158
+ const comparable = {
1159
+ memoryId: persisted.memoryId,
1160
+ agentSessionId: persisted.agentSessionId,
1161
+ sourceConversationId: persisted.sourceConversationId,
1162
+ sourceRecordIds: persisted.sourceRecordIds,
1163
+ ...(persisted.participantId ? { participantId: persisted.participantId } : {}),
1164
+ kind: persisted.kind,
1165
+ content: persisted.content,
1166
+ createdAt: persisted.createdAt,
1167
+ ...(persisted.metadata ? { metadata: persisted.metadata } : {}),
1168
+ };
1169
+ if (JSON.stringify(comparable) !== JSON.stringify(observation)) {
1170
+ throw new PersistenceConflictError(
1171
+ `identity memory id already exists with different content: ${observation.memoryId}`,
1172
+ );
1173
+ }
1174
+ return persisted;
1175
+ }
1176
+ if (!observation.memoryId.trim()) throw new Error("identity memoryId cannot be blank");
1177
+ assertInstant(observation.createdAt, "identity memory createdAt");
1178
+ const next = this.database.query<{ sequence: number }, []>(
1179
+ `UPDATE identity_state
1180
+ SET observed_through_sequence = observed_through_sequence + 1
1181
+ WHERE singleton = 1
1182
+ RETURNING observed_through_sequence AS sequence`,
1183
+ ).get();
1184
+ if (!next) throw new Error("identity state is unavailable");
1185
+ runSql(this.database,
1186
+ `INSERT INTO identity_memories(
1187
+ memory_id, agent_session_id, sequence, source_conversation_id,
1188
+ source_record_ids_json, participant_id, kind, content_json, created_at, metadata
1189
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1190
+ observation.memoryId,
1191
+ observation.agentSessionId,
1192
+ next.sequence,
1193
+ observation.sourceConversationId,
1194
+ JSON.stringify(observation.sourceRecordIds),
1195
+ observation.participantId ?? null,
1196
+ observation.kind,
1197
+ JSON.stringify(observation.content),
1198
+ observation.createdAt,
1199
+ observation.metadata ?? null,
1200
+ );
1201
+ return Object.freeze({ ...structuredClone(observation), sequence: next.sequence });
1202
+ })));
1203
+ }
1204
+
1205
+ async listAfter(sequence: number, limit = 100): Promise<readonly IdentityMemoryObservation[]> {
1206
+ const rows = this.database.query<Record<string, unknown>, [number, number]>(
1207
+ `SELECT * FROM identity_memories
1208
+ WHERE sequence > ? ORDER BY sequence LIMIT ?`,
1209
+ ).all(nonNegativeInteger(sequence, "identity sequence"), boundedInteger(limit, 1, 1_000, "identity limit"));
1210
+ return Object.freeze(rows.map(identityMemoryFromRow));
1211
+ }
1212
+
1213
+ async latestSnapshot(): Promise<PersistedIdentitySnapshot | null> {
1214
+ const row = this.database.query<Record<string, unknown>, []>(
1215
+ "SELECT * FROM identity_snapshots ORDER BY version DESC LIMIT 1",
1216
+ ).get();
1217
+ return row ? identitySnapshotFromRow(row) : null;
1218
+ }
1219
+
1220
+ async publishSnapshot(snapshot: PersistedIdentitySnapshot, expectedVersion?: number): Promise<void> {
1221
+ await this.runWrite(() => {
1222
+ if (snapshot.agentSessionId !== this.agentSessionId) {
1223
+ throw new Error("identity snapshot belongs to another agent");
1224
+ }
1225
+ const state = identityProjectionState(this.database, this.agentSessionId);
1226
+ const latest = this.database.query<{ version: number }, []>(
1227
+ "SELECT version FROM identity_snapshots ORDER BY version DESC LIMIT 1",
1228
+ ).get();
1229
+ const currentVersion = Number(latest?.version ?? 0);
1230
+ if (expectedVersion !== undefined && currentVersion !== expectedVersion) {
1231
+ throw new PersistenceConflictError(
1232
+ `identity snapshot version mismatch: expected ${expectedVersion}, found ${currentVersion}`,
1233
+ );
1234
+ }
1235
+ if (snapshot.version <= currentVersion) {
1236
+ throw new PersistenceConflictError("identity snapshot version must increase");
1237
+ }
1238
+ if (snapshot.processedThroughSequence > state.observedThroughSequence) {
1239
+ throw new Error("identity snapshot cannot process observations that do not exist");
1240
+ }
1241
+ runSql(this.database,
1242
+ `INSERT INTO identity_snapshots(
1243
+ snapshot_id, agent_session_id, version, processed_through_sequence, value_json, created_at
1244
+ ) VALUES (?, ?, ?, ?, ?, ?)`,
1245
+ snapshot.snapshotId,
1246
+ snapshot.agentSessionId,
1247
+ snapshot.version,
1248
+ snapshot.processedThroughSequence,
1249
+ JSON.stringify(snapshot.value),
1250
+ snapshot.createdAt,
1251
+ );
1252
+ runSql(this.database,
1253
+ `UPDATE identity_state
1254
+ SET processed_through_sequence = ?, active_snapshot_id = ?
1255
+ WHERE singleton = 1`,
1256
+ snapshot.processedThroughSequence,
1257
+ snapshot.snapshotId,
1258
+ );
1259
+ });
1260
+ }
1261
+
1262
+ async projectionState(): Promise<IdentityProjectionState> {
1263
+ return identityProjectionState(this.database, this.agentSessionId);
1264
+ }
1265
+ }
1266
+
1267
+ class SqliteSearchPersistence implements SearchPersistence {
1268
+ constructor(private readonly database: Database) {}
1269
+
1270
+ async search(query: SearchQuery): Promise<readonly SearchMatch[]> {
1271
+ if (!query.text.trim()) throw new Error("search text cannot be blank");
1272
+ const limit = boundedInteger(query.limit ?? 50, 1, 500, "search limit");
1273
+ const requested = query.kinds?.length
1274
+ ? query.kinds
1275
+ : (["message", "tool_call", "activity"] as const);
1276
+ const searchable = requested.filter((kind): kind is "message" | "tool_call" | "activity" =>
1277
+ kind === "message" || kind === "tool_call" || kind === "activity");
1278
+ const rows = searchable.flatMap((kind) => searchRecordKind(this.database, kind, query, limit));
1279
+ rows.sort((left, right) => left.score - right.score || left.sequence - right.sequence);
1280
+ return Object.freeze(rows.slice(0, limit).map((row): SearchMatch => Object.freeze({
1281
+ recordId: row.record_id,
1282
+ agentConversationId: row.agent_conversation_id as AgentConversationId,
1283
+ sequence: Number(row.sequence),
1284
+ kind: row.kind as ConversationRecord["kind"],
1285
+ score: Number(row.score),
1286
+ ...(row.snippet ? { snippet: row.snippet } : {}),
1287
+ })));
1288
+ }
1289
+
1290
+ async rebuild(): Promise<void> {
1291
+ for (const table of SEARCH_FTS_TABLES) {
1292
+ this.database.exec(`INSERT INTO ${table}(${table}) VALUES ('rebuild')`);
1293
+ }
1294
+ }
1295
+
1296
+ async integrityCheck(): Promise<void> {
1297
+ for (const table of SEARCH_FTS_TABLES) {
1298
+ this.database.exec(`INSERT INTO ${table}(${table}, rank) VALUES ('integrity-check', 1)`);
1299
+ }
1300
+ }
1301
+ }
1302
+
1303
+ const SEARCH_FTS_TABLES = [
1304
+ "conversation_messages_fts",
1305
+ "conversation_tool_calls_fts",
1306
+ "conversation_activities_fts",
1307
+ ] as const;
1308
+
1309
+ interface SearchRow {
1310
+ readonly record_id: string;
1311
+ readonly agent_conversation_id: string;
1312
+ readonly sequence: number;
1313
+ readonly kind: string;
1314
+ readonly score: number;
1315
+ readonly snippet: string | null;
1316
+ }
1317
+
1318
+ function searchRecordKind(
1319
+ database: Database,
1320
+ kind: "message" | "tool_call" | "activity",
1321
+ query: SearchQuery,
1322
+ limit: number,
1323
+ ): SearchRow[] {
1324
+ if (query.participantIds?.length && kind !== "message") return [];
1325
+ const table = kind === "message"
1326
+ ? "conversation_messages_fts"
1327
+ : kind === "tool_call"
1328
+ ? "conversation_tool_calls_fts"
1329
+ : "conversation_activities_fts";
1330
+ const detailTable = kind === "message" ? "conversation_messages" : null;
1331
+ const where = [`${table} MATCH ?`, "r.kind = ?"];
1332
+ const parameters: SqlValue[] = [query.text, kind];
1333
+ if (query.conversationIds?.length) {
1334
+ where.push(`r.agent_conversation_id IN (${query.conversationIds.map(() => "?").join(", ")})`);
1335
+ parameters.push(...query.conversationIds);
1336
+ }
1337
+ if (query.participantIds?.length) {
1338
+ where.push(`d.participant_id IN (${query.participantIds.map(() => "?").join(", ")})`);
1339
+ parameters.push(...query.participantIds);
1340
+ }
1341
+ if (query.after) {
1342
+ where.push("r.timestamp >= ?");
1343
+ parameters.push(query.after);
1344
+ }
1345
+ if (query.before) {
1346
+ where.push("r.timestamp <= ?");
1347
+ parameters.push(query.before);
1348
+ }
1349
+ parameters.push(limit);
1350
+ return database.query<SearchRow, SqlValue[]>(
1351
+ `SELECT
1352
+ r.record_id,
1353
+ r.agent_conversation_id,
1354
+ r.sequence,
1355
+ r.kind,
1356
+ bm25(${table}) AS score,
1357
+ snippet(${table}, 0, '[', ']', '…', 32) AS snippet
1358
+ FROM ${table}
1359
+ JOIN conversation_records r ON r.row_id = ${table}.rowid
1360
+ ${detailTable ? `JOIN ${detailTable} d ON d.record_row_id = r.row_id` : ""}
1361
+ WHERE ${where.join(" AND ")}
1362
+ ORDER BY score, r.sequence
1363
+ LIMIT ?`,
1364
+ ).all(...parameters);
1365
+ }
1366
+
1367
+ class SqliteAuditOutboxPersistence implements AuditOutboxPersistence {
1368
+ constructor(private readonly database: Database, private readonly runWrite: WriteRunner) {}
1369
+
1370
+ async initialize(
1371
+ auditLogId: string,
1372
+ captureFingerprint: string,
1373
+ now = new Date().toISOString(),
1374
+ ): Promise<AgentAuditState> {
1375
+ return await this.runWrite(() => {
1376
+ const existing = readAuditState(this.database);
1377
+ if (existing) {
1378
+ if (existing.auditLogId !== auditLogId) {
1379
+ throw new PersistenceConflictError(
1380
+ `agent audit state belongs to ${existing.auditLogId}, not ${auditLogId}`,
1381
+ );
1382
+ }
1383
+ if (existing.captureFingerprint !== captureFingerprint) {
1384
+ runSql(this.database,
1385
+ "UPDATE agent_audit_state SET capture_fingerprint = ?, updated_at = ? WHERE singleton = 1",
1386
+ captureFingerprint,
1387
+ now,
1388
+ );
1389
+ }
1390
+ return readAuditState(this.database)!;
1391
+ }
1392
+ runSql(this.database,
1393
+ `INSERT INTO agent_audit_state(
1394
+ singleton, audit_log_id, last_allocated_sequence, last_delivered_sequence,
1395
+ capture_fingerprint, created_at, updated_at
1396
+ ) VALUES (1, ?, 0, 0, ?, ?, ?)`,
1397
+ auditLogId,
1398
+ captureFingerprint,
1399
+ now,
1400
+ now,
1401
+ );
1402
+ return readAuditState(this.database)!;
1403
+ });
1404
+ }
1405
+
1406
+ async state(): Promise<AgentAuditState | null> {
1407
+ return readAuditState(this.database);
1408
+ }
1409
+
1410
+ async backlog(): Promise<AuditOutboxBacklog> {
1411
+ const row = this.database.query<{
1412
+ pending_count: number;
1413
+ pending_payload_bytes: number;
1414
+ oldest_pending_at: string | null;
1415
+ }, []>(
1416
+ `SELECT COUNT(*) AS pending_count,
1417
+ COALESCE(SUM(payload_bytes), 0) AS pending_payload_bytes,
1418
+ MIN(created_at) AS oldest_pending_at
1419
+ FROM audit_outbox`,
1420
+ ).get()!;
1421
+ return Object.freeze({
1422
+ pendingCount: Number(row.pending_count),
1423
+ pendingPayloadBytes: Number(row.pending_payload_bytes),
1424
+ ...(row.oldest_pending_at !== null ? { oldestPendingAt: row.oldest_pending_at } : {}),
1425
+ });
1426
+ }
1427
+
1428
+ async enqueue(item: NewAuditOutboxItem): Promise<AuditOutboxItem> {
1429
+ return await this.runWrite(() => {
1430
+ const payload = canonicalizeJson(item.payload);
1431
+ const payloadSha256 = createHash("sha256").update(payload, "utf8").digest("hex");
1432
+ const payloadBytes = Buffer.byteLength(payload, "utf8");
1433
+ const existing = this.database.query<Record<string, unknown>, [string]>(
1434
+ "SELECT * FROM audit_outbox WHERE source_observation_id = ?",
1435
+ ).get(item.sourceObservationId);
1436
+ if (existing) {
1437
+ const hydrated = auditOutboxFromRow(existing);
1438
+ if (!samePendingAuditItem(hydrated, item, payloadSha256)) {
1439
+ throw new PersistenceConflictError(
1440
+ `audit source observation already has different pending content: ${item.sourceObservationId}`,
1441
+ );
1442
+ }
1443
+ return hydrated;
1444
+ }
1445
+ const state = readAuditState(this.database);
1446
+ if (!state) throw new Error("agent audit state is not initialized");
1447
+ const auditSequence = state.lastAllocatedSequence + 1;
1448
+ runSql(this.database,
1449
+ `INSERT INTO audit_outbox(
1450
+ outbox_id, audit_sequence, source_observation_id, source_record_id,
1451
+ operation_id, agent_conversation_id, occurred_at, kind, capture_level,
1452
+ capture_fingerprint, payload_json, payload_sha256, payload_bytes, created_at
1453
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1454
+ item.outboxId,
1455
+ auditSequence,
1456
+ item.sourceObservationId,
1457
+ item.sourceRecordId ?? null,
1458
+ item.operationId ?? null,
1459
+ item.agentConversationId ?? null,
1460
+ item.occurredAt,
1461
+ item.kind,
1462
+ item.captureLevel,
1463
+ item.captureFingerprint,
1464
+ payload,
1465
+ payloadSha256,
1466
+ payloadBytes,
1467
+ item.createdAt,
1468
+ );
1469
+ runSql(this.database,
1470
+ `UPDATE agent_audit_state
1471
+ SET last_allocated_sequence = ?, capture_fingerprint = ?, updated_at = ?
1472
+ WHERE singleton = 1`,
1473
+ auditSequence,
1474
+ item.captureFingerprint,
1475
+ item.createdAt,
1476
+ );
1477
+ return auditOutboxFromRow(this.database.query<Record<string, unknown>, [string]>(
1478
+ "SELECT * FROM audit_outbox WHERE outbox_id = ?",
1479
+ ).get(item.outboxId)!);
1480
+ });
1481
+ }
1482
+
1483
+ async head(): Promise<AuditOutboxItem | null> {
1484
+ const row = this.database.query<Record<string, unknown>, []>(
1485
+ "SELECT * FROM audit_outbox ORDER BY audit_sequence LIMIT 1",
1486
+ ).get();
1487
+ return row ? auditOutboxFromRow(row) : null;
1488
+ }
1489
+
1490
+ async pending(limit = 100, now = new Date().toISOString()): Promise<readonly AuditOutboxItem[]> {
1491
+ const rows = this.database.query<Record<string, unknown>, [number]>(
1492
+ `SELECT * FROM audit_outbox
1493
+ ORDER BY audit_sequence LIMIT ?`,
1494
+ ).all(boundedInteger(limit, 1, 1_000, "audit outbox limit"));
1495
+ const head = rows[0];
1496
+ if (head && head.next_attempt_at !== null && String(head.next_attempt_at) > now) {
1497
+ return Object.freeze([]);
1498
+ }
1499
+ return Object.freeze(rows.map(auditOutboxFromRow));
1500
+ }
1501
+
1502
+ async acknowledge(
1503
+ outboxIds: readonly string[],
1504
+ deliveredAt = new Date().toISOString(),
1505
+ ): Promise<AgentAuditState> {
1506
+ if (outboxIds.length === 0) throw new Error("audit acknowledgement cannot be empty");
1507
+ return await this.runWrite(() => {
1508
+ const rows = this.database.query<{ outbox_id: string; audit_sequence: number }, [number]>(
1509
+ "SELECT outbox_id, audit_sequence FROM audit_outbox ORDER BY audit_sequence LIMIT ?",
1510
+ ).all(outboxIds.length);
1511
+ if (rows.length !== outboxIds.length || rows.some((row, index) => row.outbox_id !== outboxIds[index])) {
1512
+ throw new PersistenceConflictError("audit acknowledgement is not the contiguous pending head");
1513
+ }
1514
+ const throughSequence = Number(rows.at(-1)!.audit_sequence);
1515
+ const placeholders = outboxIds.map(() => "?").join(", ");
1516
+ runSql(this.database, `DELETE FROM audit_outbox WHERE outbox_id IN (${placeholders})`, ...outboxIds);
1517
+ runSql(this.database,
1518
+ `UPDATE agent_audit_state
1519
+ SET last_delivered_sequence = ?, updated_at = ?
1520
+ WHERE singleton = 1`,
1521
+ throughSequence,
1522
+ deliveredAt,
1523
+ );
1524
+ return readAuditState(this.database)!;
1525
+ });
1526
+ }
1527
+
1528
+ async markFailed(outboxId: string, error: string, nextAttemptAt?: string): Promise<void> {
1529
+ await this.runWrite(() => {
1530
+ const changed = runSql(this.database,
1531
+ `UPDATE audit_outbox
1532
+ SET attempt_count = attempt_count + 1, last_error = ?, next_attempt_at = ?
1533
+ WHERE outbox_id = ?
1534
+ AND audit_sequence = (SELECT MIN(audit_sequence) FROM audit_outbox)`,
1535
+ truncateUtf8(error, 4_096),
1536
+ nextAttemptAt ?? null,
1537
+ outboxId,
1538
+ );
1539
+ if (changed.changes === 0) throw new PersistenceConflictError(`audit outbox item is not pending head: ${outboxId}`);
1540
+ });
1541
+ }
1542
+
1543
+ async retryHead(): Promise<void> {
1544
+ await this.runWrite(() => {
1545
+ runSql(this.database,
1546
+ `UPDATE audit_outbox SET next_attempt_at = NULL
1547
+ WHERE audit_sequence = (SELECT MIN(audit_sequence) FROM audit_outbox)`,
1548
+ );
1549
+ });
1550
+ }
1551
+ }
1552
+
1553
+ class SqliteExtensionCatalog implements PersistenceExtensionCatalog {
1554
+ constructor(private readonly database: Database) {}
1555
+
1556
+ async get(extensionId: string): Promise<PersistenceExtensionRegistration | null> {
1557
+ const row = this.database.query<{
1558
+ extension_id: string;
1559
+ schema_version: number;
1560
+ installed_at: string;
1561
+ updated_at: string;
1562
+ }, [string]>("SELECT * FROM persistence_extensions WHERE extension_id = ?").get(extensionId);
1563
+ return row ? extensionRegistrationFromRow(row) : null;
1564
+ }
1565
+
1566
+ async list(): Promise<readonly PersistenceExtensionRegistration[]> {
1567
+ const rows = this.database.query<{
1568
+ extension_id: string;
1569
+ schema_version: number;
1570
+ installed_at: string;
1571
+ updated_at: string;
1572
+ }, []>("SELECT * FROM persistence_extensions ORDER BY extension_id").all();
1573
+ return Object.freeze(rows.map(extensionRegistrationFromRow));
1574
+ }
1575
+ }
1576
+
1577
+ function initializeAgentIdentity(
1578
+ database: Database,
1579
+ agentSessionId: AgentSessionId,
1580
+ metadata: string | undefined,
1581
+ ): AgentPersistenceIdentity {
1582
+ database.exec("BEGIN IMMEDIATE");
1583
+ try {
1584
+ const existing = database.query<IdentityRow, []>("SELECT * FROM agent_identity WHERE singleton = 1").get();
1585
+ if (existing && existing.agent_session_id !== agentSessionId) {
1586
+ throw new PersistenceConflictError(
1587
+ `SQLite database belongs to ${existing.agent_session_id}, not ${agentSessionId}`,
1588
+ );
1589
+ }
1590
+ if (!existing) {
1591
+ const now = new Date().toISOString();
1592
+ runSql(database,
1593
+ `INSERT INTO agent_identity(
1594
+ singleton, agent_session_id, created_at, updated_at, metadata
1595
+ ) VALUES (1, ?, ?, ?, ?)`,
1596
+ agentSessionId,
1597
+ now,
1598
+ now,
1599
+ metadata ?? null,
1600
+ );
1601
+ }
1602
+ database.exec("COMMIT");
1603
+ } catch (error) {
1604
+ if (database.inTransaction) database.exec("ROLLBACK");
1605
+ throw error;
1606
+ }
1607
+ const row = database.query<IdentityRow, []>("SELECT * FROM agent_identity WHERE singleton = 1").get();
1608
+ if (!row) throw new Error("failed to initialize SQLite agent identity");
1609
+ return Object.freeze({
1610
+ agentSessionId: row.agent_session_id as AgentSessionId,
1611
+ createdAt: row.created_at,
1612
+ updatedAt: row.updated_at,
1613
+ ...(row.metadata !== null ? { metadata: row.metadata } : {}),
1614
+ });
1615
+ }
1616
+
1617
+ function conversationRow(database: Database, id: AgentConversationId): ConversationRow | null {
1618
+ return database.query<ConversationRow, [string]>(
1619
+ "SELECT * FROM conversations WHERE agent_conversation_id = ?",
1620
+ ).get(id) ?? null;
1621
+ }
1622
+
1623
+ function requireConversation(database: Database, id: AgentConversationId): ConversationRow {
1624
+ const row = conversationRow(database, id);
1625
+ if (!row) throw new Error(`unknown conversation: ${id}`);
1626
+ return row;
1627
+ }
1628
+
1629
+ function requireConversationSummary(database: Database, id: AgentConversationId): AgentConversationSummary {
1630
+ return summaryFromRow(database, requireConversation(database, id));
1631
+ }
1632
+
1633
+ function summaryFromRow(database: Database, row: ConversationRow): AgentConversationSummary {
1634
+ const participants = database.query<{
1635
+ participant_id: string;
1636
+ kind: string;
1637
+ name: string | null;
1638
+ }, [string]>(
1639
+ `SELECT p.participant_id, p.kind, p.name
1640
+ FROM participants p
1641
+ JOIN conversation_participants cp ON cp.participant_id = p.participant_id
1642
+ WHERE cp.agent_conversation_id = ?
1643
+ ORDER BY cp.joined_at, p.participant_id`,
1644
+ ).all(row.agent_conversation_id).map((participant): ParticipantRef => Object.freeze({
1645
+ id: participant.participant_id,
1646
+ kind: participant.kind as ParticipantRef["kind"],
1647
+ ...(participant.name !== null ? { name: participant.name } : {}),
1648
+ }));
1649
+ return Object.freeze({
1650
+ agentConversationId: row.agent_conversation_id as AgentConversationId,
1651
+ agentSessionId: row.agent_session_id as AgentSessionId,
1652
+ ...(row.title !== null ? { title: row.title } : {}),
1653
+ participants: Object.freeze(participants),
1654
+ createdAt: row.created_at,
1655
+ updatedAt: row.updated_at,
1656
+ latestSequence: Number(row.latest_sequence),
1657
+ ...(row.deleted_at !== null ? { deletedAt: row.deleted_at } : {}),
1658
+ ...(row.metadata !== null ? { metadata: row.metadata } : {}),
1659
+ });
1660
+ }
1661
+
1662
+ function ensureParticipantDirect(
1663
+ database: Database,
1664
+ agentConversationId: AgentConversationId,
1665
+ input: ParticipantRef,
1666
+ now: string,
1667
+ ): ParticipantRef {
1668
+ requireConversation(database, agentConversationId);
1669
+ const participant = normalizeParticipantRef(input);
1670
+ const existing = database.query<{ kind: string; name: string | null }, [string]>(
1671
+ "SELECT kind, name FROM participants WHERE participant_id = ?",
1672
+ ).get(participant.id);
1673
+ if (existing && existing.kind !== participant.kind) {
1674
+ throw new PersistenceConflictError(
1675
+ `participant ${participant.id} is already ${existing.kind}, not ${participant.kind}`,
1676
+ );
1677
+ }
1678
+ if (!existing) {
1679
+ runSql(database,
1680
+ `INSERT INTO participants(participant_id, kind, name, created_at, updated_at)
1681
+ VALUES (?, ?, ?, ?, ?)`,
1682
+ participant.id,
1683
+ participant.kind,
1684
+ participant.name ?? null,
1685
+ now,
1686
+ now,
1687
+ );
1688
+ } else if (participant.name !== undefined && participant.name !== existing.name) {
1689
+ runSql(database,
1690
+ "UPDATE participants SET name = ?, updated_at = ? WHERE participant_id = ?",
1691
+ participant.name,
1692
+ now,
1693
+ participant.id,
1694
+ );
1695
+ }
1696
+ runSql(database,
1697
+ `INSERT OR IGNORE INTO conversation_participants(
1698
+ agent_conversation_id, participant_id, joined_at
1699
+ ) VALUES (?, ?, ?)`,
1700
+ agentConversationId,
1701
+ participant.id,
1702
+ now,
1703
+ );
1704
+ return participant;
1705
+ }
1706
+
1707
+ function providerSessionFromRow(row: Record<string, unknown>): ProviderSessionRecord {
1708
+ return Object.freeze({
1709
+ providerSessionRecordId: String(row.provider_session_record_id),
1710
+ agentConversationId: String(row.agent_conversation_id) as AgentConversationId,
1711
+ internalSessionId: String(row.internal_session_id),
1712
+ adapterId: String(row.adapter_id),
1713
+ mode: String(row.mode) as ProviderSessionRecord["mode"],
1714
+ ...(row.model !== null ? { model: String(row.model) } : {}),
1715
+ activatedAt: String(row.activated_at),
1716
+ ...(row.deactivated_at !== null ? { deactivatedAt: String(row.deactivated_at) } : {}),
1717
+ ...(row.transition_id !== null ? { transitionId: String(row.transition_id) } : {}),
1718
+ ...(row.metadata !== null ? { metadata: String(row.metadata) } : {}),
1719
+ });
1720
+ }
1721
+
1722
+ function identityMemoryFromRow(row: Record<string, unknown>): IdentityMemoryObservation {
1723
+ return Object.freeze({
1724
+ memoryId: String(row.memory_id),
1725
+ agentSessionId: String(row.agent_session_id) as AgentSessionId,
1726
+ sequence: Number(row.sequence),
1727
+ sourceConversationId: String(row.source_conversation_id) as AgentConversationId,
1728
+ sourceRecordIds: Object.freeze(parseStringArray(String(row.source_record_ids_json))),
1729
+ ...(row.participant_id !== null ? { participantId: String(row.participant_id) } : {}),
1730
+ kind: String(row.kind),
1731
+ content: parseJson(String(row.content_json)),
1732
+ createdAt: String(row.created_at),
1733
+ ...(row.metadata !== null ? { metadata: String(row.metadata) } : {}),
1734
+ });
1735
+ }
1736
+
1737
+ function identitySnapshotFromRow(row: Record<string, unknown>): PersistedIdentitySnapshot {
1738
+ return Object.freeze({
1739
+ snapshotId: String(row.snapshot_id),
1740
+ agentSessionId: String(row.agent_session_id) as AgentSessionId,
1741
+ version: Number(row.version),
1742
+ processedThroughSequence: Number(row.processed_through_sequence),
1743
+ value: parseJson(String(row.value_json)),
1744
+ createdAt: String(row.created_at),
1745
+ });
1746
+ }
1747
+
1748
+ function identityProjectionState(database: Database, agentSessionId: AgentSessionId): IdentityProjectionState {
1749
+ const row = database.query<{
1750
+ observed_through_sequence: number;
1751
+ processed_through_sequence: number;
1752
+ active_snapshot_id: string | null;
1753
+ }, []>("SELECT * FROM identity_state WHERE singleton = 1").get();
1754
+ if (!row) throw new Error("identity state is unavailable");
1755
+ return Object.freeze({
1756
+ agentSessionId,
1757
+ observedThroughSequence: Number(row.observed_through_sequence),
1758
+ processedThroughSequence: Number(row.processed_through_sequence),
1759
+ ...(row.active_snapshot_id !== null ? { activeSnapshotId: row.active_snapshot_id } : {}),
1760
+ });
1761
+ }
1762
+
1763
+ function auditOutboxFromRow(row: Record<string, unknown>): AuditOutboxItem {
1764
+ return Object.freeze({
1765
+ outboxId: String(row.outbox_id),
1766
+ auditSequence: Number(row.audit_sequence),
1767
+ sourceObservationId: String(row.source_observation_id),
1768
+ ...(row.source_record_id !== null ? { sourceRecordId: String(row.source_record_id) } : {}),
1769
+ ...(row.operation_id !== null ? { operationId: String(row.operation_id) } : {}),
1770
+ ...(row.agent_conversation_id !== null
1771
+ ? { agentConversationId: String(row.agent_conversation_id) as AgentConversationId }
1772
+ : {}),
1773
+ occurredAt: String(row.occurred_at),
1774
+ kind: String(row.kind),
1775
+ captureLevel: String(row.capture_level),
1776
+ captureFingerprint: String(row.capture_fingerprint),
1777
+ payload: parseJson(String(row.payload_json)),
1778
+ payloadSha256: String(row.payload_sha256),
1779
+ payloadBytes: Number(row.payload_bytes),
1780
+ createdAt: String(row.created_at),
1781
+ attemptCount: Number(row.attempt_count),
1782
+ ...(row.next_attempt_at !== null ? { nextAttemptAt: String(row.next_attempt_at) } : {}),
1783
+ ...(row.last_error !== null ? { lastError: String(row.last_error) } : {}),
1784
+ });
1785
+ }
1786
+
1787
+ function readAuditState(database: Database): AgentAuditState | null {
1788
+ const row = database.query<Record<string, unknown>, []>(
1789
+ "SELECT * FROM agent_audit_state WHERE singleton = 1",
1790
+ ).get();
1791
+ if (!row) return null;
1792
+ return Object.freeze({
1793
+ auditLogId: String(row.audit_log_id),
1794
+ lastAllocatedSequence: Number(row.last_allocated_sequence),
1795
+ lastDeliveredSequence: Number(row.last_delivered_sequence),
1796
+ captureFingerprint: String(row.capture_fingerprint),
1797
+ createdAt: String(row.created_at),
1798
+ updatedAt: String(row.updated_at),
1799
+ });
1800
+ }
1801
+
1802
+ function samePendingAuditItem(
1803
+ existing: AuditOutboxItem,
1804
+ candidate: NewAuditOutboxItem,
1805
+ payloadSha256: string,
1806
+ ): boolean {
1807
+ return existing.sourceObservationId === candidate.sourceObservationId
1808
+ && existing.sourceRecordId === candidate.sourceRecordId
1809
+ && existing.operationId === candidate.operationId
1810
+ && existing.agentConversationId === candidate.agentConversationId
1811
+ && existing.occurredAt === candidate.occurredAt
1812
+ && existing.kind === candidate.kind
1813
+ && existing.captureLevel === candidate.captureLevel
1814
+ && existing.captureFingerprint === candidate.captureFingerprint
1815
+ && existing.payloadSha256 === payloadSha256;
1816
+ }
1817
+
1818
+ function extensionRegistrationFromRow(row: {
1819
+ extension_id: string;
1820
+ schema_version: number;
1821
+ installed_at: string;
1822
+ updated_at: string;
1823
+ }): PersistenceExtensionRegistration {
1824
+ return Object.freeze({
1825
+ extensionId: row.extension_id,
1826
+ schemaVersion: Number(row.schema_version),
1827
+ installedAt: row.installed_at,
1828
+ updatedAt: row.updated_at,
1829
+ });
1830
+ }
1831
+
1832
+ function parseJson(value: string): PersistenceJsonValue {
1833
+ return JSON.parse(value) as PersistenceJsonValue;
1834
+ }
1835
+
1836
+ function parseStringArray(value: string): string[] {
1837
+ const parsed = JSON.parse(value) as unknown;
1838
+ if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string")) {
1839
+ throw new Error("persisted source record ids are malformed");
1840
+ }
1841
+ return parsed;
1842
+ }
1843
+
1844
+ function encodeOffset(offset: number): string {
1845
+ return Buffer.from(`offset:${offset}`, "utf8").toString("base64url");
1846
+ }
1847
+
1848
+ function decodeOffset(cursor: string | undefined): number {
1849
+ if (!cursor) return 0;
1850
+ let decoded: string;
1851
+ try {
1852
+ decoded = Buffer.from(cursor, "base64url").toString("utf8");
1853
+ } catch {
1854
+ throw new Error("invalid persistence cursor");
1855
+ }
1856
+ const match = /^offset:(\d+)$/.exec(decoded);
1857
+ if (!match) throw new Error("invalid persistence cursor");
1858
+ return nonNegativeInteger(Number(match[1]), "persistence cursor");
1859
+ }
1860
+
1861
+ async function canonicalSqlitePath(input: string): Promise<string> {
1862
+ const resolved = resolve(input);
1863
+ const parent = dirname(resolved);
1864
+ await mkdir(parent, { recursive: true });
1865
+ try {
1866
+ return await realpath(resolved);
1867
+ } catch (error) {
1868
+ if (!isNodeErrorCode(error, "ENOENT")) throw error;
1869
+ return join(await realpath(parent), basename(resolved));
1870
+ }
1871
+ }
1872
+
1873
+ function isNodeErrorCode(error: unknown, code: string): boolean {
1874
+ return !!error && typeof error === "object" && "code" in error && error.code === code;
1875
+ }
1876
+
1877
+ function truncateUtf8(value: string, maxBytes: number): string {
1878
+ const bytes = Buffer.from(value, "utf8");
1879
+ if (bytes.byteLength <= maxBytes) return value;
1880
+ return bytes.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD$/u, "");
1881
+ }
1882
+
1883
+ function boundedInteger(value: number, minimum: number, maximum: number, label: string): number {
1884
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1885
+ throw new Error(`${label} must be an integer between ${minimum} and ${maximum}`);
1886
+ }
1887
+ return value;
1888
+ }
1889
+
1890
+ function nonNegativeInteger(value: number, label: string): number {
1891
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label} must be a non-negative integer`);
1892
+ return value;
1893
+ }
1894
+
1895
+ function nonblank(value: string, label: string): string {
1896
+ if (!value.trim()) throw new Error(`${label} cannot be blank`);
1897
+ return value;
1898
+ }
1899
+
1900
+ function assertInstant(value: string, label: string): void {
1901
+ if (!value.trim() || !Number.isFinite(Date.parse(value))) throw new Error(`${label} must be an ISO-8601 instant`);
1902
+ }
1903
+
1904
+ function runSql(database: Database, sql: string, ...parameters: SqlValue[]): Changes {
1905
+ return database.query<unknown, SqlValue[]>(sql).run(...parameters);
1906
+ }
1907
+
1908
+ /** Recognizes upstream versions containing SQLite's multi-connection WAL-reset fix. */
1909
+ export function hasSafeConcurrentWal(version: string): boolean {
1910
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
1911
+ if (!match) return false;
1912
+ const major = Number(match[1]);
1913
+ const minor = Number(match[2]);
1914
+ const patch = Number(match[3]);
1915
+ if (major > 3) return true;
1916
+ if (major < 3) return false;
1917
+ if (minor > 51) return true;
1918
+ if (minor === 51) return patch >= 3;
1919
+ if (minor === 50) return patch >= 7;
1920
+ if (minor === 44) return patch >= 6;
1921
+ return false;
1922
+ }
1923
+
1924
+ export function requireSqliteSearch(backend: PersistenceBackend): SearchPersistence {
1925
+ if (!backend.search) throw new PersistenceCapabilityError("fullTextSearch");
1926
+ return backend.search;
1927
+ }