@voltagent/libsql 1.0.13 → 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.mjs CHANGED
@@ -5,16 +5,15 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
5
5
  import fs from "fs";
6
6
  import path from "path";
7
7
  import { createClient } from "@libsql/client";
8
- import {
9
- AgentRegistry,
10
- ConversationAlreadyExistsError,
11
- ConversationNotFoundError
12
- } from "@voltagent/core";
13
- import { safeStringify } from "@voltagent/internal";
8
+ import { AgentRegistry } from "@voltagent/core";
14
9
  import { createPinoLogger } from "@voltagent/logger";
15
- var LibSQLMemoryAdapter = class {
10
+
11
+ // src/memory-core.ts
12
+ import { ConversationAlreadyExistsError, ConversationNotFoundError } from "@voltagent/core";
13
+ import { safeStringify } from "@voltagent/internal";
14
+ var LibSQLMemoryCore = class {
16
15
  static {
17
- __name(this, "LibSQLMemoryAdapter");
16
+ __name(this, "LibSQLMemoryCore");
18
17
  }
19
18
  client;
20
19
  tablePrefix;
@@ -23,25 +22,14 @@ var LibSQLMemoryAdapter = class {
23
22
  maxRetries;
24
23
  retryDelayMs;
25
24
  url;
26
- constructor(options = {}) {
25
+ constructor(client, url, options, logger) {
26
+ this.client = client;
27
+ this.url = url;
27
28
  this.tablePrefix = options.tablePrefix ?? "voltagent_memory";
28
29
  this.maxRetries = options.maxRetries ?? 3;
29
30
  this.retryDelayMs = options.retryDelayMs ?? 100;
30
- this.logger = options.logger || AgentRegistry.getInstance().getGlobalLogger() || createPinoLogger({ name: "libsql-memory" });
31
- this.url = options.url ?? "file:./.voltagent/memory.db";
32
- if (this.url.startsWith("file:")) {
33
- const dbPath = this.url.replace("file:", "");
34
- const dbDir = path.dirname(dbPath);
35
- if (dbDir && dbDir !== "." && !fs.existsSync(dbDir)) {
36
- fs.mkdirSync(dbDir, { recursive: true });
37
- this.logger.debug(`Created database directory: ${dbDir}`);
38
- }
39
- }
40
- this.client = createClient({
41
- url: this.url,
42
- authToken: options.authToken
43
- });
44
- this.logger.debug("LibSQL Memory adapter initialized", { url: this.url });
31
+ this.logger = logger;
32
+ this.logger.debug("LibSQL Memory adapter core initialized", { url: this.url });
45
33
  }
46
34
  /**
47
35
  * Execute a database operation with retry logic
@@ -104,14 +92,12 @@ var LibSQLMemoryAdapter = class {
104
92
  this.logger.debug("Applied PRAGMA settings for better concurrency");
105
93
  await this.executeWithRetry(async () => {
106
94
  await this.client.batch([
107
- // Create users table (for user-level working memory)
108
95
  `CREATE TABLE IF NOT EXISTS ${usersTable} (
109
96
  id TEXT PRIMARY KEY,
110
97
  metadata TEXT,
111
98
  created_at TEXT DEFAULT CURRENT_TIMESTAMP,
112
99
  updated_at TEXT DEFAULT CURRENT_TIMESTAMP
113
100
  )`,
114
- // Create conversations table (matching existing structure)
115
101
  `CREATE TABLE IF NOT EXISTS ${conversationsTable} (
116
102
  id TEXT PRIMARY KEY,
117
103
  resource_id TEXT NOT NULL,
@@ -121,7 +107,6 @@ var LibSQLMemoryAdapter = class {
121
107
  created_at TEXT NOT NULL,
122
108
  updated_at TEXT NOT NULL
123
109
  )`,
124
- // Create messages table (matching existing structure)
125
110
  `CREATE TABLE IF NOT EXISTS ${messagesTable} (
126
111
  conversation_id TEXT NOT NULL,
127
112
  message_id TEXT NOT NULL,
@@ -133,7 +118,6 @@ var LibSQLMemoryAdapter = class {
133
118
  created_at TEXT NOT NULL,
134
119
  PRIMARY KEY (conversation_id, message_id)
135
120
  )`,
136
- // Create workflow states table
137
121
  `CREATE TABLE IF NOT EXISTS ${workflowStatesTable} (
138
122
  id TEXT PRIMARY KEY,
139
123
  workflow_id TEXT NOT NULL,
@@ -149,7 +133,6 @@ var LibSQLMemoryAdapter = class {
149
133
  created_at TEXT NOT NULL,
150
134
  updated_at TEXT NOT NULL
151
135
  )`,
152
- // Create conversation steps table
153
136
  `CREATE TABLE IF NOT EXISTS ${stepsTable} (
154
137
  id TEXT PRIMARY KEY,
155
138
  conversation_id TEXT NOT NULL,
@@ -169,7 +152,6 @@ var LibSQLMemoryAdapter = class {
169
152
  created_at TEXT NOT NULL,
170
153
  FOREIGN KEY (conversation_id) REFERENCES ${conversationsTable}(id) ON DELETE CASCADE
171
154
  )`,
172
- // Create indexes for better performance
173
155
  `CREATE INDEX IF NOT EXISTS idx_${conversationsTable}_user_id ON ${conversationsTable}(user_id)`,
174
156
  `CREATE INDEX IF NOT EXISTS idx_${conversationsTable}_resource_id ON ${conversationsTable}(resource_id)`,
175
157
  `CREATE INDEX IF NOT EXISTS idx_${messagesTable}_conversation_id ON ${messagesTable}(conversation_id)`,
@@ -186,10 +168,6 @@ var LibSQLMemoryAdapter = class {
186
168
  this.initialized = true;
187
169
  this.logger.debug("Database schema initialized");
188
170
  }
189
- /**
190
- * Add new columns to messages table for V2 format if they don't exist
191
- * This allows existing tables to support both old and new message formats
192
- */
193
171
  async addV2ColumnsToMessagesTable() {
194
172
  const messagesTableName = `${this.tablePrefix}_messages`;
195
173
  try {
@@ -262,10 +240,6 @@ var LibSQLMemoryAdapter = class {
262
240
  } catch (_) {
263
241
  }
264
242
  }
265
- /**
266
- * Migrate default user_id values in messages table
267
- * Updates messages with user_id='default' to use the actual user_id from their conversation
268
- */
269
243
  async migrateDefaultUserIds() {
270
244
  const messagesTableName = `${this.tablePrefix}_messages`;
271
245
  const conversationsTableName = `${this.tablePrefix}_conversations`;
@@ -283,14 +257,14 @@ var LibSQLMemoryAdapter = class {
283
257
  const result = await this.client.execute({
284
258
  sql: `UPDATE ${messagesTableName}
285
259
  SET user_id = (
286
- SELECT c.user_id
287
- FROM ${conversationsTableName} c
260
+ SELECT c.user_id
261
+ FROM ${conversationsTableName} c
288
262
  WHERE c.id = ${messagesTableName}.conversation_id
289
263
  )
290
264
  WHERE user_id = 'default'
291
265
  AND EXISTS (
292
- SELECT 1
293
- FROM ${conversationsTableName} c
266
+ SELECT 1
267
+ FROM ${conversationsTableName} c
294
268
  WHERE c.id = ${messagesTableName}.conversation_id
295
269
  )`,
296
270
  args: []
@@ -314,10 +288,6 @@ var LibSQLMemoryAdapter = class {
314
288
  this.logger.error("Failed to migrate default user_ids", error);
315
289
  }
316
290
  }
317
- /**
318
- * Add new columns to workflow_states table for event persistence
319
- * This migration adds support for events, output, and cancellation tracking
320
- */
321
291
  async addWorkflowStateColumns() {
322
292
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
323
293
  try {
@@ -353,9 +323,6 @@ var LibSQLMemoryAdapter = class {
353
323
  // ============================================================================
354
324
  // Message Operations
355
325
  // ============================================================================
356
- /**
357
- * Add a single message
358
- */
359
326
  async addMessage(message, userId, conversationId) {
360
327
  await this.initialize();
361
328
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -365,7 +332,7 @@ var LibSQLMemoryAdapter = class {
365
332
  }
366
333
  await this.executeWithRetry(async () => {
367
334
  await this.client.execute({
368
- sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
335
+ sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
369
336
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
370
337
  args: [
371
338
  conversationId,
@@ -375,15 +342,11 @@ var LibSQLMemoryAdapter = class {
375
342
  safeStringify(message.parts),
376
343
  message.metadata ? safeStringify(message.metadata) : null,
377
344
  2,
378
- // format_version
379
345
  (/* @__PURE__ */ new Date()).toISOString()
380
346
  ]
381
347
  });
382
348
  }, "add message");
383
349
  }
384
- /**
385
- * Add multiple messages
386
- */
387
350
  async addMessages(messages, userId, conversationId) {
388
351
  await this.initialize();
389
352
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -395,7 +358,7 @@ var LibSQLMemoryAdapter = class {
395
358
  await this.executeWithRetry(async () => {
396
359
  await this.client.batch(
397
360
  messages.map((message) => ({
398
- sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
361
+ sql: `INSERT INTO ${messagesTable} (conversation_id, message_id, user_id, role, parts, metadata, format_version, created_at)
399
362
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
400
363
  args: [
401
364
  conversationId,
@@ -405,7 +368,6 @@ var LibSQLMemoryAdapter = class {
405
368
  safeStringify(message.parts),
406
369
  message.metadata ? safeStringify(message.metadata) : null,
407
370
  2,
408
- // format_version
409
371
  now
410
372
  ]
411
373
  }))
@@ -478,9 +440,6 @@ var LibSQLMemoryAdapter = class {
478
440
  );
479
441
  }, "save conversation steps");
480
442
  }
481
- /**
482
- * Get messages with optional filtering
483
- */
484
443
  async getMessages(userId, conversationId, options) {
485
444
  await this.initialize();
486
445
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -588,9 +547,6 @@ var LibSQLMemoryAdapter = class {
588
547
  createdAt: row.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
589
548
  }));
590
549
  }
591
- /**
592
- * Clear messages for a user
593
- */
594
550
  async clearMessages(userId, conversationId) {
595
551
  await this.initialize();
596
552
  const messagesTable = `${this.tablePrefix}_messages`;
@@ -625,9 +581,6 @@ var LibSQLMemoryAdapter = class {
625
581
  // ============================================================================
626
582
  // Conversation Operations
627
583
  // ============================================================================
628
- /**
629
- * Create a new conversation
630
- */
631
584
  async createConversation(input) {
632
585
  await this.initialize();
633
586
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -638,7 +591,7 @@ var LibSQLMemoryAdapter = class {
638
591
  const now = (/* @__PURE__ */ new Date()).toISOString();
639
592
  await this.executeWithRetry(async () => {
640
593
  await this.client.execute({
641
- sql: `INSERT INTO ${conversationsTable} (id, resource_id, user_id, title, metadata, created_at, updated_at)
594
+ sql: `INSERT INTO ${conversationsTable} (id, resource_id, user_id, title, metadata, created_at, updated_at)
642
595
  VALUES (?, ?, ?, ?, ?, ?, ?)`,
643
596
  args: [
644
597
  input.id,
@@ -661,9 +614,6 @@ var LibSQLMemoryAdapter = class {
661
614
  updatedAt: now
662
615
  };
663
616
  }
664
- /**
665
- * Get a conversation by ID
666
- */
667
617
  async getConversation(id) {
668
618
  await this.initialize();
669
619
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -685,9 +635,6 @@ var LibSQLMemoryAdapter = class {
685
635
  updatedAt: row.updated_at
686
636
  };
687
637
  }
688
- /**
689
- * Get conversations by resource ID
690
- */
691
638
  async getConversations(resourceId) {
692
639
  await this.initialize();
693
640
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -705,15 +652,9 @@ var LibSQLMemoryAdapter = class {
705
652
  updatedAt: row.updated_at
706
653
  }));
707
654
  }
708
- /**
709
- * Get conversations by user ID
710
- */
711
655
  async getConversationsByUserId(userId, options) {
712
656
  return this.queryConversations({ ...options, userId });
713
657
  }
714
- /**
715
- * Query conversations with filters
716
- */
717
658
  async queryConversations(options) {
718
659
  await this.initialize();
719
660
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -749,9 +690,6 @@ var LibSQLMemoryAdapter = class {
749
690
  updatedAt: row.updated_at
750
691
  }));
751
692
  }
752
- /**
753
- * Update a conversation
754
- */
755
693
  async updateConversation(id, updates) {
756
694
  await this.initialize();
757
695
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -785,9 +723,6 @@ var LibSQLMemoryAdapter = class {
785
723
  }
786
724
  return updated;
787
725
  }
788
- /**
789
- * Delete a conversation
790
- */
791
726
  async deleteConversation(id) {
792
727
  await this.initialize();
793
728
  const conversationsTable = `${this.tablePrefix}_conversations`;
@@ -799,9 +734,6 @@ var LibSQLMemoryAdapter = class {
799
734
  // ============================================================================
800
735
  // Working Memory Operations
801
736
  // ============================================================================
802
- /**
803
- * Get working memory
804
- */
805
737
  async getWorkingMemory(params) {
806
738
  await this.initialize();
807
739
  if (params.scope === "conversation" && params.conversationId) {
@@ -821,9 +753,6 @@ var LibSQLMemoryAdapter = class {
821
753
  }
822
754
  return null;
823
755
  }
824
- /**
825
- * Set working memory
826
- */
827
756
  async setWorkingMemory(params) {
828
757
  await this.initialize();
829
758
  if (params.scope === "conversation" && params.conversationId) {
@@ -857,9 +786,6 @@ var LibSQLMemoryAdapter = class {
857
786
  }
858
787
  }
859
788
  }
860
- /**
861
- * Delete working memory
862
- */
863
789
  async deleteWorkingMemory(params) {
864
790
  await this.initialize();
865
791
  if (params.scope === "conversation" && params.conversationId) {
@@ -891,9 +817,6 @@ var LibSQLMemoryAdapter = class {
891
817
  // ============================================================================
892
818
  // Workflow State Operations
893
819
  // ============================================================================
894
- /**
895
- * Get workflow state by execution ID
896
- */
897
820
  async getWorkflowState(executionId) {
898
821
  await this.initialize();
899
822
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
@@ -921,9 +844,60 @@ var LibSQLMemoryAdapter = class {
921
844
  updatedAt: new Date(row.updated_at)
922
845
  };
923
846
  }
924
- /**
925
- * Set workflow state
926
- */
847
+ async queryWorkflowRuns(query) {
848
+ await this.initialize();
849
+ const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
850
+ const conditions = [];
851
+ const args = [];
852
+ if (query.workflowId) {
853
+ conditions.push("workflow_id = ?");
854
+ args.push(query.workflowId);
855
+ }
856
+ if (query.status) {
857
+ conditions.push("status = ?");
858
+ args.push(query.status);
859
+ }
860
+ if (query.from) {
861
+ conditions.push("created_at >= ?");
862
+ args.push(query.from.toISOString());
863
+ }
864
+ if (query.to) {
865
+ conditions.push("created_at <= ?");
866
+ args.push(query.to.toISOString());
867
+ }
868
+ let sql = `SELECT * FROM ${workflowStatesTable}`;
869
+ if (conditions.length > 0) {
870
+ sql += ` WHERE ${conditions.join(" AND ")}`;
871
+ }
872
+ sql += " ORDER BY created_at DESC";
873
+ if (query.limit !== void 0) {
874
+ sql += " LIMIT ?";
875
+ args.push(query.limit);
876
+ }
877
+ if (query.offset !== void 0) {
878
+ sql += " OFFSET ?";
879
+ args.push(query.offset);
880
+ }
881
+ const result = await this.client.execute({
882
+ sql,
883
+ args
884
+ });
885
+ return result.rows.map((row) => ({
886
+ id: row.id,
887
+ workflowId: row.workflow_id,
888
+ workflowName: row.workflow_name,
889
+ status: row.status,
890
+ suspension: row.suspension ? JSON.parse(row.suspension) : void 0,
891
+ events: row.events ? JSON.parse(row.events) : void 0,
892
+ output: row.output ? JSON.parse(row.output) : void 0,
893
+ cancellation: row.cancellation ? JSON.parse(row.cancellation) : void 0,
894
+ userId: row.user_id,
895
+ conversationId: row.conversation_id,
896
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
897
+ createdAt: new Date(row.created_at),
898
+ updatedAt: new Date(row.updated_at)
899
+ }));
900
+ }
927
901
  async setWorkflowState(executionId, state) {
928
902
  await this.initialize();
929
903
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
@@ -948,9 +922,6 @@ var LibSQLMemoryAdapter = class {
948
922
  ]
949
923
  });
950
924
  }
951
- /**
952
- * Update workflow state
953
- */
954
925
  async updateWorkflowState(executionId, updates) {
955
926
  await this.initialize();
956
927
  const existing = await this.getWorkflowState(executionId);
@@ -964,9 +935,6 @@ var LibSQLMemoryAdapter = class {
964
935
  };
965
936
  await this.setWorkflowState(executionId, updated);
966
937
  }
967
- /**
968
- * Get suspended workflow states for a workflow
969
- */
970
938
  async getSuspendedWorkflowStates(workflowId) {
971
939
  await this.initialize();
972
940
  const workflowStatesTable = `${this.tablePrefix}_workflow_states`;
@@ -990,23 +958,46 @@ var LibSQLMemoryAdapter = class {
990
958
  updatedAt: new Date(row.updated_at)
991
959
  }));
992
960
  }
993
- /**
994
- * Close database connection
995
- */
996
961
  async close() {
997
962
  this.logger.debug("Closing LibSQL Memory adapter");
998
963
  }
999
964
  };
1000
965
 
966
+ // src/memory-v2-adapter.ts
967
+ var LibSQLMemoryAdapter = class extends LibSQLMemoryCore {
968
+ static {
969
+ __name(this, "LibSQLMemoryAdapter");
970
+ }
971
+ constructor(options = {}) {
972
+ const url = options.url ?? "file:./.voltagent/memory.db";
973
+ const logger = options.logger || AgentRegistry.getInstance().getGlobalLogger() || createPinoLogger({ name: "libsql-memory" });
974
+ if (url.startsWith("file:")) {
975
+ const dbPath = url.replace("file:", "");
976
+ const dbDir = path.dirname(dbPath);
977
+ if (dbDir && dbDir !== "." && !fs.existsSync(dbDir)) {
978
+ fs.mkdirSync(dbDir, { recursive: true });
979
+ logger.debug(`Created database directory: ${dbDir}`);
980
+ }
981
+ }
982
+ const client = createClient({
983
+ url,
984
+ authToken: options.authToken
985
+ });
986
+ super(client, url, options, logger);
987
+ }
988
+ };
989
+
1001
990
  // src/observability-adapter.ts
1002
991
  import { existsSync, mkdirSync } from "fs";
1003
992
  import { dirname } from "path";
1004
993
  import { createClient as createClient2 } from "@libsql/client";
1005
- import { safeStringify as safeStringify2 } from "@voltagent/internal/utils";
1006
994
  import { createPinoLogger as createPinoLogger2 } from "@voltagent/logger";
1007
- var LibSQLObservabilityAdapter = class {
995
+
996
+ // src/observability-core.ts
997
+ import { safeStringify as safeStringify2 } from "@voltagent/internal/utils";
998
+ var LibSQLObservabilityCore = class {
1008
999
  static {
1009
- __name(this, "LibSQLObservabilityAdapter");
1000
+ __name(this, "LibSQLObservabilityCore");
1010
1001
  }
1011
1002
  client;
1012
1003
  tablePrefix;
@@ -1014,47 +1005,24 @@ var LibSQLObservabilityAdapter = class {
1014
1005
  logger;
1015
1006
  initialized;
1016
1007
  maxSpansPerQuery;
1017
- constructor(options = {}) {
1018
- this.logger = options.logger || createPinoLogger2({ name: "libsql-observability" });
1008
+ constructor(client, options, logger) {
1009
+ this.client = client;
1010
+ this.logger = logger;
1019
1011
  this.tablePrefix = options.tablePrefix || "observability";
1020
1012
  this.debug = options.debug || false;
1021
1013
  this.maxSpansPerQuery = options.maxSpansPerQuery || 1e3;
1022
- const url = options.url || "file:./.voltagent/observability.db";
1023
- if (url.startsWith("file:") && !url.includes(":memory:")) {
1024
- const filePath = url.substring(5);
1025
- const dir = dirname(filePath);
1026
- if (dir && dir !== "." && !existsSync(dir)) {
1027
- try {
1028
- mkdirSync(dir, { recursive: true });
1029
- this.debugLog("Created directory for database", { dir });
1030
- } catch (error) {
1031
- this.logger.warn("Failed to create directory for database", { dir, error });
1032
- }
1033
- }
1034
- }
1035
- this.client = createClient2({
1036
- url,
1037
- authToken: options.authToken
1038
- });
1039
- this.debugLog("LibSQL observability adapter initialized with options", {
1040
- url,
1014
+ this.debugLog("LibSQL observability adapter core initialized", {
1041
1015
  tablePrefix: this.tablePrefix,
1042
1016
  debug: this.debug,
1043
1017
  maxSpansPerQuery: this.maxSpansPerQuery
1044
1018
  });
1045
1019
  this.initialized = this.initializeDatabase();
1046
1020
  }
1047
- /**
1048
- * Log a debug message if debug is enabled
1049
- */
1050
1021
  debugLog(message, data) {
1051
1022
  if (this.debug) {
1052
1023
  this.logger.debug(`${message}`, data || "");
1053
1024
  }
1054
1025
  }
1055
- /**
1056
- * Initialize database tables for observability
1057
- */
1058
1026
  async initializeDatabase() {
1059
1027
  try {
1060
1028
  await this.client.execute(`
@@ -1081,27 +1049,27 @@ var LibSQLObservabilityAdapter = class {
1081
1049
  )
1082
1050
  `);
1083
1051
  await this.client.execute(`
1084
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_trace_id
1052
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_trace_id
1085
1053
  ON ${this.tablePrefix}_spans(trace_id)
1086
1054
  `);
1087
1055
  await this.client.execute(`
1088
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_parent_span_id
1056
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_parent_span_id
1089
1057
  ON ${this.tablePrefix}_spans(parent_span_id)
1090
1058
  `);
1091
1059
  await this.client.execute(`
1092
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_start_time
1060
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_start_time
1093
1061
  ON ${this.tablePrefix}_spans(start_time)
1094
1062
  `);
1095
1063
  await this.client.execute(`
1096
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_name
1064
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_name
1097
1065
  ON ${this.tablePrefix}_spans(name)
1098
1066
  `);
1099
1067
  await this.client.execute(`
1100
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_id
1068
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_id
1101
1069
  ON ${this.tablePrefix}_spans(entity_id)
1102
1070
  `);
1103
1071
  await this.client.execute(`
1104
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_type
1072
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_spans_entity_type
1105
1073
  ON ${this.tablePrefix}_spans(entity_type)
1106
1074
  `);
1107
1075
  await this.client.execute(`
@@ -1118,15 +1086,15 @@ var LibSQLObservabilityAdapter = class {
1118
1086
  )
1119
1087
  `);
1120
1088
  await this.client.execute(`
1121
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_start_time
1089
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_start_time
1122
1090
  ON ${this.tablePrefix}_traces(start_time DESC)
1123
1091
  `);
1124
1092
  await this.client.execute(`
1125
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_id
1093
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_id
1126
1094
  ON ${this.tablePrefix}_traces(entity_id)
1127
1095
  `);
1128
1096
  await this.client.execute(`
1129
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_type
1097
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_traces_entity_type
1130
1098
  ON ${this.tablePrefix}_traces(entity_type)
1131
1099
  `);
1132
1100
  await this.client.execute(`
@@ -1146,19 +1114,19 @@ var LibSQLObservabilityAdapter = class {
1146
1114
  )
1147
1115
  `);
1148
1116
  await this.client.execute(`
1149
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_trace_id
1117
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_trace_id
1150
1118
  ON ${this.tablePrefix}_logs(trace_id)
1151
1119
  `);
1152
1120
  await this.client.execute(`
1153
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_span_id
1121
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_span_id
1154
1122
  ON ${this.tablePrefix}_logs(span_id)
1155
1123
  `);
1156
1124
  await this.client.execute(`
1157
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_timestamp
1125
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_timestamp
1158
1126
  ON ${this.tablePrefix}_logs(timestamp DESC)
1159
1127
  `);
1160
1128
  await this.client.execute(`
1161
- CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_severity
1129
+ CREATE INDEX IF NOT EXISTS idx_${this.tablePrefix}_logs_severity
1162
1130
  ON ${this.tablePrefix}_logs(severity_number)
1163
1131
  `);
1164
1132
  this.debugLog("Database tables initialized successfully");
@@ -1167,22 +1135,15 @@ var LibSQLObservabilityAdapter = class {
1167
1135
  throw error;
1168
1136
  }
1169
1137
  }
1170
- /**
1171
- * Ensure database is initialized before operations
1172
- */
1173
1138
  async ensureInitialized() {
1174
1139
  await this.initialized;
1175
1140
  }
1176
- /**
1177
- * Add a span to the database
1178
- */
1179
1141
  async addSpan(span) {
1180
1142
  await this.ensureInitialized();
1181
1143
  try {
1182
1144
  const entityId = span.attributes?.["entity.id"] || null;
1183
1145
  const entityType = span.attributes?.["entity.type"] || null;
1184
1146
  await this.client.batch([
1185
- // Insert the span with entity columns
1186
1147
  {
1187
1148
  sql: `
1188
1149
  INSERT INTO ${this.tablePrefix}_spans (
@@ -1213,7 +1174,6 @@ var LibSQLObservabilityAdapter = class {
1213
1174
  span.instrumentationScope ? safeStringify2(span.instrumentationScope) : null
1214
1175
  ]
1215
1176
  },
1216
- // Update or insert trace metadata with entity columns
1217
1177
  {
1218
1178
  sql: `
1219
1179
  INSERT INTO ${this.tablePrefix}_traces (
@@ -1230,7 +1190,6 @@ var LibSQLObservabilityAdapter = class {
1230
1190
  args: [
1231
1191
  span.traceId,
1232
1192
  span.parentSpanId ? null : span.spanId,
1233
- // Root span if no parent
1234
1193
  entityId,
1235
1194
  entityType,
1236
1195
  span.startTime,
@@ -1247,9 +1206,6 @@ var LibSQLObservabilityAdapter = class {
1247
1206
  throw error;
1248
1207
  }
1249
1208
  }
1250
- /**
1251
- * Update an existing span
1252
- */
1253
1209
  async updateSpan(spanId, updates) {
1254
1210
  await this.ensureInitialized();
1255
1211
  try {
@@ -1286,7 +1242,7 @@ var LibSQLObservabilityAdapter = class {
1286
1242
  args.push(spanId);
1287
1243
  await this.client.execute({
1288
1244
  sql: `
1289
- UPDATE ${this.tablePrefix}_spans
1245
+ UPDATE ${this.tablePrefix}_spans
1290
1246
  SET ${setClauses.join(", ")}
1291
1247
  WHERE span_id = ?
1292
1248
  `,
@@ -1312,32 +1268,22 @@ var LibSQLObservabilityAdapter = class {
1312
1268
  throw error;
1313
1269
  }
1314
1270
  }
1315
- /**
1316
- * Get a span by ID
1317
- */
1318
1271
  async getSpan(spanId) {
1319
1272
  await this.ensureInitialized();
1320
1273
  try {
1321
1274
  const result = await this.client.execute({
1322
- sql: `
1323
- SELECT * FROM ${this.tablePrefix}_spans
1324
- WHERE span_id = ?
1325
- `,
1275
+ sql: `SELECT * FROM ${this.tablePrefix}_spans WHERE span_id = ?`,
1326
1276
  args: [spanId]
1327
1277
  });
1328
1278
  if (result.rows.length === 0) {
1329
1279
  return null;
1330
1280
  }
1331
- const row = result.rows[0];
1332
- return this.rowToSpan(row);
1281
+ return this.rowToSpan(result.rows[0]);
1333
1282
  } catch (error) {
1334
1283
  this.logger.error("Failed to get span", { error, spanId });
1335
1284
  throw error;
1336
1285
  }
1337
1286
  }
1338
- /**
1339
- * Get all spans in a trace
1340
- */
1341
1287
  async getTrace(traceId) {
1342
1288
  await this.ensureInitialized();
1343
1289
  try {
@@ -1356,9 +1302,6 @@ var LibSQLObservabilityAdapter = class {
1356
1302
  throw error;
1357
1303
  }
1358
1304
  }
1359
- /**
1360
- * List all traces with optional entity filter
1361
- */
1362
1305
  async listTraces(limit = 100, offset = 0, filter) {
1363
1306
  await this.ensureInitialized();
1364
1307
  try {
@@ -1396,52 +1339,36 @@ var LibSQLObservabilityAdapter = class {
1396
1339
  throw error;
1397
1340
  }
1398
1341
  }
1399
- /**
1400
- * Delete old spans
1401
- */
1402
1342
  async deleteOldSpans(beforeTimestamp) {
1403
1343
  await this.ensureInitialized();
1404
1344
  try {
1405
1345
  const beforeDate = new Date(beforeTimestamp).toISOString();
1406
1346
  const tracesResult = await this.client.execute({
1407
- sql: `
1408
- SELECT DISTINCT trace_id FROM ${this.tablePrefix}_spans
1409
- WHERE start_time < ?
1410
- `,
1347
+ sql: `SELECT DISTINCT trace_id FROM ${this.tablePrefix}_spans WHERE start_time < ?`,
1411
1348
  args: [beforeDate]
1412
1349
  });
1413
1350
  const affectedTraceIds = tracesResult.rows.map((row) => row.trace_id);
1414
1351
  const deleteResult = await this.client.execute({
1415
- sql: `
1416
- DELETE FROM ${this.tablePrefix}_spans
1417
- WHERE start_time < ?
1418
- `,
1352
+ sql: `DELETE FROM ${this.tablePrefix}_spans WHERE start_time < ?`,
1419
1353
  args: [beforeDate]
1420
1354
  });
1421
1355
  if (affectedTraceIds.length > 0) {
1422
1356
  for (const traceId of affectedTraceIds) {
1423
1357
  const countResult = await this.client.execute({
1424
- sql: `
1425
- SELECT COUNT(*) as count FROM ${this.tablePrefix}_spans
1426
- WHERE trace_id = ?
1427
- `,
1358
+ sql: `SELECT COUNT(*) as count FROM ${this.tablePrefix}_spans WHERE trace_id = ?`,
1428
1359
  args: [traceId]
1429
1360
  });
1430
1361
  const count = countResult.rows[0].count;
1431
1362
  if (count === 0) {
1432
1363
  await this.client.execute({
1433
- sql: `
1434
- DELETE FROM ${this.tablePrefix}_traces
1435
- WHERE trace_id = ?
1436
- `,
1364
+ sql: `DELETE FROM ${this.tablePrefix}_traces WHERE trace_id = ?`,
1437
1365
  args: [traceId]
1438
1366
  });
1439
1367
  } else {
1440
1368
  await this.client.execute({
1441
1369
  sql: `
1442
1370
  UPDATE ${this.tablePrefix}_traces
1443
- SET span_count = ?,
1444
- updated_at = CURRENT_TIMESTAMP
1371
+ SET span_count = ?, updated_at = CURRENT_TIMESTAMP
1445
1372
  WHERE trace_id = ?
1446
1373
  `,
1447
1374
  args: [count, traceId]
@@ -1457,9 +1384,6 @@ var LibSQLObservabilityAdapter = class {
1457
1384
  throw error;
1458
1385
  }
1459
1386
  }
1460
- /**
1461
- * Clear all spans, traces, and logs
1462
- */
1463
1387
  async clear() {
1464
1388
  await this.ensureInitialized();
1465
1389
  try {
@@ -1474,9 +1398,6 @@ var LibSQLObservabilityAdapter = class {
1474
1398
  throw error;
1475
1399
  }
1476
1400
  }
1477
- /**
1478
- * Convert a database row to an ObservabilitySpan
1479
- */
1480
1401
  rowToSpan(row) {
1481
1402
  const span = {
1482
1403
  traceId: row.trace_id,
@@ -1522,9 +1443,6 @@ var LibSQLObservabilityAdapter = class {
1522
1443
  }
1523
1444
  return span;
1524
1445
  }
1525
- /**
1526
- * Get statistics about stored spans
1527
- */
1528
1446
  async getStats() {
1529
1447
  await this.ensureInitialized();
1530
1448
  try {
@@ -1532,9 +1450,7 @@ var LibSQLObservabilityAdapter = class {
1532
1450
  this.client.execute(`SELECT COUNT(*) as count FROM ${this.tablePrefix}_spans`),
1533
1451
  this.client.execute(`SELECT COUNT(*) as count FROM ${this.tablePrefix}_traces`),
1534
1452
  this.client.execute(`
1535
- SELECT
1536
- MIN(start_time) as oldest,
1537
- MAX(start_time) as newest
1453
+ SELECT MIN(start_time) as oldest, MAX(start_time) as newest
1538
1454
  FROM ${this.tablePrefix}_spans
1539
1455
  `)
1540
1456
  ]);
@@ -1554,9 +1470,6 @@ var LibSQLObservabilityAdapter = class {
1554
1470
  throw error;
1555
1471
  }
1556
1472
  }
1557
- /**
1558
- * Save a log record to the database
1559
- */
1560
1473
  async saveLogRecord(logRecord) {
1561
1474
  await this.ensureInitialized();
1562
1475
  try {
@@ -1611,9 +1524,6 @@ var LibSQLObservabilityAdapter = class {
1611
1524
  throw error;
1612
1525
  }
1613
1526
  }
1614
- /**
1615
- * Get logs by trace ID
1616
- */
1617
1527
  async getLogsByTraceId(traceId) {
1618
1528
  await this.ensureInitialized();
1619
1529
  try {
@@ -1632,9 +1542,6 @@ var LibSQLObservabilityAdapter = class {
1632
1542
  throw error;
1633
1543
  }
1634
1544
  }
1635
- /**
1636
- * Get logs by span ID
1637
- */
1638
1545
  async getLogsBySpanId(spanId) {
1639
1546
  await this.ensureInitialized();
1640
1547
  try {
@@ -1653,9 +1560,6 @@ var LibSQLObservabilityAdapter = class {
1653
1560
  throw error;
1654
1561
  }
1655
1562
  }
1656
- /**
1657
- * Query logs with flexible filtering
1658
- */
1659
1563
  async queryLogs(filter) {
1660
1564
  await this.ensureInitialized();
1661
1565
  try {
@@ -1724,18 +1628,12 @@ var LibSQLObservabilityAdapter = class {
1724
1628
  throw error;
1725
1629
  }
1726
1630
  }
1727
- /**
1728
- * Delete old logs
1729
- */
1730
1631
  async deleteOldLogs(beforeTimestamp) {
1731
1632
  await this.ensureInitialized();
1732
1633
  try {
1733
1634
  const beforeDate = new Date(beforeTimestamp).toISOString();
1734
1635
  const result = await this.client.execute({
1735
- sql: `
1736
- DELETE FROM ${this.tablePrefix}_logs
1737
- WHERE timestamp < ?
1738
- `,
1636
+ sql: `DELETE FROM ${this.tablePrefix}_logs WHERE timestamp < ?`,
1739
1637
  args: [beforeDate]
1740
1638
  });
1741
1639
  const deletedCount = result.rowsAffected || 0;
@@ -1746,9 +1644,6 @@ var LibSQLObservabilityAdapter = class {
1746
1644
  throw error;
1747
1645
  }
1748
1646
  }
1749
- /**
1750
- * Convert a database row to an ObservabilityLogRecord
1751
- */
1752
1647
  rowToLogRecord(row) {
1753
1648
  const log = {
1754
1649
  timestamp: row.timestamp,
@@ -1815,26 +1710,55 @@ var LibSQLObservabilityAdapter = class {
1815
1710
  description: "Persists spans and logs to a LibSQL/Turso database for long-term retention."
1816
1711
  };
1817
1712
  }
1818
- /**
1819
- * Close the database connection
1820
- */
1821
1713
  async close() {
1822
1714
  this.debugLog("LibSQL observability adapter closed");
1823
1715
  }
1824
1716
  };
1825
1717
 
1718
+ // src/observability-adapter.ts
1719
+ var LibSQLObservabilityAdapter = class extends LibSQLObservabilityCore {
1720
+ static {
1721
+ __name(this, "LibSQLObservabilityAdapter");
1722
+ }
1723
+ constructor(options = {}) {
1724
+ const url = options.url || "file:./.voltagent/observability.db";
1725
+ const logger = options.logger || createPinoLogger2({ name: "libsql-observability" });
1726
+ if (url.startsWith("file:") && !url.includes(":memory:")) {
1727
+ const filePath = url.substring(5);
1728
+ const dir = dirname(filePath);
1729
+ if (dir && dir !== "." && !existsSync(dir)) {
1730
+ try {
1731
+ mkdirSync(dir, { recursive: true });
1732
+ if (options.debug) {
1733
+ logger.debug("Created directory for database", { dir });
1734
+ }
1735
+ } catch (error) {
1736
+ logger.warn("Failed to create directory for database", { dir, error });
1737
+ }
1738
+ }
1739
+ }
1740
+ const client = createClient2({
1741
+ url,
1742
+ authToken: options.authToken
1743
+ });
1744
+ super(client, options, logger);
1745
+ }
1746
+ };
1747
+
1826
1748
  // src/vector-adapter.ts
1827
1749
  import fs2 from "fs";
1828
1750
  import path2 from "path";
1829
1751
  import { createClient as createClient3 } from "@libsql/client";
1752
+ import { createPinoLogger as createPinoLogger3 } from "@voltagent/logger";
1753
+
1754
+ // src/vector-core.ts
1830
1755
  import {
1831
1756
  cosineSimilarity
1832
1757
  } from "@voltagent/core";
1833
1758
  import { safeStringify as safeStringify3 } from "@voltagent/internal";
1834
- import { createPinoLogger as createPinoLogger3 } from "@voltagent/logger";
1835
- var LibSQLVectorAdapter = class {
1759
+ var LibSQLVectorCore = class {
1836
1760
  static {
1837
- __name(this, "LibSQLVectorAdapter");
1761
+ __name(this, "LibSQLVectorCore");
1838
1762
  }
1839
1763
  client;
1840
1764
  tablePrefix;
@@ -1845,11 +1769,11 @@ var LibSQLVectorAdapter = class {
1845
1769
  logger;
1846
1770
  maxRetries;
1847
1771
  retryDelayMs;
1848
- url;
1849
1772
  initialized = false;
1850
1773
  vectorCache;
1851
1774
  dimensions = null;
1852
- constructor(options = {}) {
1775
+ constructor(client, options, logger) {
1776
+ this.client = client;
1853
1777
  this.tablePrefix = options.tablePrefix ?? "voltagent";
1854
1778
  this.maxVectorDimensions = options.maxVectorDimensions ?? 1536;
1855
1779
  this.cacheSize = options.cacheSize ?? 100;
@@ -1857,28 +1781,32 @@ var LibSQLVectorAdapter = class {
1857
1781
  this.maxRetries = options.maxRetries ?? 3;
1858
1782
  this.retryDelayMs = options.retryDelayMs ?? 100;
1859
1783
  this.debug = options.debug ?? false;
1860
- this.logger = options.logger ?? createPinoLogger3({
1861
- name: "libsql-vector-adapter",
1862
- level: this.debug ? "debug" : "info"
1863
- });
1864
- const requestedUrl = options.url ?? "file:./.voltagent/memory.db";
1865
- if (requestedUrl === ":memory:" || requestedUrl === "file::memory:" || requestedUrl.startsWith("file::memory:")) {
1866
- this.url = ":memory:";
1867
- } else {
1868
- this.url = requestedUrl;
1784
+ this.logger = logger;
1785
+ this.vectorCache = /* @__PURE__ */ new Map();
1786
+ }
1787
+ /**
1788
+ * Serialize a vector to binary format
1789
+ * Uses ArrayBuffer/DataView for cross-platform compatibility
1790
+ */
1791
+ serializeVector(vector) {
1792
+ const buffer = new ArrayBuffer(vector.length * 4);
1793
+ const view = new DataView(buffer);
1794
+ for (let i = 0; i < vector.length; i++) {
1795
+ view.setFloat32(i * 4, vector[i], true);
1869
1796
  }
1870
- if (this.url.startsWith("file:") && !this.url.startsWith("file::memory:")) {
1871
- const dbPath = this.url.replace("file:", "");
1872
- const dbDir = path2.dirname(dbPath);
1873
- if (!fs2.existsSync(dbDir)) {
1874
- fs2.mkdirSync(dbDir, { recursive: true });
1875
- }
1797
+ return new Uint8Array(buffer);
1798
+ }
1799
+ /**
1800
+ * Deserialize a vector from binary format
1801
+ */
1802
+ deserializeVector(data) {
1803
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
1804
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1805
+ const vector = [];
1806
+ for (let i = 0; i < bytes.length; i += 4) {
1807
+ vector.push(view.getFloat32(i, true));
1876
1808
  }
1877
- this.client = createClient3({
1878
- url: this.url,
1879
- authToken: options.authToken
1880
- });
1881
- this.vectorCache = /* @__PURE__ */ new Map();
1809
+ return vector;
1882
1810
  }
1883
1811
  /**
1884
1812
  * Initialize the database schema
@@ -1887,8 +1815,7 @@ var LibSQLVectorAdapter = class {
1887
1815
  if (this.initialized) return;
1888
1816
  const tableName = `${this.tablePrefix}_vectors`;
1889
1817
  try {
1890
- await this.client.executeMultiple(`
1891
- BEGIN;
1818
+ await this.client.execute(`
1892
1819
  CREATE TABLE IF NOT EXISTS ${tableName} (
1893
1820
  id TEXT PRIMARY KEY,
1894
1821
  vector BLOB NOT NULL,
@@ -1897,11 +1824,14 @@ var LibSQLVectorAdapter = class {
1897
1824
  content TEXT,
1898
1825
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1899
1826
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
1900
- );
1901
- CREATE INDEX IF NOT EXISTS idx_${tableName}_created ON ${tableName}(created_at);
1902
- CREATE INDEX IF NOT EXISTS idx_${tableName}_dimensions ON ${tableName}(dimensions);
1903
- COMMIT;
1827
+ )
1904
1828
  `);
1829
+ await this.client.execute(
1830
+ `CREATE INDEX IF NOT EXISTS idx_${tableName}_created ON ${tableName}(created_at)`
1831
+ );
1832
+ await this.client.execute(
1833
+ `CREATE INDEX IF NOT EXISTS idx_${tableName}_dimensions ON ${tableName}(dimensions)`
1834
+ );
1905
1835
  this.initialized = true;
1906
1836
  this.logger.debug("Vector adapter initialized");
1907
1837
  } catch (error) {
@@ -1909,34 +1839,6 @@ var LibSQLVectorAdapter = class {
1909
1839
  throw error;
1910
1840
  }
1911
1841
  }
1912
- /**
1913
- * Serialize a vector to binary format
1914
- */
1915
- serializeVector(vector) {
1916
- const buffer = Buffer.allocUnsafe(vector.length * 4);
1917
- for (let i = 0; i < vector.length; i++) {
1918
- buffer.writeFloatLE(vector[i], i * 4);
1919
- }
1920
- return buffer;
1921
- }
1922
- /**
1923
- * Deserialize a vector from binary format
1924
- */
1925
- deserializeVector(buffer) {
1926
- let bytes;
1927
- if (buffer instanceof Buffer) {
1928
- bytes = buffer;
1929
- } else if (buffer instanceof ArrayBuffer) {
1930
- bytes = Buffer.from(buffer);
1931
- } else {
1932
- bytes = Buffer.from(buffer);
1933
- }
1934
- const vector = [];
1935
- for (let i = 0; i < bytes.length; i += 4) {
1936
- vector.push(bytes.readFloatLE(i));
1937
- }
1938
- return vector;
1939
- }
1940
1842
  /**
1941
1843
  * Execute a database operation with retries
1942
1844
  */
@@ -1958,9 +1860,6 @@ var LibSQLVectorAdapter = class {
1958
1860
  this.logger.error(`Operation failed after ${this.maxRetries} attempts: ${context}`, lastError);
1959
1861
  throw lastError;
1960
1862
  }
1961
- /**
1962
- * Store a vector with associated metadata
1963
- */
1964
1863
  async store(id, vector, metadata) {
1965
1864
  await this.initialize();
1966
1865
  if (!Array.isArray(vector) || vector.length === 0) {
@@ -1984,7 +1883,7 @@ var LibSQLVectorAdapter = class {
1984
1883
  await this.executeWithRetry(async () => {
1985
1884
  await this.client.execute({
1986
1885
  sql: `
1987
- INSERT OR REPLACE INTO ${tableName}
1886
+ INSERT OR REPLACE INTO ${tableName}
1988
1887
  (id, vector, dimensions, metadata, updated_at)
1989
1888
  VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
1990
1889
  `,
@@ -1998,9 +1897,6 @@ var LibSQLVectorAdapter = class {
1998
1897
  this.vectorCache.set(id, { id, vector, metadata });
1999
1898
  this.logger.debug(`Vector stored: ${id} (${vector.length} dimensions)`);
2000
1899
  }
2001
- /**
2002
- * Store multiple vectors in batch
2003
- */
2004
1900
  async storeBatch(items) {
2005
1901
  await this.initialize();
2006
1902
  if (items.length === 0) return;
@@ -2033,9 +1929,6 @@ var LibSQLVectorAdapter = class {
2033
1929
  this.logger.debug(`Batch of ${batch.length} vectors stored`);
2034
1930
  }
2035
1931
  }
2036
- /**
2037
- * Search for similar vectors using cosine similarity
2038
- */
2039
1932
  async search(queryVector, options) {
2040
1933
  await this.initialize();
2041
1934
  const { limit = 10, threshold = 0, filter } = options || {};
@@ -2076,16 +1969,12 @@ var LibSQLVectorAdapter = class {
2076
1969
  content,
2077
1970
  score,
2078
1971
  distance: 1 - similarity
2079
- // Convert to distance metric
2080
1972
  });
2081
1973
  }
2082
1974
  }
2083
1975
  searchResults.sort((a, b) => b.score - a.score);
2084
1976
  return searchResults.slice(0, limit);
2085
1977
  }
2086
- /**
2087
- * Check if metadata matches the filter criteria
2088
- */
2089
1978
  matchesFilter(metadata, filter) {
2090
1979
  if (!metadata) {
2091
1980
  return false;
@@ -2097,9 +1986,6 @@ var LibSQLVectorAdapter = class {
2097
1986
  }
2098
1987
  return true;
2099
1988
  }
2100
- /**
2101
- * Delete a vector by ID
2102
- */
2103
1989
  async delete(id) {
2104
1990
  await this.initialize();
2105
1991
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2112,9 +1998,6 @@ var LibSQLVectorAdapter = class {
2112
1998
  this.vectorCache.delete(id);
2113
1999
  this.logger.debug(`Vector deleted: ${id}`);
2114
2000
  }
2115
- /**
2116
- * Delete multiple vectors by IDs
2117
- */
2118
2001
  async deleteBatch(ids) {
2119
2002
  await this.initialize();
2120
2003
  if (ids.length === 0) return;
@@ -2134,9 +2017,6 @@ var LibSQLVectorAdapter = class {
2134
2017
  this.logger.debug(`Batch of ${batch.length} vectors deleted`);
2135
2018
  }
2136
2019
  }
2137
- /**
2138
- * Clear all vectors
2139
- */
2140
2020
  async clear() {
2141
2021
  await this.initialize();
2142
2022
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2147,9 +2027,6 @@ var LibSQLVectorAdapter = class {
2147
2027
  this.dimensions = null;
2148
2028
  this.logger.debug("All vectors cleared");
2149
2029
  }
2150
- /**
2151
- * Get total count of stored vectors
2152
- */
2153
2030
  async count() {
2154
2031
  await this.initialize();
2155
2032
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2162,9 +2039,6 @@ var LibSQLVectorAdapter = class {
2162
2039
  if (typeof raw === "string") return Number.parseInt(raw, 10) || 0;
2163
2040
  return raw ?? 0;
2164
2041
  }
2165
- /**
2166
- * Get a specific vector by ID
2167
- */
2168
2042
  async get(id) {
2169
2043
  await this.initialize();
2170
2044
  if (this.vectorCache.has(id)) {
@@ -2173,7 +2047,6 @@ var LibSQLVectorAdapter = class {
2173
2047
  return {
2174
2048
  ...cached,
2175
2049
  vector: [...cached.vector],
2176
- // Return a copy
2177
2050
  metadata: cached.metadata ? { ...cached.metadata } : void 0
2178
2051
  };
2179
2052
  }
@@ -2208,20 +2081,10 @@ var LibSQLVectorAdapter = class {
2208
2081
  this.vectorCache.set(id, item);
2209
2082
  return item;
2210
2083
  }
2211
- /**
2212
- * Close the database connection
2213
- */
2214
2084
  async close() {
2215
2085
  this.vectorCache.clear();
2216
2086
  this.logger.debug("Vector adapter closed");
2217
- try {
2218
- this.client?.close?.();
2219
- } catch {
2220
- }
2221
2087
  }
2222
- /**
2223
- * Get statistics about the vector table and cache
2224
- */
2225
2088
  async getStats() {
2226
2089
  await this.initialize();
2227
2090
  const tableName = `${this.tablePrefix}_vectors`;
@@ -2232,12 +2095,11 @@ var LibSQLVectorAdapter = class {
2232
2095
  ),
2233
2096
  "getStats count"
2234
2097
  ),
2235
- // Approximate table size by summing blob/text lengths
2236
2098
  this.executeWithRetry(
2237
2099
  async () => await this.client.execute({
2238
- sql: `SELECT
2239
- COALESCE(SUM(LENGTH(id)),0) +
2240
- COALESCE(SUM(LENGTH(vector)),0) +
2100
+ sql: `SELECT
2101
+ COALESCE(SUM(LENGTH(id)),0) +
2102
+ COALESCE(SUM(LENGTH(vector)),0) +
2241
2103
  COALESCE(SUM(LENGTH(metadata)),0) +
2242
2104
  COALESCE(SUM(LENGTH(content)),0) AS size
2243
2105
  FROM ${tableName}`
@@ -2259,6 +2121,66 @@ var LibSQLVectorAdapter = class {
2259
2121
  };
2260
2122
  }
2261
2123
  };
2124
+
2125
+ // src/vector-adapter.ts
2126
+ var LibSQLVectorAdapter = class extends LibSQLVectorCore {
2127
+ static {
2128
+ __name(this, "LibSQLVectorAdapter");
2129
+ }
2130
+ constructor(options = {}) {
2131
+ const logger = options.logger ?? createPinoLogger3({
2132
+ name: "libsql-vector-adapter",
2133
+ level: options.debug ? "debug" : "info"
2134
+ });
2135
+ const requestedUrl = options.url ?? "file:./.voltagent/memory.db";
2136
+ let url;
2137
+ if (requestedUrl === ":memory:" || requestedUrl === "file::memory:" || requestedUrl.startsWith("file::memory:")) {
2138
+ url = ":memory:";
2139
+ } else {
2140
+ url = requestedUrl;
2141
+ }
2142
+ if (url.startsWith("file:") && !url.startsWith("file::memory:")) {
2143
+ const dbPath = url.replace("file:", "");
2144
+ const dbDir = path2.dirname(dbPath);
2145
+ if (!fs2.existsSync(dbDir)) {
2146
+ fs2.mkdirSync(dbDir, { recursive: true });
2147
+ }
2148
+ }
2149
+ const client = createClient3({
2150
+ url,
2151
+ authToken: options.authToken
2152
+ });
2153
+ super(client, options, logger);
2154
+ }
2155
+ /**
2156
+ * Override to use Buffer for more efficient serialization in Node.js
2157
+ */
2158
+ serializeVector(vector) {
2159
+ const buffer = Buffer.allocUnsafe(vector.length * 4);
2160
+ for (let i = 0; i < vector.length; i++) {
2161
+ buffer.writeFloatLE(vector[i], i * 4);
2162
+ }
2163
+ return buffer;
2164
+ }
2165
+ /**
2166
+ * Override to use Buffer for more efficient deserialization in Node.js
2167
+ */
2168
+ deserializeVector(data) {
2169
+ let buffer;
2170
+ if (data instanceof Buffer) {
2171
+ buffer = data;
2172
+ } else if (data instanceof ArrayBuffer) {
2173
+ buffer = Buffer.from(data);
2174
+ } else {
2175
+ buffer = Buffer.from(data);
2176
+ }
2177
+ const vector = [];
2178
+ for (let i = 0; i < buffer.length; i += 4) {
2179
+ vector.push(buffer.readFloatLE(i));
2180
+ }
2181
+ return vector;
2182
+ }
2183
+ };
2262
2184
  export {
2263
2185
  LibSQLMemoryAdapter,
2264
2186
  LibSQLObservabilityAdapter,