@mastra/libsql 1.2.0 → 1.3.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/dist/docs/SKILL.md +36 -26
  3. package/dist/docs/{SOURCE_MAP.json → assets/SOURCE_MAP.json} +1 -1
  4. package/dist/docs/{agents/03-agent-approval.md → references/docs-agents-agent-approval.md} +19 -19
  5. package/dist/docs/references/docs-agents-agent-memory.md +212 -0
  6. package/dist/docs/{agents/04-network-approval.md → references/docs-agents-network-approval.md} +13 -12
  7. package/dist/docs/{agents/02-networks.md → references/docs-agents-networks.md} +10 -12
  8. package/dist/docs/{memory/06-memory-processors.md → references/docs-memory-memory-processors.md} +6 -8
  9. package/dist/docs/{memory/03-message-history.md → references/docs-memory-message-history.md} +31 -20
  10. package/dist/docs/{memory/01-overview.md → references/docs-memory-overview.md} +8 -8
  11. package/dist/docs/{memory/05-semantic-recall.md → references/docs-memory-semantic-recall.md} +33 -17
  12. package/dist/docs/{memory/02-storage.md → references/docs-memory-storage.md} +29 -39
  13. package/dist/docs/{memory/04-working-memory.md → references/docs-memory-working-memory.md} +16 -27
  14. package/dist/docs/{observability/01-overview.md → references/docs-observability-overview.md} +4 -7
  15. package/dist/docs/{observability/02-default.md → references/docs-observability-tracing-exporters-default.md} +11 -14
  16. package/dist/docs/{rag/01-retrieval.md → references/docs-rag-retrieval.md} +26 -53
  17. package/dist/docs/{workflows/01-snapshots.md → references/docs-workflows-snapshots.md} +3 -5
  18. package/dist/docs/{guides/01-ai-sdk.md → references/guides-agent-frameworks-ai-sdk.md} +25 -9
  19. package/dist/docs/references/reference-core-getMemory.md +50 -0
  20. package/dist/docs/references/reference-core-listMemory.md +56 -0
  21. package/dist/docs/references/reference-core-mastra-class.md +66 -0
  22. package/dist/docs/{memory/07-reference.md → references/reference-memory-memory-class.md} +28 -14
  23. package/dist/docs/references/reference-storage-composite.md +235 -0
  24. package/dist/docs/references/reference-storage-dynamodb.md +282 -0
  25. package/dist/docs/references/reference-storage-libsql.md +135 -0
  26. package/dist/docs/{vectors/01-reference.md → references/reference-vectors-libsql.md} +105 -13
  27. package/dist/index.cjs +1690 -208
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.js +1690 -210
  30. package/dist/index.js.map +1 -1
  31. package/dist/storage/db/index.d.ts.map +1 -1
  32. package/dist/storage/domains/agents/index.d.ts +9 -12
  33. package/dist/storage/domains/agents/index.d.ts.map +1 -1
  34. package/dist/storage/domains/memory/index.d.ts +8 -2
  35. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  36. package/dist/storage/domains/prompt-blocks/index.d.ts +25 -0
  37. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
  38. package/dist/storage/domains/scorer-definitions/index.d.ts +26 -0
  39. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
  40. package/dist/storage/index.d.ts +3 -1
  41. package/dist/storage/index.d.ts.map +1 -1
  42. package/package.json +3 -4
  43. package/dist/docs/README.md +0 -39
  44. package/dist/docs/agents/01-agent-memory.md +0 -166
  45. package/dist/docs/core/01-reference.md +0 -151
  46. package/dist/docs/storage/01-reference.md +0 -556
package/dist/index.cjs CHANGED
@@ -7,6 +7,7 @@ var utils = require('@mastra/core/utils');
7
7
  var vector = require('@mastra/core/vector');
8
8
  var filter = require('@mastra/core/vector/filter');
9
9
  var base = require('@mastra/core/base');
10
+ var crypto$1 = require('crypto');
10
11
  var agent = require('@mastra/core/agent');
11
12
  var evals = require('@mastra/core/evals');
12
13
 
@@ -1993,7 +1994,7 @@ Note: This migration may take some time for large tables.
1993
1994
  if (!existingColumns.has(columnName.toLowerCase()) && schema[columnName]) {
1994
1995
  const columnDef = schema[columnName];
1995
1996
  const sqlType = this.getSqlType(columnDef.type);
1996
- const defaultValue = this.getDefaultValue(columnDef.type);
1997
+ const defaultValue = columnDef.nullable ? "DEFAULT NULL" : this.getDefaultValue(columnDef.type);
1997
1998
  const alterSql = `ALTER TABLE ${parsedTableName} ADD COLUMN "${columnName}" ${sqlType} ${defaultValue}`;
1998
1999
  await this.client.execute(alterSql);
1999
2000
  this.logger.debug(`LibSQLDB: Added column ${columnName} to table ${tableName}`);
@@ -2075,6 +2076,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2075
2076
  schema: storage.AGENTS_SCHEMA,
2076
2077
  ifNotExists: ["status", "authorId"]
2077
2078
  });
2079
+ await this.#migrateToolsToJsonbFormat();
2078
2080
  await this.#cleanupStaleDrafts();
2079
2081
  }
2080
2082
  /**
@@ -2126,7 +2128,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2126
2128
  versionNumber: 1,
2127
2129
  name: row.name ?? agentId,
2128
2130
  description: row.description ?? null,
2129
- instructions: row.instructions ?? "",
2131
+ instructions: this.serializeInstructions(row.instructions ?? ""),
2130
2132
  model: row.model ?? "{}",
2131
2133
  tools: row.tools ?? null,
2132
2134
  defaultOptions: row.defaultOptions ?? null,
@@ -2175,6 +2177,52 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2175
2177
  } catch {
2176
2178
  }
2177
2179
  }
2180
+ /**
2181
+ * Migrates the tools field from string[] format to JSONB format { "tool-key": { "description": "..." } }.
2182
+ * This handles the transition from the old format where tools were stored as an array of string keys
2183
+ * to the new format where tools can have per-agent description overrides.
2184
+ */
2185
+ async #migrateToolsToJsonbFormat() {
2186
+ try {
2187
+ const result = await this.#client.execute({
2188
+ sql: `SELECT id, tools FROM "${storage.TABLE_AGENT_VERSIONS}" WHERE tools IS NOT NULL`
2189
+ });
2190
+ if (!result.rows || result.rows.length === 0) {
2191
+ return;
2192
+ }
2193
+ for (const row of result.rows) {
2194
+ const toolsValue = row.tools;
2195
+ let parsedTools;
2196
+ try {
2197
+ if (typeof toolsValue === "string") {
2198
+ parsedTools = JSON.parse(toolsValue);
2199
+ } else if (toolsValue instanceof ArrayBuffer) {
2200
+ const decoder = new TextDecoder();
2201
+ parsedTools = JSON.parse(decoder.decode(toolsValue));
2202
+ } else {
2203
+ parsedTools = toolsValue;
2204
+ }
2205
+ } catch {
2206
+ continue;
2207
+ }
2208
+ if (Array.isArray(parsedTools)) {
2209
+ const toolsObject = {};
2210
+ for (const toolKey of parsedTools) {
2211
+ if (typeof toolKey === "string") {
2212
+ toolsObject[toolKey] = {};
2213
+ }
2214
+ }
2215
+ await this.#client.execute({
2216
+ sql: `UPDATE "${storage.TABLE_AGENT_VERSIONS}" SET tools = ? WHERE id = ?`,
2217
+ args: [JSON.stringify(toolsObject), row.id]
2218
+ });
2219
+ }
2220
+ }
2221
+ this.logger?.info?.(`Migrated agent version tools from array to object format`);
2222
+ } catch (error) {
2223
+ this.logger?.warn?.("Failed to migrate tools to JSONB format:", error);
2224
+ }
2225
+ }
2178
2226
  async dangerouslyClearAll() {
2179
2227
  await this.#db.deleteData({ tableName: storage.TABLE_AGENT_VERSIONS });
2180
2228
  await this.#db.deleteData({ tableName: storage.TABLE_AGENTS });
@@ -2224,7 +2272,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2224
2272
  updatedAt: new Date(row.updatedAt)
2225
2273
  };
2226
2274
  }
2227
- async getAgentById({ id }) {
2275
+ async getById(id) {
2228
2276
  try {
2229
2277
  const result = await this.#db.select({
2230
2278
  tableName: storage.TABLE_AGENTS,
@@ -2232,6 +2280,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2232
2280
  });
2233
2281
  return result ? this.parseRow(result) : null;
2234
2282
  } catch (error$1) {
2283
+ if (error$1 instanceof error.MastraError) throw error$1;
2235
2284
  throw new error.MastraError(
2236
2285
  {
2237
2286
  id: storage.createStorageErrorId("LIBSQL", "GET_AGENT_BY_ID", "FAILED"),
@@ -2243,7 +2292,8 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2243
2292
  );
2244
2293
  }
2245
2294
  }
