@mastra/memory 1.13.1 → 1.14.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 (31) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/{chunk-SWCWXIDJ.js → chunk-FQGF36BE.js} +60 -35
  3. package/dist/chunk-FQGF36BE.js.map +1 -0
  4. package/dist/{chunk-HNVSYZRA.cjs → chunk-X7E3WPF2.cjs} +60 -35
  5. package/dist/chunk-X7E3WPF2.cjs.map +1 -0
  6. package/dist/docs/SKILL.md +1 -1
  7. package/dist/docs/assets/SOURCE_MAP.json +39 -39
  8. package/dist/index.cjs +12 -12
  9. package/dist/index.js +4 -4
  10. package/dist/{observational-memory-4VT6QEB7.cjs → observational-memory-22RZ4253.cjs} +26 -26
  11. package/dist/{observational-memory-4VT6QEB7.cjs.map → observational-memory-22RZ4253.cjs.map} +1 -1
  12. package/dist/{observational-memory-74TRS2R6.js → observational-memory-JQ34KLFS.js} +3 -3
  13. package/dist/{observational-memory-74TRS2R6.js.map → observational-memory-JQ34KLFS.js.map} +1 -1
  14. package/dist/processors/index.cjs +24 -24
  15. package/dist/processors/index.js +1 -1
  16. package/dist/processors/observational-memory/index.d.ts +1 -1
  17. package/dist/processors/observational-memory/index.d.ts.map +1 -1
  18. package/dist/processors/observational-memory/observation-strategies/base.d.ts +3 -3
  19. package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +1 -1
  20. package/dist/processors/observational-memory/observation-strategies/types.d.ts +9 -0
  21. package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +1 -1
  22. package/dist/processors/observational-memory/observation-turn/step.d.ts.map +1 -1
  23. package/dist/processors/observational-memory/observational-memory.d.ts +4 -3
  24. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  25. package/dist/processors/observational-memory/processor.d.ts.map +1 -1
  26. package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -1
  27. package/dist/processors/observational-memory/types.d.ts +13 -2
  28. package/dist/processors/observational-memory/types.d.ts.map +1 -1
  29. package/package.json +4 -4
  30. package/dist/chunk-HNVSYZRA.cjs.map +0 -1
  31. package/dist/chunk-SWCWXIDJ.js.map +0 -1
@@ -952,7 +952,7 @@ var ObservationStrategy = class _ObservationStrategy {
952
952
  static create;
953
953
  /**
954
954
  * Run the full observation lifecycle.
955
- * @returns `true` if a full observation cycle completed; `false` if skipped (stale lock) or async-buffer failure was swallowed.
955
+ * @returns Result with `observed` flag and optional `usage` from the observer LLM call.
956
956
  * @throws On sync/resource-scoped observer failure after failed markers (same as pre–Option-A contract).
957
957
  */
958
958
  async run() {
@@ -962,7 +962,7 @@ var ObservationStrategy = class _ObservationStrategy {
962
962
  if (this.needsLock) {
963
963
  const fresh = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
964
964
  if (fresh?.lastObservedAt && record.lastObservedAt && fresh.lastObservedAt > record.lastObservedAt) {
965
- return false;
965
+ return { observed: false };
966
966
  }
967
967
  }
968
968
  const { messages, existingObservations } = await this.prepare();
@@ -983,7 +983,7 @@ var ObservationStrategy = class _ObservationStrategy {
983
983
  observabilityContext: this.opts.observabilityContext
984
984
  });
985
985
  }
986
- return true;
986
+ return { observed: true, usage: output.usage };
987
987
  } catch (error) {
988
988
  await this.emitFailedMarkers(cycleId, error);
989
989
  if (!this.rethrowOnFailure) {
@@ -1002,7 +1002,7 @@ var ObservationStrategy = class _ObservationStrategy {
1002
1002
  });
1003
1003
  if (abortSignal?.aborted) throw error;
1004
1004
  omError("[OM] Observation failed", error);
1005
- return false;
1005
+ return { observed: false };
1006
1006
  }
