@voltagent/libsql 0.1.0 → 1.0.0-next.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.d.ts CHANGED
@@ -1,117 +1,201 @@
1
- import { WorkflowHistoryEntry, WorkflowStepHistoryEntry, WorkflowTimelineEvent, WorkflowStats, MemoryOptions, Memory, MessageFilterOptions, MemoryMessage, NewTimelineEvent, CreateConversationInput, Conversation, ConversationQueryOptions } from '@voltagent/core';
1
+ import { StorageAdapter, GetMessagesOptions, CreateConversationInput, Conversation, ConversationQueryOptions, WorkingMemoryScope, WorkflowStateEntry, ObservabilityStorageAdapter, ObservabilitySpan, ObservabilityLogRecord, LogFilter, VectorAdapter, VectorItem, VectorSearchOptions, SearchResult } from '@voltagent/core';
2
2
  import { Logger } from '@voltagent/logger';
3
- import { Client } from '@libsql/client';
3
+ import { UIMessage } from 'ai';
4
4
 
5
5
  /**
6
- * LibSQL extension for workflow memory operations
7
- * This class provides workflow-specific storage operations for LibSQL
6
+ * LibSQL Storage Adapter for Memory
7
+ * Stores conversations and messages in SQLite/Turso database
8
+ * Compatible with existing LibSQL storage structure
8
9
  */