2246
- async createAgent({ agent }) {
2295
+ async create(input) {
2296
+ const { agent } = input;
2247
2297
  try {
2248
2298
  const now = /* @__PURE__ */ new Date();
2249
2299
  await this.#db.insert({
@@ -2268,7 +2318,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2268
2318
  changedFields: Object.keys(snapshotConfig),
2269
2319
  changeMessage: "Initial version"
2270
2320
  });
2271
- const created = await this.getAgentById({ id: agent.id });
2321
+ const created = await this.getById(agent.id);
2272
2322
  if (!created) {
2273
2323
  throw new error.MastraError({
2274
2324
  id: storage.createStorageErrorId("LIBSQL", "CREATE_AGENT", "NOT_FOUND_AFTER_CREATE"),
@@ -2294,9 +2344,10 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2294
2344
  );
2295
2345
  }
2296
2346
  }
2297
- async updateAgent({ id, ...updates }) {
2347
+ async update(input) {
2348
+ const { id, ...updates } = input;
2298
2349
  try {
2299
- const existingAgent = await this.getAgentById({ id });
2350
+ const existingAgent = await this.getById(id);
2300
2351
  if (!existingAgent) {
2301
2352
  throw new error.MastraError({
2302
2353
  id: storage.createStorageErrorId("LIBSQL", "UPDATE_AGENT", "NOT_FOUND"),
@@ -2335,14 +2386,17 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2335
2386
  latestSnapshot[field] = latestVersion[field];
2336
2387
  }
2337
2388
  }
2389
+ const sanitizedConfigFields = Object.fromEntries(
2390
+ Object.entries(configFields).map(([key, value]) => [key, value === null ? void 0 : value])
2391
+ );
2338
2392
  const versionInput = {
2339
2393
  id: crypto.randomUUID(),
2340
2394
  agentId: id,
2341
2395
  versionNumber: nextVersionNumber,
2342
2396
  ...latestSnapshot,
2343
2397
  // Start from latest version
2344
- ...configFields,
2345
- // Apply updates
2398
+ ...sanitizedConfigFields,
2399
+ // Apply updates (null values converted to undefined)
2346
2400
  changedFields: Object.keys(configFields),
2347
2401
  changeMessage: `Updated: ${Object.keys(configFields).join(", ")}`
2348
2402
  };
@@ -2365,7 +2419,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2365
2419
  data
2366
2420
  });
2367
2421
  }
2368
- const updatedAgent = await this.getAgentById({ id });
2422
+ const updatedAgent = await this.getById(id);
2369
2423
  if (!updatedAgent) {
2370
2424
  throw new error.MastraError({
2371
2425
  id: storage.createStorageErrorId("LIBSQL", "UPDATE_AGENT", "NOT_FOUND_AFTER_UPDATE"),
@@ -2391,14 +2445,15 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2391
2445
  );
2392
2446
  }
2393
2447
  }
2394
- async deleteAgent({ id }) {
2448
+ async delete(id) {
2395
2449
  try {
2396
- await this.deleteVersionsByAgentId(id);
2450
+ await this.deleteVersionsByParentId(id);
2397
2451
  await this.#db.delete({
2398
2452
  tableName: storage.TABLE_AGENTS,
2399
2453
  keys: { id }
2400
2454
  });
2401
2455
  } catch (error$1) {
2456
+ if (error$1 instanceof error.MastraError) throw error$1;
2402
2457
  throw new error.MastraError(
2403
2458
  {
2404
2459
  id: storage.createStorageErrorId("LIBSQL", "DELETE_AGENT", "FAILED"),
@@ -2410,7 +2465,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2410
2465
  );
2411
2466
  }
2412
2467
  }
2413
- async listAgents(args) {
2468
+ async list(args) {
2414
2469
  const { page = 0, perPage: perPageInput, orderBy } = args || {};
2415
2470
  const { field, direction } = this.parseOrderBy(orderBy);
2416
2471
  if (page < 0) {
@@ -2453,6 +2508,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2453
2508
  hasMore: perPageInput === false ? false : offset + perPage < total
2454
2509
  };
2455
2510
  } catch (error$1) {
2511
+ if (error$1 instanceof error.MastraError) throw error$1;
2456
2512
  throw new error.MastraError(
2457
2513
  {
2458
2514
  id: storage.createStorageErrorId("LIBSQL", "LIST_AGENTS", "FAILED"),
@@ -2463,88 +2519,6 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2463
2519
  );
2464
2520
  }
2465
2521
  }
2466
- async listAgentsResolved(args) {
2467
- const { page = 0, perPage: perPageInput, orderBy } = args || {};
2468
- const { field, direction } = this.parseOrderBy(orderBy);
2469
- if (page < 0) {
2470
- throw new error.MastraError(
2471
- {
2472
- id: storage.createStorageErrorId("LIBSQL", "LIST_AGENTS_RESOLVED", "INVALID_PAGE"),
2473
- domain: error.ErrorDomain.STORAGE,
2474
- category: error.ErrorCategory.USER,
2475
- details: { page }
2476
- },
2477
- new Error("page must be >= 0")
2478
- );
2479
- }
2480
- const perPage = storage.normalizePerPage(perPageInput, 100);
2481
- const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2482
- try {
2483
- const total = await this.#db.selectTotalCount({ tableName: storage.TABLE_AGENTS });
2484
- if (total === 0) {
2485
- return {
2486
- agents: [],
2487
- total: 0,
2488
- page,
2489
- perPage: perPageForResponse,
2490
- hasMore: false
2491
- };
2492
- }
2493
- const limitValue = perPageInput === false ? total : perPage;
2494
- const agents = await this.#db.selectMany({
2495
- tableName: storage.TABLE_AGENTS,
2496
- orderBy: `"${field}" ${direction}`,
2497
- limit: limitValue,
2498
- offset
2499
- });
2500
- const resolvedAgents = await Promise.all(
2501
- agents.map(async (agent) => {
2502
- let version = null;
2503
- if (agent.activeVersionId) {
2504
- version = await this.getVersion(agent.activeVersionId);
2505
- }
2506
- if (!version) {
2507
- version = await this.getLatestVersion(agent.id);
2508
- }
2509
- if (!version) {
2510
- return agent;
2511
- }
2512
- return {
2513
- ...agent,
2514
- name: version.name,
2515
- description: version.description,
2516
- instructions: version.instructions,
2517
- model: version.model,
2518
- tools: version.tools,
2519
- defaultOptions: version.defaultOptions,
2520
- workflows: version.workflows,
2521
- agents: version.agents,
2522
- integrationTools: version.integrationTools,
2523
- inputProcessors: version.inputProcessors,
2524
- outputProcessors: version.outputProcessors,
2525
- memory: version.memory,
2526
- scorers: version.scorers
2527
- };
2528
- })
2529
- );
2530
- return {
2531
- agents: resolvedAgents,
2532
- total,
2533
- page,
2534
- perPage: perPageForResponse,
2535
- hasMore: perPageInput === false ? false : offset + perPage < total
2536
- };
2537
- } catch (error$1) {
2538
- throw new error.MastraError(
2539
- {
2540
- id: storage.createStorageErrorId("LIBSQL", "LIST_AGENTS_RESOLVED", "FAILED"),
2541
- domain: error.ErrorDomain.STORAGE,
2542
- category: error.ErrorCategory.THIRD_PARTY
2543
- },
2544
- error$1
2545
- );
2546
- }
2547
- }
2548
2522
  // ==========================================================================
2549
2523
  // Agent Version Methods
2550
2524
  // ==========================================================================
@@ -2559,7 +2533,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2559
2533
  versionNumber: input.versionNumber,
2560
2534
  name: input.name ?? null,
2561
2535
  description: input.description ?? null,
2562
- instructions: input.instructions,
2536
+ instructions: this.serializeInstructions(input.instructions),
2563
2537
  model: input.model,
2564
2538
  tools: input.tools ?? null,
2565
2539
  defaultOptions: input.defaultOptions ?? null,
@@ -2580,6 +2554,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2580
2554
  createdAt: now
2581
2555
  };
2582
2556
  } catch (error$1) {
2557
+ if (error$1 instanceof error.MastraError) throw error$1;
2583
2558
  throw new error.MastraError(
2584
2559
  {
2585
2560
  id: storage.createStorageErrorId("LIBSQL", "CREATE_VERSION", "FAILED"),
@@ -2602,6 +2577,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2602
2577
  }
2603
2578
  return this.parseVersionRow(result);
2604
2579
  } catch (error$1) {
2580
+ if (error$1 instanceof error.MastraError) throw error$1;
2605
2581
  throw new error.MastraError(
2606
2582
  {
2607
2583
  id: storage.createStorageErrorId("LIBSQL", "GET_VERSION", "FAILED"),
@@ -2628,6 +2604,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2628
2604
  }
2629
2605
  return this.parseVersionRow(rows[0]);
2630
2606
  } catch (error$1) {
2607
+ if (error$1 instanceof error.MastraError) throw error$1;
2631
2608
  throw new error.MastraError(
2632
2609
  {
2633
2610
  id: storage.createStorageErrorId("LIBSQL", "GET_VERSION_BY_NUMBER", "FAILED"),
@@ -2655,6 +2632,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2655
2632
  }
2656
2633
  return this.parseVersionRow(rows[0]);
2657
2634
  } catch (error$1) {
2635
+ if (error$1 instanceof error.MastraError) throw error$1;
2658
2636
  throw new error.MastraError(
2659
2637
  {
2660
2638
  id: storage.createStorageErrorId("LIBSQL", "GET_LATEST_VERSION", "FAILED"),
@@ -2719,6 +2697,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2719
2697
  hasMore: perPageInput === false ? false : offset + perPage < total
2720
2698
  };
2721
2699
  } catch (error$1) {
2700
+ if (error$1 instanceof error.MastraError) throw error$1;
2722
2701
  throw new error.MastraError(
2723
2702
  {
2724
2703
  id: storage.createStorageErrorId("LIBSQL", "LIST_VERSIONS", "FAILED"),
@@ -2737,6 +2716,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2737
2716
  keys: { id }
2738
2717
  });
2739
2718
  } catch (error$1) {
2719
+ if (error$1 instanceof error.MastraError) throw error$1;
2740
2720
  throw new error.MastraError(
2741
2721
  {
2742
2722
  id: storage.createStorageErrorId("LIBSQL", "DELETE_VERSION", "FAILED"),
@@ -2748,13 +2728,13 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2748
2728
  );
2749
2729
  }
2750
2730
  }
2751
- async deleteVersionsByAgentId(agentId) {
2731
+ async deleteVersionsByParentId(entityId) {
2752
2732
  try {
2753
2733
  const versions = await this.#db.selectMany({
2754
2734
  tableName: storage.TABLE_AGENT_VERSIONS,
2755
2735
  whereClause: {
2756
2736
  sql: "WHERE agentId = ?",
2757
- args: [agentId]
2737
+ args: [entityId]
2758
2738
  }
2759
2739
  });
2760
2740
  for (const version of versions) {
@@ -2764,12 +2744,13 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2764
2744
  });
2765
2745
  }
2766
2746
  } catch (error$1) {
2747
+ if (error$1 instanceof error.MastraError) throw error$1;
2767
2748
  throw new error.MastraError(
2768
2749
  {
2769
2750
  id: storage.createStorageErrorId("LIBSQL", "DELETE_VERSIONS_BY_AGENT_ID", "FAILED"),
2770
2751
  domain: error.ErrorDomain.STORAGE,
2771
2752
  category: error.ErrorCategory.THIRD_PARTY,
2772
- details: { agentId }
2753
+ details: { agentId: entityId }
2773
2754
  },
2774
2755
  error$1
2775
2756
  );
@@ -2786,6 +2767,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2786
2767
  });
2787
2768
  return count;
2788
2769
  } catch (error$1) {
2770
+ if (error$1 instanceof error.MastraError) throw error$1;
2789
2771
  throw new error.MastraError(
2790
2772
  {
2791
2773
  id: storage.createStorageErrorId("LIBSQL", "COUNT_VERSIONS", "FAILED"),
@@ -2800,6 +2782,18 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2800
2782
  // ==========================================================================
2801
2783
  // Private Helper Methods
2802
2784
  // ==========================================================================
2785
+ serializeInstructions(instructions) {
2786
+ return Array.isArray(instructions) ? JSON.stringify(instructions) : instructions;
2787
+ }
2788
+ deserializeInstructions(raw) {
2789
+ if (!raw) return raw;
2790
+ try {
2791
+ const parsed = JSON.parse(raw);
2792
+ if (Array.isArray(parsed)) return parsed;
2793
+ } catch {
2794
+ }
2795
+ return raw;
2796
+ }
2803
2797
  parseVersionRow(row) {
2804
2798
  return {
2805
2799
  id: row.id,
@@ -2807,7 +2801,7 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2807
2801
  versionNumber: row.versionNumber,
2808
2802
  name: row.name,
2809
2803
  description: row.description,
2810
- instructions: row.instructions,
2804
+ instructions: this.deserializeInstructions(row.instructions),
2811
2805
  model: this.parseJson(row.model, "model"),
2812
2806
  tools: this.parseJson(row.tools, "tools"),
2813
2807
  defaultOptions: this.parseJson(row.defaultOptions, "defaultOptions"),
@@ -2853,7 +2847,22 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
2853
2847
  await this.#db.alterTable({
2854
2848
  tableName: OM_TABLE,
2855
2849
  schema: omSchema,
2856
- ifNotExists: ["observedMessageIds", "observedTimezone"]
2850
+ ifNotExists: [
2851
+ "observedMessageIds",
2852
+ "observedTimezone",
2853
+ "bufferedObservations",
2854
+ "bufferedObservationTokens",
2855
+ "bufferedMessageIds",
2856
+ "bufferedReflection",
2857
+ "bufferedReflectionTokens",
2858
+ "bufferedReflectionInputTokens",
2859
+ "reflectedObservationLineCount",
2860
+ "bufferedObservationChunks",
2861
+ "isBufferingObservation",
2862
+ "isBufferingReflection",
2863
+ "lastBufferedAtTokens",
2864
+ "lastBufferedAtTime"
2865
+ ]
2857
2866
  });
2858
2867
  }
2859
2868
  await this.#db.alterTable({
@@ -3897,12 +3906,26 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
3897
3906
  originType: row.originType || "initial",
3898
3907
  generationCount: Number(row.generationCount || 0),
3899
3908
  activeObservations: row.activeObservations || "",
3909
+ // Handle new chunk-based structure
3910
+ bufferedObservationChunks: row.bufferedObservationChunks ? typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks : void 0,
3911
+ // Deprecated fields (for backward compatibility)
3900
3912
  bufferedObservations: row.activeObservationsPendingUpdate || void 0,
3913
+ bufferedObservationTokens: row.bufferedObservationTokens ? Number(row.bufferedObservationTokens) : void 0,
3914
+ bufferedMessageIds: void 0,
3915
+ // Use bufferedObservationChunks instead
3916
+ bufferedReflection: row.bufferedReflection || void 0,
3917
+ bufferedReflectionTokens: row.bufferedReflectionTokens ? Number(row.bufferedReflectionTokens) : void 0,
3918
+ bufferedReflectionInputTokens: row.bufferedReflectionInputTokens ? Number(row.bufferedReflectionInputTokens) : void 0,
3919
+ reflectedObservationLineCount: row.reflectedObservationLineCount ? Number(row.reflectedObservationLineCount) : void 0,
3901
3920
  totalTokensObserved: Number(row.totalTokensObserved || 0),
3902
3921
  observationTokenCount: Number(row.observationTokenCount || 0),
3903
3922
  pendingMessageTokens: Number(row.pendingMessageTokens || 0),
3904
3923
  isReflecting: Boolean(row.isReflecting),
3905
3924
  isObserving: Boolean(row.isObserving),
3925
+ isBufferingObservation: row.isBufferingObservation === true || row.isBufferingObservation === "true" || row.isBufferingObservation === 1,
3926
+ isBufferingReflection: row.isBufferingReflection === true || row.isBufferingReflection === "true" || row.isBufferingReflection === 1,
3927
+ lastBufferedAtTokens: typeof row.lastBufferedAtTokens === "number" ? row.lastBufferedAtTokens : parseInt(String(row.lastBufferedAtTokens ?? "0"), 10) || 0,
3928
+ lastBufferedAtTime: row.lastBufferedAtTime ? new Date(String(row.lastBufferedAtTime)) : null,
3906
3929
  config: row.config ? JSON.parse(row.config) : {},
3907
3930
  metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
3908
3931
  observedMessageIds: row.observedMessageIds ? JSON.parse(row.observedMessageIds) : void 0,
@@ -3974,6 +3997,10 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
3974
3997
  pendingMessageTokens: 0,
3975
3998
  isReflecting: false,
3976
3999
  isObserving: false,
4000
+ isBufferingObservation: false,
4001
+ isBufferingReflection: false,
4002
+ lastBufferedAtTokens: 0,
4003
+ lastBufferedAtTime: null,
3977
4004
  config: input.config,
3978
4005
  observedTimezone: input.observedTimezone
3979
4006
  };
@@ -3983,8 +4010,9 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
3983
4010
  "activeObservations", "activeObservationsPendingUpdate",
3984
4011
  "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
3985
4012
  "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
3986
- "isObserving", "isReflecting", "observedTimezone", "createdAt", "updatedAt"
3987
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4013
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
4014
+ "observedTimezone", "createdAt", "updatedAt"
4015
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3988
4016
  args: [
3989
4017
  id,
3990
4018
  lookupKey,
@@ -4003,6 +4031,14 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
4003
4031
  0,
4004
4032
  false,
4005
4033
  false,
4034
+ false,
4035
+ // isBufferingObservation
4036
+ false,
4037
+ // isBufferingReflection
4038
+ 0,
4039
+ // lastBufferedAtTokens
4040
+ null,
4041
+ // lastBufferedAtTime
4006
4042
  input.observedTimezone || null,
4007
4043
  now.toISOString(),
4008
4044
  now.toISOString()
@@ -4090,6 +4126,10 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
4090
4126
  pendingMessageTokens: 0,
4091
4127
  isReflecting: false,
4092
4128
  isObserving: false,
4129
+ isBufferingObservation: false,
4130
+ isBufferingReflection: false,
4131
+ lastBufferedAtTokens: 0,
4132
+ lastBufferedAtTime: null,
4093
4133
  config: input.currentRecord.config,
4094
4134
  metadata: input.currentRecord.metadata,
4095
4135
  observedTimezone: input.currentRecord.observedTimezone
@@ -4100,8 +4140,9 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
4100
4140
  "activeObservations", "activeObservationsPendingUpdate",
4101
4141
  "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
4102
4142
  "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
4103
- "isObserving", "isReflecting", "observedTimezone", "createdAt", "updatedAt"
4104
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4143
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
4144
+ "observedTimezone", "createdAt", "updatedAt"
4145
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4105
4146
  args: [
4106
4147
  id,
4107
4148
  lookupKey,
@@ -4119,7 +4160,17 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
4119
4160
  record.totalTokensObserved,
4120
4161
  record.observationTokenCount,
4121
4162
  false,
4163
+ // isObserving
4164
+ false,
4165
+ // isReflecting
4122
4166
  false,
4167
+ // isBufferingObservation
4168
+ false,
4169
+ // isBufferingReflection
4170
+ 0,
4171
+ // lastBufferedAtTokens
4172
+ null,
4173
+ // lastBufferedAtTime
4123
4174
  record.observedTimezone || null,
4124
4175
  now.toISOString(),
4125
4176
  now.toISOString()
@@ -4198,41 +4249,56 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
4198
4249
  );
4199
4250
  }
4200
4251
  }
