@mastra/libsql 1.17.0-alpha.4 → 1.17.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -8306,46 +8306,49 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8306
8306
  config: input.config,
8307
8307
  observedTimezone: input.observedTimezone
8308
8308
  };
8309
- await this.#client.execute({
8310
- sql: `INSERT INTO "${OM_TABLE}" (
8311
- id, "lookupKey", scope, "resourceId", "threadId",
8312
- "activeObservations", "activeObservationsPendingUpdate",
8313
- "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
8314
- "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
8315
- "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
8316
- "observedTimezone", "createdAt", "updatedAt"
8317
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
8318
- args: [
8319
- id,
8320
- lookupKey,
8321
- input.scope,
8322
- input.resourceId,
8323
- input.threadId || null,
8324
- "",
8325
- null,
8326
- "initial",
8327
- JSON.stringify(input.config),
8328
- 0,
8329
- null,
8330
- null,
8331
- 0,
8332
- 0,
8333
- 0,
8334
- false,
8335
- false,
8336
- false,
8337
- // isBufferingObservation
8338
- false,
8339
- // isBufferingReflection
8340
- 0,
8341
- // lastBufferedAtTokens
8342
- null,
8343
- // lastBufferedAtTime
8344
- input.observedTimezone || null,
8345
- now.toISOString(),
8346
- now.toISOString()
8347
- ]
8348
- });
8309
+ await withClientWriteLock(
8310
+ this.#client,
8311
+ () => this.#client.execute({
8312
+ sql: `INSERT INTO "${OM_TABLE}" (
8313
+ id, "lookupKey", scope, "resourceId", "threadId",
8314
+ "activeObservations", "activeObservationsPendingUpdate",
8315
+ "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
8316
+ "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
8317
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
8318
+ "observedTimezone", "createdAt", "updatedAt"
8319
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
8320
+ args: [
8321
+ id,
8322
+ lookupKey,
8323
+ input.scope,
8324
+ input.resourceId,
8325
+ input.threadId || null,
8326
+ "",
8327
+ null,
8328
+ "initial",
8329
+ JSON.stringify(input.config),
8330
+ 0,
8331
+ null,
8332
+ null,
8333
+ 0,
8334
+ 0,
8335
+ 0,
8336
+ false,
8337
+ false,
8338
+ false,
8339
+ // isBufferingObservation
8340
+ false,
8341
+ // isBufferingReflection
8342
+ 0,
8343
+ // lastBufferedAtTokens
8344
+ null,
8345
+ // lastBufferedAtTime
8346
+ input.observedTimezone || null,
8347
+ now.toISOString(),
8348
+ now.toISOString()
8349
+ ]
8350
+ })
8351
+ );
8349
8352
  return record;