9
- declare class LibSQLWorkflowExtension {
10
+
11
+ /**
12
+ * LibSQL configuration options for Memory
13
+ */
14
+ interface LibSQLMemoryOptions {
15
+ /**
16
+ * Database URL (e.g., 'file:./conversations.db' or 'libsql://...')
17
+ * @default "file:./.voltagent/memory.db"
18
+ */
19
+ url?: string;
20
+ /**
21
+ * Auth token for remote connections (optional)
22
+ */
23
+ authToken?: string;
24
+ /**
25
+ * Maximum number of messages to store per conversation
26
+ * @default 100
27
+ */
28
+ storageLimit?: number;
29
+ /**
30
+ * Prefix for table names
31
+ * @default "voltagent_memory"
32
+ */
33
+ tablePrefix?: string;
34
+ /**
35
+ * Enable debug logging
36
+ * @default false
37
+ */
38
+ debug?: boolean;
39
+ /**
40
+ * Logger instance
41
+ */
42
+ logger?: Logger;
43
+ /**
44
+ * Maximum number of retries for database operations
45
+ * @default 3
46
+ */
47
+ maxRetries?: number;
48
+ /**
49
+ * Initial retry delay in milliseconds
50
+ * @default 100
51
+ */
52
+ retryDelayMs?: number;
53
+ }
54
+ /**
55
+ * LibSQL Storage Adapter for Memory
56
+ * Production-ready storage for conversations and messages
57
+ * Compatible with existing LibSQL storage structure
58
+ */
59
+ declare class LibSQLMemoryAdapter implements StorageAdapter {
10
60
  private client;
11
- private _tablePrefix;
61
+ private storageLimit;
62
+ private tablePrefix;
63
+ private initialized;
12
64
  private logger;
13
- constructor(client: Client, _tablePrefix?: string, logger?: Logger);
65
+ private maxRetries;
66
+ private retryDelayMs;
67
+ private url;
68
+ constructor(options?: LibSQLMemoryOptions);
69
+ /**
70
+ * Execute a database operation with retry logic
71
+ */
72
+ private executeWithRetry;
73
+ /**
74
+ * Initialize database schema
75
+ */
76
+ private initialize;
14
77
  /**
15
- * Store a workflow history entry
78
+ * Add new columns to messages table for V2 format if they don't exist
79
+ * This allows existing tables to support both old and new message formats
16
80
  */
17
- storeWorkflowHistory(entry: WorkflowHistoryEntry): Promise<void>;
81
+ private addV2ColumnsToMessagesTable;
18
82
  /**
19
- * Get a workflow history entry by ID
83
+ * Migrate default user_id values in messages table
84
+ * Updates messages with user_id='default' to use the actual user_id from their conversation
20
85
  */
21
- getWorkflowHistory(id: string): Promise<WorkflowHistoryEntry | null>;
86
+ private migrateDefaultUserIds;
22
87
  /**
23
- * Get all workflow history entries for a specific workflow
88
+ * Add a single message
24
89
  */
25
- getWorkflowHistoryByWorkflowId(workflowId: string): Promise<WorkflowHistoryEntry[]>;
90
+ addMessage(message: UIMessage, userId: string, conversationId: string): Promise<void>;
26
91
  /**
27
- * Update a workflow history entry
92
+ * Add multiple messages
28
93
  */
29
- updateWorkflowHistory(id: string, updates: Partial<WorkflowHistoryEntry>): Promise<void>;
94
+ addMessages(messages: UIMessage[], userId: string, conversationId: string): Promise<void>;
30
95
  /**
31
- * Delete a workflow history entry
96
+ * Apply storage limit to a conversation
32
97
  */
33
- deleteWorkflowHistory(id: string): Promise<void>;
98
+ private applyStorageLimit;
34
99
  /**
35
- * Store a workflow step entry
100
+ * Get messages with optional filtering
36
101
  */
37
- storeWorkflowStep(step: WorkflowStepHistoryEntry): Promise<void>;
102
+ getMessages(userId: string, conversationId: string, options?: GetMessagesOptions): Promise<UIMessage[]>;
38
103
  /**
39
- * Get a workflow step by ID
104
+ * Clear messages for a user
40
105
  */
41
- getWorkflowStep(id: string): Promise<WorkflowStepHistoryEntry | null>;
106
+ clearMessages(userId: string, conversationId?: string): Promise<void>;
42
107
  /**
43
- * Get all workflow steps for a specific workflow history
108
+ * Create a new conversation
44
109
  */
45
- getWorkflowSteps(workflowHistoryId: string): Promise<WorkflowStepHistoryEntry[]>;
110
+ createConversation(input: CreateConversationInput): Promise<Conversation>;
46
111
  /**
47
- * Update a workflow step
112
+ * Get a conversation by ID
48
113
  */
49
- updateWorkflowStep(id: string, updates: Partial<WorkflowStepHistoryEntry>): Promise<void>;
114
+ getConversation(id: string): Promise<Conversation | null>;
50
115
  /**
51
- * Delete a workflow step
116
+ * Get conversations by resource ID
52
117
  */
53
- deleteWorkflowStep(id: string): Promise<void>;
118
+ getConversations(resourceId: string): Promise<Conversation[]>;
54
119
  /**
55
- * Store a workflow timeline event
120
+ * Get conversations by user ID
56
121
  */
57
- storeWorkflowTimelineEvent(event: WorkflowTimelineEvent): Promise<void>;
122
+ getConversationsByUserId(userId: string, options?: Omit<ConversationQueryOptions, "userId">): Promise<Conversation[]>;
58
123
  /**
59
- * Get a workflow timeline event by ID
124
+ * Query conversations with filters
60
125
  */
61
- getWorkflowTimelineEvent(id: string): Promise<WorkflowTimelineEvent | null>;
126
+ queryConversations(options: ConversationQueryOptions): Promise<Conversation[]>;
62
127
  /**
63
- * Get all workflow timeline events for a specific workflow history
128
+ * Update a conversation
64
129
  */
65
- getWorkflowTimelineEvents(workflowHistoryId: string): Promise<WorkflowTimelineEvent[]>;
130
+ updateConversation(id: string, updates: Partial<Omit<Conversation, "id" | "createdAt" | "updatedAt">>): Promise<Conversation>;
66
131
  /**
67
- * Delete a workflow timeline event
132
+ * Delete a conversation
68
133
  */
69
- deleteWorkflowTimelineEvent(id: string): Promise<void>;
134
+ deleteConversation(id: string): Promise<void>;
70
135
  /**
71
- * Get all workflow IDs
136
+ * Get working memory
72
137
  */
73
- getAllWorkflowIds(): Promise<string[]>;
138
+ getWorkingMemory(params: {
139
+ conversationId?: string;
140
+ userId?: string;
141
+ scope: WorkingMemoryScope;
142
+ }): Promise<string | null>;
74
143
  /**
75
- * Get workflow statistics
144
+ * Set working memory
76
145
  */
77
- getWorkflowStats(workflowId: string): Promise<WorkflowStats>;
146
+ setWorkingMemory(params: {
147
+ conversationId?: string;
148
+ userId?: string;
149
+ content: string;
150
+ scope: WorkingMemoryScope;
151
+ }): Promise<void>;
78
152
  /**
79
- * Get workflow history with all related data (steps and events)
153
+ * Delete working memory
80
154
  */
81
- getWorkflowHistoryWithStepsAndEvents(id: string): Promise<WorkflowHistoryEntry | null>;
155
+ deleteWorkingMemory(params: {
156
+ conversationId?: string;
157
+ userId?: string;
158
+ scope: WorkingMemoryScope;
159
+ }): Promise<void>;
82
160
  /**
83
- * Delete workflow history and all related data
161
+ * Get workflow state by execution ID
84
162
  */
85
- deleteWorkflowHistoryWithRelated(id: string): Promise<void>;
163
+ getWorkflowState(executionId: string): Promise<WorkflowStateEntry | null>;
86
164
  /**
87
- * Clean up old workflow histories
165
+ * Set workflow state
88
166
  */
89
- cleanupOldWorkflowHistories(workflowId: string, maxEntries: number): Promise<number>;
167
+ setWorkflowState(executionId: string, state: WorkflowStateEntry): Promise<void>;
90
168
  /**
91
- * Parse workflow history row from database
169
+ * Update workflow state
92
170
  */
93
- private parseWorkflowHistoryRow;
171
+ updateWorkflowState(executionId: string, updates: Partial<WorkflowStateEntry>): Promise<void>;
94
172
  /**
95
- * Parse workflow step row from database
173
+ * Get suspended workflow states for a workflow
96
174
  */
97
- private parseWorkflowStepRow;
175
+ getSuspendedWorkflowStates(workflowId: string): Promise<WorkflowStateEntry[]>;
98
176
  /**
99
- * Parse workflow timeline event row from database
177
+ * Close database connection
100
178
  */
101
- private parseWorkflowTimelineEventRow;
179
+ close(): Promise<void>;
102
180
  }
103
181
 
104
182
  /**
105
- * Options for configuring the LibSQLStorage
183
+ * LibSQL Observability Adapter
184
+ * Provides persistent storage for OpenTelemetry spans using LibSQL/Turso database
185
+ * Part of the OpenTelemetry observability migration (Phase 3)
186
+ */
187
+
188
+ /**
189
+ * Options for configuring the LibSQLObservabilityAdapter
106
190
  */
107
- interface LibSQLStorageOptions extends MemoryOptions {
191
+ interface LibSQLObservabilityOptions {
108
192
  /**
109
193
  * LibSQL connection URL
110
194
  * Can be either a remote Turso URL or a local file path
111
- * @default "file:./.voltagent/memory.db"
195
+ * @default "file:./.voltagent/observability.db"
112
196
  * @example "libsql://your-database.turso.io" for remote Turso
113
- * @example "file:memory.db" for local SQLite in current directory
114
- * @example "file:.voltagent/memory.db" for local SQLite in .voltagent folder
197
+ * @example "file:observability.db" for local SQLite in current directory
198
+ * @example "file:.voltagent/observability.db" for local SQLite in .voltagent folder
115
199
  */
116
200
  url?: string;
117
201
  /**
@@ -121,7 +205,7 @@ interface LibSQLStorageOptions extends MemoryOptions {
121
205
  authToken?: string;
122
206
  /**
123
207
  * Prefix for table names
124
- * @default "voltagent_memory"
208
+ * @default "observability"
125
209
  */
126
210
  tablePrefix?: string;
127
211
  /**
@@ -130,390 +214,257 @@ interface LibSQLStorageOptions extends MemoryOptions {
130
214
  */
131
215
  debug?: boolean;
132
216
  /**
133
- * Storage limit for the LibSQLStorage
134
- * @default 100
217
+ * Optional logger instance
135
218
  */
136
- storageLimit?: number;
219
+ logger?: Logger;
137
220
  /**
138
- * Number of retry attempts for database operations when encountering busy/locked errors
139
- * @default 3
221
+ * Maximum number of spans to return in a single query
222
+ * @default 1000
140
223
  */
141
- retryAttempts?: number;
224
+ maxSpansPerQuery?: number;
225
+ }
226
+ /**
227
+ * LibSQL Observability Adapter
228
+ * Provides observability storage using LibSQL/Turso database
229
+ * Implements the ObservabilityStorageAdapter interface for OpenTelemetry spans
230
+ */
231
+ declare class LibSQLObservabilityAdapter implements ObservabilityStorageAdapter {
232
+ private client;
233
+ private tablePrefix;
234
+ private debug;
235
+ private logger;
236
+ private initialized;
237
+ private maxSpansPerQuery;
238
+ constructor(options?: LibSQLObservabilityOptions);
142
239
  /**
143
- * Base delay in milliseconds before retrying a failed operation
144
- * Uses a jittered exponential backoff strategy for better load distribution
145
- * @default 50
240
+ * Log a debug message if debug is enabled
146
241
  */
147
- baseDelayMs?: number;
242
+ private debugLog;
148
243
  /**
149
- * Optional logger instance
244
+ * Initialize database tables for observability
150
245
  */
151
- logger?: Logger;
152
- }
153
- declare class LibSQLStorage implements Memory {
154
- private client;
155
- private options;
156
- private initialized;
157
- private workflowExtension;
158
- private logger;
159
- private retryAttempts;
160
- private baseDelayMs;
246
+ private initializeDatabase;
161
247
  /**
162
- * Create a new LibSQL storage
163
- * @param options Configuration options
248
+ * Ensure database is initialized before operations
164
249
  */
165
- constructor(options: LibSQLStorageOptions);
250
+ private ensureInitialized;
166
251
  /**
167
- * Log a debug message if debug is enabled
168
- * @param message Message to log
169
- * @param data Additional data to log
252
+ * Add a span to the database
170
253
  */
171
- private debug;
254
+ addSpan(span: ObservabilitySpan): Promise<void>;
172
255
  /**
173
- * Calculate delay with jitter for better load distribution
174
- * @param attempt Current retry attempt number
175
- * @returns Delay in milliseconds
256
+ * Update an existing span
176
257
  */
177
- private calculateRetryDelay;
258
+ updateSpan(spanId: string, updates: Partial<ObservabilitySpan>): Promise<void>;
178
259
  /**
179
- * Execute a database operation with retry strategy
180
- * Implements jittered exponential backoff
181
- * @param operationFn The operation function to execute
182
- * @param operationName Operation name for logging
183
- * @returns The result of the operation
260
+ * Get a span by ID
184
261
  */
185
- private executeWithRetryStrategy;
262
+ getSpan(spanId: string): Promise<ObservabilitySpan | null>;
186
263
  /**
187
- * Initialize workflow tables
264
+ * Get all spans in a trace
188
265
  */
189
- private initializeWorkflowTables;
266
+ getTrace(traceId: string): Promise<ObservabilitySpan[]>;
190
267
  /**
191
- * Initialize the database tables
192
- * @returns Promise that resolves when initialization is complete
268
+ * List all traces with optional entity filter
193
269
  */
194
- private initializeDatabase;
270
+ listTraces(limit?: number, offset?: number, filter?: {
271
+ entityId?: string;
272
+ entityType?: "agent" | "workflow";
273
+ }): Promise<string[]>;
195
274
  /**
196
- * Generate a unique ID for a message
197
- * @returns Unique ID
275
+ * Delete old spans
198
276
  */
199
- private generateId;
277
+ deleteOldSpans(beforeTimestamp: number): Promise<number>;
200
278
  /**
201
- * Get messages with filtering options
202
- * @param options Filtering options
203
- * @returns Filtered messages
279
+ * Clear all spans, traces, and logs
204
280
  */
205
- getMessages(options?: MessageFilterOptions): Promise<MemoryMessage[]>;
281
+ clear(): Promise<void>;
206
282
  /**
207
- * Add a message to the conversation history
208
- * @param message Message to add
209
- * @param userId User identifier (optional, defaults to "default")
210
- * @param conversationId Conversation identifier (optional, defaults to "default")
283
+ * Convert a database row to an ObservabilitySpan
211
284
  */
212
- addMessage(message: MemoryMessage, conversationId?: string): Promise<void>;
285
+ private rowToSpan;
213
286
  /**
214
- * Prune old messages to respect storage limit
215
- * @param conversationId Conversation ID to prune messages for
287
+ * Get statistics about stored spans
216
288
  */
217
- private pruneOldMessages;
289
+ getStats(): Promise<{
290
+ spanCount: number;
291
+ traceCount: number;
292
+ oldestSpan?: Date;
293
+ newestSpan?: Date;
294
+ }>;
218
295
  /**
219
- * Clear messages from memory
296
+ * Save a log record to the database
220
297
  */
221
- clearMessages(options: {
222
- userId: string;
223
- conversationId?: string;
224
- }): Promise<void>;
298
+ saveLogRecord(logRecord: any): Promise<void>;
299
+ /**
300
+ * Get logs by trace ID
301
+ */
302
+ getLogsByTraceId(traceId: string): Promise<ObservabilityLogRecord[]>;
303
+ /**
304
+ * Get logs by span ID
305
+ */
306
+ getLogsBySpanId(spanId: string): Promise<ObservabilityLogRecord[]>;
307
+ /**
308
+ * Query logs with flexible filtering
309
+ */
310
+ queryLogs(filter: LogFilter): Promise<ObservabilityLogRecord[]>;
311
+ /**
312
+ * Delete old logs
313
+ */
314
+ deleteOldLogs(beforeTimestamp: number): Promise<number>;
315
+ /**
316
+ * Convert a database row to an ObservabilityLogRecord
317
+ */
318
+ private rowToLogRecord;
225
319
  /**
226
320
  * Close the database connection
227
321
  */
228
322
  close(): Promise<void>;
323
+ }
324
+
325
+ /**
326
+ * LibSQL Vector Adapter
327
+ * Provides vector storage and similarity search using LibSQL/Turso database
328
+ * Stores vectors as binary BLOBs for efficiency
329
+ */
330
+
331
+ /**
332
+ * LibSQL Vector Adapter configuration options
333
+ */
334
+ interface LibSQLVectorOptions {
229
335
  /**
230
- * Add or update a history entry
231
- * @param key Entry ID
232
- * @param value Entry data
233
- * @param agentId Agent ID for filtering
336
+ * Database URL (e.g., 'file:./memory.db' or 'libsql://...')
337
+ * @default "file:./.voltagent/memory.db"
234
338
  */
235
- addHistoryEntry(key: string, value: any, agentId: string): Promise<void>;
339
+ url?: string;
236
340
  /**
237
- * Update an existing history entry
238
- * @param key Entry ID
239
- * @param value Updated entry data
240
- * @param agentId Agent ID for filtering
341
+ * Auth token for remote connections (optional)
241
342
  */
242
- updateHistoryEntry(key: string, value: any, agentId: string): Promise<void>;
343
+ authToken?: string;
243
344
  /**
244
- * Add a history step
245
- * @param key Step ID
246
- * @param value Step data
247
- * @param historyId Related history entry ID
248
- * @param agentId Agent ID for filtering
345
+ * Prefix for table names
346
+ * @default "voltagent"
249
347
  */
250
- addHistoryStep(key: string, value: any, historyId: string, agentId: string): Promise<void>;
348
+ tablePrefix?: string;
251
349
  /**
252
- * Update a history step
253
- * @param key Step ID
254
- * @param value Updated step data
255
- * @param historyId Related history entry ID
256
- * @param agentId Agent ID for filtering
350
+ * Maximum vector dimensions allowed
351
+ * @default 1536
257
352
  */
258
- updateHistoryStep(key: string, value: any, historyId: string, agentId: string): Promise<void>;
353
+ maxVectorDimensions?: number;
259
354
  /**
260
- * Add a timeline event
261
- * @param key Event ID (UUID)
262
- * @param value Timeline event data
263
- * @param historyId Related history entry ID
264
- * @param agentId Agent ID for filtering
355
+ * Size of the LRU cache for frequently accessed vectors
356
+ * @default 100
265
357
  */
266
- addTimelineEvent(key: string, value: NewTimelineEvent, historyId: string, agentId: string): Promise<void>;
358
+ cacheSize?: number;
267
359
  /**
268
- * Get a history entry by ID
269
- * @param key Entry ID
270
- * @returns The history entry or undefined if not found
360
+ * Batch size for bulk operations
361
+ * @default 100
271
362
  */
272
- getHistoryEntry(key: string): Promise<any | undefined>;
363
+ batchSize?: number;
273
364
  /**
274
- * Get a history step by ID
275
- * @param key Step ID
276
- * @returns The history step or undefined if not found
365
+ * Enable debug logging
366
+ * @default false
277
367
  */
278
- getHistoryStep(key: string): Promise<any | undefined>;
279
- createConversation(conversation: CreateConversationInput): Promise<Conversation>;
280
- getConversation(id: string): Promise<Conversation | null>;
281
- getConversations(resourceId: string): Promise<Conversation[]>;
282
- getConversationsByUserId(userId: string, options?: Omit<ConversationQueryOptions, "userId">): Promise<Conversation[]>;
368
+ debug?: boolean;
283
369
  /**
284
- * Query conversations with filtering and pagination options
285
- *
286
- * @param options Query options for filtering and pagination
287
- * @returns Promise that resolves to an array of conversations matching the criteria
288
- * @see {@link https://voltagent.dev/docs/agents/memory/libsql#querying-conversations | Querying Conversations}
370
+ * Logger instance
289
371
  */
290
- queryConversations(options: ConversationQueryOptions): Promise<Conversation[]>;
372
+ logger?: Logger;
291
373
  /**
292
- * Get messages for a specific conversation with pagination support
293
- *
294
- * @param conversationId The unique identifier of the conversation to retrieve messages from
295
- * @param options Optional pagination and filtering options
296
- * @returns Promise that resolves to an array of messages in chronological order (oldest first)
297
- * @see {@link https://voltagent.dev/docs/agents/memory/libsql#conversation-messages | Getting Conversation Messages}
298
- */
299
- getConversationMessages(conversationId: string, options?: {
300
- limit?: number;
301
- offset?: number;
302
- }): Promise<MemoryMessage[]>;
303
- updateConversation(id: string, updates: Partial<Omit<Conversation, "id" | "createdAt" | "updatedAt">>): Promise<Conversation>;
304
- deleteConversation(id: string): Promise<void>;
374
+ * Maximum number of retries for database operations
375
+ * @default 3
376
+ */
377
+ maxRetries?: number;
305
378
  /**
306
- * Get all history entries for an agent with pagination
307
- * @param agentId Agent ID
308
- * @param page Page number (0-based)
309
- * @param limit Number of entries per page
310
- * @returns Object with entries array and total count
379
+ * Initial retry delay in milliseconds
380
+ * @default 100
311
381
  */
312
- getAllHistoryEntriesByAgent(agentId: string, page: number, limit: number): Promise<{
313
- entries: any[];
314
- total: number;
315
- }>;
382
+ retryDelayMs?: number;
383
+ }
384
+ /**
385
+ * LibSQL Vector Adapter
386
+ * Production-ready vector storage with similarity search
387
+ */
388
+ declare class LibSQLVectorAdapter implements VectorAdapter {
389
+ private client;
390
+ private tablePrefix;
391
+ private maxVectorDimensions;
392
+ private cacheSize;
393
+ private batchSize;
394
+ private debug;
395
+ private logger;
396
+ private maxRetries;
397
+ private retryDelayMs;
398
+ private url;
399
+ private initialized;
400
+ private vectorCache;
401
+ private dimensions;
402
+ constructor(options?: LibSQLVectorOptions);
316
403
  /**
317
- * Migrates agent history data from old structure to new structure.
318
- * If migration fails, it can be rolled back using the backup mechanism.
319
- *
320
- * Old database structure:
321
- * CREATE TABLE voltagent_memory_agent_history (
322
- * key TEXT PRIMARY KEY,
323
- * value TEXT NOT NULL,
324
- * agent_id TEXT
325
- * );
326
- */
327
- migrateAgentHistoryData(options?: {
328
- createBackup?: boolean;
329
- restoreFromBackup?: boolean;
330
- deleteBackupAfterSuccess?: boolean;
331
- }): Promise<{
332
- success: boolean;
333
- migratedCount?: number;
334
- error?: Error;
335
- backupCreated?: boolean;
336
- }>;
404
+ * Initialize the database schema
405
+ */
406
+ private initialize;
337
407
  /**
338
- * Migrate conversation schema to add user_id and update messages table
339
- *
340
- * ⚠️ **CRITICAL WARNING: DESTRUCTIVE OPERATION** ⚠️
341
- *
342
- * This method performs a DESTRUCTIVE schema migration that:
343
- * - DROPS and recreates existing tables
344
- * - Creates temporary tables during migration
345
- * - Modifies the primary key structure of the messages table
346
- * - Can cause DATA LOSS if interrupted or if errors occur
347
- *
348
- * **IMPORTANT SAFETY REQUIREMENTS:**
349
- * - 🛑 STOP all application instances before running this migration
350
- * - 🛑 Ensure NO concurrent database operations are running
351
- * - 🛑 Take a full database backup before running (independent of built-in backup)
352
- * - 🛑 Test the migration on a copy of production data first
353
- * - 🛑 Plan for downtime during migration execution
354
- *
355
- * **What this migration does:**
356
- * 1. Creates backup tables (if createBackup=true)
357
- * 2. Creates temporary tables with new schema
358
- * 3. Migrates data from old tables to new schema
359
- * 4. DROPS original tables
360
- * 5. Renames temporary tables to original names
361
- * 6. All operations are wrapped in a transaction for atomicity
362
- *
363
- * @param options Migration configuration options
364
- * @param options.createBackup Whether to create backup tables before migration (default: true, HIGHLY RECOMMENDED)
365
- * @param options.restoreFromBackup Whether to restore from existing backup instead of migrating (default: false)
366
- * @param options.deleteBackupAfterSuccess Whether to delete backup tables after successful migration (default: false)
367
- *
368
- * @returns Promise resolving to migration result with success status, migrated count, and backup info
369
- *
370
- * @example
371
- * ```typescript
372
- * // RECOMMENDED: Run with backup creation (default)
373
- * const result = await storage.migrateConversationSchema({
374
- * createBackup: true,
375
- * deleteBackupAfterSuccess: false // Keep backup for safety
376
- * });
377
- *
378
- * if (result.success) {
379
- * console.log(`Migrated ${result.migratedCount} conversations successfully`);
380
- * } else {
381
- * console.error('Migration failed:', result.error);
382
- * // Consider restoring from backup
383
- * }
384
- *
385
- * // If migration fails, restore from backup:
386
- * const restoreResult = await storage.migrateConversationSchema({
387
- * restoreFromBackup: true
388
- * });
389
- * ```
390
- *
391
- * @throws {Error} If migration fails and transaction is rolled back
392
- *
393
- * @since This migration is typically only needed when upgrading from older schema versions
394
- */
395
- private migrateConversationSchema;
396
- /**
397
- * Get conversations for a user with a fluent query builder interface
398
- * @param userId User ID to filter by
399
- * @returns Query builder object
400
- */
401
- getUserConversations(userId: string): {
402
- /**
403
- * Limit the number of results
404
- * @param count Number of conversations to return
405
- * @returns Query builder
406
- */
407
- limit: (count: number) => {
408
- /**
409
- * Order results by a specific field
410
- * @param field Field to order by
411
- * @param direction Sort direction
412
- * @returns Query builder
413
- */
414
- orderBy: (field?: "created_at" | "updated_at" | "title", direction?: "ASC" | "DESC") => {
415
- /**
416
- * Execute the query and return results
417
- * @returns Promise of conversations
418
- */
419
- execute: () => Promise<Conversation[]>;
420
- };
421
- /**
422
- * Execute the query with default ordering
423
- * @returns Promise of conversations
424
- */
425
- execute: () => Promise<Conversation[]>;
426
- };
427
- /**
428
- * Order results by a specific field
429
- * @param field Field to order by
430
- * @param direction Sort direction
431
- * @returns Query builder
432
- */
433
- orderBy: (field?: "created_at" | "updated_at" | "title", direction?: "ASC" | "DESC") => {
434
- /**
435
- * Limit the number of results
436
- * @param count Number of conversations to return
437
- * @returns Query builder
438
- */
439
- limit: (count: number) => {
440
- /**
441
- * Execute the query and return results
442
- * @returns Promise of conversations
443
- */
444
- execute: () => Promise<Conversation[]>;
445
- };
446
- /**
447
- * Execute the query without limit
448
- * @returns Promise of conversations
449
- */
450
- execute: () => Promise<Conversation[]>;
451
- };
452
- /**
453
- * Execute the query with default options
454
- * @returns Promise of conversations
455
- */
456
- execute: () => Promise<Conversation[]>;
457
- };
458
- /**
459
- * Get conversation by ID and ensure it belongs to the specified user
460
- * @param conversationId Conversation ID
461
- * @param userId User ID to validate ownership
462
- * @returns Conversation or null
463
- */
464
- getUserConversation(conversationId: string, userId: string): Promise<Conversation | null>;
465
- /**
466
- * Get paginated conversations for a user
467
- * @param userId User ID
468
- * @param page Page number (1-based)
469
- * @param pageSize Number of items per page
470
- * @returns Object with conversations and pagination info
471
- */
472
- getPaginatedUserConversations(userId: string, page?: number, pageSize?: number): Promise<{
473
- conversations: Conversation[];
474
- page: number;
475
- pageSize: number;
476
- hasMore: boolean;
477
- }>;
408
+ * Serialize a vector to binary format
409
+ */
410
+ private serializeVector;
411
+ /**
412
+ * Deserialize a vector from binary format
413
+ */
414
+ private deserializeVector;
415
+ /**
416
+ * Execute a database operation with retries
417
+ */
418
+ private executeWithRetry;
478
419
  /**
479
- * Check and create migration flag table, return if migration already completed
480
- * @param migrationType Type of migration to check
481
- * @returns Object with completion status and details
482
- */
483
- private checkMigrationFlag;
484
- /**
485
- * Set migration flag after successful completion
486
- * @param migrationType Type of migration completed
487
- * @param migratedCount Number of records migrated
488
- */
489
- private setMigrationFlag;
490
- /**
491
- * Migrate agent history schema to add userId and conversationId columns
492
- */
493
- private migrateAgentHistorySchema;
494
- storeWorkflowHistory(entry: any): Promise<void>;
495
- getWorkflowHistory(id: string): Promise<any>;
496
- getWorkflowHistoryByWorkflowId(workflowId: string): Promise<any[]>;
497
- updateWorkflowHistory(id: string, updates: any): Promise<void>;
498
- deleteWorkflowHistory(id: string): Promise<void>;
499
- storeWorkflowStep(step: any): Promise<void>;
500
- getWorkflowStep(id: string): Promise<any>;
501
- getWorkflowSteps(workflowHistoryId: string): Promise<any[]>;
502
- updateWorkflowStep(id: string, updates: any): Promise<void>;
503
- deleteWorkflowStep(id: string): Promise<void>;
504
- storeWorkflowTimelineEvent(event: any): Promise<void>;
505
- getWorkflowTimelineEvent(id: string): Promise<any>;
506
- getWorkflowTimelineEvents(workflowHistoryId: string): Promise<any[]>;
507
- deleteWorkflowTimelineEvent(id: string): Promise<void>;
508
- getAllWorkflowIds(): Promise<string[]>;
509
- getWorkflowStats(workflowId: string): Promise<any>;
510
- getWorkflowHistoryWithStepsAndEvents(id: string): Promise<any>;
511
- deleteWorkflowHistoryWithRelated(id: string): Promise<void>;
512
- cleanupOldWorkflowHistories(workflowId: string, maxEntries: number): Promise<number>;
513
- /**
514
- * Get the workflow extension for advanced workflow operations
515
- */
516
- getWorkflowExtension(): LibSQLWorkflowExtension;
420
+ * Store a vector with associated metadata
421
+ */
422
+ store(id: string, vector: number[], metadata?: Record<string, unknown>): Promise<void>;
423
+ /**
424
+ * Store multiple vectors in batch
425
+ */
426
+ storeBatch(items: VectorItem[]): Promise<void>;
427
+ /**
428
+ * Search for similar vectors using cosine similarity
429
+ */
430
+ search(queryVector: number[], options?: VectorSearchOptions): Promise<SearchResult[]>;
431
+ /**
432
+ * Check if metadata matches the filter criteria
433
+ */
434
+ private matchesFilter;
435
+ /**
436
+ * Delete a vector by ID
437
+ */
438
+ delete(id: string): Promise<void>;
439
+ /**
440
+ * Delete multiple vectors by IDs
441
+ */
442
+ deleteBatch(ids: string[]): Promise<void>;
443
+ /**
444
+ * Clear all vectors
445
+ */
446
+ clear(): Promise<void>;
447
+ /**
448
+ * Get total count of stored vectors
449
+ */
450
+ count(): Promise<number>;
451
+ /**
452
+ * Get a specific vector by ID
453
+ */
454
+ get(id: string): Promise<VectorItem | null>;
455
+ /**
456
+ * Close the database connection
457
+ */
458
+ close(): Promise<void>;
459
+ /**
460
+ * Get statistics about the vector table and cache
461
+ */
462
+ getStats(): Promise<{
463
+ count: number;
464
+ dimensions: number | null;
465
+ cacheSize: number;
466
+ tableSizeBytes: number;
467
+ }>;
517
468
  }
518
469
 
519
- export { LibSQLStorage, type LibSQLStorageOptions };
470
+ export { LibSQLMemoryAdapter, type LibSQLMemoryOptions, LibSQLObservabilityAdapter, type LibSQLObservabilityOptions, LibSQLVectorAdapter, type LibSQLVectorOptions };