4201
- async clearObservationalMemory(threadId, resourceId) {
4252
+ async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
4202
4253
  try {
4203
- const lookupKey = this.getOMKey(threadId, resourceId);
4204
- await this.#client.execute({
4205
- sql: `DELETE FROM "${OM_TABLE}" WHERE "lookupKey" = ?`,
4206
- args: [lookupKey]
4207
- });
4254
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
4255
+ let sql;
4256
+ let args;
4257
+ if (lastBufferedAtTokens !== void 0) {
4258
+ sql = `UPDATE "${OM_TABLE}" SET "isBufferingObservation" = ?, "lastBufferedAtTokens" = ?, "updatedAt" = ? WHERE id = ?`;
4259
+ args = [isBuffering, lastBufferedAtTokens, nowStr, id];
4260
+ } else {
4261
+ sql = `UPDATE "${OM_TABLE}" SET "isBufferingObservation" = ?, "updatedAt" = ? WHERE id = ?`;
4262
+ args = [isBuffering, nowStr, id];
4263
+ }
4264
+ const result = await this.#client.execute({ sql, args });
4265
+ if (result.rowsAffected === 0) {
4266
+ throw new error.MastraError({
4267
+ id: storage.createStorageErrorId("LIBSQL", "SET_BUFFERING_OBSERVATION_FLAG", "NOT_FOUND"),
4268
+ text: `Observational memory record not found: ${id}`,
4269
+ domain: error.ErrorDomain.STORAGE,
4270
+ category: error.ErrorCategory.THIRD_PARTY,
4271
+ details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
4272
+ });
4273
+ }
4208
4274
  } catch (error$1) {
4275
+ if (error$1 instanceof error.MastraError) {
4276
+ throw error$1;
4277
+ }
4209
4278
  throw new error.MastraError(
4210
4279
  {
4211
- id: storage.createStorageErrorId("LIBSQL", "CLEAR_OBSERVATIONAL_MEMORY", "FAILED"),
4280
+ id: storage.createStorageErrorId("LIBSQL", "SET_BUFFERING_OBSERVATION_FLAG", "FAILED"),
4212
4281
  domain: error.ErrorDomain.STORAGE,
4213
4282
  category: error.ErrorCategory.THIRD_PARTY,
4214
- details: { threadId, resourceId }
4283
+ details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
4215
4284
  },
4216
4285
  error$1
4217
4286
  );
4218
4287
  }
4219
4288
  }
4220
- async addPendingMessageTokens(id, tokenCount) {
4289
+ async setBufferingReflectionFlag(id, isBuffering) {
4221
4290
  try {
4222
4291
  const result = await this.#client.execute({
4223
- sql: `UPDATE "${OM_TABLE}" SET
4224
- "pendingMessageTokens" = "pendingMessageTokens" + ?,
4225
- "updatedAt" = ?
4226
- WHERE id = ?`,
4227
- args: [tokenCount, (/* @__PURE__ */ new Date()).toISOString(), id]
4292
+ sql: `UPDATE "${OM_TABLE}" SET "isBufferingReflection" = ?, "updatedAt" = ? WHERE id = ?`,
4293
+ args: [isBuffering, (/* @__PURE__ */ new Date()).toISOString(), id]
4228
4294
  });
4229
4295
  if (result.rowsAffected === 0) {
4230
4296
  throw new error.MastraError({
4231
- id: storage.createStorageErrorId("LIBSQL", "ADD_PENDING_MESSAGE_TOKENS", "NOT_FOUND"),
4297
+ id: storage.createStorageErrorId("LIBSQL", "SET_BUFFERING_REFLECTION_FLAG", "NOT_FOUND"),
4232
4298
  text: `Observational memory record not found: ${id}`,
4233
4299
  domain: error.ErrorDomain.STORAGE,
4234
4300
  category: error.ErrorCategory.THIRD_PARTY,
4235
- details: { id, tokenCount }
4301
+ details: { id, isBuffering }
4236
4302
  });
4237
4303
  }
4238
4304
  } catch (error$1) {
@@ -4241,129 +4307,505 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
4241
4307
  }
4242
4308
  throw new error.MastraError(
4243
4309
  {
4244
- id: storage.createStorageErrorId("LIBSQL", "ADD_PENDING_MESSAGE_TOKENS", "FAILED"),
4310
+ id: storage.createStorageErrorId("LIBSQL", "SET_BUFFERING_REFLECTION_FLAG", "FAILED"),
4245
4311
  domain: error.ErrorDomain.STORAGE,
4246
4312
  category: error.ErrorCategory.THIRD_PARTY,
4247
- details: { id, tokenCount }
4313
+ details: { id, isBuffering }
4248
4314
  },
4249
4315
  error$1
4250
4316
  );
4251
4317
  }
4252
4318
  }
4253
- };
4254
- var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
4255
- #db;
4256
- constructor(config) {
4257
- super();
4258
- const client = resolveClient(config);
4259
- this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
4260
- }
4261
- async init() {
4262
- await this.#db.createTable({ tableName: storage.TABLE_SPANS, schema: storage.SPAN_SCHEMA });
4263
- }
4264
- async dangerouslyClearAll() {
4265
- await this.#db.deleteData({ tableName: storage.TABLE_SPANS });
4266
- }
4267
- /**
4268
- * Manually run the spans migration to deduplicate and add the unique constraint.
4269
- * This is intended to be called from the CLI when duplicates are detected.
4270
- *
4271
- * @returns Migration result with status and details
4272
- */
4273
- async migrateSpans() {
4274
- return this.#db.migrateSpans();
4275
- }
4276
- /**
4277
- * Check migration status for the spans table.
4278
- * Returns information about whether migration is needed.
4279
- */
4280
- async checkSpansMigrationStatus() {
4281
- return this.#db.checkSpansMigrationStatus();
4282
- }
4283
- get tracingStrategy() {
4284
- return {
4285
- preferred: "batch-with-updates",
4286
- supported: ["batch-with-updates", "insert-only"]
4287
- };
4288
- }
4289
- async createSpan(args) {
4290
- const { span } = args;
4319
+ async clearObservationalMemory(threadId, resourceId) {
4291
4320
  try {
4292
- const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
4293
- const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
4294
- const now = (/* @__PURE__ */ new Date()).toISOString();
4295
- const record = {
4296
- ...span,
4297
- startedAt,
4298
- endedAt,
4299
- createdAt: now,
4300
- updatedAt: now
4301
- };
4302
- return this.#db.insert({ tableName: storage.TABLE_SPANS, record });
4321
+ const lookupKey = this.getOMKey(threadId, resourceId);
4322
+ await this.#client.execute({
4323
+ sql: `DELETE FROM "${OM_TABLE}" WHERE "lookupKey" = ?`,
4324
+ args: [lookupKey]
4325
+ });
4303
4326
  } catch (error$1) {
4304
4327
  throw new error.MastraError(
4305
4328
  {
4306
- id: storage.createStorageErrorId("LIBSQL", "CREATE_SPAN", "FAILED"),
4329
+ id: storage.createStorageErrorId("LIBSQL", "CLEAR_OBSERVATIONAL_MEMORY", "FAILED"),
4307
4330
  domain: error.ErrorDomain.STORAGE,
4308
- category: error.ErrorCategory.USER,
4309
- details: {
4310
- spanId: span.spanId,
4311
- traceId: span.traceId,
4312
- spanType: span.spanType,
4313
- name: span.name
4314
- }
4331
+ category: error.ErrorCategory.THIRD_PARTY,
4332
+ details: { threadId, resourceId }
4315
4333
  },
4316
4334
  error$1
4317
4335
  );
4318
4336
  }
4319
4337
  }
4320
- async getSpan(args) {
4321
- const { traceId, spanId } = args;
4338
+ async setPendingMessageTokens(id, tokenCount) {
4322
4339
  try {
4323
- const rows = await this.#db.selectMany({
4324
- tableName: storage.TABLE_SPANS,
4325
- whereClause: { sql: " WHERE traceId = ? AND spanId = ?", args: [traceId, spanId] },
4326
- limit: 1
4340
+ const result = await this.#client.execute({
4341
+ sql: `UPDATE "${OM_TABLE}" SET
4342
+ "pendingMessageTokens" = ?,
4343
+ "updatedAt" = ?
4344
+ WHERE id = ?`,
4345
+ args: [tokenCount, (/* @__PURE__ */ new Date()).toISOString(), id]
4327
4346
  });
4328
- if (!rows || rows.length === 0) {
4329
- return null;
4347
+ if (result.rowsAffected === 0) {
4348
+ throw new error.MastraError({
4349
+ id: storage.createStorageErrorId("LIBSQL", "SET_PENDING_MESSAGE_TOKENS", "NOT_FOUND"),
4350
+ text: `Observational memory record not found: ${id}`,
4351
+ domain: error.ErrorDomain.STORAGE,
4352
+ category: error.ErrorCategory.THIRD_PARTY,
4353
+ details: { id, tokenCount }
4354
+ });
4330
4355
  }
4331
- return {
4332
- span: transformFromSqlRow({ tableName: storage.TABLE_SPANS, sqlRow: rows[0] })
4333
- };
4334
4356
  } catch (error$1) {
4357
+ if (error$1 instanceof error.MastraError) {
4358
+ throw error$1;
4359
+ }
4335
4360
  throw new error.MastraError(
4336
4361
  {
4337
- id: storage.createStorageErrorId("LIBSQL", "GET_SPAN", "FAILED"),
4362
+ id: storage.createStorageErrorId("LIBSQL", "SET_PENDING_MESSAGE_TOKENS", "FAILED"),
4338
4363
  domain: error.ErrorDomain.STORAGE,
4339
- category: error.ErrorCategory.USER,
4340
- details: { traceId, spanId }
4364
+ category: error.ErrorCategory.THIRD_PARTY,
4365
+ details: { id, tokenCount }
4341
4366
  },
4342
4367
  error$1
4343
4368
  );
4344
4369
  }
4345
4370
  }
