@mastra/memory 1.2.0-alpha.0 → 1.2.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.
@@ -1415,6 +1415,30 @@ var ObservationalMemory = class _ObservationalMemory {
1415
1415
  _ObservationalMemory.reflectionBufferCycleIds.delete(obsBufKey);
1416
1416
  }
1417
1417
  }
1418
+ /**
1419
+ * Await any in-flight async buffering operations for a given thread/resource.
1420
+ * Returns once all buffering promises have settled (or after timeout).
1421
+ */
1422
+ static async awaitBuffering(threadId, resourceId, scope, timeoutMs = 3e4) {
1423
+ const lockKey = scope === "resource" && resourceId ? `resource:${resourceId}` : `thread:${threadId ?? "unknown"}`;
1424
+ const obsKey = `obs:${lockKey}`;
1425
+ const reflKey = `refl:${lockKey}`;
1426
+ const promises = [];
1427
+ const obsOp = _ObservationalMemory.asyncBufferingOps.get(obsKey);
1428
+ if (obsOp) promises.push(obsOp);
1429
+ const reflOp = _ObservationalMemory.asyncBufferingOps.get(reflKey);
1430
+ if (reflOp) promises.push(reflOp);
1431
+ if (promises.length === 0) {
1432
+ return;
1433
+ }
1434
+ try {
1435
+ await Promise.race([
1436
+ Promise.all(promises),
1437
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), timeoutMs))
1438
+ ]);
1439
+ } catch {
1440
+ }
1441
+ }
1418
1442
  /**
1419
1443
  * Safely get bufferedObservationChunks as an array.
1420
1444
  * Handles cases where it might be a JSON string or undefined.
@@ -1674,6 +1698,13 @@ Async buffering is enabled by default \u2014 this opt-out is only needed when us
1674
1698
  }
1675
1699
  };
1676
1700
  }
1701
+ /**
1702
+ * Wait for any in-flight async buffering operations for the given thread/resource.
1703
+ * Used by server endpoints to block until buffering completes so the UI can get final state.
1704
+ */
1705
+ async waitForBuffering(threadId, resourceId, timeoutMs = 3e4) {
1706
+ return _ObservationalMemory.awaitBuffering(threadId, resourceId, this.scope, timeoutMs);
1707
+ }
1677
1708
  /**
1678
1709
  * Get the full config including resolved model names.
1679
1710
  * This is async because it needs to resolve the model configs.
@@ -2107,6 +2138,34 @@ Async buffering is enabled by default \u2014 this opt-out is only needed when us
2107
2138
  }
2108
2139
  }
2109
2140
  }
2141
+ /**
2142
+ * Persist a marker to the last assistant message in storage.
2143
+ * Unlike persistMarkerToMessage, this fetches messages directly from the DB
2144
+ * so it works even when no MessageList is available (e.g. async buffering ops).
2145
+ */
2146
+ async persistMarkerToStorage(marker, threadId, resourceId) {
2147
+ try {
2148
+ const result = await this.storage.listMessages({
2149
+ threadId,
2150
+ perPage: 20,
2151
+ orderBy: { field: "createdAt", direction: "DESC" }
2152
+ });
2153
+ const messages = result?.messages ?? [];
2154
+ for (const msg of messages) {
2155
+ if (msg?.role === "assistant" && msg.content?.parts && Array.isArray(msg.content.parts)) {
2156
+ msg.content.parts.push(marker);
2157
+ await this.messageHistory.persistMessages({
2158
+ messages: [msg],
2159
+ threadId,
2160
+ resourceId
2161
+ });
2162
+ return;
2163
+ }
2164
+ }
2165
+ } catch (e) {
2166
+ omDebug(`[OM:persistMarkerToStorage] failed to save marker to DB: ${e}`);
2167
+ }
2168
+ }
2110
2169
  /**
2111
2170
  * Find the last completed observation boundary in a message's parts.
2112
2171
  * A completed observation is a start marker followed by an end marker.
@@ -3251,6 +3310,8 @@ NOTE: Any messages following this system reminder are newer than your memories.
3251
3310
  },
3252
3311
  currentObservationTokens
3253
3312
  );
3313
+ this.storage.setPendingMessageTokens(freshRecord.id, totalPendingTokens).catch(() => {
3314
+ });
3254
3315
  }
3255
3316
  return messageList;
3256
3317
  }
@@ -3791,6 +3852,7 @@ ${result.observations}` : result.observations;
3791
3852
  });
3792
3853
  void writer.custom(failedMarker).catch(() => {
3793
3854
  });
3855
+ await this.persistMarkerToStorage(failedMarker, threadId, freshRecord.resourceId ?? void 0);
3794
3856
  }
3795
3857
  omError("[OM] Async buffered observation failed", error);
3796
3858
  }
@@ -3853,6 +3915,7 @@ ${result.observations}` : result.observations;
3853
3915
  });
3854
3916
  void writer.custom(endMarker).catch(() => {
3855
3917
  });
3918
+ await this.persistMarkerToStorage(endMarker, threadId, record.resourceId ?? void 0);
3856
3919
  }
3857
3920
  }
3858
3921
  /**
@@ -3979,7 +4042,7 @@ ${bufferedObservations}`;
3979
4042
  this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
3980
4043
  omError("[OM] Failed to set buffering reflection flag", err);
3981
4044
  });
3982
- const asyncOp = this.doAsyncBufferedReflection(record, bufferKey, writer).catch((error) => {
4045
+ const asyncOp = this.doAsyncBufferedReflection(record, bufferKey, writer).catch(async (error) => {
3983
4046
  if (writer) {
3984
4047
  const failedMarker = this.createBufferingFailedMarker({
3985
4048
  cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
@@ -3992,6 +4055,7 @@ ${bufferedObservations}`;
3992
4055
  });
3993
4056
  void writer.custom(failedMarker).catch(() => {
3994
4057
  });
4058
+ await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
3995
4059
  }
3996
4060
  omError("[OM] Async buffered reflection failed", error);
3997
4061
  }).finally(() => {
@@ -4085,6 +4149,7 @@ ${bufferedObservations}`;
4085
4149
  });
4086
4150
  void writer.custom(endMarker).catch(() => {
4087
4151
  });
4152
+ await this.persistMarkerToStorage(endMarker, currentRecord.threadId ?? "", currentRecord.resourceId ?? void 0);
4088
4153
  }
4089
4154
  }
4090
4155
  /**
@@ -4773,5 +4838,5 @@ exports.formatMessagesForObserver = formatMessagesForObserver;
4773
4838
  exports.hasCurrentTaskSection = hasCurrentTaskSection;
4774
4839
  exports.optimizeObservationsForContext = optimizeObservationsForContext;
4775
4840
  exports.parseObserverOutput = parseObserverOutput;
4776
- //# sourceMappingURL=chunk-AWE2QQPI.cjs.map
4777
- //# sourceMappingURL=chunk-AWE2QQPI.cjs.map
4841
+ //# sourceMappingURL=chunk-7SCXX4S7.cjs.map
4842
+ //# sourceMappingURL=chunk-7SCXX4S7.cjs.map