@voltagent/libsql 1.0.14 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -41,12 +41,15 @@ module.exports = __toCommonJS(index_exports);
41
41
  var import_node_fs = __toESM(require("fs"));
42
42
  var import_node_path = __toESM(require("path"));
43
43
  var import_client = require("@libsql/client");
44
+ var import_core2 = require("@voltagent/core");
45
+ var import_logger = require("@voltagent/logger");
46
+
47
+ // src/memory-core.ts
44
48
  var import_core = require("@voltagent/core");
45
49
  var import_internal = require("@voltagent/internal");
46
- var import_logger = require("@voltagent/logger");
47
- var LibSQLMemoryAdapter = class {
50
+ var LibSQLMemoryCore = class {
48
51
  static {
49
- __name(this, "LibSQLMemoryAdapter");
52
+ __name(this, "LibSQLMemoryCore");
50
53
  }
51
54
  client;
52
55
  tablePrefix;
@@ -55,25 +58,14 @@ var LibSQLMemoryAdapter = class {
55
58
  maxRetries;
56
59
  retryDelayMs;
57
60
  url;
58
- constructor(options = {}) {
61
+ constructor(client, url, options, logger) {
62
+ this.client = client;
63
+ this.url = url;
59
64
  this.tablePrefix = options.tablePrefix ?? "voltagent_memory";
60
65
  this.maxRetries = options.maxRetries ?? 3;
61
66
  this.retryDelayMs = options.retryDelayMs ?? 100;
62
- this.logger = options.logger || import_core.AgentRegistry.getInstance().getGlobalLogger() || (0, import_logger.createPinoLogger)({ name: "libsql-memory" });
63
- this.url = options.url ?? "file:./.voltagent/memory.db";
64
- if (this.url.startsWith("file:")) {
65
- const dbPath = this.url.replace("file:", "");
66
- const dbDir = import_node_path.default.dirname(dbPath);
67
- if (dbDir && dbDir !== "." && !import_node_fs.default.existsSync(dbDir)) {
68
- import_node_fs.default.mkdirSync(dbDir, { recursive: true });
69
- this.logger.debug(`Created database directory: ${dbDir}`);
70
- }
71
- }
72
- this.client = (0, import_client.createClient)({
73
- url: this.url,
74
- authToken: options.authToken
75
- });
76
- this.logger.debug("LibSQL Memory adapter initialized", { url: this.url });
67
+ this.logger = logger;
68
+ this.logger.debug("LibSQL Memory adapter core initialized", { url: this.url });
77
69
  }
78
70
  /**
79
71
  * Execute a database operation with retry logic
@@ -136,14 +128,12 @@ var LibSQLMemoryAdapter = class {
136
128
  this.logger.debug("Applied PRAGMA settings for better concurrency");
137
129
  await this.executeWithRetry(async () => {
138
130
  await this.client.batch([
139
- // Create users table (for user-level working memory)
140
131
  `CREATE TABLE IF NOT EXISTS ${usersTable} (
141
132
  id TEXT PRIMARY KEY,
142
133
  metadata TEXT,
143
134
  created_at TEXT DEFAULT CURRENT_TIMESTAMP,
144
135
  updated_at TEXT DEFAULT CURRENT_TIMESTAMP
145
136
  )`,
146
- // Create conversations table (matching existing structure)
147
137
  `CREATE TABLE IF NOT EXISTS ${conversationsTable} (
148
138
  id TEXT PRIMARY KEY,
149
139
  resource_id TEXT NOT NULL,
@@ -153,7 +143,6 @@ var LibSQLMemoryAdapter = class {
153
143
  created_at TEXT NOT NULL,
154
144
  updated_at TEXT NOT NULL
155
145
  )`,
156
- // Create messages table (matching existing structure)
157
146
  `CREATE TABLE IF NOT EXISTS ${messagesTable} (
158
147
  conversation_id TEXT NOT NULL,
159
148
  message_id TEXT NOT NULL,
@@ -165,7 +154,6 @@ var LibSQLMemoryAdapter = class {
165
154
  created_at TEXT NOT NULL,
166
155
  PRIMARY KEY (conversation_id, message_id)
167
156
  )`,
168
- // Create workflow states table
169
157
  `CREATE TABLE IF NOT EXISTS ${workflowStatesTable} (
170
158
  id TEXT PRIMARY KEY,
171
159
  workflow_id TEXT NOT NULL,
@@ -181,7 +169,6 @@ var LibSQLMemoryAdapter = class {
181
169
  created_at TEXT NOT NULL,
182
170
  updated_at TEXT NOT NULL
183
171
  )`,
184
- // Create conversation steps table
185
172
  `CREATE TABLE IF NOT EXISTS ${stepsTable} (
186
173
  id TEXT PRIMARY KEY,
187
174
  conversation_id TEXT NOT NULL,
@@ -201,7 +188,6 @@ var LibSQLMemoryAdapter = class {
201
188
  created_at TEXT NOT NULL,
202
189
  FOREIGN KEY (conversation_id) REFERENCES ${conversationsTable}(id) ON DELETE CASCADE
203
190
  )`,
204
- // Create indexes for better performance
205
191
  `CREATE INDEX IF NOT EXISTS idx_${conversationsTable}_user_id ON ${conversationsTable}(user_id)`,
206
192
  `CREATE INDEX IF NOT EXISTS idx_${conversationsTable}_resource_id ON ${conversationsTable}(resource_id)`,
207
193
  `CREATE INDEX IF NOT EXISTS idx_${messagesTable}_conversation_id ON ${messagesTable}(conversation_id)`,
@@ -218,10 +204,6 @@ var LibSQLMemoryAdapter = class {
218
204
  this.initialized = true;
219
205
  this.logger.debug("Database schema initialized");
220
206
  }
221
- /**
222
- * Add new columns to messages table for V2 format if they don't exist
223
- * This allows existing tables to support both old and new message formats
224
- */
225
207
  async addV2ColumnsToMessagesTable() {
226
208
  const messagesTableName = `${this.tablePrefix}_messages`;
227
209
  try {
@@ -294,10 +276,6 @@ var LibSQLMemoryAdapter = class {
294
276
  } catch (_) {
295
277
  }
296
278
  }
297
- /**
298
- * Migrate default user_id values in messages table
299
- * Updates messages with user_id='default' to use the actual user_id from their conversation
300
- */
301
279
  async migrateDefaultUserIds() {
302
280
  const messagesTableName = `${this.tablePrefix}_messages`;
303
281
  const conversationsTableName = `${this.tablePrefix}_conversations`;
@@ -315,14 +293,14 @@ var LibSQLMemoryAdapter = class {
315
293
  const result = await this.client.execute({
316
294
  sql: `UPDATE ${messagesTableName}
317
295
  SET user_id = (
318
- SELECT c.user_id
319
- FROM ${conversationsTableName} c
296
+ SELECT c.user_id
297
+ FROM ${conversationsTableName} c
320
298
  WHERE c.id = ${messagesTableName}.conversation_id
321
299
  )
322
300
  WHERE user_id = 'default'
323
301
  AND EXISTS (
324
- SELECT 1
325
- FROM ${conversationsTableName} c
302
+ SELECT 1
303
+ FROM ${conversationsTableName} c
326
304
  WHERE c.id = ${messagesTableName}.conversation_id
327
305
  )`,
328
306
  args: []
@@ -346,10 +324,6 @@ var LibSQLMemoryAdapter = class {
346
324
  this.logger.error("Failed to migrate default user_ids", error);
347
325
  }
348
326
  }
349
- /**
350
- * Add new columns to workflow_states table for event persistence
351
- * This migration adds support for events, output, and cancellation tracking
352
- */
353
327
  async addWorkflowStateColumns() {
354
328
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
355
329
  try {
@@ -385,9 +359,6 @@ var LibSQLMemoryAdapter = class {
385
359
  // ============================================================================
386
360
  // Message Operations
387
361
  // ============================================================================
388
- /**
389
- * Add a single message
390
- */
391
362
  async addMessage(message, userId, conversationId) {
392
363
  await this.initialize();
393
364
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -397,7 +368,7 @@ var LibSQLMemoryAdapter = class {
397
368
  }
398
369
  await this.executeWithRetry(async () => {
399
370
  await this.client.execute({
400
- sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
371
+ sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
401
372
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
402
373
  args: [
403
374
  conversationId,
@@ -407,15 +378,11 @@ var LibSQLMemoryAdapter = class {
407
378
  (0, import_internal.safeStringify)(message.parts),
408
379
  message.metadata ? (0, import_internal.safeStringify)(message.metadata) : null,
409
380
  2,
410
- // format_version
411
381
  (/* @__PURE__ */ new Date()).toISOString()
412
382
  ]
413
383
  });
414
384
  }, "add message");
415
385
  }
416
- /**
417
- * Add multiple messages
418
- */
419
386
  async addMessages(messages, userId, conversationId) {
420
387
  await this.initialize();
421
388
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -427,7 +394,7 @@ var LibSQLMemoryAdapter = class {
427
394
  await this.executeWithRetry(async () => {
428
395
  await this.client.batch(
429
396
  messages.map((message) => ({
430
- sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
397
+ sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
431
398
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
432
399
  args: [
433
400
  conversationId,
@@ -437,7 +404,6 @@ var LibSQLMemoryAdapter = class {
437
404
  (0, import_internal.safeStringify)(message.parts),
438
405
  message.metadata ? (0, import_internal.safeStringify)(message.metadata) : null,
439
406
  2,
440
- // format_version
441
407
  now
442
408
  ]
443
409
  }))
@@ -510,9 +476,6 @@ var LibSQLMemoryAdapter = class {
510
476
  );
511
477
  }, "save conversation steps");
512
478
  }
513
- /**
514
- * Get messages with optional filtering
515
- */
516
479
  async getMessages(userId, conversationId, options) {
517
480
  await this.initialize();
518
481
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -620,9 +583,6 @@ var LibSQLMemoryAdapter = class {
620
583
  createdAt: row.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
621
584
  }));
622
585
  }
623
- /**
624
- * Clear messages for a user
625
- */
626
586
  async clearMessages(userId, conversationId) {
627
587
  await this.initialize();
628
588
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -657,9 +617,6 @@ var LibSQLMemoryAdapter = class {
657
617
  // ============================================================================
658
618
  // Conversation Operations
659
619
  // ============================================================================
660
- /**
661
- * Create a new conversation
662
- */
663
620
  async createConversation(input) {
664
621
  await this.initialize();
665
622
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -670,7 +627,7 @@ var LibSQLMemoryAdapter = class {
670
627
  const now = (/* @__PURE__ */ new Date()).toISOString();
671
628
  await this.executeWithRetry(async () => {
672
629
  await this.client.execute({
673
- sql: `INSERT INTO ${conversationsTable} (id, resource_id, user_id, title, metadata, created_at, updated_at)
630
+ sql: `INSERT INTO ${conversationsTable} (id, resource_id, user_id, title, metadata, created_at, updated_at)
674
631
  VALUES (?, ?, ?, ?, ?, ?, ?)`,
675
632
  args: [
676
633
  input.id,
@@ -693,9 +650,6 @@ var LibSQLMemoryAdapter = class {
693
650
  updatedAt: now
694
651
  };
695
652
  }
696
- /**
697
- * Get a conversation by ID
698
- */
699
653
  async getConversation(id) {
700
654
  await this.initialize();
701
655
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -717,9 +671,6 @@ var LibSQLMemoryAdapter = class {
717
671
  updatedAt: row.updated_at
718
672
  };
719
673
  }
720
- /**
721
- * Get conversations by resource ID
722
- */
723
674
  async getConversations(resourceId) {
724
675
  await this.initialize();
725
676
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -737,15 +688,9 @@ var LibSQLMemoryAdapter = class {
737
688
  updatedAt: row.updated_at
738
689
  }));
739
690
  }
740
- /**
741
- * Get conversations by user ID
742
- */
743
691
  async getConversationsByUserId(userId, options) {
744
692
  return this.queryConversations({ ...options, userId });
745
693
  }
746
- /**
747
- * Query conversations with filters
748
- */
749
694
  async queryConversations(options) {
750
695
  await this.initialize();
751
696
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -781,9 +726,6 @@ var LibSQLMemoryAdapter = class {
781
726
  updatedAt: row.updated_at
782
727
  }));
783
728
  }
784
- /**
785
- * Update a conversation
786
- */
787
729
  async updateConversation(id, updates) {
788
730
  await this.initialize();
789
731
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -817,9 +759,6 @@ var LibSQLMemoryAdapter = class {
817
759
  }
818
760
  return updated;
819
761
  }
820
- /**
821
- * Delete a conversation
822
- */
823
762
  async deleteConversation(id) {
824
763
  await this.initialize();
825
764
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -831,9 +770,6 @@ var LibSQLMemoryAdapter = class {
831
770
  // ============================================================================
832
771
  // Working Memory Operations
833
772
  // ============================================================================
834
- /**
835
- * Get working memory
836
- */
837
773
  async getWorkingMemory(params) {
838
774
  await this.initialize();
839
775
  if (params.scope === "conversation" && params.conversationId) {
@@ -853,9 +789,6 @@ var LibSQLMemoryAdapter = class {
853
789
  }
854
790
  return null;
855
791
  }
856
- /**
857
- * Set working memory
858
- */
859
792
  async setWorkingMemory(params) {
860
793
  await this.initialize();
861
794
  if (params.scope === "conversation" && params.conversationId) {
@@ -889,9 +822,6 @@ var LibSQLMemoryAdapter = class {
889
822
  }
890
823
  }
891
824
  }
892
- /**
893
- * Delete working memory
894
- */
895
825
  async deleteWorkingMemory(params) {
896
826
  await this.initialize();
897
827
  if (params.scope === "conversation" && params.conversationId) {
@@ -923,9 +853,6 @@ var LibSQLMemoryAdapter = class {
923
853
  // ============================================================================
924
854
  // Workflow State Operations
925
855
  // ============================================================================
926
- /**
927
- * Get workflow state by execution ID
928
- */
929
856
  async getWorkflowState(executionId) {
930
857
  await this.initialize();
931
858
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
@@ -953,9 +880,6 @@ var LibSQLMemoryAdapter = class {
953
880
  updatedAt: new Date(row.updated_at)
954
881
  };
955
882
  }
956
- /**
957
- * Query workflow states with optional filters
958
- */
959
883
  async queryWorkflowRuns(query) {
960
884
  await this.initialize();
961
885
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
@@ -1010,9 +934,6 @@ var LibSQLMemoryAdapter = class {
1010
934
  updatedAt: new Date(row.updated_at)
1011
935
  }));
1012
936
  }
1013
- /**
1014
- * Set workflow state
1015
- */
1016
937
  async setWorkflowState(executionId, state) {
1017
938
  await this.initialize();
1018
939
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
@@ -1037,9 +958,6 @@ var LibSQLMemoryAdapter = class {
1037
958
  ]
1038
959
  });
1039
960
  }
1040
- /**
1041
- * Update workflow state
1042
- */
1043
961
  async updateWorkflowState(executionId, updates) {
1044
962
  await this.initialize();
1045
963
  const existing = await this.getWorkflowState(executionId);
@@ -1053,9 +971,6 @@ var LibSQLMemoryAdapter = class {
1053
971
  };
1054
972
  await this.setWorkflowState(executionId, updated);
1055
973
  }
1056
- /**
1057
- * Get suspended workflow states for a workflow
1058
- */
1059
974
  async getSuspendedWorkflowStates(workflowId) {
1060
975
  await this.initialize();
1061
976
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
@@ -1079,23 +994,46 @@ var LibSQLMemoryAdapter = class {
1079
994
  updatedAt: new Date(row.updated_at)
1080
995
  }));
1081
996
  }
1082
- /**
1083
- * Close database connection
1084
- */
1085
997
  async close() {
1086
998
  this.logger.debug("Closing LibSQL Memory adapter");
1087
999
  }
1088
1000
  };
1089
1001
 
1002
+ // src/memory-v2-adapter.ts
1003
+ var LibSQLMemoryAdapter = class extends LibSQLMemoryCore {
1004
+ static {
1005
+ __name(this, "LibSQLMemoryAdapter");
1006
+ }
1007
+ constructor(options = {}) {
1008
+ const url = options.url ?? "file:./.voltagent/memory.db";
1009
+ const logger = options.logger || import_core2.AgentRegistry.getInstance().getGlobalLogger() || (0, import_logger.createPinoLogger)({ name: "libsql-memory" });
1010
+ if (url.startsWith("file:")) {
1011
+ const dbPath = url.replace("file:", "");
1012
+ const dbDir = import_node_path.default.dirname(dbPath);
1013
+ if (dbDir && dbDir !== "." && !import_node_fs.default.existsSync(dbDir)) {
1014
+ import_node_fs.default.mkdirSync(dbDir, { recursive: true });
1015
+ logger.debug(`Created database directory: ${dbDir}`);
1016
+ }
1017
+ }
1018
+ const client = (0, import_client.createClient)({
1019
+ url,
1020
+ authToken: options.authToken
1021
+ });
1022
+ super(client, url, options, logger);
1023
+ }
1024
+ };
1025
+
1090
1026
  // src/observability-adapter.ts
1091
1027
  var import_node_fs2 = require("fs");
1092
1028
  var import_node_path2 = require("path");
1093
1029
  var import_client2 = require("@libsql/client");
1094
- var import_utils = require("@voltagent/internal/utils");
1095
1030
  var import_logger2 = require("@voltagent/logger");
1096
- var LibSQLObservabilityAdapter = class {
1031
+
1032
+ // src/observability-core.ts
1033
+ var import_utils = require("@voltagent/internal/utils");
1034
+ var LibSQLObservabilityCore = class {
1097
1035
  static {
1098
- __name(this, "LibSQLObservabilityAdapter");
1036
+ __name(this, "LibSQLObservabilityCore");
1099
1037
  }
1100
1038
  client;
1101
1039
  tablePrefix;
@@ -1103,47 +1041,24 @@ var LibSQLObservabilityAdapter = class {
1103
1041
  logger;
1104
1042
  initialized;
1105
1043
  maxSpansPerQuery;
1106
- constructor(options = {}) {
1107
- this.logger = options.logger || (0, import_logger2.createPinoLogger)({ name: "libsql-observability" });
1044
+ constructor(client, options, logger) {
1045
+ this.client = client;
1046
+ this.logger = logger;
1108
1047
  this.tablePrefix = options.tablePrefix || "observability";
1109
1048
  this.debug = options.debug || false;
1110
1049
  this.maxSpansPerQuery = options.maxSpansPerQuery || 1e3;
1111
- const url = options.url || "file:./.voltagent/observability.db";
1112
- if (url.startsWith("file:") && !url.includes(":memory:")) {
1113
- const filePath = url.substring(5);
1114
- const dir = (0, import_node_path2.dirname)(filePath);
1115
- if (dir && dir !== "." && !(0, import_node_fs2.existsSync)(dir)) {
1116
- try {
1117
- (0, import_node_fs2.mkdirSync)(dir, { recursive: true });
1118
- this.debugLog("Created directory for database", { dir });
1119
- } catch (error) {
1120
- this.logger.warn("Failed to create directory for database", { dir, error });
1121
- }
1122
- }
1123
- }
1124
- this.client = (0, import_client2.createClient)({
1125
- url,
1126
- authToken: options.authToken
1127
- });
1128
- this.debugLog("LibSQL observability adapter initialized with options", {
1129
- url,
1050
+ this.debugLog("LibSQL observability adapter core initialized", {
1130
1051
  tablePrefix: this.tablePrefix,
1131
1052
  debug: this.debug,
1132
1053
  maxSpansPerQuery: this.maxSpansPerQuery
1133
1054
  });
1134
1055
  this.initialized = this.initializeDatabase();
1135
1056
  }
1136
- /**
1137
- * Log a debug message if debug is enabled
1138
- */
1139
1057
  debugLog(message, data) {
1140
1058
  if (this.debug) {
1141
1059
  this.logger.debug(`${message}`, data || "");
1142
1060
  }
1143
1061
  }
1144
- /**
1145
- * Initialize database tables for observability
1146
- */
1147
1062
  async initializeDatabase() {
1148
1063
  try {
1149
1064
  await this.client.execute(`
@@ -1170,27 +1085,27 @@ var LibSQLObservabilityAdapter = class {
1170
1085
  )
1171
1086
  `);
1172
1087
  await this.client.execute(`
1173
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_trace_id
1088
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_trace_id
1174
1089
  ON ${this.tablePrefix}_spans(trace_id)
1175
1090
  `);
1176
1091
  await this.client.execute(`
1177
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_parent_span_id
1092
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_parent_span_id
1178
1093
  ON ${this.tablePrefix}_spans(parent_span_id)
1179
1094
  `);
1180
1095
  await this.client.execute(`
1181
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_start_time
1096
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_start_time
1182
1097
  ON ${this.tablePrefix}_spans(start_time)
1183
1098
  `);
1184
1099
  await this.client.execute(`
1185
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_name
1100
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_name
1186
1101
  ON ${this.tablePrefix}_spans(name)
1187
1102
  `);
1188
1103
  await this.client.execute(`
1189
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_id
1104
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_id
1190
1105
  ON ${this.tablePrefix}_spans(entity_id)
1191
1106
  `);
1192
1107
  await this.client.execute(`
1193
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_type
1108
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_type
1194
1109
  ON ${this.tablePrefix}_spans(entity_type)
1195
1110
  `);
1196
1111
  await this.client.execute(`
@@ -1207,15 +1122,15 @@ var LibSQLObservabilityAdapter = class {
1207
1122
  )
1208
1123
  `);
1209
1124
  await this.client.execute(`
1210
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_start_time
1125
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_start_time
1211
1126
  ON ${this.tablePrefix}_traces(start_time DESC)
1212
1127
  `);
1213
1128
  await this.client.execute(`
1214
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_id
1129
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_id
1215
1130
  ON ${this.tablePrefix}_traces(entity_id)
1216
1131
  `);
1217
1132
  await this.client.execute(`
1218
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_type
1133
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_type
1219
1134
  ON ${this.tablePrefix}_traces(entity_type)
1220
1135
  `);
1221
1136
  await this.client.execute(`
@@ -1235,19 +1150,19 @@ var LibSQLObservabilityAdapter = class {
1235
1150
  )
1236
1151
  `);
1237
1152
  await this.client.execute(`
1238
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_trace_id
1153
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_trace_id
1239
1154
  ON ${this.tablePrefix}_logs(trace_id)
1240
1155
  `);
1241
1156
  await this.client.execute(`
1242
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_span_id
1157
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_span_id
1243
1158
  ON ${this.tablePrefix}_logs(span_id)
1244
1159
  `);
1245
1160
  await this.client.execute(`
1246
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_timestamp
1161
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_timestamp
1247
1162
  ON ${this.tablePrefix}_logs(timestamp DESC)
1248
1163
  `);
1249
1164
  await this.client.execute(`
1250
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_severity
1165
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_severity
1251
1166
  ON ${this.tablePrefix}_logs(severity_number)
1252
1167
  `);
1253
1168
  this.debugLog("Database tables initialized successfully");
@@ -1256,22 +1171,15 @@ var LibSQLObservabilityAdapter = class {
1256
1171
  throw error;
1257
1172
  }
1258
1173
  }
1259
- /**
1260
- * Ensure database is initialized before operations
1261
- */
1262
1174
  async ensureInitialized() {
1263
1175
  await this.initialized;
1264
1176
  }
1265
- /**
1266
- * Add a span to the database
1267
- */
1268
1177
  async addSpan(span) {
1269
1178
  await this.ensureInitialized();
1270
1179
  try {
1271
1180
  const entityId = span.attributes?.["entity.id"] || null;
1272
1181
  const entityType = span.attributes?.["entity.type"] || null;
1273
1182
  await this.client.batch([
1274
- // Insert the span with entity columns
1275
1183
  {
1276
1184
  sql: `
1277
1185
  INSERT INTO ${this.tablePrefix}_spans (
@@ -1302,7 +1210,6 @@ var LibSQLObservabilityAdapter = class {
1302
1210
  span.instrumentationScope ? (0, import_utils.safeStringify)(span.instrumentationScope) : null
1303
1211
  ]
1304
1212
  },
1305
- // Update or insert trace metadata with entity columns
1306
1213
  {
1307
1214
  sql: `
1308
1215
  INSERT INTO ${this.tablePrefix}_traces (
@@ -1319,7 +1226,6 @@ var LibSQLObservabilityAdapter = class {
1319
1226
  args: [
1320
1227
  span.traceId,
1321
1228
  span.parentSpanId ? null : span.spanId,
1322
- // Root span if no parent
1323
1229
  entityId,
1324
1230
  entityType,
1325
1231
  span.startTime,
@@ -1336,9 +1242,6 @@ var LibSQLObservabilityAdapter = class {
1336
1242
  throw error;
1337
1243
  }
1338
1244
  }
1339
- /**
1340
- * Update an existing span
1341
- */
1342
1245
  async updateSpan(spanId, updates) {
1343
1246
  await this.ensureInitialized();
1344
1247
  try {
@@ -1375,7 +1278,7 @@ var LibSQLObservabilityAdapter = class {
1375
1278
  args.push(spanId);
1376
1279
  await this.client.execute({
1377
1280
  sql: `
1378
- UPDATE ${this.tablePrefix}_spans
1281
+ UPDATE ${this.tablePrefix}_spans
1379
1282
  SET ${setClauses.join(", ")}
1380
1283
  WHERE span_id = ?
1381
1284
  `,
@@ -1401,32 +1304,22 @@ var LibSQLObservabilityAdapter = class {
1401
1304
  throw error;
1402
1305
  }
1403
1306
  }
1404
- /**
1405
- * Get a span by ID
1406
- */
1407
1307
  async getSpan(spanId) {
1408
1308
  await this.ensureInitialized();
1409
1309
  try {
1410
1310
  const result = await this.client.execute({
1411
- sql: `
1412
- SELECT * FROM ${this.tablePrefix}_spans
1413
- WHERE span_id = ?
1414
- `,
1311
+ sql: `SELECT * FROM ${this.tablePrefix}_spans WHERE span_id = ?`,
1415
1312
  args: [spanId]
1416
1313
  });
1417
1314
  if (result.rows.length === 0) {
1418
1315
  return null;
1419
1316
  }
1420
- const row = result.rows[0];
1421
- return this.rowToSpan(row);
1317
+ return this.rowToSpan(result.rows[0]);
1422
1318
  } catch (error) {
1423
1319
  this.logger.error("Failed to get span", { error, spanId });
1424
1320
  throw error;
1425
1321
  }
1426
1322
  }
1427
- /**
1428
- * Get all spans in a trace
1429
- */
1430
1323
  async getTrace(traceId) {
1431
1324
  await this.ensureInitialized();
1432
1325
  try {
@@ -1445,9 +1338,6 @@ var LibSQLObservabilityAdapter = class {
1445
1338
  throw error;
1446
1339
  }
1447
1340
  }
1448
- /**
1449
- * List all traces with optional entity filter
1450
- */
1451
1341
  async listTraces(limit = 100, offset = 0, filter) {
1452
1342
  await this.ensureInitialized();
1453
1343
  try {
@@ -1485,52 +1375,36 @@ var LibSQLObservabilityAdapter = class {
1485
1375
  throw error;
1486
1376
  }
1487
1377
  }
1488
- /**
1489
- * Delete old spans
1490
- */
1491
1378
  async deleteOldSpans(beforeTimestamp) {
1492
1379
  await this.ensureInitialized();
1493
1380
  try {
1494
1381
  const beforeDate = new Date(beforeTimestamp).toISOString();
1495
1382
  const tracesResult = await this.client.execute({
1496
- sql: `
1497
- SELECT DISTINCT trace_id FROM ${this.tablePrefix}_spans
1498
- WHERE start_time < ?
1499
- `,
1383
+ sql: `SELECT DISTINCT trace_id FROM ${this.tablePrefix}_spans WHERE start_time < ?`,
1500
1384
  args: [beforeDate]
1501
1385
  });
1502
1386
  const affectedTraceIds = tracesResult.rows.map((row) => row.trace_id);
1503
1387
  const deleteResult = await this.client.execute({
1504
- sql: `
1505
- DELETE FROM ${this.tablePrefix}_spans
1506
- WHERE start_time < ?
1507
- `,
1388
+ sql: `DELETE FROM ${this.tablePrefix}_spans WHERE start_time < ?`,
1508
1389
  args: [beforeDate]
1509
1390
  });
1510
1391
  if (affectedTraceIds.length > 0) {
1511
1392
  for (const traceId of affectedTraceIds) {
1512
1393
  const countResult = await this.client.execute({
1513
- sql: `
1514
- SELECT COUNT(*) as count FROM ${this.tablePrefix}_spans
1515
- WHERE trace_id = ?
1516
- `,
1394
+ sql: `SELECT COUNT(*) as count FROM ${this.tablePrefix}_spans WHERE trace_id = ?`,
1517
1395
  args: [traceId]
1518
1396
  });
1519
1397
  const count = countResult.rows[0].count;
1520
1398
  if (count === 0) {
1521
1399
  await this.client.execute({
1522
- sql: `
1523
- DELETE FROM ${this.tablePrefix}_traces
1524
- WHERE trace_id = ?
1525
- `,
1400
+ sql: `DELETE FROM ${this.tablePrefix}_traces WHERE trace_id = ?`,
1526
1401
  args: [traceId]
1527
1402
  });
1528
1403
  } else {
1529
1404
  await this.client.execute({
1530
1405
  sql: `
1531
1406
  UPDATE ${this.tablePrefix}_traces
1532
- SET span_count = ?,
1533
- updated_at = CURRENT_TIMESTAMP
1407
+ SET span_count = ?, updated_at = CURRENT_TIMESTAMP
1534
1408
  WHERE trace_id = ?
1535
1409
  `,
1536
1410
  args: [count, traceId]
@@ -1546,9 +1420,6 @@ var LibSQLObservabilityAdapter = class {
1546
1420
  throw error;
1547
1421
  }
1548
1422
  }
1549
- /**
1550
- * Clear all spans, traces, and logs
1551
- */
1552
1423
  async clear() {
1553
1424
  await this.ensureInitialized();
1554
1425
  try {
@@ -1563,9 +1434,6 @@ var LibSQLObservabilityAdapter = class {
1563
1434
  throw error;
1564
1435
  }
1565
1436
  }
1566
- /**
1567
- * Convert a database row to an ObservabilitySpan
1568
- */
1569
1437
  rowToSpan(row) {
1570
1438
  const span = {
1571
1439
  traceId: row.trace_id,
@@ -1611,9 +1479,6 @@ var LibSQLObservabilityAdapter = class {
1611
1479
  }
1612
1480
  return span;
1613
1481
  }
1614
- /**
1615
- * Get statistics about stored spans
1616
- */
1617
1482
  async getStats() {
1618
1483
  await this.ensureInitialized();
1619
1484
  try {
@@ -1621,9 +1486,7 @@ var LibSQLObservabilityAdapter = class {
1621
1486
  this.client.execute(`SELECT COUNT(*) as count FROM ${this.tablePrefix}_spans`),
1622
1487
  this.client.execute(`SELECT COUNT(*) as count FROM ${this.tablePrefix}_traces`),
1623
1488
  this.client.execute(`
1624
- SELECT
1625
- MIN(start_time) as oldest,
1626
- MAX(start_time) as newest
1489
+ SELECT MIN(start_time) as oldest, MAX(start_time) as newest
1627
1490
  FROM ${this.tablePrefix}_spans
1628
1491
  `)
1629
1492
  ]);
@@ -1643,9 +1506,6 @@ var LibSQLObservabilityAdapter = class {
1643
1506
  throw error;
1644
1507
  }
1645
1508
  }
1646
- /**
1647
- * Save a log record to the database
1648
- */
1649
1509
  async saveLogRecord(logRecord) {
1650
1510
  await this.ensureInitialized();
1651
1511
  try {
@@ -1700,9 +1560,6 @@ var LibSQLObservabilityAdapter = class {
1700
1560
  throw error;
1701
1561
  }
1702
1562
  }
1703
- /**
1704
- * Get logs by trace ID
1705
- */
1706
1563
  async getLogsByTraceId(traceId) {
1707
1564
  await this.ensureInitialized();
1708
1565
  try {
@@ -1721,9 +1578,6 @@ var LibSQLObservabilityAdapter = class {
1721
1578
  throw error;
1722
1579
  }
1723
1580
  }
1724
- /**
1725
- * Get logs by span ID
1726
- */
1727
1581
  async getLogsBySpanId(spanId) {
1728
1582
  await this.ensureInitialized();
1729
1583
  try {
@@ -1742,9 +1596,6 @@ var LibSQLObservabilityAdapter = class {
1742
1596
  throw error;
1743
1597
  }
1744
1598
  }
1745
- /**
1746
- * Query logs with flexible filtering
1747
- */
1748
1599
  async queryLogs(filter) {
1749
1600
  await this.ensureInitialized();
1750
1601
  try {
@@ -1813,18 +1664,12 @@ var LibSQLObservabilityAdapter = class {
1813
1664
  throw error;
1814
1665
  }
1815
1666
  }
1816
- /**
1817
- * Delete old logs
1818
- */
1819
1667
  async deleteOldLogs(beforeTimestamp) {
1820
1668
  await this.ensureInitialized();
1821
1669
  try {
1822
1670
  const beforeDate = new Date(beforeTimestamp).toISOString();
1823
1671
  const result = await this.client.execute({
1824
- sql: `
1825
- DELETE FROM ${this.tablePrefix}_logs
1826
- WHERE timestamp < ?
1827
- `,
1672
+ sql: `DELETE FROM ${this.tablePrefix}_logs WHERE timestamp < ?`,
1828
1673
  args: [beforeDate]
1829
1674
  });
1830
1675
  const deletedCount = result.rowsAffected || 0;
@@ -1835,9 +1680,6 @@ var LibSQLObservabilityAdapter = class {
1835
1680
  throw error;
1836
1681
  }
1837
1682
  }
1838
- /**
1839
- * Convert a database row to an ObservabilityLogRecord
1840
- */
1841
1683
  rowToLogRecord(row) {
1842
1684
  const log = {
1843
1685
  timestamp: row.timestamp,
@@ -1904,24 +1746,53 @@ var LibSQLObservabilityAdapter = class {
1904
1746
  description: "Persists spans and logs to a LibSQL/Turso database for long-term retention."
1905
1747
  };
1906
1748
  }
1907
- /**
1908
- * Close the database connection
1909
- */
1910
1749
  async close() {
1911
1750
  this.debugLog("LibSQL observability adapter closed");
1912
1751
  }
1913
1752
  };
1914
1753
 
1754
+ // src/observability-adapter.ts
1755
+ var LibSQLObservabilityAdapter = class extends LibSQLObservabilityCore {
1756
+ static {
1757
+ __name(this, "LibSQLObservabilityAdapter");
1758
+ }
1759
+ constructor(options = {}) {
1760
+ const url = options.url || "file:./.voltagent/observability.db";
1761
+ const logger = options.logger || (0, import_logger2.createPinoLogger)({ name: "libsql-observability" });
1762
+ if (url.startsWith("file:") && !url.includes(":memory:")) {
1763
+ const filePath = url.substring(5);
1764
+ const dir = (0, import_node_path2.dirname)(filePath);
1765
+ if (dir && dir !== "." && !(0, import_node_fs2.existsSync)(dir)) {
1766
+ try {
1767
+ (0, import_node_fs2.mkdirSync)(dir, { recursive: true });
1768
+ if (options.debug) {
1769
+ logger.debug("Created directory for database", { dir });
1770
+ }
1771
+ } catch (error) {
1772
+ logger.warn("Failed to create directory for database", { dir, error });
1773
+ }
1774
+ }
1775
+ }
1776
+ const client = (0, import_client2.createClient)({
1777
+ url,
1778
+ authToken: options.authToken
1779
+ });
1780
+ super(client, options, logger);
1781
+ }
1782
+ };
1783
+
1915
1784
  // src/vector-adapter.ts
1916
1785
  var import_node_fs3 = __toESM(require("fs"));
1917
1786
  var import_node_path3 = __toESM(require("path"));
1918
1787
  var import_client3 = require("@libsql/client");
1919
- var import_core2 = require("@voltagent/core");
1920
- var import_internal2 = require("@voltagent/internal");
1921
1788
  var import_logger3 = require("@voltagent/logger");
1922
- var LibSQLVectorAdapter = class {
1789
+
1790
+ // src/vector-core.ts
1791
+ var import_core3 = require("@voltagent/core");
1792
+ var import_internal2 = require("@voltagent/internal");
1793
+ var LibSQLVectorCore = class {
1923
1794
  static {
1924
- __name(this, "LibSQLVectorAdapter");
1795
+ __name(this, "LibSQLVectorCore");
1925
1796
  }
1926
1797
  client;
1927
1798
  tablePrefix;
@@ -1932,11 +1803,11 @@ var LibSQLVectorAdapter = class {
1932
1803
  logger;
1933
1804
  maxRetries;
1934
1805
  retryDelayMs;
1935
- url;
1936
1806
  initialized = false;
1937
1807
  vectorCache;
1938
1808
  dimensions = null;
1939
- constructor(options = {}) {
1809
+ constructor(client, options, logger) {
1810
+ this.client = client;
1940
1811
  this.tablePrefix = options.tablePrefix ?? "voltagent";
1941
1812
  this.maxVectorDimensions = options.maxVectorDimensions ?? 1536;
1942
1813
  this.cacheSize = options.cacheSize ?? 100;
@@ -1944,28 +1815,32 @@ var LibSQLVectorAdapter = class {
1944
1815
  this.maxRetries = options.maxRetries ?? 3;
1945
1816
  this.retryDelayMs = options.retryDelayMs ?? 100;
1946
1817
  this.debug = options.debug ?? false;
1947
- this.logger = options.logger ?? (0, import_logger3.createPinoLogger)({
1948
- name: "libsql-vector-adapter",
1949
- level: this.debug ? "debug" : "info"
1950
- });
1951
- const requestedUrl = options.url ?? "file:./.voltagent/memory.db";
1952
- if (requestedUrl === ":memory:" || requestedUrl === "file::memory:" || requestedUrl.startsWith("file::memory:")) {
1953
- this.url = ":memory:";
1954
- } else {
1955
- this.url = requestedUrl;
1818
+ this.logger = logger;
1819
+ this.vectorCache = /* @__PURE__ */ new Map();
1820
+ }
1821
+ /**
1822
+ * Serialize a vector to binary format
1823
+ * Uses ArrayBuffer/DataView for cross-platform compatibility
1824
+ */
1825
+ serializeVector(vector) {
1826
+ const buffer = new ArrayBuffer(vector.length * 4);
1827
+ const view = new DataView(buffer);
1828
+ for (let i = 0; i < vector.length; i++) {
1829
+ view.setFloat32(i * 4, vector[i], true);
1956
1830
  }
1957
- if (this.url.startsWith("file:") && !this.url.startsWith("file::memory:")) {
1958
- const dbPath = this.url.replace("file:", "");
1959
- const dbDir = import_node_path3.default.dirname(dbPath);
1960
- if (!import_node_fs3.default.existsSync(dbDir)) {
1961
- import_node_fs3.default.mkdirSync(dbDir, { recursive: true });
1962
- }
1831
+ return new Uint8Array(buffer);
1832
+ }
1833
+ /**
1834
+ * Deserialize a vector from binary format
1835
+ */
1836
+ deserializeVector(data) {
1837
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
1838
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1839
+ const vector = [];
1840
+ for (let i = 0; i < bytes.length; i += 4) {
1841
+ vector.push(view.getFloat32(i, true));
1963
1842
  }
1964
- this.client = (0, import_client3.createClient)({
1965
- url: this.url,
1966
- authToken: options.authToken
1967
- });
1968
- this.vectorCache = /* @__PURE__ */ new Map();
1843
+ return vector;
1969
1844
  }
1970
1845
  /**
1971
1846
  * Initialize the database schema
@@ -1974,8 +1849,7 @@ var LibSQLVectorAdapter = class {
1974
1849
  if (this.initialized) return;
1975
1850
  const tableName = `${this.tablePrefix}_vectors`;
1976
1851
  try {
1977
- await this.client.executeMultiple(`
1978
- BEGIN;
1852
+ await this.client.execute(`
1979
1853
  CREATE TABLE IF NOT EXISTS ${tableName} (
1980
1854
  id TEXT PRIMARY KEY,
1981
1855
  vector BLOB NOT NULL,
@@ -1984,11 +1858,14 @@ var LibSQLVectorAdapter = class {
1984
1858
  content TEXT,
1985
1859
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1986
1860
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
1987
- );
1988
- CREATE INDEX IF NOT EXISTS idx_${tableName}_created ON ${tableName}(created_at);
1989
- CREATE INDEX IF NOT EXISTS idx_${tableName}_dimensions ON ${tableName}(dimensions);
1990
- COMMIT;
1861
+ )
1991
1862
  `);
1863
+ await this.client.execute(
1864
+ `CREATE INDEX IF NOT EXISTS idx_${tableName}_created ON ${tableName}(created_at)`
1865
+ );
1866
+ await this.client.execute(
1867
+ `CREATE INDEX IF NOT EXISTS idx_${tableName}_dimensions ON ${tableName}(dimensions)`
1868
+ );
1992
1869
  this.initialized = true;
1993
1870
  this.logger.debug("Vector adapter initialized");
1994
1871
  } catch (error) {
@@ -1996,34 +1873,6 @@ var LibSQLVectorAdapter = class {
1996
1873
  throw error;
1997
1874
  }
1998
1875
  }
1999
- /**
2000
- * Serialize a vector to binary format
2001
- */
2002
- serializeVector(vector) {
2003
- const buffer = Buffer.allocUnsafe(vector.length * 4);
2004
- for (let i = 0; i < vector.length; i++) {
2005
- buffer.writeFloatLE(vector[i], i * 4);
2006
- }
2007
- return buffer;
2008
- }
2009
- /**
2010
- * Deserialize a vector from binary format
2011
- */
2012
- deserializeVector(buffer) {
2013
- let bytes;
2014
- if (buffer instanceof Buffer) {
2015
- bytes = buffer;
2016
- } else if (buffer instanceof ArrayBuffer) {
2017
- bytes = Buffer.from(buffer);
2018
- } else {
2019
- bytes = Buffer.from(buffer);
2020
- }
2021
- const vector = [];
2022
- for (let i = 0; i < bytes.length; i += 4) {
2023
- vector.push(bytes.readFloatLE(i));
2024
- }
2025
- return vector;
2026
- }
2027
1876
  /**
2028
1877
  * Execute a database operation with retries
2029
1878
  */
@@ -2045,9 +1894,6 @@ var LibSQLVectorAdapter = class {
2045
1894
  this.logger.error(`Operation failed after ${this.maxRetries} attempts: ${context}`, lastError);
2046
1895
  throw lastError;
2047
1896
  }
2048
- /**
2049
- * Store a vector with associated metadata
2050
- */
2051
1897
  async store(id, vector, metadata) {
2052
1898
  await this.initialize();
2053
1899
  if (!Array.isArray(vector) || vector.length === 0) {
@@ -2071,7 +1917,7 @@ var LibSQLVectorAdapter = class {
2071
1917
  await this.executeWithRetry(async () => {
2072
1918
  await this.client.execute({
2073
1919
  sql: `
2074
- INSERT OR REPLACE INTO ${tableName}
1920
+ INSERT OR REPLACE INTO ${tableName}
2075
1921
  (id, vector, dimensions, metadata, updated_at)
2076
1922
  VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
2077
1923
  `,
@@ -2085,9 +1931,6 @@ var LibSQLVectorAdapter = class {
2085
1931
  this.vectorCache.set(id, { id, vector, metadata });
2086
1932
  this.logger.debug(`Vector stored: ${id} (${vector.length} dimensions)`);
2087
1933
  }
2088
- /**
2089
- * Store multiple vectors in batch
2090
- */
2091
1934
  async storeBatch(items) {
2092
1935
  await this.initialize();
2093
1936
  if (items.length === 0) return;
@@ -2120,9 +1963,6 @@ var LibSQLVectorAdapter = class {
2120
1963
  this.logger.debug(`Batch of ${batch.length} vectors stored`);
2121
1964
  }
2122
1965
  }
2123
- /**
2124
- * Search for similar vectors using cosine similarity
2125
- */
2126
1966
  async search(queryVector, options) {
2127
1967
  await this.initialize();
2128
1968
  const { limit = 10, threshold = 0, filter } = options || {};
@@ -2153,7 +1993,7 @@ var LibSQLVectorAdapter = class {
2153
1993
  continue;
2154
1994
  }
2155
1995
  const vector = this.deserializeVector(vectorBlob);
2156
- const similarity = (0, import_core2.cosineSimilarity)(queryVector, vector);
1996
+ const similarity = (0, import_core3.cosineSimilarity)(queryVector, vector);
2157
1997
  const score = (similarity + 1) / 2;
2158
1998
  if (score >= threshold) {
2159
1999
  searchResults.push({
@@ -2163,16 +2003,12 @@ var LibSQLVectorAdapter = class {
2163
2003
  content,
2164
2004
  score,
2165
2005
  distance: 1 - similarity
2166
- // Convert to distance metric
2167
2006
  });
2168
2007
  }
2169
2008
  }
2170
2009
  searchResults.sort((a, b) => b.score - a.score);
2171
2010
  return searchResults.slice(0, limit);
2172
2011
  }
2173
- /**
2174
- * Check if metadata matches the filter criteria
2175
- */
2176
2012
  matchesFilter(metadata, filter) {
2177
2013
  if (!metadata) {
2178
2014
  return false;
@@ -2184,9 +2020,6 @@ var LibSQLVectorAdapter = class {
2184
2020
  }
2185
2021
  return true;
2186
2022
  }
2187
- /**
2188
- * Delete a vector by ID
2189
- */
2190
2023
  async delete(id) {
2191
2024
  await this.initialize();
2192
2025
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2199,9 +2032,6 @@ var LibSQLVectorAdapter = class {
2199
2032
  this.vectorCache.delete(id);
2200
2033
  this.logger.debug(`Vector deleted: ${id}`);
2201
2034
  }
2202
- /**
2203
- * Delete multiple vectors by IDs
2204
- */
2205
2035
  async deleteBatch(ids) {
2206
2036
  await this.initialize();
2207
2037
  if (ids.length === 0) return;
@@ -2221,9 +2051,6 @@ var LibSQLVectorAdapter = class {
2221
2051
  this.logger.debug(`Batch of ${batch.length} vectors deleted`);
2222
2052
  }
2223
2053
  }
2224
- /**
2225
- * Clear all vectors
2226
- */
2227
2054
  async clear() {
2228
2055
  await this.initialize();
2229
2056
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2234,9 +2061,6 @@ var LibSQLVectorAdapter = class {
2234
2061
  this.dimensions = null;
2235
2062
  this.logger.debug("All vectors cleared");
2236
2063
  }
2237
- /**
2238
- * Get total count of stored vectors
2239
- */
2240
2064
  async count() {
2241
2065
  await this.initialize();
2242
2066
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2249,9 +2073,6 @@ var LibSQLVectorAdapter = class {
2249
2073
  if (typeof raw === "string") return Number.parseInt(raw, 10) || 0;
2250
2074
  return raw ?? 0;
2251
2075
  }
2252
- /**
2253
- * Get a specific vector by ID
2254
- */
2255
2076
  async get(id) {
2256
2077
  await this.initialize();
2257
2078
  if (this.vectorCache.has(id)) {
@@ -2260,7 +2081,6 @@ var LibSQLVectorAdapter = class {
2260
2081
  return {
2261
2082
  ...cached,
2262
2083
  vector: [...cached.vector],
2263
- // Return a copy
2264
2084
  metadata: cached.metadata ? { ...cached.metadata } : void 0
2265
2085
  };
2266
2086
  }
@@ -2295,20 +2115,10 @@ var LibSQLVectorAdapter = class {
2295
2115
  this.vectorCache.set(id, item);
2296
2116
  return item;
2297
2117
  }
2298
- /**
2299
- * Close the database connection
2300
- */
2301
2118
  async close() {
2302
2119
  this.vectorCache.clear();
2303
2120
  this.logger.debug("Vector adapter closed");
2304
- try {
2305
- this.client?.close?.();
2306
- } catch {
2307
- }
2308
2121
  }
2309
- /**
2310
- * Get statistics about the vector table and cache
2311
- */
2312
2122
  async getStats() {
2313
2123
  await this.initialize();
2314
2124
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2319,12 +2129,11 @@ var LibSQLVectorAdapter = class {
2319
2129
  ),
2320
2130
  "getStats count"
2321
2131
  ),
2322
- // Approximate table size by summing blob/text lengths
2323
2132
  this.executeWithRetry(
2324
2133
  async () => await this.client.execute({
2325
- sql: `SELECT
2326
- COALESCE(SUM(LENGTH(id)),0) +
2327
- COALESCE(SUM(LENGTH(vector)),0) +
2134
+ sql: `SELECT
2135
+ COALESCE(SUM(LENGTH(id)),0) +
2136
+ COALESCE(SUM(LENGTH(vector)),0) +
2328
2137
  COALESCE(SUM(LENGTH(metadata)),0) +
2329
2138
  COALESCE(SUM(LENGTH(content)),0) AS size
2330
2139
  FROM ${tableName}`
@@ -2346,6 +2155,66 @@ var LibSQLVectorAdapter = class {
2346
2155
  };
2347
2156
  }
2348
2157
  };
2158
+
2159
+ // src/vector-adapter.ts
2160
+ var LibSQLVectorAdapter = class extends LibSQLVectorCore {
2161
+ static {
2162
+ __name(this, "LibSQLVectorAdapter");
2163
+ }
2164
+ constructor(options = {}) {
2165
+ const logger = options.logger ?? (0, import_logger3.createPinoLogger)({
2166
+ name: "libsql-vector-adapter",
2167
+ level: options.debug ? "debug" : "info"
2168
+ });
2169
+ const requestedUrl = options.url ?? "file:./.voltagent/memory.db";
2170
+ let url;
2171
+ if (requestedUrl === ":memory:" || requestedUrl === "file::memory:" || requestedUrl.startsWith("file::memory:")) {
2172
+ url = ":memory:";
2173
+ } else {
2174
+ url = requestedUrl;
2175
+ }
2176
+ if (url.startsWith("file:") && !url.startsWith("file::memory:")) {
2177
+ const dbPath = url.replace("file:", "");
2178
+ const dbDir = import_node_path3.default.dirname(dbPath);
2179
+ if (!import_node_fs3.default.existsSync(dbDir)) {
2180
+ import_node_fs3.default.mkdirSync(dbDir, { recursive: true });
2181
+ }
2182
+ }
2183
+ const client = (0, import_client3.createClient)({
2184
+ url,
2185
+ authToken: options.authToken
2186
+ });
2187
+ super(client, options, logger);
2188
+ }
2189
+ /**
2190
+ * Override to use Buffer for more efficient serialization in Node.js
2191
+ */
2192
+ serializeVector(vector) {
2193
+ const buffer = Buffer.allocUnsafe(vector.length * 4);
2194
+ for (let i = 0; i < vector.length; i++) {
2195
+ buffer.writeFloatLE(vector[i], i * 4);
2196
+ }
2197
+ return buffer;
2198
+ }
2199
+ /**
2200
+ * Override to use Buffer for more efficient deserialization in Node.js
2201
+ */
2202
+ deserializeVector(data) {
2203
+ let buffer;
2204
+ if (data instanceof Buffer) {
2205
+ buffer = data;
2206
+ } else if (data instanceof ArrayBuffer) {
2207
+ buffer = Buffer.from(data);
2208
+ } else {
2209
+ buffer = Buffer.from(data);
2210
+ }
2211
+ const vector = [];
2212
+ for (let i = 0; i < buffer.length; i += 4) {
2213
+ vector.push(buffer.readFloatLE(i));
2214
+ }
2215
+ return vector;
2216
+ }
2217
+ };
2349
2218
  // Annotate the CommonJS export names for ESM import in node:
2350
2219
  0 && (module.exports = {
2351
2220
  LibSQLMemoryAdapter,