@axiom-lattice/pg-stores 1.0.1

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/dist/index.js ADDED
@@ -0,0 +1,614 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ MigrationManager: () => MigrationManager,
24
+ PostgreSQLAssistantStore: () => PostgreSQLAssistantStore,
25
+ PostgreSQLThreadStore: () => PostgreSQLThreadStore,
26
+ createAssistantsTable: () => createAssistantsTable,
27
+ createThreadsTable: () => createThreadsTable
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+
31
+ // src/stores/PostgreSQLThreadStore.ts
32
+ var import_pg = require("pg");
33
+
34
+ // src/migrations/migration.ts
35
+ var MigrationManager = class {
36
+ constructor(pool) {
37
+ this.migrations = [];
38
+ this.pool = pool;
39
+ }
40
+ /**
41
+ * Register a migration
42
+ */
43
+ register(migration) {
44
+ this.migrations.push(migration);
45
+ this.migrations.sort((a, b) => a.version - b.version);
46
+ }
47
+ /**
48
+ * Initialize migrations table if it doesn't exist
49
+ */
50
+ async ensureMigrationsTable(client) {
51
+ await client.query(`
52
+ CREATE TABLE IF NOT EXISTS lattice_schema_migrations (
53
+ version INTEGER PRIMARY KEY,
54
+ name VARCHAR(255) NOT NULL,
55
+ applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
56
+ )
57
+ `);
58
+ }
59
+ /**
60
+ * Get applied migrations from database
61
+ */
62
+ async getAppliedMigrations(client) {
63
+ await client.query(`
64
+ CREATE TABLE IF NOT EXISTS lattice_schema_migrations (
65
+ version INTEGER PRIMARY KEY,
66
+ name VARCHAR(255) NOT NULL,
67
+ applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
68
+ )
69
+ `);
70
+ const result = await client.query(
71
+ "SELECT version, name, applied_at FROM lattice_schema_migrations ORDER BY version"
72
+ );
73
+ return result.rows;
74
+ }
75
+ /**
76
+ * Apply pending migrations
77
+ */
78
+ async migrate() {
79
+ const client = await this.pool.connect();
80
+ try {
81
+ await client.query("BEGIN");
82
+ await this.ensureMigrationsTable(client);
83
+ const appliedMigrations = await this.getAppliedMigrations(client);
84
+ const appliedVersions = new Set(appliedMigrations.map((m) => m.version));
85
+ const pendingMigrations = this.migrations.filter(
86
+ (m) => !appliedVersions.has(m.version)
87
+ );
88
+ if (pendingMigrations.length === 0) {
89
+ console.log("No pending migrations");
90
+ await client.query("COMMIT");
91
+ return;
92
+ }
93
+ for (const migration of pendingMigrations) {
94
+ console.log(
95
+ `Applying migration ${migration.version}: ${migration.name}`
96
+ );
97
+ await migration.up(client);
98
+ await client.query(
99
+ "INSERT INTO lattice_schema_migrations (version, name) VALUES ($1, $2)",
100
+ [migration.version, migration.name]
101
+ );
102
+ }
103
+ await client.query("COMMIT");
104
+ console.log(`Applied ${pendingMigrations.length} migration(s)`);
105
+ } catch (error) {
106
+ await client.query("ROLLBACK");
107
+ throw error;
108
+ } finally {
109
+ client.release();
110
+ }
111
+ }
112
+ /**
113
+ * Rollback last migration
114
+ */
115
+ async rollback() {
116
+ const client = await this.pool.connect();
117
+ try {
118
+ await client.query("BEGIN");
119
+ const appliedMigrations = await this.getAppliedMigrations(client);
120
+ if (appliedMigrations.length === 0) {
121
+ console.log("No migrations to rollback");
122
+ await client.query("COMMIT");
123
+ return;
124
+ }
125
+ const lastMigration = appliedMigrations[appliedMigrations.length - 1];
126
+ const migration = this.migrations.find(
127
+ (m) => m.version === lastMigration.version
128
+ );
129
+ if (!migration || !migration.down) {
130
+ throw new Error(
131
+ `Migration ${lastMigration.version} does not have a down migration`
132
+ );
133
+ }
134
+ console.log(
135
+ `Rolling back migration ${lastMigration.version}: ${lastMigration.name}`
136
+ );
137
+ await migration.down(client);
138
+ await client.query(
139
+ "DELETE FROM lattice_schema_migrations WHERE version = $1",
140
+ [lastMigration.version]
141
+ );
142
+ await client.query("COMMIT");
143
+ console.log("Rollback completed");
144
+ } catch (error) {
145
+ await client.query("ROLLBACK");
146
+ throw error;
147
+ } finally {
148
+ client.release();
149
+ }
150
+ }
151
+ /**
152
+ * Get current migration version
153
+ */
154
+ async getCurrentVersion() {
155
+ const client = await this.pool.connect();
156
+ try {
157
+ const appliedMigrations = await this.getAppliedMigrations(client);
158
+ if (appliedMigrations.length === 0) {
159
+ return 0;
160
+ }
161
+ return Math.max(...appliedMigrations.map((m) => m.version));
162
+ } finally {
163
+ client.release();
164
+ }
165
+ }
166
+ };
167
+
168
+ // src/migrations/thread_migrations.ts
169
+ var createThreadsTable = {
170
+ version: 1,
171
+ name: "create_threads_table",
172
+ up: async (client) => {
173
+ await client.query(`
174
+ CREATE TABLE IF NOT EXISTS lattice_threads (
175
+ id VARCHAR(255) NOT NULL,
176
+ assistant_id VARCHAR(255) NOT NULL,
177
+ metadata JSONB DEFAULT '{}',
178
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
179
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
180
+ PRIMARY KEY (id, assistant_id)
181
+ )
182
+ `);
183
+ await client.query(`
184
+ CREATE INDEX IF NOT EXISTS idx_lattice_threads_assistant_id
185
+ ON lattice_threads(assistant_id)
186
+ `);
187
+ await client.query(`
188
+ CREATE INDEX IF NOT EXISTS idx_lattice_threads_created_at
189
+ ON lattice_threads(created_at DESC)
190
+ `);
191
+ },
192
+ down: async (client) => {
193
+ await client.query("DROP INDEX IF EXISTS idx_lattice_threads_created_at");
194
+ await client.query("DROP INDEX IF EXISTS idx_lattice_threads_assistant_id");
195
+ await client.query("DROP TABLE IF EXISTS lattice_threads");
196
+ }
197
+ };
198
+
199
+ // src/stores/PostgreSQLThreadStore.ts
200
+ var PostgreSQLThreadStore = class {
201
+ constructor(options) {
202
+ this.initialized = false;
203
+ this.ownsPool = true;
204
+ if (typeof options.poolConfig === "string") {
205
+ this.pool = new import_pg.Pool({ connectionString: options.poolConfig });
206
+ } else {
207
+ this.pool = new import_pg.Pool(options.poolConfig);
208
+ }
209
+ this.migrationManager = new MigrationManager(this.pool);
210
+ this.migrationManager.register(createThreadsTable);
211
+ if (options.autoMigrate !== false) {
212
+ this.initialize().catch((error) => {
213
+ console.error("Failed to initialize PostgreSQLThreadStore:", error);
214
+ throw error;
215
+ });
216
+ }
217
+ }
218
+ /**
219
+ * Dispose resources and close the connection pool
220
+ * Should be called when the store is no longer needed
221
+ */
222
+ async dispose() {
223
+ if (this.ownsPool && this.pool) {
224
+ await this.pool.end();
225
+ }
226
+ }
227
+ /**
228
+ * Initialize the store and run migrations
229
+ */
230
+ async initialize() {
231
+ if (this.initialized) {
232
+ return;
233
+ }
234
+ await this.migrationManager.migrate();
235
+ this.initialized = true;
236
+ }
237
+ /**
238
+ * Get all threads for a specific assistant
239
+ */
240
+ async getThreadsByAssistantId(assistantId) {
241
+ await this.ensureInitialized();
242
+ const result = await this.pool.query(
243
+ `
244
+ SELECT id, assistant_id, metadata, created_at, updated_at
245
+ FROM lattice_threads
246
+ WHERE assistant_id = $1
247
+ ORDER BY created_at DESC
248
+ `,
249
+ [assistantId]
250
+ );
251
+ return result.rows.map(this.mapRowToThread);
252
+ }
253
+ /**
254
+ * Get a thread by ID for a specific assistant
255
+ */
256
+ async getThreadById(assistantId, threadId) {
257
+ await this.ensureInitialized();
258
+ const result = await this.pool.query(
259
+ `
260
+ SELECT id, assistant_id, metadata, created_at, updated_at
261
+ FROM lattice_threads
262
+ WHERE id = $1 AND assistant_id = $2
263
+ `,
264
+ [threadId, assistantId]
265
+ );
266
+ if (result.rows.length === 0) {
267
+ return void 0;
268
+ }
269
+ return this.mapRowToThread(result.rows[0]);
270
+ }
271
+ /**
272
+ * Create a new thread for an assistant
273
+ */
274
+ async createThread(assistantId, threadId, data) {
275
+ await this.ensureInitialized();
276
+ const now = /* @__PURE__ */ new Date();
277
+ const metadata = data.metadata || {};
278
+ await this.pool.query(
279
+ `
280
+ INSERT INTO lattice_threads (id, assistant_id, metadata, created_at, updated_at)
281
+ VALUES ($1, $2, $3, $4, $5)
282
+ ON CONFLICT (id, assistant_id) DO UPDATE SET
283
+ metadata = EXCLUDED.metadata,
284
+ updated_at = EXCLUDED.updated_at
285
+ `,
286
+ [threadId, assistantId, JSON.stringify(metadata), now, now]
287
+ );
288
+ return {
289
+ id: threadId,
290
+ assistantId,
291
+ metadata,
292
+ createdAt: now,
293
+ updatedAt: now
294
+ };
295
+ }
296
+ /**
297
+ * Update an existing thread
298
+ */
299
+ async updateThread(assistantId, threadId, updates) {
300
+ await this.ensureInitialized();
301
+ const existing = await this.getThreadById(assistantId, threadId);
302
+ if (!existing) {
303
+ return null;
304
+ }
305
+ const updatedMetadata = {
306
+ ...existing.metadata,
307
+ ...updates.metadata || {}
308
+ };
309
+ const now = /* @__PURE__ */ new Date();
310
+ await this.pool.query(
311
+ `
312
+ UPDATE lattice_threads
313
+ SET metadata = $1, updated_at = $2
314
+ WHERE id = $3 AND assistant_id = $4
315
+ `,
316
+ [JSON.stringify(updatedMetadata), now, threadId, assistantId]
317
+ );
318
+ return {
319
+ ...existing,
320
+ metadata: updatedMetadata,
321
+ updatedAt: now
322
+ };
323
+ }
324
+ /**
325
+ * Delete a thread by ID
326
+ */
327
+ async deleteThread(assistantId, threadId) {
328
+ await this.ensureInitialized();
329
+ const result = await this.pool.query(
330
+ `
331
+ DELETE FROM lattice_threads
332
+ WHERE id = $1 AND assistant_id = $2
333
+ `,
334
+ [threadId, assistantId]
335
+ );
336
+ return result.rowCount !== null && result.rowCount > 0;
337
+ }
338
+ /**
339
+ * Check if thread exists
340
+ */
341
+ async hasThread(assistantId, threadId) {
342
+ await this.ensureInitialized();
343
+ const result = await this.pool.query(
344
+ `
345
+ SELECT 1 FROM lattice_threads
346
+ WHERE id = $1 AND assistant_id = $2
347
+ LIMIT 1
348
+ `,
349
+ [threadId, assistantId]
350
+ );
351
+ return result.rows.length > 0;
352
+ }
353
+ /**
354
+ * Ensure store is initialized
355
+ */
356
+ async ensureInitialized() {
357
+ if (!this.initialized) {
358
+ await this.initialize();
359
+ }
360
+ }
361
+ /**
362
+ * Map database row to Thread object
363
+ */
364
+ mapRowToThread(row) {
365
+ return {
366
+ id: row.id,
367
+ assistantId: row.assistant_id,
368
+ metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata || {},
369
+ createdAt: row.created_at,
370
+ updatedAt: row.updated_at
371
+ };
372
+ }
373
+ };
374
+
375
+ // src/stores/PostgreSQLAssistantStore.ts
376
+ var import_pg2 = require("pg");
377
+
378
+ // src/migrations/assistant_migrations.ts
379
+ var createAssistantsTable = {
380
+ version: 1,
381
+ name: "create_assistants_table",
382
+ up: async (client) => {
383
+ await client.query(`
384
+ CREATE TABLE IF NOT EXISTS lattice_assistants (
385
+ id VARCHAR(255) PRIMARY KEY,
386
+ name VARCHAR(255) NOT NULL,
387
+ description TEXT,
388
+ graph_definition JSONB NOT NULL,
389
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
390
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
391
+ )
392
+ `);
393
+ await client.query(`
394
+ CREATE INDEX IF NOT EXISTS idx_lattice_assistants_name
395
+ ON lattice_assistants(name)
396
+ `);
397
+ await client.query(`
398
+ CREATE INDEX IF NOT EXISTS idx_lattice_assistants_created_at
399
+ ON lattice_assistants(created_at DESC)
400
+ `);
401
+ },
402
+ down: async (client) => {
403
+ await client.query(
404
+ "DROP INDEX IF EXISTS idx_lattice_assistants_created_at"
405
+ );
406
+ await client.query("DROP INDEX IF EXISTS idx_lattice_assistants_name");
407
+ await client.query("DROP TABLE IF EXISTS lattice_assistants");
408
+ }
409
+ };
410
+
411
+ // src/stores/PostgreSQLAssistantStore.ts
412
+ var PostgreSQLAssistantStore = class {
413
+ constructor(options) {
414
+ this.initialized = false;
415
+ this.ownsPool = true;
416
+ if (typeof options.poolConfig === "string") {
417
+ this.pool = new import_pg2.Pool({ connectionString: options.poolConfig });
418
+ } else {
419
+ this.pool = new import_pg2.Pool(options.poolConfig);
420
+ }
421
+ this.migrationManager = new MigrationManager(this.pool);
422
+ this.migrationManager.register(createAssistantsTable);
423
+ if (options.autoMigrate !== false) {
424
+ this.initialize().catch((error) => {
425
+ console.error("Failed to initialize PostgreSQLAssistantStore:", error);
426
+ throw error;
427
+ });
428
+ }
429
+ }
430
+ /**
431
+ * Initialize the store and run migrations
432
+ */
433
+ async initialize() {
434
+ if (this.initialized) {
435
+ return;
436
+ }
437
+ await this.migrationManager.migrate();
438
+ this.initialized = true;
439
+ }
440
+ /**
441
+ * Get all assistants
442
+ */
443
+ async getAllAssistants() {
444
+ await this.ensureInitialized();
445
+ const result = await this.pool.query(
446
+ `
447
+ SELECT id, name, description, graph_definition, created_at, updated_at
448
+ FROM lattice_assistants
449
+ ORDER BY created_at DESC
450
+ `
451
+ );
452
+ return result.rows.map(this.mapRowToAssistant);
453
+ }
454
+ /**
455
+ * Get assistant by ID
456
+ */
457
+ async getAssistantById(id) {
458
+ await this.ensureInitialized();
459
+ const result = await this.pool.query(
460
+ `
461
+ SELECT id, name, description, graph_definition, created_at, updated_at
462
+ FROM lattice_assistants
463
+ WHERE id = $1
464
+ `,
465
+ [id]
466
+ );
467
+ if (result.rows.length === 0) {
468
+ return null;
469
+ }
470
+ return this.mapRowToAssistant(result.rows[0]);
471
+ }
472
+ /**
473
+ * Create a new assistant
474
+ */
475
+ async createAssistant(id, data) {
476
+ await this.ensureInitialized();
477
+ const now = /* @__PURE__ */ new Date();
478
+ await this.pool.query(
479
+ `
480
+ INSERT INTO lattice_assistants (id, name, description, graph_definition, created_at, updated_at)
481
+ VALUES ($1, $2, $3, $4, $5, $6)
482
+ ON CONFLICT (id) DO UPDATE SET
483
+ name = EXCLUDED.name,
484
+ description = EXCLUDED.description,
485
+ graph_definition = EXCLUDED.graph_definition,
486
+ updated_at = EXCLUDED.updated_at
487
+ `,
488
+ [
489
+ id,
490
+ data.name,
491
+ data.description || null,
492
+ JSON.stringify(data.graphDefinition),
493
+ now,
494
+ now
495
+ ]
496
+ );
497
+ return {
498
+ id,
499
+ name: data.name,
500
+ description: data.description,
501
+ graphDefinition: data.graphDefinition,
502
+ createdAt: now,
503
+ updatedAt: now
504
+ };
505
+ }
506
+ /**
507
+ * Update an existing assistant
508
+ */
509
+ async updateAssistant(id, updates) {
510
+ await this.ensureInitialized();
511
+ const existing = await this.getAssistantById(id);
512
+ if (!existing) {
513
+ return null;
514
+ }
515
+ const updateFields = [];
516
+ const updateValues = [];
517
+ let paramIndex = 1;
518
+ if (updates.name !== void 0) {
519
+ updateFields.push(`name = $${paramIndex++}`);
520
+ updateValues.push(updates.name);
521
+ }
522
+ if (updates.description !== void 0) {
523
+ updateFields.push(`description = $${paramIndex++}`);
524
+ updateValues.push(updates.description || null);
525
+ }
526
+ if (updates.graphDefinition !== void 0) {
527
+ updateFields.push(`graph_definition = $${paramIndex++}`);
528
+ updateValues.push(JSON.stringify(updates.graphDefinition));
529
+ }
530
+ if (updateFields.length === 0) {
531
+ return existing;
532
+ }
533
+ updateFields.push(`updated_at = $${paramIndex++}`);
534
+ updateValues.push(/* @__PURE__ */ new Date());
535
+ updateValues.push(id);
536
+ await this.pool.query(
537
+ `
538
+ UPDATE lattice_assistants
539
+ SET ${updateFields.join(", ")}
540
+ WHERE id = $${paramIndex}
541
+ `,
542
+ updateValues
543
+ );
544
+ return await this.getAssistantById(id);
545
+ }
546
+ /**
547
+ * Delete an assistant by ID
548
+ */
549
+ async deleteAssistant(id) {
550
+ await this.ensureInitialized();
551
+ const result = await this.pool.query(
552
+ `
553
+ DELETE FROM lattice_assistants
554
+ WHERE id = $1
555
+ `,
556
+ [id]
557
+ );
558
+ return result.rowCount !== null && result.rowCount > 0;
559
+ }
560
+ /**
561
+ * Check if assistant exists
562
+ */
563
+ async hasAssistant(id) {
564
+ await this.ensureInitialized();
565
+ const result = await this.pool.query(
566
+ `
567
+ SELECT 1 FROM lattice_assistants
568
+ WHERE id = $1
569
+ LIMIT 1
570
+ `,
571
+ [id]
572
+ );
573
+ return result.rows.length > 0;
574
+ }
575
+ /**
576
+ * Dispose resources and close the connection pool
577
+ * Should be called when the store is no longer needed
578
+ */
579
+ async dispose() {
580
+ if (this.ownsPool && this.pool) {
581
+ await this.pool.end();
582
+ }
583
+ }
584
+ /**
585
+ * Ensure store is initialized
586
+ */
587
+ async ensureInitialized() {
588
+ if (!this.initialized) {
589
+ await this.initialize();
590
+ }
591
+ }
592
+ /**
593
+ * Map database row to Assistant object
594
+ */
595
+ mapRowToAssistant(row) {
596
+ return {
597
+ id: row.id,
598
+ name: row.name,
599
+ description: row.description || void 0,
600
+ graphDefinition: typeof row.graph_definition === "string" ? JSON.parse(row.graph_definition) : row.graph_definition,
601
+ createdAt: row.created_at,
602
+ updatedAt: row.updated_at
603
+ };
604
+ }
605
+ };
606
+ // Annotate the CommonJS export names for ESM import in node:
607
+ 0 && (module.exports = {
608
+ MigrationManager,
609
+ PostgreSQLAssistantStore,
610
+ PostgreSQLThreadStore,
611
+ createAssistantsTable,
612
+ createThreadsTable
613
+ });
614
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/stores/PostgreSQLThreadStore.ts","../src/migrations/migration.ts","../src/migrations/thread_migrations.ts","../src/stores/PostgreSQLAssistantStore.ts","../src/migrations/assistant_migrations.ts"],"sourcesContent":["/**\n * PostgreSQL Stores Package\n *\n * Provides PostgreSQL implementations for various stores\n */\n\nexport * from \"./stores/PostgreSQLThreadStore\";\nexport * from \"./stores/PostgreSQLAssistantStore\";\nexport * from \"./migrations/migration\";\nexport * from \"./migrations/thread_migrations\";\nexport * from \"./migrations/assistant_migrations\";\n\n// Re-export for convenience\nexport { PostgreSQLThreadStore } from \"./stores/PostgreSQLThreadStore\";\nexport { PostgreSQLAssistantStore } from \"./stores/PostgreSQLAssistantStore\";\n\n// Re-export types from protocols\nexport type {\n ThreadStore,\n Thread,\n CreateThreadRequest,\n AssistantStore,\n Assistant,\n CreateAssistantRequest,\n} from \"@axiom-lattice/protocols\";\n","/**\n * PostgreSQL implementation of ThreadStore\n */\n\nimport { Pool, PoolClient, PoolConfig } from \"pg\";\nimport {\n ThreadStore,\n Thread,\n CreateThreadRequest,\n} from \"@axiom-lattice/protocols\";\nimport { MigrationManager } from \"../migrations/migration\";\nimport { createThreadsTable } from \"../migrations/thread_migrations\";\n\n/**\n * PostgreSQL ThreadStore options\n */\nexport interface PostgreSQLThreadStoreOptions {\n /**\n * PostgreSQL connection pool configuration\n * Can be a connection string or PoolConfig object\n */\n poolConfig: string | PoolConfig;\n\n /**\n * Whether to run migrations automatically on initialization\n * @default true\n */\n autoMigrate?: boolean;\n}\n\n/**\n * PostgreSQL implementation of ThreadStore\n */\nexport class PostgreSQLThreadStore implements ThreadStore {\n private pool: Pool;\n private migrationManager: MigrationManager;\n private initialized: boolean = false;\n private ownsPool: boolean = true;\n\n constructor(options: PostgreSQLThreadStoreOptions) {\n // Create Pool from config\n if (typeof options.poolConfig === \"string\") {\n this.pool = new Pool({ connectionString: options.poolConfig });\n } else {\n this.pool = new Pool(options.poolConfig);\n }\n\n this.migrationManager = new MigrationManager(this.pool);\n this.migrationManager.register(createThreadsTable);\n\n // Auto-migrate by default\n if (options.autoMigrate !== false) {\n this.initialize().catch((error) => {\n console.error(\"Failed to initialize PostgreSQLThreadStore:\", error);\n throw error;\n });\n }\n }\n\n /**\n * Dispose resources and close the connection pool\n * Should be called when the store is no longer needed\n */\n async dispose(): Promise<void> {\n if (this.ownsPool && this.pool) {\n await this.pool.end();\n }\n }\n\n /**\n * Initialize the store and run migrations\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n await this.migrationManager.migrate();\n this.initialized = true;\n }\n\n /**\n * Get all threads for a specific assistant\n */\n async getThreadsByAssistantId(assistantId: string): Promise<Thread[]> {\n await this.ensureInitialized();\n\n const result = await this.pool.query<{\n id: string;\n assistant_id: string;\n metadata: any;\n created_at: Date;\n updated_at: Date;\n }>(\n `\n SELECT id, assistant_id, metadata, created_at, updated_at\n FROM lattice_threads\n WHERE assistant_id = $1\n ORDER BY created_at DESC\n `,\n [assistantId]\n );\n\n return result.rows.map(this.mapRowToThread);\n }\n\n /**\n * Get a thread by ID for a specific assistant\n */\n async getThreadById(\n assistantId: string,\n threadId: string\n ): Promise<Thread | undefined> {\n await this.ensureInitialized();\n\n const result = await this.pool.query<{\n id: string;\n assistant_id: string;\n metadata: any;\n created_at: Date;\n updated_at: Date;\n }>(\n `\n SELECT id, assistant_id, metadata, created_at, updated_at\n FROM lattice_threads\n WHERE id = $1 AND assistant_id = $2\n `,\n [threadId, assistantId]\n );\n\n if (result.rows.length === 0) {\n return undefined;\n }\n\n return this.mapRowToThread(result.rows[0]);\n }\n\n /**\n * Create a new thread for an assistant\n */\n async createThread(\n assistantId: string,\n threadId: string,\n data: CreateThreadRequest\n ): Promise<Thread> {\n await this.ensureInitialized();\n\n const now = new Date();\n const metadata = data.metadata || {};\n\n await this.pool.query(\n `\n INSERT INTO lattice_threads (id, assistant_id, metadata, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (id, assistant_id) DO UPDATE SET\n metadata = EXCLUDED.metadata,\n updated_at = EXCLUDED.updated_at\n `,\n [threadId, assistantId, JSON.stringify(metadata), now, now]\n );\n\n return {\n id: threadId,\n assistantId,\n metadata,\n createdAt: now,\n updatedAt: now,\n };\n }\n\n /**\n * Update an existing thread\n */\n async updateThread(\n assistantId: string,\n threadId: string,\n updates: Partial<CreateThreadRequest>\n ): Promise<Thread | null> {\n await this.ensureInitialized();\n\n // Get existing thread\n const existing = await this.getThreadById(assistantId, threadId);\n if (!existing) {\n return null;\n }\n\n // Merge metadata\n const updatedMetadata = {\n ...existing.metadata,\n ...(updates.metadata || {}),\n };\n\n const now = new Date();\n\n await this.pool.query(\n `\n UPDATE lattice_threads\n SET metadata = $1, updated_at = $2\n WHERE id = $3 AND assistant_id = $4\n `,\n [JSON.stringify(updatedMetadata), now, threadId, assistantId]\n );\n\n return {\n ...existing,\n metadata: updatedMetadata,\n updatedAt: now,\n };\n }\n\n /**\n * Delete a thread by ID\n */\n async deleteThread(assistantId: string, threadId: string): Promise<boolean> {\n await this.ensureInitialized();\n\n const result = await this.pool.query(\n `\n DELETE FROM lattice_threads\n WHERE id = $1 AND assistant_id = $2\n `,\n [threadId, assistantId]\n );\n\n return result.rowCount !== null && result.rowCount > 0;\n }\n\n /**\n * Check if thread exists\n */\n async hasThread(assistantId: string, threadId: string): Promise<boolean> {\n await this.ensureInitialized();\n\n const result = await this.pool.query(\n `\n SELECT 1 FROM lattice_threads\n WHERE id = $1 AND assistant_id = $2\n LIMIT 1\n `,\n [threadId, assistantId]\n );\n\n return result.rows.length > 0;\n }\n\n /**\n * Ensure store is initialized\n */\n private async ensureInitialized(): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Map database row to Thread object\n */\n private mapRowToThread(row: {\n id: string;\n assistant_id: string;\n metadata: any;\n created_at: Date;\n updated_at: Date;\n }): Thread {\n return {\n id: row.id,\n assistantId: row.assistant_id,\n metadata:\n typeof row.metadata === \"string\"\n ? JSON.parse(row.metadata)\n : row.metadata || {},\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n }\n}\n","/**\n * Migration system for database schema management\n */\n\nimport { Pool, PoolClient } from \"pg\";\n\n/**\n * Migration record stored in database\n */\ninterface MigrationRecord {\n version: number;\n name: string;\n applied_at: Date;\n}\n\n/**\n * Migration definition\n */\nexport interface Migration {\n version: number;\n name: string;\n up: (client: PoolClient) => Promise<void>;\n down?: (client: PoolClient) => Promise<void>;\n}\n\n/**\n * Migration manager\n */\nexport class MigrationManager {\n private pool: Pool;\n private migrations: Migration[] = [];\n\n constructor(pool: Pool) {\n this.pool = pool;\n }\n\n /**\n * Register a migration\n */\n register(migration: Migration): void {\n this.migrations.push(migration);\n // Sort migrations by version\n this.migrations.sort((a, b) => a.version - b.version);\n }\n\n /**\n * Initialize migrations table if it doesn't exist\n */\n private async ensureMigrationsTable(client: PoolClient): Promise<void> {\n await client.query(`\n CREATE TABLE IF NOT EXISTS lattice_schema_migrations (\n version INTEGER PRIMARY KEY,\n name VARCHAR(255) NOT NULL,\n applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n )\n `);\n }\n\n /**\n * Get applied migrations from database\n */\n private async getAppliedMigrations(\n client: PoolClient\n ): Promise<MigrationRecord[]> {\n await client.query(`\n CREATE TABLE IF NOT EXISTS lattice_schema_migrations (\n version INTEGER PRIMARY KEY,\n name VARCHAR(255) NOT NULL,\n applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n )\n `);\n\n const result = await client.query<MigrationRecord>(\n \"SELECT version, name, applied_at FROM lattice_schema_migrations ORDER BY version\"\n );\n return result.rows;\n }\n\n /**\n * Apply pending migrations\n */\n async migrate(): Promise<void> {\n const client = await this.pool.connect();\n try {\n await client.query(\"BEGIN\");\n\n await this.ensureMigrationsTable(client);\n const appliedMigrations = await this.getAppliedMigrations(client);\n const appliedVersions = new Set(appliedMigrations.map((m) => m.version));\n\n // Find pending migrations\n const pendingMigrations = this.migrations.filter(\n (m) => !appliedVersions.has(m.version)\n );\n\n if (pendingMigrations.length === 0) {\n console.log(\"No pending migrations\");\n await client.query(\"COMMIT\");\n return;\n }\n\n // Apply pending migrations\n for (const migration of pendingMigrations) {\n console.log(\n `Applying migration ${migration.version}: ${migration.name}`\n );\n await migration.up(client);\n await client.query(\n \"INSERT INTO lattice_schema_migrations (version, name) VALUES ($1, $2)\",\n [migration.version, migration.name]\n );\n }\n\n await client.query(\"COMMIT\");\n console.log(`Applied ${pendingMigrations.length} migration(s)`);\n } catch (error) {\n await client.query(\"ROLLBACK\");\n throw error;\n } finally {\n client.release();\n }\n }\n\n /**\n * Rollback last migration\n */\n async rollback(): Promise<void> {\n const client = await this.pool.connect();\n try {\n await client.query(\"BEGIN\");\n\n const appliedMigrations = await this.getAppliedMigrations(client);\n if (appliedMigrations.length === 0) {\n console.log(\"No migrations to rollback\");\n await client.query(\"COMMIT\");\n return;\n }\n\n const lastMigration = appliedMigrations[appliedMigrations.length - 1];\n const migration = this.migrations.find(\n (m) => m.version === lastMigration.version\n );\n\n if (!migration || !migration.down) {\n throw new Error(\n `Migration ${lastMigration.version} does not have a down migration`\n );\n }\n\n console.log(\n `Rolling back migration ${lastMigration.version}: ${lastMigration.name}`\n );\n await migration.down(client);\n await client.query(\n \"DELETE FROM lattice_schema_migrations WHERE version = $1\",\n [lastMigration.version]\n );\n\n await client.query(\"COMMIT\");\n console.log(\"Rollback completed\");\n } catch (error) {\n await client.query(\"ROLLBACK\");\n throw error;\n } finally {\n client.release();\n }\n }\n\n /**\n * Get current migration version\n */\n async getCurrentVersion(): Promise<number> {\n const client = await this.pool.connect();\n try {\n const appliedMigrations = await this.getAppliedMigrations(client);\n if (appliedMigrations.length === 0) {\n return 0;\n }\n return Math.max(...appliedMigrations.map((m) => m.version));\n } finally {\n client.release();\n }\n }\n}\n","/**\n * Thread table migrations\n */\n\nimport { PoolClient } from \"pg\";\nimport { Migration } from \"./migration\";\n\n/**\n * Initial migration: Create threads table\n */\nexport const createThreadsTable: Migration = {\n version: 1,\n name: \"create_threads_table\",\n up: async (client: PoolClient) => {\n await client.query(`\n CREATE TABLE IF NOT EXISTS lattice_threads (\n id VARCHAR(255) NOT NULL,\n assistant_id VARCHAR(255) NOT NULL,\n metadata JSONB DEFAULT '{}',\n created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY (id, assistant_id)\n )\n `);\n\n // Create indexes for better query performance\n await client.query(`\n CREATE INDEX IF NOT EXISTS idx_lattice_threads_assistant_id \n ON lattice_threads(assistant_id)\n `);\n\n await client.query(`\n CREATE INDEX IF NOT EXISTS idx_lattice_threads_created_at \n ON lattice_threads(created_at DESC)\n `);\n },\n down: async (client: PoolClient) => {\n await client.query(\"DROP INDEX IF EXISTS idx_lattice_threads_created_at\");\n await client.query(\"DROP INDEX IF EXISTS idx_lattice_threads_assistant_id\");\n await client.query(\"DROP TABLE IF EXISTS lattice_threads\");\n },\n};\n","/**\n * PostgreSQL implementation of AssistantStore\n */\n\nimport { Pool, PoolClient, PoolConfig } from \"pg\";\nimport {\n AssistantStore,\n Assistant,\n CreateAssistantRequest,\n} from \"@axiom-lattice/protocols\";\nimport { MigrationManager } from \"../migrations/migration\";\nimport { createAssistantsTable } from \"../migrations/assistant_migrations\";\n\n/**\n * PostgreSQL AssistantStore options\n */\nexport interface PostgreSQLAssistantStoreOptions {\n /**\n * PostgreSQL connection pool configuration\n * Can be a connection string or PoolConfig object\n */\n poolConfig: string | PoolConfig;\n\n /**\n * Whether to run migrations automatically on initialization\n * @default true\n */\n autoMigrate?: boolean;\n}\n\n/**\n * PostgreSQL implementation of AssistantStore\n */\nexport class PostgreSQLAssistantStore implements AssistantStore {\n private pool: Pool;\n private migrationManager: MigrationManager;\n private initialized: boolean = false;\n private ownsPool: boolean = true;\n\n constructor(options: PostgreSQLAssistantStoreOptions) {\n // Create Pool from config\n if (typeof options.poolConfig === \"string\") {\n this.pool = new Pool({ connectionString: options.poolConfig });\n } else {\n this.pool = new Pool(options.poolConfig);\n }\n\n this.migrationManager = new MigrationManager(this.pool);\n this.migrationManager.register(createAssistantsTable);\n\n // Auto-migrate by default\n if (options.autoMigrate !== false) {\n this.initialize().catch((error) => {\n console.error(\"Failed to initialize PostgreSQLAssistantStore:\", error);\n throw error;\n });\n }\n }\n\n /**\n * Initialize the store and run migrations\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n await this.migrationManager.migrate();\n this.initialized = true;\n }\n\n /**\n * Get all assistants\n */\n async getAllAssistants(): Promise<Assistant[]> {\n await this.ensureInitialized();\n\n const result = await this.pool.query<{\n id: string;\n name: string;\n description: string | null;\n graph_definition: any;\n created_at: Date;\n updated_at: Date;\n }>(\n `\n SELECT id, name, description, graph_definition, created_at, updated_at\n FROM lattice_assistants\n ORDER BY created_at DESC\n `\n );\n\n return result.rows.map(this.mapRowToAssistant);\n }\n\n /**\n * Get assistant by ID\n */\n async getAssistantById(id: string): Promise<Assistant | null> {\n await this.ensureInitialized();\n\n const result = await this.pool.query<{\n id: string;\n name: string;\n description: string | null;\n graph_definition: any;\n created_at: Date;\n updated_at: Date;\n }>(\n `\n SELECT id, name, description, graph_definition, created_at, updated_at\n FROM lattice_assistants\n WHERE id = $1\n `,\n [id]\n );\n\n if (result.rows.length === 0) {\n return null;\n }\n\n return this.mapRowToAssistant(result.rows[0]);\n }\n\n /**\n * Create a new assistant\n */\n async createAssistant(\n id: string,\n data: CreateAssistantRequest\n ): Promise<Assistant> {\n await this.ensureInitialized();\n\n const now = new Date();\n\n await this.pool.query(\n `\n INSERT INTO lattice_assistants (id, name, description, graph_definition, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (id) DO UPDATE SET\n name = EXCLUDED.name,\n description = EXCLUDED.description,\n graph_definition = EXCLUDED.graph_definition,\n updated_at = EXCLUDED.updated_at\n `,\n [\n id,\n data.name,\n data.description || null,\n JSON.stringify(data.graphDefinition),\n now,\n now,\n ]\n );\n\n return {\n id,\n name: data.name,\n description: data.description,\n graphDefinition: data.graphDefinition,\n createdAt: now,\n updatedAt: now,\n };\n }\n\n /**\n * Update an existing assistant\n */\n async updateAssistant(\n id: string,\n updates: Partial<CreateAssistantRequest>\n ): Promise<Assistant | null> {\n await this.ensureInitialized();\n\n // Get existing assistant\n const existing = await this.getAssistantById(id);\n if (!existing) {\n return null;\n }\n\n // Build update query dynamically based on provided fields\n const updateFields: string[] = [];\n const updateValues: any[] = [];\n let paramIndex = 1;\n\n if (updates.name !== undefined) {\n updateFields.push(`name = $${paramIndex++}`);\n updateValues.push(updates.name);\n }\n\n if (updates.description !== undefined) {\n updateFields.push(`description = $${paramIndex++}`);\n updateValues.push(updates.description || null);\n }\n\n if (updates.graphDefinition !== undefined) {\n updateFields.push(`graph_definition = $${paramIndex++}`);\n updateValues.push(JSON.stringify(updates.graphDefinition));\n }\n\n if (updateFields.length === 0) {\n // No fields to update\n return existing;\n }\n\n // Always update updated_at\n updateFields.push(`updated_at = $${paramIndex++}`);\n updateValues.push(new Date());\n\n // Add id for WHERE clause\n updateValues.push(id);\n\n await this.pool.query(\n `\n UPDATE lattice_assistants\n SET ${updateFields.join(\", \")}\n WHERE id = $${paramIndex}\n `,\n updateValues\n );\n\n // Return updated assistant\n return await this.getAssistantById(id);\n }\n\n /**\n * Delete an assistant by ID\n */\n async deleteAssistant(id: string): Promise<boolean> {\n await this.ensureInitialized();\n\n const result = await this.pool.query(\n `\n DELETE FROM lattice_assistants\n WHERE id = $1\n `,\n [id]\n );\n\n return result.rowCount !== null && result.rowCount > 0;\n }\n\n /**\n * Check if assistant exists\n */\n async hasAssistant(id: string): Promise<boolean> {\n await this.ensureInitialized();\n\n const result = await this.pool.query(\n `\n SELECT 1 FROM lattice_assistants\n WHERE id = $1\n LIMIT 1\n `,\n [id]\n );\n\n return result.rows.length > 0;\n }\n\n /**\n * Dispose resources and close the connection pool\n * Should be called when the store is no longer needed\n */\n async dispose(): Promise<void> {\n if (this.ownsPool && this.pool) {\n await this.pool.end();\n }\n }\n\n /**\n * Ensure store is initialized\n */\n private async ensureInitialized(): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Map database row to Assistant object\n */\n private mapRowToAssistant(row: {\n id: string;\n name: string;\n description: string | null;\n graph_definition: any;\n created_at: Date;\n updated_at: Date;\n }): Assistant {\n return {\n id: row.id,\n name: row.name,\n description: row.description || undefined,\n graphDefinition:\n typeof row.graph_definition === \"string\"\n ? JSON.parse(row.graph_definition)\n : row.graph_definition,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n }\n}\n","/**\n * Assistant table migrations\n */\n\nimport { PoolClient } from \"pg\";\nimport { Migration } from \"./migration\";\n\n/**\n * Initial migration: Create assistants table\n */\nexport const createAssistantsTable: Migration = {\n version: 1,\n name: \"create_assistants_table\",\n up: async (client: PoolClient) => {\n await client.query(`\n CREATE TABLE IF NOT EXISTS lattice_assistants (\n id VARCHAR(255) PRIMARY KEY,\n name VARCHAR(255) NOT NULL,\n description TEXT,\n graph_definition JSONB NOT NULL,\n created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n )\n `);\n\n // Create indexes for better query performance\n await client.query(`\n CREATE INDEX IF NOT EXISTS idx_lattice_assistants_name \n ON lattice_assistants(name)\n `);\n\n await client.query(`\n CREATE INDEX IF NOT EXISTS idx_lattice_assistants_created_at \n ON lattice_assistants(created_at DESC)\n `);\n },\n down: async (client: PoolClient) => {\n await client.query(\n \"DROP INDEX IF EXISTS idx_lattice_assistants_created_at\"\n );\n await client.query(\"DROP INDEX IF EXISTS idx_lattice_assistants_name\");\n await client.query(\"DROP TABLE IF EXISTS lattice_assistants\");\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,gBAA6C;;;ACwBt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