4346
- async getRootSpan(args) {
4347
- const { traceId } = args;
4371
+ // ============================================
4372
+ // Async Buffering Methods
4373
+ // ============================================
4374
+ async updateBufferedObservations(input) {
4348
4375
  try {
4349
- const rows = await this.#db.selectMany({
4350
- tableName: storage.TABLE_SPANS,
4351
- whereClause: { sql: " WHERE traceId = ? AND parentSpanId IS NULL", args: [traceId] },
4352
- limit: 1
4376
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
4377
+ const current = await this.#client.execute({
4378
+ sql: `SELECT "bufferedObservationChunks" FROM "${OM_TABLE}" WHERE id = ?`,
4379
+ args: [input.id]
4353
4380
  });
4354
- if (!rows || rows.length === 0) {
4355
- return null;
4381
+ if (!current.rows || current.rows.length === 0) {
4382
+ throw new error.MastraError({
4383
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
4384
+ text: `Observational memory record not found: ${input.id}`,
4385
+ domain: error.ErrorDomain.STORAGE,
4386
+ category: error.ErrorCategory.THIRD_PARTY,
4387
+ details: { id: input.id }
4388
+ });
4356
4389
  }
4357
- return {
4358
- span: transformFromSqlRow({ tableName: storage.TABLE_SPANS, sqlRow: rows[0] })
4390
+ const row = current.rows[0];
4391
+ let existingChunks = [];
4392
+ if (row.bufferedObservationChunks) {
4393
+ try {
4394
+ const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
4395
+ existingChunks = Array.isArray(parsed) ? parsed : [];
4396
+ } catch {
4397
+ existingChunks = [];
4398
+ }
4399
+ }
4400
+ const newChunk = {
4401
+ id: `ombuf-${crypto$1.randomUUID()}`,
4402
+ cycleId: input.chunk.cycleId,
4403
+ observations: input.chunk.observations,
4404
+ tokenCount: input.chunk.tokenCount,
4405
+ messageIds: input.chunk.messageIds,
4406
+ messageTokens: input.chunk.messageTokens,
4407
+ lastObservedAt: input.chunk.lastObservedAt,
4408
+ createdAt: /* @__PURE__ */ new Date(),
4409
+ suggestedContinuation: input.chunk.suggestedContinuation,
4410
+ currentTask: input.chunk.currentTask
4359
4411
  };
4412
+ const newChunks = [...existingChunks, newChunk];
4413
+ const lastBufferedAtTime = input.lastBufferedAtTime ? input.lastBufferedAtTime.toISOString() : null;
4414
+ const result = await this.#client.execute({
4415
+ sql: `UPDATE "${OM_TABLE}" SET
4416
+ "bufferedObservationChunks" = ?,
4417
+ "lastBufferedAtTime" = COALESCE(?, "lastBufferedAtTime"),
4418
+ "updatedAt" = ?
4419
+ WHERE id = ?`,
4420
+ args: [JSON.stringify(newChunks), lastBufferedAtTime, nowStr, input.id]
4421
+ });
4422
+ if (result.rowsAffected === 0) {
4423
+ throw new error.MastraError({
4424
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
4425
+ text: `Observational memory record not found: ${input.id}`,
4426
+ domain: error.ErrorDomain.STORAGE,
4427
+ category: error.ErrorCategory.THIRD_PARTY,
4428
+ details: { id: input.id }
4429
+ });
4430
+ }
4360
4431
  } catch (error$1) {
4432
+ if (error$1 instanceof error.MastraError) {
4433
+ throw error$1;
4434
+ }
4361
4435
  throw new error.MastraError(
4362
4436
  {
4363
- id: storage.createStorageErrorId("LIBSQL", "GET_ROOT_SPAN", "FAILED"),
4437
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "FAILED"),
4364
4438
  domain: error.ErrorDomain.STORAGE,
4365
- category: error.ErrorCategory.USER,
4366
- details: { traceId }
4439
+ category: error.ErrorCategory.THIRD_PARTY,
4440
+ details: { id: input.id }
4441
+ },
4442
+ error$1
4443
+ );
4444
+ }
4445
+ }
4446
+ async swapBufferedToActive(input) {
4447
+ try {
4448
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
4449
+ const current = await this.#client.execute({
4450
+ sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
4451
+ args: [input.id]
4452
+ });
4453
+ if (!current.rows || current.rows.length === 0) {
4454
+ throw new error.MastraError({
4455
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_TO_ACTIVE", "NOT_FOUND"),
4456
+ text: `Observational memory record not found: ${input.id}`,
4457
+ domain: error.ErrorDomain.STORAGE,
4458
+ category: error.ErrorCategory.THIRD_PARTY,
4459
+ details: { id: input.id }
4460
+ });
4461
+ }
4462
+ const row = current.rows[0];
4463
+ let chunks = [];
4464
+ if (row.bufferedObservationChunks) {
4465
+ try {
4466
+ const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
4467
+ chunks = Array.isArray(parsed) ? parsed : [];
4468
+ } catch {
4469
+ chunks = [];
4470
+ }
4471
+ }
4472
+ if (chunks.length === 0) {
4473
+ return {
4474
+ chunksActivated: 0,
4475
+ messageTokensActivated: 0,
4476
+ observationTokensActivated: 0,
4477
+ messagesActivated: 0,
4478
+ activatedCycleIds: [],
4479
+ activatedMessageIds: []
4480
+ };
4481
+ }
4482
+ const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
4483
+ const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
4484
+ let cumulativeMessageTokens = 0;
4485
+ let bestBoundary = 0;
4486
+ let bestBoundaryMessageTokens = 0;
4487
+ for (let i = 0; i < chunks.length; i++) {
4488
+ cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
4489
+ const boundary = i + 1;
4490
+ const isUnder = cumulativeMessageTokens <= targetMessageTokens;
4491
+ const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
4492
+ if (bestBoundary === 0) {
4493
+ bestBoundary = boundary;
4494
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
4495
+ } else if (isUnder && !bestIsUnder) {
4496
+ bestBoundary = boundary;
4497
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
4498
+ } else if (isUnder && bestIsUnder) {
4499
+ if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
4500
+ bestBoundary = boundary;
4501
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
4502
+ }
4503
+ } else if (!isUnder && !bestIsUnder) {
4504
+ if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
4505
+ bestBoundary = boundary;
4506
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
4507
+ }
4508
+ }
4509
+ }
4510
+ const chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
4511
+ const activatedChunks = chunks.slice(0, chunksToActivate);
4512
+ const remainingChunks = chunks.slice(chunksToActivate);
4513
+ const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
4514
+ const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
4515
+ const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
4516
+ const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
4517
+ const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((id) => !!id);
4518
+ const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
4519
+ const latestChunk = activatedChunks[activatedChunks.length - 1];
4520
+ const lastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
4521
+ const lastObservedAtStr = lastObservedAt.toISOString();
4522
+ const existingActive = row.activeObservations || "";
4523
+ const existingTokenCount = Number(row.observationTokenCount || 0);
4524
+ const newActive = existingActive ? `${existingActive}
4525
+
4526
+ ${activatedContent}` : activatedContent;
4527
+ const newTokenCount = existingTokenCount + activatedTokens;
4528
+ const existingPending = Number(row.pendingMessageTokens || 0);
4529
+ const newPending = Math.max(0, existingPending - activatedMessageTokens);
4530
+ await this.#client.execute({
4531
+ sql: `UPDATE "${OM_TABLE}" SET
4532
+ "activeObservations" = ?,
4533
+ "observationTokenCount" = ?,
4534
+ "pendingMessageTokens" = ?,
4535
+ "bufferedObservationChunks" = ?,
4536
+ "lastObservedAt" = ?,
4537
+ "updatedAt" = ?
4538
+ WHERE id = ?`,
4539
+ args: [
4540
+ newActive,
4541
+ newTokenCount,
4542
+ newPending,
4543
+ remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,
4544
+ lastObservedAtStr,
4545
+ nowStr,
4546
+ input.id
4547
+ ]
4548
+ });
4549
+ return {
4550
+ chunksActivated: activatedChunks.length,
4551
+ messageTokensActivated: activatedMessageTokens,
4552
+ observationTokensActivated: activatedTokens,
4553
+ messagesActivated: activatedMessageCount,
4554
+ activatedCycleIds,
4555
+ activatedMessageIds,
4556
+ observations: activatedContent,
4557
+ perChunk: activatedChunks.map((c) => ({
4558
+ cycleId: c.cycleId ?? "",
4559
+ messageTokens: c.messageTokens ?? 0,
4560
+ observationTokens: c.tokenCount,
4561
+ messageCount: c.messageIds.length,
4562
+ observations: c.observations
4563
+ }))
4564
+ };
4565
+ } catch (error$1) {
4566
+ if (error$1 instanceof error.MastraError) {
4567
+ throw error$1;
4568
+ }
4569
+ throw new error.MastraError(
4570
+ {
4571
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_TO_ACTIVE", "FAILED"),
4572
+ domain: error.ErrorDomain.STORAGE,
4573
+ category: error.ErrorCategory.THIRD_PARTY,
4574
+ details: { id: input.id }
4575
+ },
4576
+ error$1
4577
+ );
4578
+ }
4579
+ }
4580
+ async updateBufferedReflection(input) {
4581
+ try {
4582
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
4583
+ const result = await this.#client.execute({
4584
+ sql: `UPDATE "${OM_TABLE}" SET
4585
+ "bufferedReflection" = CASE
4586
+ WHEN "bufferedReflection" IS NOT NULL AND "bufferedReflection" != ''
4587
+ THEN "bufferedReflection" || char(10) || char(10) || ?
4588
+ ELSE ?
4589
+ END,
4590
+ "bufferedReflectionTokens" = COALESCE("bufferedReflectionTokens", 0) + ?,
4591
+ "bufferedReflectionInputTokens" = COALESCE("bufferedReflectionInputTokens", 0) + ?,
4592
+ "reflectedObservationLineCount" = ?,
4593
+ "updatedAt" = ?
4594
+ WHERE id = ?`,
4595
+ args: [
4596
+ input.reflection,
4597
+ input.reflection,
4598
+ input.tokenCount,
4599
+ input.inputTokenCount,
4600
+ input.reflectedObservationLineCount,
4601
+ nowStr,
4602
+ input.id
4603
+ ]
4604
+ });
4605
+ if (result.rowsAffected === 0) {
4606
+ throw new error.MastraError({
4607
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_REFLECTION", "NOT_FOUND"),
4608
+ text: `Observational memory record not found: ${input.id}`,
4609
+ domain: error.ErrorDomain.STORAGE,
4610
+ category: error.ErrorCategory.THIRD_PARTY,
4611
+ details: { id: input.id }
4612
+ });
4613
+ }
4614
+ } catch (error$1) {
4615
+ if (error$1 instanceof error.MastraError) {
4616
+ throw error$1;
4617
+ }
4618
+ throw new error.MastraError(
4619
+ {
4620
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_REFLECTION", "FAILED"),
4621
+ domain: error.ErrorDomain.STORAGE,
4622
+ category: error.ErrorCategory.THIRD_PARTY,
4623
+ details: { id: input.id }
4624
+ },
4625
+ error$1
4626
+ );
4627
+ }
4628
+ }
4629
+ async swapBufferedReflectionToActive(input) {
4630
+ try {
4631
+ const current = await this.#client.execute({
4632
+ sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
4633
+ args: [input.currentRecord.id]
4634
+ });
4635
+ if (!current.rows || current.rows.length === 0) {
4636
+ throw new error.MastraError({
4637
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
4638
+ text: `Observational memory record not found: ${input.currentRecord.id}`,
4639
+ domain: error.ErrorDomain.STORAGE,
4640
+ category: error.ErrorCategory.THIRD_PARTY,
4641
+ details: { id: input.currentRecord.id }
4642
+ });
4643
+ }
4644
+ const row = current.rows[0];
4645
+ const bufferedReflection = row.bufferedReflection || "";
4646
+ const reflectedLineCount = Number(row.reflectedObservationLineCount || 0);
4647
+ if (!bufferedReflection) {
4648
+ throw new error.MastraError({
4649
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
4650
+ text: "No buffered reflection to swap",
4651
+ domain: error.ErrorDomain.STORAGE,
4652
+ category: error.ErrorCategory.USER,
4653
+ details: { id: input.currentRecord.id }
4654
+ });
4655
+ }
4656
+ const currentObservations = row.activeObservations || "";
4657
+ const allLines = currentObservations.split("\n");
4658
+ const unreflectedLines = allLines.slice(reflectedLineCount);
4659
+ const unreflectedContent = unreflectedLines.join("\n").trim();
4660
+ const newObservations = unreflectedContent ? `${bufferedReflection}
4661
+
4662
+ ${unreflectedContent}` : bufferedReflection;
4663
+ const newRecord = await this.createReflectionGeneration({
4664
+ currentRecord: input.currentRecord,
4665
+ reflection: newObservations,
4666
+ tokenCount: input.tokenCount
4667
+ });
4668
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
4669
+ await this.#client.execute({
4670
+ sql: `UPDATE "${OM_TABLE}" SET
4671
+ "bufferedReflection" = NULL,
4672
+ "bufferedReflectionTokens" = NULL,
4673
+ "bufferedReflectionInputTokens" = NULL,
4674
+ "reflectedObservationLineCount" = NULL,
4675
+ "updatedAt" = ?
4676
+ WHERE id = ?`,
4677
+ args: [nowStr, input.currentRecord.id]
4678
+ });
4679
+ return newRecord;
4680
+ } catch (error$1) {
4681
+ if (error$1 instanceof error.MastraError) {
4682
+ throw error$1;
4683
+ }
4684
+ throw new error.MastraError(
4685
+ {
4686
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "FAILED"),
4687
+ domain: error.ErrorDomain.STORAGE,
4688
+ category: error.ErrorCategory.THIRD_PARTY,
4689
+ details: { id: input.currentRecord.id }
4690
+ },
4691
+ error$1
4692
+ );
4693
+ }
4694
+ }
4695
+ };
4696
+ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
4697
+ #db;
4698
+ constructor(config) {
4699
+ super();
4700
+ const client = resolveClient(config);
4701
+ this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
4702
+ }
4703
+ async init() {
4704
+ await this.#db.createTable({ tableName: storage.TABLE_SPANS, schema: storage.SPAN_SCHEMA });
4705
+ }
4706
+ async dangerouslyClearAll() {
4707
+ await this.#db.deleteData({ tableName: storage.TABLE_SPANS });
4708
+ }
4709
+ /**
4710
+ * Manually run the spans migration to deduplicate and add the unique constraint.
4711
+ * This is intended to be called from the CLI when duplicates are detected.
4712
+ *
4713
+ * @returns Migration result with status and details
4714
+ */
4715
+ async migrateSpans() {
4716
+ return this.#db.migrateSpans();
4717
+ }
4718
+ /**
4719
+ * Check migration status for the spans table.
4720
+ * Returns information about whether migration is needed.
4721
+ */
4722
+ async checkSpansMigrationStatus() {
4723
+ return this.#db.checkSpansMigrationStatus();
4724
+ }
4725
+ get tracingStrategy() {
4726
+ return {
4727
+ preferred: "batch-with-updates",
4728
+ supported: ["batch-with-updates", "insert-only"]
4729
+ };
4730
+ }
4731
+ async createSpan(args) {
4732
+ const { span } = args;
4733
+ try {
4734
+ const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
4735
+ const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
4736
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4737
+ const record = {
4738
+ ...span,
4739
+ startedAt,
4740
+ endedAt,
4741
+ createdAt: now,
4742
+ updatedAt: now
4743
+ };
4744
+ return this.#db.insert({ tableName: storage.TABLE_SPANS, record });
4745
+ } catch (error$1) {
4746
+ throw new error.MastraError(
4747
+ {
4748
+ id: storage.createStorageErrorId("LIBSQL", "CREATE_SPAN", "FAILED"),
4749
+ domain: error.ErrorDomain.STORAGE,
4750
+ category: error.ErrorCategory.USER,
4751
+ details: {
4752
+ spanId: span.spanId,
4753
+ traceId: span.traceId,
4754
+ spanType: span.spanType,
4755
+ name: span.name
4756
+ }
4757
+ },
4758
+ error$1
4759
+ );
4760
+ }
4761
+ }
4762
+ async getSpan(args) {
4763
+ const { traceId, spanId } = args;
4764
+ try {
4765
+ const rows = await this.#db.selectMany({
4766
+ tableName: storage.TABLE_SPANS,
4767
+ whereClause: { sql: " WHERE traceId = ? AND spanId = ?", args: [traceId, spanId] },
4768
+ limit: 1
4769
+ });
4770
+ if (!rows || rows.length === 0) {
4771
+ return null;
4772
+ }
4773
+ return {
4774
+ span: transformFromSqlRow({ tableName: storage.TABLE_SPANS, sqlRow: rows[0] })
4775
+ };
4776
+ } catch (error$1) {
4777
+ throw new error.MastraError(
4778
+ {
4779
+ id: storage.createStorageErrorId("LIBSQL", "GET_SPAN", "FAILED"),
4780
+ domain: error.ErrorDomain.STORAGE,
4781
+ category: error.ErrorCategory.USER,
4782
+ details: { traceId, spanId }
4783
+ },
4784
+ error$1
4785
+ );
4786
+ }
4787
+ }
4788
+ async getRootSpan(args) {
4789
+ const { traceId } = args;
4790
+ try {
4791
+ const rows = await this.#db.selectMany({
4792
+ tableName: storage.TABLE_SPANS,
4793
+ whereClause: { sql: " WHERE traceId = ? AND parentSpanId IS NULL", args: [traceId] },
4794
+ limit: 1
4795
+ });
4796
+ if (!rows || rows.length === 0) {
4797
+ return null;
4798
+ }
4799
+ return {
4800
+ span: transformFromSqlRow({ tableName: storage.TABLE_SPANS, sqlRow: rows[0] })
4801
+ };
4802
+ } catch (error$1) {
4803
+ throw new error.MastraError(
4804
+ {
4805
+ id: storage.createStorageErrorId("LIBSQL", "GET_ROOT_SPAN", "FAILED"),
4806
+ domain: error.ErrorDomain.STORAGE,
4807
+ category: error.ErrorCategory.USER,
4808
+ details: { traceId }
4367
4809
  },
4368
4810
  error$1
4369
4811
  );
@@ -4702,6 +5144,1040 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
4702
5144
  }