8350
8353
  } catch (error$1) {
8351
8354
  throw new error.MastraError(
@@ -8362,53 +8365,56 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8362
8365
  async insertObservationalMemoryRecord(record) {
8363
8366
  try {
8364
8367
  const lookupKey = this.getOMKey(record.threadId, record.resourceId);
8365
- await this.#client.execute({
8366
- sql: `INSERT INTO "${OM_TABLE}" (
8367
- id, "lookupKey", scope, "resourceId", "threadId",
8368
- "activeObservations", "activeObservationsPendingUpdate",
8369
- "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
8370
- "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
8371
- "observedMessageIds", "bufferedObservationChunks",
8372
- "bufferedReflection", "bufferedReflectionTokens", "bufferedReflectionInputTokens",
8373
- "reflectedObservationLineCount",
8374
- "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection",
8375
- "lastBufferedAtTokens", "lastBufferedAtTime",
8376
- "observedTimezone", metadata, "createdAt", "updatedAt"
8377
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
8378
- args: [
8379
- record.id,
8380
- lookupKey,
8381
- record.scope,
8382
- record.resourceId,
8383
- record.threadId || null,
8384
- record.activeObservations || "",
8385
- null,
8386
- record.originType || "initial",
8387
- record.config ? JSON.stringify(record.config) : null,
8388
- record.generationCount || 0,
8389
- record.lastObservedAt ? record.lastObservedAt.toISOString() : null,
8390
- null,
8391
- record.pendingMessageTokens || 0,
8392
- record.totalTokensObserved || 0,
8393
- record.observationTokenCount || 0,
8394
- record.observedMessageIds ? JSON.stringify(record.observedMessageIds) : null,
8395
- record.bufferedObservationChunks ? JSON.stringify(record.bufferedObservationChunks) : null,
8396
- record.bufferedReflection || null,
8397
- record.bufferedReflectionTokens ?? null,
8398
- record.bufferedReflectionInputTokens ?? null,
8399
- record.reflectedObservationLineCount ?? null,
8400
- record.isObserving || false,
8401
- record.isReflecting || false,
8402
- record.isBufferingObservation || false,
8403
- record.isBufferingReflection || false,
8404
- record.lastBufferedAtTokens || 0,
8405
- record.lastBufferedAtTime ? record.lastBufferedAtTime.toISOString() : null,
8406
- record.observedTimezone || null,
8407
- record.metadata ? JSON.stringify(record.metadata) : null,
8408
- record.createdAt.toISOString(),
8409
- record.updatedAt.toISOString()
8410
- ]
8411
- });
8368
+ await withClientWriteLock(
8369
+ this.#client,
8370
+ () => this.#client.execute({
8371
+ sql: `INSERT INTO "${OM_TABLE}" (
8372
+ id, "lookupKey", scope, "resourceId", "threadId",
8373
+ "activeObservations", "activeObservationsPendingUpdate",
8374
+ "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
8375
+ "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
8376
+ "observedMessageIds", "bufferedObservationChunks",
8377
+ "bufferedReflection", "bufferedReflectionTokens", "bufferedReflectionInputTokens",
8378
+ "reflectedObservationLineCount",
8379
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection",
8380
+ "lastBufferedAtTokens", "lastBufferedAtTime",
8381
+ "observedTimezone", metadata, "createdAt", "updatedAt"
8382
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
8383
+ args: [
8384
+ record.id,
8385
+ lookupKey,
8386
+ record.scope,
8387
+ record.resourceId,
8388
+ record.threadId || null,
8389
+ record.activeObservations || "",
8390
+ null,
8391
+ record.originType || "initial",
8392
+ record.config ? JSON.stringify(record.config) : null,
8393
+ record.generationCount || 0,
8394
+ record.lastObservedAt ? record.lastObservedAt.toISOString() : null,
8395
+ null,
8396
+ record.pendingMessageTokens || 0,
8397
+ record.totalTokensObserved || 0,
8398
+ record.observationTokenCount || 0,
8399
+ record.observedMessageIds ? JSON.stringify(record.observedMessageIds) : null,
8400
+ record.bufferedObservationChunks ? JSON.stringify(record.bufferedObservationChunks) : null,
8401
+ record.bufferedReflection || null,
8402
+ record.bufferedReflectionTokens ?? null,
8403
+ record.bufferedReflectionInputTokens ?? null,
8404
+ record.reflectedObservationLineCount ?? null,
8405
+ record.isObserving || false,
8406
+ record.isReflecting || false,
8407
+ record.isBufferingObservation || false,
8408
+ record.isBufferingReflection || false,
8409
+ record.lastBufferedAtTokens || 0,
8410
+ record.lastBufferedAtTime ? record.lastBufferedAtTime.toISOString() : null,
8411
+ record.observedTimezone || null,
8412
+ record.metadata ? JSON.stringify(record.metadata) : null,
8413
+ record.createdAt.toISOString(),
8414
+ record.updatedAt.toISOString()
8415
+ ]
8416
+ })
8417
+ );
8412
8418
  } catch (error$1) {
8413
8419
  throw new error.MastraError(
8414
8420
  {
@@ -8425,26 +8431,29 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8425
8431
  try {
8426
8432
  const now = /* @__PURE__ */ new Date();
8427
8433
  const observedMessageIdsJson = input.observedMessageIds ? JSON.stringify(input.observedMessageIds) : null;
8428
- const result = await this.#client.execute({
8429
- sql: `UPDATE "${OM_TABLE}" SET
8430
- "activeObservations" = ?,
8431
- "lastObservedAt" = ?,
8432
- "pendingMessageTokens" = 0,
8433
- "observationTokenCount" = ?,
8434
- "totalTokensObserved" = "totalTokensObserved" + ?,
8435
- "observedMessageIds" = ?,
8436
- "updatedAt" = ?
8437
- WHERE id = ?`,
8438
- args: [
8439
- input.observations,
8440
- input.lastObservedAt.toISOString(),
8441
- input.tokenCount,
8442
- input.tokenCount,
8443
- observedMessageIdsJson,
8444
- now.toISOString(),
8445
- input.id
8446
- ]
8447
- });
8434
+ const result = await withClientWriteLock(
8435
+ this.#client,
8436
+ () => this.#client.execute({
8437
+ sql: `UPDATE "${OM_TABLE}" SET
8438
+ "activeObservations" = ?,
8439
+ "lastObservedAt" = ?,
8440
+ "pendingMessageTokens" = 0,
8441
+ "observationTokenCount" = ?,
8442
+ "totalTokensObserved" = "totalTokensObserved" + ?,
8443
+ "observedMessageIds" = ?,
8444
+ "updatedAt" = ?
8445
+ WHERE id = ?`,
8446
+ args: [
8447
+ input.observations,
8448
+ input.lastObservedAt.toISOString(),
8449
+ input.tokenCount,
8450
+ input.tokenCount,
8451
+ observedMessageIdsJson,
8452
+ now.toISOString(),
8453
+ input.id
8454
+ ]
8455
+ })
8456
+ );
8448
8457
  if (result.rowsAffected === 0) {
8449
8458
  throw new error.MastraError({
8450
8459
  id: storage.createStorageErrorId("LIBSQL", "UPDATE_ACTIVE_OBSERVATIONS", "NOT_FOUND"),
@@ -8471,78 +8480,21 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8471
8480
  }
8472
8481
  async createReflectionGeneration(input) {
8473
8482
  try {
8474
- const id = crypto.randomUUID();
8475
- const now = /* @__PURE__ */ new Date();
8476
- const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
8477
- const record = {
8478
- id,
8479
- scope: input.currentRecord.scope,
8480
- threadId: input.currentRecord.threadId,
8481
- resourceId: input.currentRecord.resourceId,
8482
- createdAt: now,
8483
- updatedAt: now,
8484
- lastObservedAt: input.currentRecord.lastObservedAt,
8485
- originType: "reflection",
8486
- generationCount: input.currentRecord.generationCount + 1,
8487
- activeObservations: input.reflection,
8488
- totalTokensObserved: input.currentRecord.totalTokensObserved,
8489
- observationTokenCount: input.tokenCount,
8490
- pendingMessageTokens: 0,
8491
- isReflecting: false,
8492
- isObserving: false,
8493
- isBufferingObservation: false,
8494
- isBufferingReflection: false,
8495
- lastBufferedAtTokens: 0,
8496
- lastBufferedAtTime: null,
8497
- config: input.currentRecord.config,
8498
- metadata: input.currentRecord.metadata,
8499
- observedTimezone: input.currentRecord.observedTimezone
8500
- };
8501
- await this.#client.execute({
8502
- sql: `INSERT INTO "${OM_TABLE}" (
8503
- id, "lookupKey", scope, "resourceId", "threadId",
8504
- "activeObservations", "activeObservationsPendingUpdate",
8505
- "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
8506
- "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
8507
- "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
8508
- "observedTimezone", metadata, "createdAt", "updatedAt"
8509
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
8510
- args: [
8511
- id,
8512
- lookupKey,
8513
- record.scope,
8514
- record.resourceId,
8515
- record.threadId || null,
8516
- input.reflection,
8517
- null,
8518
- "reflection",
8519
- JSON.stringify(record.config),
8520
- input.currentRecord.generationCount + 1,
8521
- record.lastObservedAt?.toISOString() || null,
8522
- now.toISOString(),
8523
- record.pendingMessageTokens,
8524
- record.totalTokensObserved,
8525
- record.observationTokenCount,
8526
- false,
8527
- // isObserving
8528
- false,
8529
- // isReflecting
8530
- false,
8531
- // isBufferingObservation
8532
- false,
8533
- // isBufferingReflection
8534
- 0,
8535
- // lastBufferedAtTokens
8536
- null,
8537
- // lastBufferedAtTime
8538
- record.observedTimezone || null,
8539
- record.metadata ? JSON.stringify(record.metadata) : null,
8540
- now.toISOString(),
8541
- now.toISOString()
8542
- ]
8483
+ return await withClientWriteLock(this.#client, async () => {
8484
+ const tx = await this.#client.transaction("write");
8485
+ try {
8486
+ const record = await this.#insertReflectionGeneration(tx, input);
8487
+ await tx.commit();
8488
+ return record;
8489
+ } catch (error) {
8490
+ if (!tx.closed) await tx.rollback();
8491
+ throw error;
8492
+ }
8543
8493
  });
8544
- return record;
8545
8494
  } catch (error$1) {
8495
+ if (error$1 instanceof error.MastraError) {
8496
+ throw error$1;
8497
+ }
8546
8498
  throw new error.MastraError(
8547
8499
  {
8548
8500
  id: storage.createStorageErrorId("LIBSQL", "CREATE_REFLECTION_GENERATION", "FAILED"),
@@ -8554,12 +8506,94 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8554
8506
  );
8555
8507
  }
8556
8508
  }
8509
+ /**
8510
+ * Inserts a new reflection-generation row. Called inside a locked write
8511
+ * transaction — either from {@link createReflectionGeneration} (standalone)
8512
+ * or from {@link swapBufferedReflectionToActive} (as part of a compound
8513
+ * swap). Must not acquire the write lock itself; the caller owns it.
8514
+ */
8515
+ async #insertReflectionGeneration(tx, input) {
8516
+ const id = crypto.randomUUID();
8517
+ const now = /* @__PURE__ */ new Date();
8518
+ const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
8519
+ const record = {
8520
+ id,
8521
+ scope: input.currentRecord.scope,
8522
+ threadId: input.currentRecord.threadId,
8523
+ resourceId: input.currentRecord.resourceId,
8524
+ createdAt: now,
8525
+ updatedAt: now,
8526
+ lastObservedAt: input.currentRecord.lastObservedAt,
8527
+ originType: "reflection",
8528
+ generationCount: input.currentRecord.generationCount + 1,
8529
+ activeObservations: input.reflection,
8530
+ totalTokensObserved: input.currentRecord.totalTokensObserved,
8531
+ observationTokenCount: input.tokenCount,
8532
+ pendingMessageTokens: 0,
8533
+ isReflecting: false,
8534
+ isObserving: false,
8535
+ isBufferingObservation: false,
8536
+ isBufferingReflection: false,
8537
+ lastBufferedAtTokens: 0,
8538
+ lastBufferedAtTime: null,
8539
+ config: input.currentRecord.config,
8540
+ metadata: input.currentRecord.metadata,
8541
+ observedTimezone: input.currentRecord.observedTimezone
8542
+ };
8543
+ await tx.execute({
8544
+ sql: `INSERT INTO "${OM_TABLE}" (
8545
+ id, "lookupKey", scope, "resourceId", "threadId",
8546
+ "activeObservations", "activeObservationsPendingUpdate",
8547
+ "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
8548
+ "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
8549
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
8550
+ "observedTimezone", metadata, "createdAt", "updatedAt"
8551
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
8552
+ args: [
8553
+ id,
8554
+ lookupKey,
8555
+ record.scope,
8556
+ record.resourceId,
8557
+ record.threadId || null,
8558
+ input.reflection,
8559
+ null,
8560
+ "reflection",
8561
+ JSON.stringify(record.config),
8562
+ input.currentRecord.generationCount + 1,
8563
+ record.lastObservedAt?.toISOString() || null,
8564
+ now.toISOString(),
8565
+ record.pendingMessageTokens,
8566
+ record.totalTokensObserved,
8567
+ record.observationTokenCount,
8568
+ false,
8569
+ // isObserving
8570
+ false,
8571
+ // isReflecting
8572
+ false,
8573
+ // isBufferingObservation
8574
+ false,
8575
+ // isBufferingReflection
8576
+ 0,
8577
+ // lastBufferedAtTokens
8578
+ null,
8579
+ // lastBufferedAtTime
8580
+ record.observedTimezone || null,
8581
+ record.metadata ? JSON.stringify(record.metadata) : null,
8582
+ now.toISOString(),
8583
+ now.toISOString()
8584
+ ]
8585
+ });
8586
+ return record;
8587
+ }
8557
8588
  async setReflectingFlag(id, isReflecting) {
8558
8589
  try {
8559
- const result = await this.#client.execute({
8560
- sql: `UPDATE "${OM_TABLE}" SET "isReflecting" = ?, "updatedAt" = ? WHERE id = ?`,
8561
- args: [isReflecting, (/* @__PURE__ */ new Date()).toISOString(), id]
8562
- });
8590
+ const result = await withClientWriteLock(
8591
+ this.#client,
8592
+ () => this.#client.execute({
8593
+ sql: `UPDATE "${OM_TABLE}" SET "isReflecting" = ?, "updatedAt" = ? WHERE id = ?`,
8594
+ args: [isReflecting, (/* @__PURE__ */ new Date()).toISOString(), id]
8595
+ })
8596
+ );
8563
8597
  if (result.rowsAffected === 0) {
8564
8598
  throw new error.MastraError({
8565
8599
  id: storage.createStorageErrorId("LIBSQL", "SET_REFLECTING_FLAG", "NOT_FOUND"),
@@ -8586,10 +8620,13 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8586
8620
  }
8587
8621
  async setObservingFlag(id, isObserving) {
8588
8622
  try {
8589
- const result = await this.#client.execute({
8590
- sql: `UPDATE "${OM_TABLE}" SET "isObserving" = ?, "updatedAt" = ? WHERE id = ?`,
8591
- args: [isObserving, (/* @__PURE__ */ new Date()).toISOString(), id]
8592
- });
8623
+ const result = await withClientWriteLock(
8624
+ this.#client,
8625
+ () => this.#client.execute({
8626
+ sql: `UPDATE "${OM_TABLE}" SET "isObserving" = ?, "updatedAt" = ? WHERE id = ?`,
8627
+ args: [isObserving, (/* @__PURE__ */ new Date()).toISOString(), id]
8628
+ })
8629
+ );
8593
8630
  if (result.rowsAffected === 0) {
8594
8631
  throw new error.MastraError({
8595
8632
  id: storage.createStorageErrorId("LIBSQL", "SET_OBSERVING_FLAG", "NOT_FOUND"),
@@ -8626,7 +8663,7 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8626
8663
  sql = `UPDATE "${OM_TABLE}" SET "isBufferingObservation" = ?, "updatedAt" = ? WHERE id = ?`;
8627
8664
  args = [isBuffering, nowStr, id];
8628
8665
  }
8629
- const result = await this.#client.execute({ sql, args });
8666
+ const result = await withClientWriteLock(this.#client, () => this.#client.execute({ sql, args }));
8630
8667
  if (result.rowsAffected === 0) {
8631
8668
  throw new error.MastraError({
8632
8669
  id: storage.createStorageErrorId("LIBSQL", "SET_BUFFERING_OBSERVATION_FLAG", "NOT_FOUND"),
@@ -8653,10 +8690,13 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8653
8690
  }
8654
8691
  async setBufferingReflectionFlag(id, isBuffering) {
8655
8692
  try {
8656
- const result = await this.#client.execute({
8657
- sql: `UPDATE "${OM_TABLE}" SET "isBufferingReflection" = ?, "updatedAt" = ? WHERE id = ?`,
8658
- args: [isBuffering, (/* @__PURE__ */ new Date()).toISOString(), id]
8659
- });
8693
+ const result = await withClientWriteLock(
8694
+ this.#client,
8695
+ () => this.#client.execute({
8696
+ sql: `UPDATE "${OM_TABLE}" SET "isBufferingReflection" = ?, "updatedAt" = ? WHERE id = ?`,
8697
+ args: [isBuffering, (/* @__PURE__ */ new Date()).toISOString(), id]
8698
+ })
8699
+ );
8660
8700
  if (result.rowsAffected === 0) {
8661
8701
  throw new error.MastraError({
8662
8702
  id: storage.createStorageErrorId("LIBSQL", "SET_BUFFERING_REFLECTION_FLAG", "NOT_FOUND"),
@@ -8684,10 +8724,13 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8684
8724
  async clearObservationalMemory(threadId, resourceId) {
8685
8725
  try {
8686
8726
  const lookupKey = this.getOMKey(threadId, resourceId);
8687
- await this.#client.execute({
8688
- sql: `DELETE FROM "${OM_TABLE}" WHERE "lookupKey" = ?`,
8689
- args: [lookupKey]
8690
- });
8727
+ await withClientWriteLock(
8728
+ this.#client,
8729
+ () => this.#client.execute({
8730
+ sql: `DELETE FROM "${OM_TABLE}" WHERE "lookupKey" = ?`,
8731
+ args: [lookupKey]
8732
+ })
8733
+ );
8691
8734
  } catch (error$1) {
8692
8735
  throw new error.MastraError(
8693
8736
  {
@@ -8702,13 +8745,16 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8702
8745
  }
8703
8746
  async setPendingMessageTokens(id, tokenCount) {
8704
8747
  try {
8705
- const result = await this.#client.execute({
8706
- sql: `UPDATE "${OM_TABLE}" SET
8707
- "pendingMessageTokens" = ?,
8708
- "updatedAt" = ?
8709
- WHERE id = ?`,
8710
- args: [tokenCount, (/* @__PURE__ */ new Date()).toISOString(), id]
8711
- });
8748
+ const result = await withClientWriteLock(
8749
+ this.#client,
8750
+ () => this.#client.execute({
8751
+ sql: `UPDATE "${OM_TABLE}" SET
8752
+ "pendingMessageTokens" = ?,
8753
+ "updatedAt" = ?
8754
+ WHERE id = ?`,
8755
+ args: [tokenCount, (/* @__PURE__ */ new Date()).toISOString(), id]
8756
+ })
8757
+ );
8712
8758
  if (result.rowsAffected === 0) {
8713
8759
  throw new error.MastraError({
8714
8760
  id: storage.createStorageErrorId("LIBSQL", "SET_PENDING_MESSAGE_TOKENS", "NOT_FOUND"),
@@ -8735,25 +8781,34 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8735
8781
  }
8736
8782
  async updateObservationalMemoryConfig(input) {
8737
8783
  try {
8738
- const selectResult = await this.#client.execute({
8739
- sql: `SELECT config FROM "${OM_TABLE}" WHERE id = ?`,
8740
- args: [input.id]
8741
- });
8742
- if (selectResult.rows.length === 0) {
8743
- throw new error.MastraError({
8744
- id: storage.createStorageErrorId("LIBSQL", "UPDATE_OM_CONFIG", "NOT_FOUND"),
8745
- text: `Observational memory record not found: ${input.id}`,
8746
- domain: error.ErrorDomain.STORAGE,
8747
- category: error.ErrorCategory.THIRD_PARTY,
8748
- details: { id: input.id }
8749
- });
8750
- }
8751
- const row = selectResult.rows[0];
8752
- const existing = row.config ? JSON.parse(row.config) : {};
8753
- const merged = this.deepMergeConfig(existing, input.config);
8754
- await this.#client.execute({
8755
- sql: `UPDATE "${OM_TABLE}" SET config = ?, "updatedAt" = ? WHERE id = ?`,
8756
- args: [JSON.stringify(merged), (/* @__PURE__ */ new Date()).toISOString(), input.id]
8784
+ await withClientWriteLock(this.#client, async () => {
8785
+ const tx = await this.#client.transaction("write");
8786
+ try {
8787
+ const selectResult = await tx.execute({
8788
+ sql: `SELECT config FROM "${OM_TABLE}" WHERE id = ?`,
8789
+ args: [input.id]
8790
+ });
8791
+ if (selectResult.rows.length === 0) {
8792
+ throw new error.MastraError({
8793
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_OM_CONFIG", "NOT_FOUND"),
8794
+ text: `Observational memory record not found: ${input.id}`,
8795
+ domain: error.ErrorDomain.STORAGE,
8796
+ category: error.ErrorCategory.THIRD_PARTY,
8797
+ details: { id: input.id }
8798
+ });
8799
+ }
8800
+ const row = selectResult.rows[0];
8801
+ const existing = row.config ? JSON.parse(row.config) : {};
8802
+ const merged = this.deepMergeConfig(existing, input.config);
8803
+ await tx.execute({
8804
+ sql: `UPDATE "${OM_TABLE}" SET config = ?, "updatedAt" = ? WHERE id = ?`,
8805
+ args: [JSON.stringify(merged), (/* @__PURE__ */ new Date()).toISOString(), input.id]
8806
+ });
8807
+ await tx.commit();
8808
+ } catch (error) {
8809
+ if (!tx.closed) await tx.rollback();
8810
+ throw error;
8811
+ }
8757
8812
  });
8758
8813
  } catch (error$1) {
8759
8814
  if (error$1 instanceof error.MastraError) {
@@ -8776,63 +8831,72 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8776
8831
  async updateBufferedObservations(input) {
8777
8832
  try {
8778
8833
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
8779
- const current = await this.#client.execute({
8780
- sql: `SELECT "bufferedObservationChunks" FROM "${OM_TABLE}" WHERE id = ?`,
8781
- args: [input.id]
8782
- });
8783
- if (!current.rows || current.rows.length === 0) {
8784
- throw new error.MastraError({
8785
- id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
8786
- text: `Observational memory record not found: ${input.id}`,
8787
- domain: error.ErrorDomain.STORAGE,
8788
- category: error.ErrorCategory.THIRD_PARTY,
8789
- details: { id: input.id }
8790
- });
8791
- }
8792
- const row = current.rows[0];
8793
- let existingChunks = [];
8794
- if (row.bufferedObservationChunks) {
8834
+ await withClientWriteLock(this.#client, async () => {
8835
+ const tx = await this.#client.transaction("write");
8795
8836
  try {
8796
- const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
8797
- existingChunks = Array.isArray(parsed) ? parsed : [];
8798
- } catch {
8799
- existingChunks = [];
8837
+ const current = await tx.execute({
8838
+ sql: `SELECT "bufferedObservationChunks" FROM "${OM_TABLE}" WHERE id = ?`,
8839
+ args: [input.id]
8840
+ });
8841
+ if (!current.rows || current.rows.length === 0) {
8842
+ throw new error.MastraError({
8843
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
8844
+ text: `Observational memory record not found: ${input.id}`,
8845
+ domain: error.ErrorDomain.STORAGE,
8846
+ category: error.ErrorCategory.THIRD_PARTY,
8847
+ details: { id: input.id }
8848
+ });
8849
+ }
8850
+ const row = current.rows[0];
8851
+ let existingChunks = [];
8852
+ if (row.bufferedObservationChunks) {
8853
+ try {
8854
+ const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
8855
+ existingChunks = Array.isArray(parsed) ? parsed : [];
8856
+ } catch {
8857
+ existingChunks = [];
8858
+ }
8859
+ }
8860
+ const newChunk = {
8861
+ id: `ombuf-${crypto$1.randomUUID()}`,
8862
+ cycleId: input.chunk.cycleId,
8863
+ observations: input.chunk.observations,
8864
+ tokenCount: input.chunk.tokenCount,
8865
+ messageIds: input.chunk.messageIds,
8866
+ messageTokens: input.chunk.messageTokens,
8867
+ lastObservedAt: input.chunk.lastObservedAt,
8868
+ createdAt: /* @__PURE__ */ new Date(),
8869
+ suggestedContinuation: input.chunk.suggestedContinuation,
8870
+ currentTask: input.chunk.currentTask,
8871
+ threadTitle: input.chunk.threadTitle,
8872
+ extractedValues: input.chunk.extractedValues,
8873
+ extractionFailures: input.chunk.extractionFailures
8874
+ };
8875
+ const newChunks = [...existingChunks, newChunk];
8876
+ const lastBufferedAtTime = input.lastBufferedAtTime ? input.lastBufferedAtTime.toISOString() : null;
8877
+ const result = await tx.execute({
8878
+ sql: `UPDATE "${OM_TABLE}" SET
8879
+ "bufferedObservationChunks" = ?,
8880
+ "lastBufferedAtTime" = COALESCE(?, "lastBufferedAtTime"),
8881
+ "updatedAt" = ?
8882
+ WHERE id = ?`,
8883
+ args: [JSON.stringify(newChunks), lastBufferedAtTime, nowStr, input.id]
8884
+ });
8885
+ if (result.rowsAffected === 0) {
8886
+ throw new error.MastraError({
8887
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
8888
+ text: `Observational memory record not found: ${input.id}`,
8889
+ domain: error.ErrorDomain.STORAGE,
8890
+ category: error.ErrorCategory.THIRD_PARTY,
8891
+ details: { id: input.id }
8892
+ });
8893
+ }
8894
+ await tx.commit();
8895
+ } catch (error) {
8896
+ if (!tx.closed) await tx.rollback();
8897
+ throw error;
8800
8898
  }
8801
- }
8802
- const newChunk = {
8803
- id: `ombuf-${crypto$1.randomUUID()}`,
8804
- cycleId: input.chunk.cycleId,
8805
- observations: input.chunk.observations,
8806
- tokenCount: input.chunk.tokenCount,
8807
- messageIds: input.chunk.messageIds,
8808
- messageTokens: input.chunk.messageTokens,
8809
- lastObservedAt: input.chunk.lastObservedAt,
8810
- createdAt: /* @__PURE__ */ new Date(),
8811
- suggestedContinuation: input.chunk.suggestedContinuation,
8812
- currentTask: input.chunk.currentTask,
8813
- threadTitle: input.chunk.threadTitle,
8814
- extractedValues: input.chunk.extractedValues,
8815
- extractionFailures: input.chunk.extractionFailures
8816
- };
8817
- const newChunks = [...existingChunks, newChunk];
8818
- const lastBufferedAtTime = input.lastBufferedAtTime ? input.lastBufferedAtTime.toISOString() : null;
8819
- const result = await this.#client.execute({
8820
- sql: `UPDATE "${OM_TABLE}" SET
8821
- "bufferedObservationChunks" = ?,
8822
- "lastBufferedAtTime" = COALESCE(?, "lastBufferedAtTime"),
8823
- "updatedAt" = ?
8824
- WHERE id = ?`,
8825
- args: [JSON.stringify(newChunks), lastBufferedAtTime, nowStr, input.id]
8826
8899
  });
8827
- if (result.rowsAffected === 0) {
8828
- throw new error.MastraError({
8829
- id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
8830
- text: `Observational memory record not found: ${input.id}`,
8831
- domain: error.ErrorDomain.STORAGE,
8832
- category: error.ErrorCategory.THIRD_PARTY,
8833
- details: { id: input.id }
8834
- });
8835
- }
8836
8900
  } catch (error$1) {
8837
8901
  if (error$1 instanceof error.MastraError) {
8838
8902
  throw error$1;
@@ -8851,150 +8915,160 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
8851
8915
  async swapBufferedToActive(input) {
8852
8916
  try {
8853
8917
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
8854
- const current = await this.#client.execute({
8855
- sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
8856
- args: [input.id]
8857
- });
8858
- if (!current.rows || current.rows.length === 0) {
8859
- throw new error.MastraError({
8860
- id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_TO_ACTIVE", "NOT_FOUND"),
8861
- text: `Observational memory record not found: ${input.id}`,
8862
- domain: error.ErrorDomain.STORAGE,
8863
- category: error.ErrorCategory.THIRD_PARTY,
8864
- details: { id: input.id }
8865
- });
8866
- }
8867
- const row = current.rows[0];
8868
- let chunks = [];
8869
- if (row.bufferedObservationChunks) {
8918
+ return await withClientWriteLock(this.#client, async () => {
8919
+ const tx = await this.#client.transaction("write");
8870
8920
  try {
8871
- const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
8872
- chunks = Array.isArray(parsed) ? parsed : [];
8873
- } catch {
8874
- chunks = [];
8875
- }
8876
- }
8877
- if (chunks.length === 0) {
8878
- return {
8879
- chunksActivated: 0,
8880
- messageTokensActivated: 0,
8881
- observationTokensActivated: 0,
8882
- messagesActivated: 0,
8883
- activatedCycleIds: [],
8884
- activatedMessageIds: []
8885
- };
8886
- }
8887
- const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
8888
- const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
8889
- let cumulativeMessageTokens = 0;
8890
- let bestOverBoundary = 0;
8891
- let bestOverTokens = 0;
8892
- let bestUnderBoundary = 0;
8893
- let bestUnderTokens = 0;
8894
- for (let i = 0; i < chunks.length; i++) {
8895
- cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
8896
- const boundary2 = i + 1;
8897
- if (cumulativeMessageTokens >= targetMessageTokens) {
8898
- if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
8899
- bestOverBoundary = boundary2;
8900
- bestOverTokens = cumulativeMessageTokens;
8921
+ const current = await tx.execute({
8922
+ sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
8923
+ args: [input.id]
8924
+ });
8925
+ if (!current.rows || current.rows.length === 0) {
8926
+ throw new error.MastraError({
8927
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_TO_ACTIVE", "NOT_FOUND"),
8928
+ text: `Observational memory record not found: ${input.id}`,
8929
+ domain: error.ErrorDomain.STORAGE,
8930
+ category: error.ErrorCategory.THIRD_PARTY,
8931
+ details: { id: input.id }
8932
+ });
8901
8933
  }
8902
- } else {
8903
- if (cumulativeMessageTokens > bestUnderTokens) {
8904
- bestUnderBoundary = boundary2;
8905
- bestUnderTokens = cumulativeMessageTokens;
8934
+ const row = current.rows[0];
8935
+ let chunks = [];
8936
+ if (row.bufferedObservationChunks) {
8937
+ try {
8938
+ const parsed = typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks;
8939
+ chunks = Array.isArray(parsed) ? parsed : [];
8940
+ } catch {
8941
+ chunks = [];
8942
+ }
8906
8943
  }
8907
- }
8908
- }
8909
- const maxOvershoot = retentionFloor * 0.95;
8910
- const overshoot = bestOverTokens - targetMessageTokens;
8911
- const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
8912
- const remainingAfterUnder = input.currentPendingTokens - bestUnderTokens;
8913
- const minRemaining = Math.min(1e3, retentionFloor);
8914
- let chunksToActivate;
8915
- if (input.forceMaxActivation && bestOverBoundary > 0 && remainingAfterOver >= minRemaining) {
8916
- chunksToActivate = bestOverBoundary;
8917
- } else if (bestOverBoundary > 0 && overshoot <= maxOvershoot && remainingAfterOver >= minRemaining) {
8918
- chunksToActivate = bestOverBoundary;
8919
- } else if (bestUnderBoundary > 0 && remainingAfterUnder >= minRemaining) {
8920
- chunksToActivate = bestUnderBoundary;
8921
- } else if (bestOverBoundary > 0) {
8922
- chunksToActivate = bestOverBoundary;
8923
- } else {
8924
- chunksToActivate = 1;
8925
- }
8926
- const activatedChunks = chunks.slice(0, chunksToActivate);
8927
- const remainingChunks = chunks.slice(chunksToActivate);
8928
- const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
8929
- const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
8930
- const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
8931
- const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
8932
- const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((id) => !!id);
8933
- const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
8934
- const latestChunk = activatedChunks[activatedChunks.length - 1];
8935
- const lastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
8936
- const lastObservedAtStr = lastObservedAt.toISOString();
8937
- const existingActive = row.activeObservations || "";
8938
- const existingTokenCount = Number(row.observationTokenCount || 0);
8939
- const boundary = `
8944
+ if (chunks.length === 0) {
8945
+ await tx.commit();
8946
+ return {
8947
+ chunksActivated: 0,
8948
+ messageTokensActivated: 0,
8949
+ observationTokensActivated: 0,
8950
+ messagesActivated: 0,
8951
+ activatedCycleIds: [],
8952
+ activatedMessageIds: []
8953
+ };
8954
+ }
8955
+ const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
8956
+ const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
8957
+ let cumulativeMessageTokens = 0;
8958
+ let bestOverBoundary = 0;
8959
+ let bestOverTokens = 0;
8960
+ let bestUnderBoundary = 0;
8961
+ let bestUnderTokens = 0;
8962
+ for (let i = 0; i < chunks.length; i++) {
8963
+ cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
8964
+ const boundary2 = i + 1;
8965
+ if (cumulativeMessageTokens >= targetMessageTokens) {
8966
+ if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
8967
+ bestOverBoundary = boundary2;
8968
+ bestOverTokens = cumulativeMessageTokens;
8969
+ }
8970
+ } else {
8971
+ if (cumulativeMessageTokens > bestUnderTokens) {
8972
+ bestUnderBoundary = boundary2;
8973
+ bestUnderTokens = cumulativeMessageTokens;
8974
+ }
8975
+ }
8976
+ }
8977
+ const maxOvershoot = retentionFloor * 0.95;
8978
+ const overshoot = bestOverTokens - targetMessageTokens;
8979
+ const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
8980
+ const remainingAfterUnder = input.currentPendingTokens - bestUnderTokens;
8981
+ const minRemaining = Math.min(1e3, retentionFloor);
8982
+ let chunksToActivate;
8983
+ if (input.forceMaxActivation && bestOverBoundary > 0 && remainingAfterOver >= minRemaining) {
8984
+ chunksToActivate = bestOverBoundary;
8985
+ } else if (bestOverBoundary > 0 && overshoot <= maxOvershoot && remainingAfterOver >= minRemaining) {
8986
+ chunksToActivate = bestOverBoundary;
8987
+ } else if (bestUnderBoundary > 0 && remainingAfterUnder >= minRemaining) {
8988
+ chunksToActivate = bestUnderBoundary;
8989
+ } else if (bestOverBoundary > 0) {
8990
+ chunksToActivate = bestOverBoundary;
8991
+ } else {
8992
+ chunksToActivate = 1;
8993
+ }
8994
+ const activatedChunks = chunks.slice(0, chunksToActivate);
8995
+ const remainingChunks = chunks.slice(chunksToActivate);
8996
+ const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
8997
+ const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
8998
+ const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
8999
+ const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
9000
+ const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((id) => !!id);
9001
+ const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
9002
+ const latestChunk = activatedChunks[activatedChunks.length - 1];
9003
+ const lastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
9004
+ const lastObservedAtStr = lastObservedAt.toISOString();
9005
+ const existingActive = row.activeObservations || "";
9006
+ const existingTokenCount = Number(row.observationTokenCount || 0);
9007
+ const boundary = `
8940
9008
 
8941
9009
  --- message boundary (${lastObservedAt.toISOString()}) ---
8942
9010
 
8943
9011
  `;
8944
- const newActive = existingActive ? `${existingActive}${boundary}${activatedContent}` : activatedContent;
8945
- const newTokenCount = existingTokenCount + activatedTokens;
8946
- const existingPending = Number(row.pendingMessageTokens || 0);
8947
- const newPending = Math.max(0, existingPending - activatedMessageTokens);
8948
- const updateResult = await this.#client.execute({
8949
- sql: `UPDATE "${OM_TABLE}" SET
8950
- "activeObservations" = ?,
8951
- "observationTokenCount" = ?,
8952
- "pendingMessageTokens" = ?,
8953
- "bufferedObservationChunks" = ?,
8954
- "lastObservedAt" = ?,
8955
- "updatedAt" = ?
8956
- WHERE id = ?
8957
- AND "bufferedObservationChunks" IS NOT NULL
8958
- AND "bufferedObservationChunks" != '[]'`,
8959
- args: [
8960
- newActive,
8961
- newTokenCount,
8962
- newPending,
8963
- remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,
8964
- lastObservedAtStr,
8965
- nowStr,
8966
- input.id
8967
- ]
9012
+ const newActive = existingActive ? `${existingActive}${boundary}${activatedContent}` : activatedContent;
9013
+ const newTokenCount = existingTokenCount + activatedTokens;
9014
+ const existingPending = Number(row.pendingMessageTokens || 0);
9015
+ const newPending = Math.max(0, existingPending - activatedMessageTokens);
9016
+ const updateResult = await tx.execute({
9017
+ sql: `UPDATE "${OM_TABLE}" SET
9018
+ "activeObservations" = ?,
9019
+ "observationTokenCount" = ?,
9020
+ "pendingMessageTokens" = ?,
9021
+ "bufferedObservationChunks" = ?,
9022
+ "lastObservedAt" = ?,
9023
+ "updatedAt" = ?
9024
+ WHERE id = ?
9025
+ AND "bufferedObservationChunks" IS NOT NULL
9026
+ AND "bufferedObservationChunks" != '[]'`,
9027
+ args: [
9028
+ newActive,
9029
+ newTokenCount,
9030
+ newPending,
9031
+ remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,
9032
+ lastObservedAtStr,
9033
+ nowStr,
9034
+ input.id
9035
+ ]
9036
+ });
9037
+ await tx.commit();
9038
+ if (updateResult.rowsAffected === 0) {
9039
+ return {
9040
+ chunksActivated: 0,
9041
+ messageTokensActivated: 0,
9042
+ observationTokensActivated: 0,
9043
+ messagesActivated: 0,
9044
+ activatedCycleIds: [],
9045
+ activatedMessageIds: []
9046
+ };
9047
+ }
9048
+ const latestChunkHints = activatedChunks[activatedChunks.length - 1];
9049
+ return {
9050
+ chunksActivated: activatedChunks.length,
9051
+ messageTokensActivated: activatedMessageTokens,
9052
+ observationTokensActivated: activatedTokens,
9053
+ messagesActivated: activatedMessageCount,
9054
+ activatedCycleIds,
9055
+ activatedMessageIds,
9056
+ observations: activatedContent,
9057
+ perChunk: activatedChunks.map((c) => ({
9058
+ cycleId: c.cycleId ?? "",
9059
+ messageTokens: c.messageTokens ?? 0,
9060
+ observationTokens: c.tokenCount,
9061
+ messageCount: c.messageIds.length,
9062
+ observations: c.observations
9063
+ })),
9064
+ suggestedContinuation: latestChunkHints?.suggestedContinuation ?? void 0,
9065
+ currentTask: latestChunkHints?.currentTask ?? void 0
9066
+ };
9067
+ } catch (error) {
9068
+ if (!tx.closed) await tx.rollback();
9069
+ throw error;
9070
+ }
8968
9071
  });
8969
- if (updateResult.rowsAffected === 0) {
8970
- return {
8971
- chunksActivated: 0,
8972
- messageTokensActivated: 0,
8973
- observationTokensActivated: 0,
8974
- messagesActivated: 0,
8975
- activatedCycleIds: [],
8976
- activatedMessageIds: []
8977
- };
8978
- }
8979
- const latestChunkHints = activatedChunks[activatedChunks.length - 1];
8980
- return {
8981
- chunksActivated: activatedChunks.length,
8982
- messageTokensActivated: activatedMessageTokens,
8983
- observationTokensActivated: activatedTokens,
8984
- messagesActivated: activatedMessageCount,
8985
- activatedCycleIds,
8986
- activatedMessageIds,
8987
- observations: activatedContent,
8988
- perChunk: activatedChunks.map((c) => ({
8989
- cycleId: c.cycleId ?? "",
8990
- messageTokens: c.messageTokens ?? 0,
8991
- observationTokens: c.tokenCount,
8992
- messageCount: c.messageIds.length,
8993
- observations: c.observations
8994
- })),
8995
- suggestedContinuation: latestChunkHints?.suggestedContinuation ?? void 0,
8996
- currentTask: latestChunkHints?.currentTask ?? void 0
8997
- };
8998
9072
  } catch (error$1) {
8999
9073
  if (error$1 instanceof error.MastraError) {
9000
9074
  throw error$1;
@@ -9013,28 +9087,31 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
9013
9087
  async updateBufferedReflection(input) {
9014
9088
  try {
9015
9089
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9016
- const result = await this.#client.execute({
9017
- sql: `UPDATE "${OM_TABLE}" SET
9018
- "bufferedReflection" = CASE
9019
- WHEN "bufferedReflection" IS NOT NULL AND "bufferedReflection" != ''
9020
- THEN "bufferedReflection" || char(10) || char(10) || ?
9021
- ELSE ?
9022
- END,
9023
- "bufferedReflectionTokens" = COALESCE("bufferedReflectionTokens", 0) + ?,
9024
- "bufferedReflectionInputTokens" = COALESCE("bufferedReflectionInputTokens", 0) + ?,
9025
- "reflectedObservationLineCount" = ?,
9026
- "updatedAt" = ?
9027
- WHERE id = ?`,
9028
- args: [
9029
- input.reflection,
9030
- input.reflection,
9031
- input.tokenCount,
9032
- input.inputTokenCount,
9033
- input.reflectedObservationLineCount,
9034
- nowStr,
9035
- input.id
9036
- ]
9037
- });
9090
+ const result = await withClientWriteLock(
9091
+ this.#client,
9092
+ () => this.#client.execute({
9093
+ sql: `UPDATE "${OM_TABLE}" SET
9094
+ "bufferedReflection" = CASE
9095
+ WHEN "bufferedReflection" IS NOT NULL AND "bufferedReflection" != ''
9096
+ THEN "bufferedReflection" || char(10) || char(10) || ?
9097
+ ELSE ?
9098
+ END,
9099
+ "bufferedReflectionTokens" = COALESCE("bufferedReflectionTokens", 0) + ?,
9100
+ "bufferedReflectionInputTokens" = COALESCE("bufferedReflectionInputTokens", 0) + ?,
9101
+ "reflectedObservationLineCount" = ?,
9102
+ "updatedAt" = ?
9103
+ WHERE id = ?`,
9104
+ args: [
9105
+ input.reflection,
9106
+ input.reflection,
9107
+ input.tokenCount,
9108
+ input.inputTokenCount,
9109
+ input.reflectedObservationLineCount,
9110
+ nowStr,
9111
+ input.id
9112
+ ]
9113
+ })
9114
+ );
9038
9115
  if (result.rowsAffected === 0) {
9039
9116
  throw new error.MastraError({
9040
9117
  id: storage.createStorageErrorId("LIBSQL", "UPDATE_BUFFERED_REFLECTION", "NOT_FOUND"),
@@ -9061,55 +9138,64 @@ var MemoryLibSQL = class _MemoryLibSQL extends storage.MemoryStorage {
9061
9138
  }
9062
9139
  async swapBufferedReflectionToActive(input) {
9063
9140
  try {
9064
- const current = await this.#client.execute({
9065
- sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
9066
- args: [input.currentRecord.id]
9067
- });
9068
- if (!current.rows || current.rows.length === 0) {
9069
- throw new error.MastraError({
9070
- id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
9071
- text: `Observational memory record not found: ${input.currentRecord.id}`,
9072
- domain: error.ErrorDomain.STORAGE,
9073
- category: error.ErrorCategory.THIRD_PARTY,
9074
- details: { id: input.currentRecord.id }
9075
- });
9076
- }
9077
- const row = current.rows[0];
9078
- const bufferedReflection = row.bufferedReflection || "";
9079
- const reflectedLineCount = Number(row.reflectedObservationLineCount || 0);
9080
- if (!bufferedReflection) {
9081
- throw new error.MastraError({
9082
- id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
9083
- text: "No buffered reflection to swap",
9084
- domain: error.ErrorDomain.STORAGE,
9085
- category: error.ErrorCategory.USER,
9086
- details: { id: input.currentRecord.id }
9087
- });
9088
- }
9089
- const currentObservations = row.activeObservations || "";
9090
- const allLines = currentObservations.split("\n");
9091
- const unreflectedLines = allLines.slice(reflectedLineCount);
9092
- const unreflectedContent = unreflectedLines.join("\n").trim();
9093
- const newObservations = unreflectedContent ? `${bufferedReflection}
9141
+ return await withClientWriteLock(this.#client, async () => {
9142
+ const tx = await this.#client.transaction("write");
9143
+ try {
9144
+ const current = await tx.execute({
9145
+ sql: `SELECT * FROM "${OM_TABLE}" WHERE id = ?`,
9146
+ args: [input.currentRecord.id]
9147
+ });
9148
+ if (!current.rows || current.rows.length === 0) {
9149
+ throw new error.MastraError({
9150
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
9151
+ text: `Observational memory record not found: ${input.currentRecord.id}`,
9152
+ domain: error.ErrorDomain.STORAGE,
9153
+ category: error.ErrorCategory.THIRD_PARTY,
9154
+ details: { id: input.currentRecord.id }
9155
+ });
9156
+ }
9157
+ const row = current.rows[0];
9158
+ const bufferedReflection = row.bufferedReflection || "";
9159
+ const reflectedLineCount = Number(row.reflectedObservationLineCount || 0);
9160
+ if (!bufferedReflection) {
9161
+ throw new error.MastraError({
9162
+ id: storage.createStorageErrorId("LIBSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
9163
+ text: "No buffered reflection to swap",
9164
+ domain: error.ErrorDomain.STORAGE,
9165
+ category: error.ErrorCategory.USER,
9166
+ details: { id: input.currentRecord.id }
9167
+ });
9168
+ }
9169
+ const currentObservations = row.activeObservations || "";
9170
+ const allLines = currentObservations.split("\n");
9171
+ const unreflectedLines = allLines.slice(reflectedLineCount);
9172
+ const unreflectedContent = unreflectedLines.join("\n").trim();
9173
+ const newObservations = unreflectedContent ? `${bufferedReflection}
9094
9174
 
9095
9175
  ${unreflectedContent}` : bufferedReflection;
9096
- const newRecord = await this.createReflectionGeneration({
9097
- currentRecord: input.currentRecord,
9098
- reflection: newObservations,
9099
- tokenCount: input.tokenCount
9176
+ const newRecord = await this.#insertReflectionGeneration(tx, {
9177
+ currentRecord: input.currentRecord,
9178
+ reflection: newObservations,
9179
+ tokenCount: input.tokenCount
9180
+ });
9181
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9182
+ await tx.execute({
9183
+ sql: `UPDATE "${OM_TABLE}" SET
9184
+ "bufferedReflection" = NULL,
9185
+ "bufferedReflectionTokens" = NULL,
9186
+ "bufferedReflectionInputTokens" = NULL,
9187
+ "reflectedObservationLineCount" = NULL,
9188
+ "updatedAt" = ?
9189
+ WHERE id = ?`,
9190
+ args: [nowStr, input.currentRecord.id]
9191
+ });
9192
+ await tx.commit();
9193
+ return newRecord;
9194
+ } catch (error) {
9195
+ if (!tx.closed) await tx.rollback();
9196
+ throw error;
9197
+ }
9100
9198
  });
9101
- const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9102
- await this.#client.execute({
9103
- sql: `UPDATE "${OM_TABLE}" SET
9104
- "bufferedReflection" = NULL,
9105
- "bufferedReflectionTokens" = NULL,
9106
- "bufferedReflectionInputTokens" = NULL,
9107
- "reflectedObservationLineCount" = NULL,
9108
- "updatedAt" = ?
9109
- WHERE id = ?`,
9110
- args: [nowStr, input.currentRecord.id]
9111
- });
9112
- return newRecord;
9113
9199
  } catch (error$1) {
9114
9200
  if (error$1 instanceof error.MastraError) {
9115
9201
  throw error$1;