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