4703
5145
  }
4704
5146
  };
5147
+ var SNAPSHOT_FIELDS2 = ["name", "description", "content", "rules"];
5148
+ var PromptBlocksLibSQL = class extends storage.PromptBlocksStorage {
5149
+ #db;
5150
+ #client;
5151
+ constructor(config) {
5152
+ super();
5153
+ const client = resolveClient(config);
5154
+ this.#client = client;
5155
+ this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
5156
+ }
5157
+ async init() {
5158
+ await this.#db.createTable({ tableName: storage.TABLE_PROMPT_BLOCKS, schema: storage.PROMPT_BLOCKS_SCHEMA });
5159
+ await this.#db.createTable({ tableName: storage.TABLE_PROMPT_BLOCK_VERSIONS, schema: storage.PROMPT_BLOCK_VERSIONS_SCHEMA });
5160
+ await this.#client.execute(
5161
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_prompt_block_versions_block_version ON "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" ("blockId", "versionNumber")`
5162
+ );
5163
+ }
5164
+ async dangerouslyClearAll() {
5165
+ await this.#db.deleteData({ tableName: storage.TABLE_PROMPT_BLOCKS });
5166
+ await this.#db.deleteData({ tableName: storage.TABLE_PROMPT_BLOCK_VERSIONS });
5167
+ }
5168
+ // ==========================================================================
5169
+ // Prompt Block CRUD
5170
+ // ==========================================================================
5171
+ async getById(id) {
5172
+ try {
5173
+ const result = await this.#client.execute({
5174
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_PROMPT_BLOCKS)} FROM "${storage.TABLE_PROMPT_BLOCKS}" WHERE id = ?`,
5175
+ args: [id]
5176
+ });
5177
+ const row = result.rows?.[0];
5178
+ return row ? this.#parseBlockRow(row) : null;
5179
+ } catch (error$1) {
5180
+ if (error$1 instanceof error.MastraError) throw error$1;
5181
+ throw new error.MastraError(
5182
+ {
5183
+ id: storage.createStorageErrorId("LIBSQL", "GET_PROMPT_BLOCK", "FAILED"),
5184
+ domain: error.ErrorDomain.STORAGE,
5185
+ category: error.ErrorCategory.THIRD_PARTY
5186
+ },
5187
+ error$1
5188
+ );
5189
+ }
5190
+ }
5191
+ async create(input) {
5192
+ const { promptBlock } = input;
5193
+ try {
5194
+ const now = /* @__PURE__ */ new Date();
5195
+ await this.#db.insert({
5196
+ tableName: storage.TABLE_PROMPT_BLOCKS,
5197
+ record: {
5198
+ id: promptBlock.id,
5199
+ status: "draft",
5200
+ activeVersionId: null,
5201
+ authorId: promptBlock.authorId ?? null,
5202
+ metadata: promptBlock.metadata ?? null,
5203
+ createdAt: now.toISOString(),
5204
+ updatedAt: now.toISOString()
5205
+ }
5206
+ });
5207
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = promptBlock;
5208
+ const versionId = crypto.randomUUID();
5209
+ await this.createVersion({
5210
+ id: versionId,
5211
+ blockId: promptBlock.id,
5212
+ versionNumber: 1,
5213
+ ...snapshotConfig,
5214
+ changedFields: Object.keys(snapshotConfig),
5215
+ changeMessage: "Initial version"
5216
+ });
5217
+ return {
5218
+ id: promptBlock.id,
5219
+ status: "draft",
5220
+ activeVersionId: void 0,
5221
+ authorId: promptBlock.authorId,
5222
+ metadata: promptBlock.metadata,
5223
+ createdAt: now,
5224
+ updatedAt: now
5225
+ };
5226
+ } catch (error$1) {
5227
+ if (error$1 instanceof error.MastraError) throw error$1;
5228
+ throw new error.MastraError(
5229
+ {
5230
+ id: storage.createStorageErrorId("LIBSQL", "CREATE_PROMPT_BLOCK", "FAILED"),
5231
+ domain: error.ErrorDomain.STORAGE,
5232
+ category: error.ErrorCategory.THIRD_PARTY
5233
+ },
5234
+ error$1
5235
+ );
5236
+ }
5237
+ }
5238
+ async update(input) {
5239
+ const { id, ...updates } = input;
5240
+ try {
5241
+ const existing = await this.getById(id);
5242
+ if (!existing) {
5243
+ throw new Error(`Prompt block with id ${id} not found`);
5244
+ }
5245
+ const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
5246
+ const configFieldNames = SNAPSHOT_FIELDS2;
5247
+ const hasConfigUpdate = configFieldNames.some((field) => field in configFields);
5248
+ const updateData = {
5249
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5250
+ };
5251
+ if (authorId !== void 0) updateData.authorId = authorId;
5252
+ if (activeVersionId !== void 0) {
5253
+ updateData.activeVersionId = activeVersionId;
5254
+ if (status === void 0) {
5255
+ updateData.status = "published";
5256
+ }
5257
+ }
5258
+ if (status !== void 0) updateData.status = status;
5259
+ if (metadata !== void 0) {
5260
+ updateData.metadata = { ...existing.metadata, ...metadata };
5261
+ }
5262
+ await this.#db.update({
5263
+ tableName: storage.TABLE_PROMPT_BLOCKS,
5264
+ keys: { id },
5265
+ data: updateData
5266
+ });
5267
+ if (hasConfigUpdate) {
5268
+ const latestVersion = await this.getLatestVersion(id);
5269
+ if (!latestVersion) {
5270
+ throw new Error(`No versions found for prompt block ${id}`);
5271
+ }
5272
+ const {
5273
+ id: _versionId,
5274
+ blockId: _blockId,
5275
+ versionNumber: _versionNumber,
5276
+ changedFields: _changedFields,
5277
+ changeMessage: _changeMessage,
5278
+ createdAt: _createdAt,
5279
+ ...latestConfig
5280
+ } = latestVersion;
5281
+ const newConfig = { ...latestConfig, ...configFields };
5282
+ const changedFields = configFieldNames.filter(
5283
+ (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
5284
+ );
5285
+ const newVersionId = crypto.randomUUID();
5286
+ await this.createVersion({
5287
+ id: newVersionId,
5288
+ blockId: id,
5289
+ versionNumber: latestVersion.versionNumber + 1,
5290
+ ...newConfig,
5291
+ changedFields,
5292
+ changeMessage: `Updated ${changedFields.join(", ")}`
5293
+ });
5294
+ }
5295
+ const updated = await this.getById(id);
5296
+ if (!updated) {
5297
+ throw new error.MastraError({
5298
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
5299
+ domain: error.ErrorDomain.STORAGE,
5300
+ category: error.ErrorCategory.SYSTEM,
5301
+ text: `Prompt block ${id} not found after update`,
5302
+ details: { id }
5303
+ });
5304
+ }
5305
+ return updated;
5306
+ } catch (error$1) {
5307
+ if (error$1 instanceof error.MastraError) throw error$1;
5308
+ throw new error.MastraError(
5309
+ {
5310
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_PROMPT_BLOCK", "FAILED"),
5311
+ domain: error.ErrorDomain.STORAGE,
5312
+ category: error.ErrorCategory.THIRD_PARTY
5313
+ },
5314
+ error$1
5315
+ );
5316
+ }
5317
+ }
5318
+ async delete(id) {
5319
+ try {
5320
+ await this.deleteVersionsByParentId(id);
5321
+ await this.#client.execute({
5322
+ sql: `DELETE FROM "${storage.TABLE_PROMPT_BLOCKS}" WHERE "id" = ?`,
5323
+ args: [id]
5324
+ });
5325
+ } catch (error$1) {
5326
+ if (error$1 instanceof error.MastraError) throw error$1;
5327
+ throw new error.MastraError(
5328
+ {
5329
+ id: storage.createStorageErrorId("LIBSQL", "DELETE_PROMPT_BLOCK", "FAILED"),
5330
+ domain: error.ErrorDomain.STORAGE,
5331
+ category: error.ErrorCategory.THIRD_PARTY
5332
+ },
5333
+ error$1
5334
+ );
5335
+ }
5336
+ }
5337
+ async list(args) {
5338
+ try {
5339
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
5340
+ const { field, direction } = this.parseOrderBy(orderBy);
5341
+ const conditions = [];
5342
+ const queryParams = [];
5343
+ if (authorId !== void 0) {
5344
+ conditions.push("authorId = ?");
5345
+ queryParams.push(authorId);
5346
+ }
5347
+ if (metadata && Object.keys(metadata).length > 0) {
5348
+ for (const [key, value] of Object.entries(metadata)) {
5349
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
5350
+ throw new error.MastraError({
5351
+ id: storage.createStorageErrorId("LIBSQL", "LIST_PROMPT_BLOCKS", "INVALID_METADATA_KEY"),
5352
+ domain: error.ErrorDomain.STORAGE,
5353
+ category: error.ErrorCategory.USER,
5354
+ text: `Invalid metadata key: ${key}. Keys must be alphanumeric with underscores.`,
5355
+ details: { key }
5356
+ });
5357
+ }
5358
+ conditions.push(`json_extract(metadata, '$.${key}') = ?`);
5359
+ queryParams.push(typeof value === "string" ? value : JSON.stringify(value));
5360
+ }
5361
+ }
5362
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5363
+ const countResult = await this.#client.execute({
5364
+ sql: `SELECT COUNT(*) as count FROM "${storage.TABLE_PROMPT_BLOCKS}" ${whereClause}`,
5365
+ args: queryParams
5366
+ });
5367
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
5368
+ if (total === 0) {
5369
+ return {
5370
+ promptBlocks: [],
5371
+ total: 0,
5372
+ page,
5373
+ perPage: perPageInput ?? 100,
5374
+ hasMore: false
5375
+ };
5376
+ }
5377
+ const perPage = storage.normalizePerPage(perPageInput, 100);
5378
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
5379
+ const limitValue = perPageInput === false ? total : perPage;
5380
+ const end = perPageInput === false ? total : start + perPage;
5381
+ const result = await this.#client.execute({
5382
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_PROMPT_BLOCKS)} FROM "${storage.TABLE_PROMPT_BLOCKS}" ${whereClause} ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
5383
+ args: [...queryParams, limitValue, start]
5384
+ });
5385
+ const promptBlocks = result.rows?.map((row) => this.#parseBlockRow(row)) ?? [];
5386
+ return {
5387
+ promptBlocks,
5388
+ total,
5389
+ page,
5390
+ perPage: perPageForResponse,
5391
+ hasMore: end < total
5392
+ };
5393
+ } catch (error$1) {
5394
+ if (error$1 instanceof error.MastraError) throw error$1;
5395
+ throw new error.MastraError(
5396
+ {
5397
+ id: storage.createStorageErrorId("LIBSQL", "LIST_PROMPT_BLOCKS", "FAILED"),
5398
+ domain: error.ErrorDomain.STORAGE,
5399
+ category: error.ErrorCategory.THIRD_PARTY
5400
+ },
5401
+ error$1
5402
+ );
5403
+ }
5404
+ }
5405
+ // ==========================================================================
5406
+ // Prompt Block Version Methods
5407
+ // ==========================================================================
5408
+ async createVersion(input) {
5409
+ try {
5410
+ const now = /* @__PURE__ */ new Date();
5411
+ await this.#db.insert({
5412
+ tableName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
5413
+ record: {
5414
+ id: input.id,
5415
+ blockId: input.blockId,
5416
+ versionNumber: input.versionNumber,
5417
+ name: input.name,
5418
+ description: input.description ?? null,
5419
+ content: input.content,
5420
+ rules: input.rules ?? null,
5421
+ changedFields: input.changedFields ?? null,
5422
+ changeMessage: input.changeMessage ?? null,
5423
+ createdAt: now.toISOString()
5424
+ }
5425
+ });
5426
+ return {
5427
+ ...input,
5428
+ createdAt: now
5429
+ };
5430
+ } catch (error$1) {
5431
+ if (error$1 instanceof error.MastraError) throw error$1;
5432
+ throw new error.MastraError(
5433
+ {
5434
+ id: storage.createStorageErrorId("LIBSQL", "CREATE_PROMPT_BLOCK_VERSION", "FAILED"),
5435
+ domain: error.ErrorDomain.STORAGE,
5436
+ category: error.ErrorCategory.THIRD_PARTY
5437
+ },
5438
+ error$1
5439
+ );
5440
+ }
5441
+ }
5442
+ async getVersion(id) {
5443
+ try {
5444
+ const result = await this.#client.execute({
5445
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE id = ?`,
5446
+ args: [id]
5447
+ });
5448
+ const row = result.rows?.[0];
5449
+ return row ? this.#parseVersionRow(row) : null;
5450
+ } catch (error$1) {
5451
+ if (error$1 instanceof error.MastraError) throw error$1;
5452
+ throw new error.MastraError(
5453
+ {
5454
+ id: storage.createStorageErrorId("LIBSQL", "GET_PROMPT_BLOCK_VERSION", "FAILED"),
5455
+ domain: error.ErrorDomain.STORAGE,
5456
+ category: error.ErrorCategory.THIRD_PARTY
5457
+ },
5458
+ error$1
5459
+ );
5460
+ }
5461
+ }
5462
+ async getVersionByNumber(blockId, versionNumber) {
5463
+ try {
5464
+ const result = await this.#client.execute({
5465
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ? AND versionNumber = ?`,
5466
+ args: [blockId, versionNumber]
5467
+ });
5468
+ const row = result.rows?.[0];
5469
+ return row ? this.#parseVersionRow(row) : null;
5470
+ } catch (error$1) {
5471
+ if (error$1 instanceof error.MastraError) throw error$1;
5472
+ throw new error.MastraError(
5473
+ {
5474
+ id: storage.createStorageErrorId("LIBSQL", "GET_PROMPT_BLOCK_VERSION_BY_NUMBER", "FAILED"),
5475
+ domain: error.ErrorDomain.STORAGE,
5476
+ category: error.ErrorCategory.THIRD_PARTY
5477
+ },
5478
+ error$1
5479
+ );
5480
+ }
5481
+ }
5482
+ async getLatestVersion(blockId) {
5483
+ try {
5484
+ const result = await this.#client.execute({
5485
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ? ORDER BY versionNumber DESC LIMIT 1`,
5486
+ args: [blockId]
5487
+ });
5488
+ const row = result.rows?.[0];
5489
+ return row ? this.#parseVersionRow(row) : null;
5490
+ } catch (error$1) {
5491
+ if (error$1 instanceof error.MastraError) throw error$1;
5492
+ throw new error.MastraError(
5493
+ {
5494
+ id: storage.createStorageErrorId("LIBSQL", "GET_LATEST_PROMPT_BLOCK_VERSION", "FAILED"),
5495
+ domain: error.ErrorDomain.STORAGE,
5496
+ category: error.ErrorCategory.THIRD_PARTY
5497
+ },
5498
+ error$1
5499
+ );
5500
+ }
5501
+ }
5502
+ async listVersions(input) {
5503
+ try {
5504
+ const { blockId, page = 0, perPage: perPageInput, orderBy } = input;
5505
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
5506
+ const countResult = await this.#client.execute({
5507
+ sql: `SELECT COUNT(*) as count FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ?`,
5508
+ args: [blockId]
5509
+ });
5510
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
5511
+ if (total === 0) {
5512
+ return {
5513
+ versions: [],
5514
+ total: 0,
5515
+ page,
5516
+ perPage: perPageInput ?? 20,
5517
+ hasMore: false
5518
+ };
5519
+ }
5520
+ const perPage = storage.normalizePerPage(perPageInput, 20);
5521
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
5522
+ const limitValue = perPageInput === false ? total : perPage;
5523
+ const end = perPageInput === false ? total : start + perPage;
5524
+ const result = await this.#client.execute({
5525
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_PROMPT_BLOCK_VERSIONS)} FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ? ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
5526
+ args: [blockId, limitValue, start]
5527
+ });
5528
+ const versions = result.rows?.map((row) => this.#parseVersionRow(row)) ?? [];
5529
+ return {
5530
+ versions,
5531
+ total,
5532
+ page,
5533
+ perPage: perPageForResponse,
5534
+ hasMore: end < total
5535
+ };
5536
+ } catch (error$1) {
5537
+ if (error$1 instanceof error.MastraError) throw error$1;
5538
+ throw new error.MastraError(
5539
+ {
5540
+ id: storage.createStorageErrorId("LIBSQL", "LIST_PROMPT_BLOCK_VERSIONS", "FAILED"),
5541
+ domain: error.ErrorDomain.STORAGE,
5542
+ category: error.ErrorCategory.THIRD_PARTY
5543
+ },
5544
+ error$1
5545
+ );
5546
+ }
5547
+ }
5548
+ async deleteVersion(id) {
5549
+ try {
5550
+ await this.#client.execute({
5551
+ sql: `DELETE FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE "id" = ?`,
5552
+ args: [id]
5553
+ });
5554
+ } catch (error$1) {
5555
+ if (error$1 instanceof error.MastraError) throw error$1;
5556
+ throw new error.MastraError(
5557
+ {
5558
+ id: storage.createStorageErrorId("LIBSQL", "DELETE_PROMPT_BLOCK_VERSION", "FAILED"),
5559
+ domain: error.ErrorDomain.STORAGE,
5560
+ category: error.ErrorCategory.THIRD_PARTY
5561
+ },
5562
+ error$1
5563
+ );
5564
+ }
5565
+ }
5566
+ async deleteVersionsByParentId(entityId) {
5567
+ try {
5568
+ await this.#client.execute({
5569
+ sql: `DELETE FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE "blockId" = ?`,
5570
+ args: [entityId]
5571
+ });
5572
+ } catch (error$1) {
5573
+ if (error$1 instanceof error.MastraError) throw error$1;
5574
+ throw new error.MastraError(
5575
+ {
5576
+ id: storage.createStorageErrorId("LIBSQL", "DELETE_PROMPT_BLOCK_VERSIONS_BY_BLOCK", "FAILED"),
5577
+ domain: error.ErrorDomain.STORAGE,
5578
+ category: error.ErrorCategory.THIRD_PARTY
5579
+ },
5580
+ error$1
5581
+ );
5582
+ }
5583
+ }
5584
+ async countVersions(blockId) {
5585
+ try {
5586
+ const result = await this.#client.execute({
5587
+ sql: `SELECT COUNT(*) as count FROM "${storage.TABLE_PROMPT_BLOCK_VERSIONS}" WHERE blockId = ?`,
5588
+ args: [blockId]
5589
+ });
5590
+ return Number(result.rows?.[0]?.count ?? 0);
5591
+ } catch (error$1) {
5592
+ if (error$1 instanceof error.MastraError) throw error$1;
5593
+ throw new error.MastraError(
5594
+ {
5595
+ id: storage.createStorageErrorId("LIBSQL", "COUNT_PROMPT_BLOCK_VERSIONS", "FAILED"),
5596
+ domain: error.ErrorDomain.STORAGE,
5597
+ category: error.ErrorCategory.THIRD_PARTY
5598
+ },
5599
+ error$1
5600
+ );
5601
+ }
5602
+ }
5603
+ // ==========================================================================
5604
+ // Private Helpers
5605
+ // ==========================================================================
5606
+ #parseBlockRow(row) {
5607
+ const safeParseJSON = (val) => {
5608
+ if (val === null || val === void 0) return void 0;
5609
+ if (typeof val === "string") {
5610
+ try {
5611
+ return JSON.parse(val);
5612
+ } catch {
5613
+ return val;
5614
+ }
5615
+ }
5616
+ return val;
5617
+ };
5618
+ return {
5619
+ id: row.id,
5620
+ status: row.status ?? "draft",
5621
+ activeVersionId: row.activeVersionId ?? void 0,
5622
+ authorId: row.authorId ?? void 0,
5623
+ metadata: safeParseJSON(row.metadata),
5624
+ createdAt: new Date(row.createdAt),
5625
+ updatedAt: new Date(row.updatedAt)
5626
+ };
5627
+ }
5628
+ #parseVersionRow(row) {
5629
+ const safeParseJSON = (val) => {
5630
+ if (val === null || val === void 0) return void 0;
5631
+ if (typeof val === "string") {
5632
+ try {
5633
+ return JSON.parse(val);
5634
+ } catch {
5635
+ return val;
5636
+ }
5637
+ }
5638
+ return val;
5639
+ };
5640
+ return {
5641
+ id: row.id,
5642
+ blockId: row.blockId,
5643
+ versionNumber: Number(row.versionNumber),
5644
+ name: row.name,
5645
+ description: row.description ?? void 0,
5646
+ content: row.content,
5647
+ rules: safeParseJSON(row.rules),
5648
+ changedFields: safeParseJSON(row.changedFields),
5649
+ changeMessage: row.changeMessage ?? void 0,
5650
+ createdAt: new Date(row.createdAt)
5651
+ };
5652
+ }
5653
+ };
5654
+ var SNAPSHOT_FIELDS3 = [
5655
+ "name",
5656
+ "description",
5657
+ "type",
5658
+ "model",
5659
+ "instructions",
5660
+ "scoreRange",
5661
+ "presetConfig",
5662
+ "defaultSampling"
5663
+ ];
5664
+ var ScorerDefinitionsLibSQL = class extends storage.ScorerDefinitionsStorage {
5665
+ #db;
5666
+ #client;
5667
+ constructor(config) {
5668
+ super();
5669
+ const client = resolveClient(config);
5670
+ this.#client = client;
5671
+ this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
5672
+ }
5673
+ async init() {
5674
+ await this.#db.createTable({ tableName: storage.TABLE_SCORER_DEFINITIONS, schema: storage.SCORER_DEFINITIONS_SCHEMA });
5675
+ await this.#db.createTable({
5676
+ tableName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
5677
+ schema: storage.SCORER_DEFINITION_VERSIONS_SCHEMA
5678
+ });
5679
+ await this.#client.execute(
5680
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_scorer_definition_versions_scorer_version ON "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" ("scorerDefinitionId", "versionNumber")`
5681
+ );
5682
+ }
5683
+ async dangerouslyClearAll() {
5684
+ await this.#db.deleteData({ tableName: storage.TABLE_SCORER_DEFINITIONS });
5685
+ await this.#db.deleteData({ tableName: storage.TABLE_SCORER_DEFINITION_VERSIONS });
5686
+ }
5687
+ // ==========================================================================
5688
+ // Scorer Definition CRUD
5689
+ // ==========================================================================
5690
+ async getById(id) {
5691
+ try {
5692
+ const result = await this.#client.execute({
5693
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_SCORER_DEFINITIONS)} FROM "${storage.TABLE_SCORER_DEFINITIONS}" WHERE id = ?`,
5694
+ args: [id]
5695
+ });
5696
+ const row = result.rows?.[0];
5697
+ return row ? this.#parseScorerRow(row) : null;
5698
+ } catch (error$1) {
5699
+ if (error$1 instanceof error.MastraError) throw error$1;
5700
+ throw new error.MastraError(
5701
+ {
5702
+ id: storage.createStorageErrorId("LIBSQL", "GET_SCORER_DEFINITION", "FAILED"),
5703
+ domain: error.ErrorDomain.STORAGE,
5704
+ category: error.ErrorCategory.THIRD_PARTY
5705
+ },
5706
+ error$1
5707
+ );
5708
+ }
5709
+ }
5710
+ async create(input) {
5711
+ const { scorerDefinition } = input;
5712
+ try {
5713
+ const now = /* @__PURE__ */ new Date();
5714
+ await this.#db.insert({
5715
+ tableName: storage.TABLE_SCORER_DEFINITIONS,
5716
+ record: {
5717
+ id: scorerDefinition.id,
5718
+ status: "draft",
5719
+ activeVersionId: null,
5720
+ authorId: scorerDefinition.authorId ?? null,
5721
+ metadata: scorerDefinition.metadata ?? null,
5722
+ createdAt: now.toISOString(),
5723
+ updatedAt: now.toISOString()
5724
+ }
5725
+ });
5726
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = scorerDefinition;
5727
+ const versionId = crypto.randomUUID();
5728
+ await this.createVersion({
5729
+ id: versionId,
5730
+ scorerDefinitionId: scorerDefinition.id,
5731
+ versionNumber: 1,
5732
+ ...snapshotConfig,
5733
+ changedFields: Object.keys(snapshotConfig),
5734
+ changeMessage: "Initial version"
5735
+ });
5736
+ return {
5737
+ id: scorerDefinition.id,
5738
+ status: "draft",
5739
+ activeVersionId: void 0,
5740
+ authorId: scorerDefinition.authorId,
5741
+ metadata: scorerDefinition.metadata,
5742
+ createdAt: now,
5743
+ updatedAt: now
5744
+ };
5745
+ } catch (error$1) {
5746
+ if (error$1 instanceof error.MastraError) throw error$1;
5747
+ throw new error.MastraError(
5748
+ {
5749
+ id: storage.createStorageErrorId("LIBSQL", "CREATE_SCORER_DEFINITION", "FAILED"),
5750
+ domain: error.ErrorDomain.STORAGE,
5751
+ category: error.ErrorCategory.THIRD_PARTY
5752
+ },
5753
+ error$1
5754
+ );
5755
+ }
5756
+ }
5757
+ async update(input) {
5758
+ const { id, ...updates } = input;
5759
+ try {
5760
+ const existing = await this.getById(id);
5761
+ if (!existing) {
5762
+ throw new Error(`Scorer definition with id ${id} not found`);
5763
+ }
5764
+ const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
5765
+ const configFieldNames = SNAPSHOT_FIELDS3;
5766
+ const hasConfigUpdate = configFieldNames.some((field) => field in configFields);
5767
+ const updateData = {
5768
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5769
+ };
5770
+ if (authorId !== void 0) updateData.authorId = authorId;
5771
+ if (activeVersionId !== void 0) {
5772
+ updateData.activeVersionId = activeVersionId;
5773
+ if (status === void 0) {
5774
+ updateData.status = "published";
5775
+ }
5776
+ }
5777
+ if (status !== void 0) updateData.status = status;
5778
+ if (metadata !== void 0) {
5779
+ updateData.metadata = { ...existing.metadata, ...metadata };
5780
+ }
5781
+ await this.#db.update({
5782
+ tableName: storage.TABLE_SCORER_DEFINITIONS,
5783
+ keys: { id },
5784
+ data: updateData
5785
+ });
5786
+ if (hasConfigUpdate) {
5787
+ const latestVersion = await this.getLatestVersion(id);
5788
+ if (!latestVersion) {
5789
+ throw new Error(`No versions found for scorer definition ${id}`);
5790
+ }
5791
+ const {
5792
+ id: _versionId,
5793
+ scorerDefinitionId: _scorerDefinitionId,
5794
+ versionNumber: _versionNumber,
5795
+ changedFields: _changedFields,
5796
+ changeMessage: _changeMessage,
5797
+ createdAt: _createdAt,
5798
+ ...latestConfig
5799
+ } = latestVersion;
5800
+ const newConfig = { ...latestConfig, ...configFields };
5801
+ const changedFields = configFieldNames.filter(
5802
+ (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
5803
+ );
5804
+ const newVersionId = crypto.randomUUID();
5805
+ await this.createVersion({
5806
+ id: newVersionId,
5807
+ scorerDefinitionId: id,
5808
+ versionNumber: latestVersion.versionNumber + 1,
5809
+ ...newConfig,
5810
+ changedFields,
5811
+ changeMessage: `Updated ${changedFields.join(", ")}`
5812
+ });
5813
+ }
5814
+ const updated = await this.getById(id);
5815
+ if (!updated) {
5816
+ throw new error.MastraError({
5817
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
5818
+ domain: error.ErrorDomain.STORAGE,
5819
+ category: error.ErrorCategory.SYSTEM,
5820
+ text: `Scorer definition ${id} not found after update`,
5821
+ details: { id }
5822
+ });
5823
+ }
5824
+ return updated;
5825
+ } catch (error$1) {
5826
+ if (error$1 instanceof error.MastraError) throw error$1;
5827
+ throw new error.MastraError(
5828
+ {
5829
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_SCORER_DEFINITION", "FAILED"),
5830
+ domain: error.ErrorDomain.STORAGE,
5831
+ category: error.ErrorCategory.THIRD_PARTY
5832
+ },
5833
+ error$1
5834
+ );
5835
+ }
5836
+ }
5837
+ async delete(id) {
5838
+ try {
5839
+ await this.deleteVersionsByParentId(id);
5840
+ await this.#client.execute({
5841
+ sql: `DELETE FROM "${storage.TABLE_SCORER_DEFINITIONS}" WHERE "id" = ?`,
5842
+ args: [id]
5843
+ });
5844
+ } catch (error$1) {
5845
+ if (error$1 instanceof error.MastraError) throw error$1;
5846
+ throw new error.MastraError(
5847
+ {
5848
+ id: storage.createStorageErrorId("LIBSQL", "DELETE_SCORER_DEFINITION", "FAILED"),
5849
+ domain: error.ErrorDomain.STORAGE,
5850
+ category: error.ErrorCategory.THIRD_PARTY
5851
+ },
5852
+ error$1
5853
+ );
5854
+ }
5855
+ }
5856
+ async list(args) {
5857
+ try {
5858
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
5859
+ const { field, direction } = this.parseOrderBy(orderBy);
5860
+ const conditions = [];
5861
+ const queryParams = [];
5862
+ if (authorId !== void 0) {
5863
+ conditions.push("authorId = ?");
5864
+ queryParams.push(authorId);
5865
+ }
5866
+ if (metadata && Object.keys(metadata).length > 0) {
5867
+ for (const [key, value] of Object.entries(metadata)) {
5868
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
5869
+ throw new error.MastraError({
5870
+ id: storage.createStorageErrorId("LIBSQL", "LIST_SCORER_DEFINITIONS", "INVALID_METADATA_KEY"),
5871
+ domain: error.ErrorDomain.STORAGE,
5872
+ category: error.ErrorCategory.USER,
5873
+ text: `Invalid metadata key: ${key}. Keys must be alphanumeric with underscores.`,
5874
+ details: { key }
5875
+ });
5876
+ }
5877
+ conditions.push(`json_extract(metadata, '$.${key}') = ?`);
5878
+ queryParams.push(typeof value === "string" ? value : JSON.stringify(value));
5879
+ }
5880
+ }
5881
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5882
+ const countResult = await this.#client.execute({
5883
+ sql: `SELECT COUNT(*) as count FROM "${storage.TABLE_SCORER_DEFINITIONS}" ${whereClause}`,
5884
+ args: queryParams
5885
+ });
5886
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
5887
+ if (total === 0) {
5888
+ return {
5889
+ scorerDefinitions: [],
5890
+ total: 0,
5891
+ page,
5892
+ perPage: perPageInput ?? 100,
5893
+ hasMore: false
5894
+ };
5895
+ }
5896
+ const perPage = storage.normalizePerPage(perPageInput, 100);
5897
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
5898
+ const limitValue = perPageInput === false ? total : perPage;
5899
+ const end = perPageInput === false ? total : start + perPage;
5900
+ const result = await this.#client.execute({
5901
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_SCORER_DEFINITIONS)} FROM "${storage.TABLE_SCORER_DEFINITIONS}" ${whereClause} ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
5902
+ args: [...queryParams, limitValue, start]
5903
+ });
5904
+ const scorerDefinitions = result.rows?.map((row) => this.#parseScorerRow(row)) ?? [];
5905
+ return {
5906
+ scorerDefinitions,
5907
+ total,
5908
+ page,
5909
+ perPage: perPageForResponse,
5910
+ hasMore: end < total
5911
+ };
5912
+ } catch (error$1) {
5913
+ if (error$1 instanceof error.MastraError) throw error$1;
5914
+ throw new error.MastraError(
5915
+ {
5916
+ id: storage.createStorageErrorId("LIBSQL", "LIST_SCORER_DEFINITIONS", "FAILED"),
5917
+ domain: error.ErrorDomain.STORAGE,
5918
+ category: error.ErrorCategory.THIRD_PARTY
5919
+ },
5920
+ error$1
5921
+ );
5922
+ }
5923
+ }
5924
+ // ==========================================================================
5925
+ // Scorer Definition Version Methods
5926
+ // ==========================================================================
5927
+ async createVersion(input) {
5928
+ try {
5929
+ const now = /* @__PURE__ */ new Date();
5930
+ await this.#db.insert({
5931
+ tableName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
5932
+ record: {
5933
+ id: input.id,
5934
+ scorerDefinitionId: input.scorerDefinitionId,
5935
+ versionNumber: input.versionNumber,
5936
+ name: input.name,
5937
+ description: input.description ?? null,
5938
+ type: input.type,
5939
+ model: input.model ?? null,
5940
+ instructions: input.instructions ?? null,
5941
+ scoreRange: input.scoreRange ?? null,
5942
+ presetConfig: input.presetConfig ?? null,
5943
+ defaultSampling: input.defaultSampling ?? null,
5944
+ changedFields: input.changedFields ?? null,
5945
+ changeMessage: input.changeMessage ?? null,
5946
+ createdAt: now.toISOString()
5947
+ }
5948
+ });
5949
+ return {
5950
+ ...input,
5951
+ createdAt: now
5952
+ };
5953
+ } catch (error$1) {
5954
+ if (error$1 instanceof error.MastraError) throw error$1;
5955
+ throw new error.MastraError(
5956
+ {
5957
+ id: storage.createStorageErrorId("LIBSQL", "CREATE_SCORER_DEFINITION_VERSION", "FAILED"),
5958
+ domain: error.ErrorDomain.STORAGE,
5959
+ category: error.ErrorCategory.THIRD_PARTY
5960
+ },
5961
+ error$1
5962
+ );
5963
+ }
5964
+ }
5965
+ async getVersion(id) {
5966
+ try {
5967
+ const result = await this.#client.execute({
5968
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE id = ?`,
5969
+ args: [id]
5970
+ });
5971
+ const row = result.rows?.[0];
5972
+ return row ? this.#parseVersionRow(row) : null;
5973
+ } catch (error$1) {
5974
+ if (error$1 instanceof error.MastraError) throw error$1;
5975
+ throw new error.MastraError(
5976
+ {
5977
+ id: storage.createStorageErrorId("LIBSQL", "GET_SCORER_DEFINITION_VERSION", "FAILED"),
5978
+ domain: error.ErrorDomain.STORAGE,
5979
+ category: error.ErrorCategory.THIRD_PARTY
5980
+ },
5981
+ error$1
5982
+ );
5983
+ }
5984
+ }
5985
+ async getVersionByNumber(scorerDefinitionId, versionNumber) {
5986
+ try {
5987
+ const result = await this.#client.execute({
5988
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ? AND versionNumber = ?`,
5989
+ args: [scorerDefinitionId, versionNumber]
5990
+ });
5991
+ const row = result.rows?.[0];
5992
+ return row ? this.#parseVersionRow(row) : null;
5993
+ } catch (error$1) {
5994
+ if (error$1 instanceof error.MastraError) throw error$1;
5995
+ throw new error.MastraError(
5996
+ {
5997
+ id: storage.createStorageErrorId("LIBSQL", "GET_SCORER_DEFINITION_VERSION_BY_NUMBER", "FAILED"),
5998
+ domain: error.ErrorDomain.STORAGE,
5999
+ category: error.ErrorCategory.THIRD_PARTY
6000
+ },
6001
+ error$1
6002
+ );
6003
+ }
6004
+ }
6005
+ async getLatestVersion(scorerDefinitionId) {
6006
+ try {
6007
+ const result = await this.#client.execute({
6008
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ? ORDER BY versionNumber DESC LIMIT 1`,
6009
+ args: [scorerDefinitionId]
6010
+ });
6011
+ const row = result.rows?.[0];
6012
+ return row ? this.#parseVersionRow(row) : null;
6013
+ } catch (error$1) {
6014
+ if (error$1 instanceof error.MastraError) throw error$1;
6015
+ throw new error.MastraError(
6016
+ {
6017
+ id: storage.createStorageErrorId("LIBSQL", "GET_LATEST_SCORER_DEFINITION_VERSION", "FAILED"),
6018
+ domain: error.ErrorDomain.STORAGE,
6019
+ category: error.ErrorCategory.THIRD_PARTY
6020
+ },
6021
+ error$1
6022
+ );
6023
+ }
6024
+ }
6025
+ async listVersions(input) {
6026
+ try {
6027
+ const { scorerDefinitionId, page = 0, perPage: perPageInput, orderBy } = input;
6028
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
6029
+ const countResult = await this.#client.execute({
6030
+ sql: `SELECT COUNT(*) as count FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ?`,
6031
+ args: [scorerDefinitionId]
6032
+ });
6033
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
6034
+ if (total === 0) {
6035
+ return {
6036
+ versions: [],
6037
+ total: 0,
6038
+ page,
6039
+ perPage: perPageInput ?? 20,
6040
+ hasMore: false
6041
+ };
6042
+ }
6043
+ const perPage = storage.normalizePerPage(perPageInput, 20);
6044
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
6045
+ const limitValue = perPageInput === false ? total : perPage;
6046
+ const end = perPageInput === false ? total : start + perPage;
6047
+ const result = await this.#client.execute({
6048
+ sql: `SELECT ${buildSelectColumns(storage.TABLE_SCORER_DEFINITION_VERSIONS)} FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ? ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
6049
+ args: [scorerDefinitionId, limitValue, start]
6050
+ });
6051
+ const versions = result.rows?.map((row) => this.#parseVersionRow(row)) ?? [];
6052
+ return {
6053
+ versions,
6054
+ total,
6055
+ page,
6056
+ perPage: perPageForResponse,
6057
+ hasMore: end < total
6058
+ };
6059
+ } catch (error$1) {
6060
+ if (error$1 instanceof error.MastraError) throw error$1;
6061
+ throw new error.MastraError(
6062
+ {
6063
+ id: storage.createStorageErrorId("LIBSQL", "LIST_SCORER_DEFINITION_VERSIONS", "FAILED"),
6064
+ domain: error.ErrorDomain.STORAGE,
6065
+ category: error.ErrorCategory.THIRD_PARTY
6066
+ },
6067
+ error$1
6068
+ );
6069
+ }
6070
+ }
6071
+ async deleteVersion(id) {
6072
+ try {
6073
+ await this.#client.execute({
6074
+ sql: `DELETE FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE "id" = ?`,
6075
+ args: [id]
6076
+ });
6077
+ } catch (error$1) {
6078
+ if (error$1 instanceof error.MastraError) throw error$1;
6079
+ throw new error.MastraError(
6080
+ {
6081
+ id: storage.createStorageErrorId("LIBSQL", "DELETE_SCORER_DEFINITION_VERSION", "FAILED"),
6082
+ domain: error.ErrorDomain.STORAGE,
6083
+ category: error.ErrorCategory.THIRD_PARTY
6084
+ },
6085
+ error$1
6086
+ );
6087
+ }
6088
+ }
6089
+ async deleteVersionsByParentId(entityId) {
6090
+ try {
6091
+ await this.#client.execute({
6092
+ sql: `DELETE FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE "scorerDefinitionId" = ?`,
6093
+ args: [entityId]
6094
+ });
6095
+ } catch (error$1) {
6096
+ if (error$1 instanceof error.MastraError) throw error$1;
6097
+ throw new error.MastraError(
6098
+ {
6099
+ id: storage.createStorageErrorId("LIBSQL", "DELETE_SCORER_DEFINITION_VERSIONS_BY_SCORER", "FAILED"),
6100
+ domain: error.ErrorDomain.STORAGE,
6101
+ category: error.ErrorCategory.THIRD_PARTY
6102
+ },
6103
+ error$1
6104
+ );
6105
+ }
6106
+ }
6107
+ async countVersions(scorerDefinitionId) {
6108
+ try {
6109
+ const result = await this.#client.execute({
6110
+ sql: `SELECT COUNT(*) as count FROM "${storage.TABLE_SCORER_DEFINITION_VERSIONS}" WHERE scorerDefinitionId = ?`,
6111
+ args: [scorerDefinitionId]
6112
+ });
6113
+ return Number(result.rows?.[0]?.count ?? 0);
6114
+ } catch (error$1) {
6115
+ if (error$1 instanceof error.MastraError) throw error$1;
6116
+ throw new error.MastraError(
6117
+ {
6118
+ id: storage.createStorageErrorId("LIBSQL", "COUNT_SCORER_DEFINITION_VERSIONS", "FAILED"),
6119
+ domain: error.ErrorDomain.STORAGE,
6120
+ category: error.ErrorCategory.THIRD_PARTY
6121
+ },
6122
+ error$1
6123
+ );
6124
+ }
6125
+ }
6126
+ // ==========================================================================
6127
+ // Private Helpers
6128
+ // ==========================================================================
6129
+ #parseScorerRow(row) {
6130
+ const safeParseJSON = (val) => {
6131
+ if (val === null || val === void 0) return void 0;
6132
+ if (typeof val === "string") {
6133
+ try {
6134
+ return JSON.parse(val);
6135
+ } catch {
6136
+ return val;
6137
+ }
6138
+ }
6139
+ return val;
6140
+ };
6141
+ return {
6142
+ id: row.id,
6143
+ status: row.status ?? "draft",
6144
+ activeVersionId: row.activeVersionId ?? void 0,
6145
+ authorId: row.authorId ?? void 0,
6146
+ metadata: safeParseJSON(row.metadata),
6147
+ createdAt: new Date(row.createdAt),
6148
+ updatedAt: new Date(row.updatedAt)
6149
+ };
6150
+ }
6151
+ #parseVersionRow(row) {
6152
+ const safeParseJSON = (val) => {
6153
+ if (val === null || val === void 0) return void 0;
6154
+ if (typeof val === "string") {
6155
+ try {
6156
+ return JSON.parse(val);
6157
+ } catch {
6158
+ return val;
6159
+ }
6160
+ }
6161
+ return val;
6162
+ };
6163
+ return {
6164
+ id: row.id,
6165
+ scorerDefinitionId: row.scorerDefinitionId,
6166
+ versionNumber: Number(row.versionNumber),
6167
+ name: row.name,
6168
+ description: row.description ?? void 0,
6169
+ type: row.type,
6170
+ model: safeParseJSON(row.model),
6171
+ instructions: row.instructions ?? void 0,
6172
+ scoreRange: safeParseJSON(row.scoreRange),
6173
+ presetConfig: safeParseJSON(row.presetConfig),
6174
+ defaultSampling: safeParseJSON(row.defaultSampling),
6175
+ changedFields: safeParseJSON(row.changedFields),
6176
+ changeMessage: row.changeMessage ?? void 0,
6177
+ createdAt: new Date(row.createdAt)
6178
+ };
6179
+ }
6180
+ };
4705
6181
  var ScoresLibSQL = class extends storage.ScoresStorage {
4706
6182
  #db;
4707
6183
  #client;
@@ -5354,12 +6830,16 @@ var LibSQLStore = class extends storage.MastraCompositeStore {
5354
6830
  const memory = new MemoryLibSQL(domainConfig);
5355
6831
  const observability = new ObservabilityLibSQL(domainConfig);
5356
6832
  const agents = new AgentsLibSQL(domainConfig);
6833
+ const promptBlocks = new PromptBlocksLibSQL(domainConfig);
6834
+ const scorerDefinitions = new ScorerDefinitionsLibSQL(domainConfig);
5357
6835
  this.stores = {
5358
6836
  scores,
5359
6837
  workflows,
5360
6838
  memory,
5361
6839
  observability,
5362
- agents
6840
+ agents,
6841
+ promptBlocks,
6842
+ scorerDefinitions
5363
6843
  };
5364
6844
  }
5365
6845
  };
@@ -5470,6 +6950,8 @@ exports.LibSQLStore = LibSQLStore;
5470
6950
  exports.LibSQLVector = LibSQLVector;
5471
6951
  exports.MemoryLibSQL = MemoryLibSQL;
5472
6952
  exports.ObservabilityLibSQL = ObservabilityLibSQL;
6953
+ exports.PromptBlocksLibSQL = PromptBlocksLibSQL;
6954
+ exports.ScorerDefinitionsLibSQL = ScorerDefinitionsLibSQL;
5473
6955
  exports.ScoresLibSQL = ScoresLibSQL;
5474
6956
  exports.WorkflowsLibSQL = WorkflowsLibSQL;
5475
6957
  //# sourceMappingURL=index.cjs.map