1007
1007
  omError("[OM] Observation failed", error);
1008
1008
  throw error;
@@ -2030,6 +2030,26 @@ var ObservationStep = class {
2030
2030
  if (statusSnapshot.shouldBuffer && !hasIncompleteToolCalls) {
2031
2031
  const allMessages = messageList.get.all.db();
2032
2032
  const unobservedMessages = om.getUnobservedMessages(allMessages, statusSnapshot.record);
2033
+ const candidates = om.getUnobservedMessages(unobservedMessages, statusSnapshot.record, {
2034
+ excludeBuffered: true
2035
+ });
2036
+ if (candidates.length > 0) {
2037
+ om.sealMessagesForBuffering(candidates);
2038
+ try {
2039
+ await this.turn.hooks?.onBufferChunkSealed?.();
2040
+ } catch (error) {
2041
+ omDebug(
2042
+ `[OM:buffer] onBufferChunkSealed hook failed: ${error instanceof Error ? error.message : String(error)}`
2043
+ );
2044
+ }
2045
+ if (this.turn.memory) {
2046
+ await this.turn.memory.persistMessages(candidates);
2047
+ }
2048
+ messageList.removeByIds(candidates.map((msg) => msg.id));
2049
+ for (const msg of candidates) {
2050
+ messageList.add(msg, "memory");
2051
+ }
2052
+ }
2033
2053
  void om.buffer({
2034
2054
  threadId,
2035
2055
  resourceId,
@@ -2038,23 +2058,7 @@ var ObservationStep = class {
2038
2058
  record: statusSnapshot.record,
2039
2059
  writer: this.turn.writer,
2040
2060
  requestContext: this.turn.requestContext,
2041
- observabilityContext: this.turn.observabilityContext,
2042
- beforeBuffer: async (candidates) => {
2043
- if (candidates.length === 0) {
2044
- return;
2045
- }
2046
- om.sealMessagesForBuffering(candidates);
2047
- try {
2048
- await this.turn.hooks?.onBufferChunkSealed?.();
2049
- } catch (error) {
2050
- omDebug(
2051
- `[OM:buffer] onBufferChunkSealed hook failed: ${error instanceof Error ? error.message : String(error)}`
2052
- );
2053
- }
2054
- if (this.turn.memory) {
2055
- await this.turn.memory.persistMessages(candidates);
2056
- }
2057
- }
2061
+ observabilityContext: this.turn.observabilityContext
2058
2062
  }).catch((err) => {
2059
2063
  omDebug(`[OM:buffer] fire-and-forget buffer failed: ${err?.message}`);
2060
2064
  });
@@ -4196,7 +4200,7 @@ var ReflectorRunner = class {
4196
4200
  /**
4197
4201
  * Start an async buffered reflection in the background.
4198
4202
  */
4199
- startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext) {
4203
+ startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks) {
4200
4204
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
4201
4205
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) {
4202
4206
  return;
@@ -4206,7 +4210,10 @@ var ReflectorRunner = class {
4206
4210
  this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
4207
4211
  omError("[OM] Failed to set buffering reflection flag", err);
4208
4212
  });
4209
- const asyncOp = this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext).catch(async (error) => {
4213
+ reflectionHooks?.onReflectionStart?.();
4214
+ const asyncOp = this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext).then((usage) => {
4215
+ reflectionHooks?.onReflectionEnd?.({ usage });
4216
+ }).catch(async (error) => {
4210
4217
  if (writer) {
4211
4218
  const failedMarker = createBufferingFailedMarker({
4212
4219
  cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
@@ -4222,6 +4229,10 @@ var ReflectorRunner = class {
4222
4229
  await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
4223
4230
  }
4224
4231
  omError("[OM] Async buffered reflection failed", error);
4232
+ reflectionHooks?.onReflectionEnd?.({
4233
+ usage: void 0,
4234
+ error: error instanceof Error ? error : new Error(String(error))
4235
+ });
4225
4236
  BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
4226
4237
  }).finally(() => {
4227
4238
  BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
@@ -4315,6 +4326,7 @@ var ReflectorRunner = class {
4315
4326
  });
4316
4327
  await this.persistMarkerToStorage(endMarker, currentRecord.threadId ?? "", currentRecord.resourceId ?? void 0);
4317
4328
  }
4329
+ return reflectResult.usage;
4318
4330
  }
4319
4331
  /**
4320
4332
  * Try to activate buffered reflection when threshold is reached.
@@ -4435,7 +4447,8 @@ ${unreflectedContent}` : freshRecord.bufferedReflection;
4435
4447
  lockKey,
4436
4448
  writer,
4437
4449
  requestContext,
4438
- observabilityContext
4450
+ observabilityContext,
4451
+ reflectionHooks
4439
4452
  );
4440
4453
  }
4441
4454
  }
@@ -4469,7 +4482,8 @@ ${unreflectedContent}` : freshRecord.bufferedReflection;
4469
4482
  lockKey,
4470
4483
  writer,
4471
4484
  requestContext,
4472
- observabilityContext
4485
+ observabilityContext,
4486
+ reflectionHooks
4473
4487
  );
4474
4488
  return;
4475
4489
  }
@@ -4508,6 +4522,8 @@ ${unreflectedContent}` : freshRecord.bufferedReflection;
4508
4522
  recordId: record.id,
4509
4523
  threadId
4510
4524
  } : void 0;
4525
+ let reflectionUsage;
4526
+ let reflectionError;
4511
4527
  try {
4512
4528
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
4513
4529
  const reflectResult = await this.call(
@@ -4521,6 +4537,7 @@ ${unreflectedContent}` : freshRecord.bufferedReflection;
4521
4537
  requestContext,
4522
4538
  observabilityContext
4523
4539
  );
4540
+ reflectionUsage = reflectResult.usage;
4524
4541
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
4525
4542
  await this.storage.createReflectionGeneration({
4526
4543
  currentRecord: record,
@@ -4565,13 +4582,14 @@ ${unreflectedContent}` : freshRecord.bufferedReflection;
4565
4582
  await writer.custom(failedMarker).catch(() => {
4566
4583
  });
4567
4584
  }
4585
+ reflectionError = error instanceof Error ? error : new Error(String(error));
4568
4586
  if (abortSignal?.aborted) {
4569
4587
  throw error;
4570
4588
  }
4571
4589
  omError("[OM] Reflection failed", error);
4572
4590
  } finally {
4573
4591
  await this.storage.setReflectingFlag(record.id, false);
4574
- reflectionHooks?.onReflectionEnd?.();
4592
+ reflectionHooks?.onReflectionEnd?.({ usage: reflectionUsage, error: reflectionError });
4575
4593
  unregisterOp(record.id, "reflecting");
4576
4594
  }
4577
4595
  }
@@ -7916,6 +7934,7 @@ ${grouped}` : grouped;
7916
7934
  const lockKey = this.buffering.getLockKey(threadId, resourceId);
7917
7935
  const reflectionHooks = hooks ? { onReflectionStart: hooks.onReflectionStart, onReflectionEnd: hooks.onReflectionEnd } : void 0;
7918
7936
  let observed = false;
7937
+ let observationUsage;
7919
7938
  let generationBefore = -1;
7920
7939
  await this.withLock(lockKey, async () => {
7921
7940
  const freshRecord = await this.getOrCreateRecord(threadId, resourceId);
@@ -7932,8 +7951,9 @@ ${grouped}` : grouped;
7932
7951
  return;
7933
7952
  }
7934
7953
  hooks?.onObservationStart?.();
7954
+ let observationError;
7935
7955
  try {
7936
- observed = await ObservationStrategy.create(this, {
7956
+ const result = await ObservationStrategy.create(this, {
7937
7957
  record: freshRecord,
7938
7958
  threadId,
7939
7959
  resourceId,
@@ -7943,8 +7963,13 @@ ${grouped}` : grouped;
7943
7963
  writer: opts.writer,
7944
7964
  observabilityContext: opts.observabilityContext
7945
7965
  }).run();
7966
+ observed = result.observed;
7967
+ observationUsage = result.usage;
7968
+ } catch (error) {
7969
+ observationError = error instanceof Error ? error : new Error(String(error));
7970
+ throw error;
7946
7971
  } finally {
7947
- hooks?.onObservationEnd?.();
7972
+ hooks?.onObservationEnd?.({ usage: observationUsage, error: observationError });
7948
7973
  }
7949
7974
  });
7950
7975
  const record = await this.getOrCreateRecord(threadId, resourceId);
@@ -7965,7 +7990,7 @@ ${grouped}` : grouped;
7965
7990
  async reflect(threadId, resourceId, prompt, requestContext, observabilityContext) {
7966
7991
  const record = await this.getOrCreateRecord(threadId, resourceId);
7967
7992
  if (!record.activeObservations) {
7968
- return { reflected: false, record };
7993
+ return { reflected: false, record, usage: void 0 };
7969
7994
  }
7970
7995
  await this.storage.setReflectingFlag(record.id, true);
7971
7996
  registerOp(record.id, "reflecting");
@@ -7990,11 +8015,11 @@ ${grouped}` : grouped;
7990
8015
  tokenCount: reflectionTokenCount
7991
8016
  });
7992
8017
  const updatedRecord = await this.getOrCreateRecord(threadId, resourceId);
7993
- return { reflected: true, record: updatedRecord };
8018
+ return { reflected: true, record: updatedRecord, usage: reflectResult.usage };
7994
8019
  } catch (error) {
7995
8020
  omError("[OM] reflect() failed", error);
7996
8021
  const latestRecord = await this.getOrCreateRecord(threadId, resourceId);
7997
- return { reflected: false, record: latestRecord };
8022
+ return { reflected: false, record: latestRecord, usage: void 0 };
7998
8023
  } finally {
7999
8024
  await this.storage.setReflectingFlag(record.id, false);
8000
8025
  unregisterOp(record.id, "reflecting");
@@ -8018,9 +8043,9 @@ ${grouped}` : grouped;
8018
8043
  /**
8019
8044
  * Get observation history (previous generations)
8020
8045
  */
8021
- async getHistory(threadId, resourceId, limit) {
8046
+ async getHistory(threadId, resourceId, limit, options) {
8022
8047
  const ids = this.getStorageIds(threadId, resourceId);
8023
- return this.storage.getObservationalMemoryHistory(ids.threadId, ids.resourceId, limit);
8048
+ return this.storage.getObservationalMemoryHistory(ids.threadId, ids.resourceId, limit, options);
8024
8049
  }
8025
8050
  /**
8026
8051
  * Clear all memory for a specific thread/resource
@@ -8591,5 +8616,5 @@ exports.stripEphemeralAnchorIds = stripEphemeralAnchorIds;
8591
8616
  exports.stripObservationGroups = stripObservationGroups;
8592
8617
  exports.truncateStringByTokens = truncateStringByTokens;
8593
8618
  exports.wrapInObservationGroup = wrapInObservationGroup;
8594
- //# sourceMappingURL=chunk-HNVSYZRA.cjs.map
8595
- //# sourceMappingURL=chunk-HNVSYZRA.cjs.map
8619
+ //# sourceMappingURL=chunk-X7E3WPF2.cjs.map
8620
+ //# sourceMappingURL=chunk-X7E3WPF2.cjs.map