@mastra/memory 1.27.0-alpha.3 → 1.28.0-alpha.2

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 (38) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/dist/docs/SKILL.md +4 -2
  3. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  4. package/dist/docs/references/docs-guides-context-engineering.md +297 -0
  5. package/dist/docs/references/docs-storage.md +1 -0
  6. package/dist/docs/references/integrations-databases-mongodb.md +1 -1
  7. package/dist/docs/references/integrations-databases-postgresql.md +2 -0
  8. package/dist/docs/references/integrations-databases-valkey.md +99 -0
  9. package/dist/docs/references/reference-vectors-mongodb.md +11 -11
  10. package/dist/docs/references/reference-vectors-pg.md +2 -0
  11. package/dist/index.cjs +1 -1
  12. package/dist/index.d.ts +6 -3
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/processors/index.cjs +1 -1
  16. package/dist/processors/index.js +1 -1
  17. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +1 -1
  18. package/dist/processors/observational-memory/observation-strategies/sync.d.ts.map +1 -1
  19. package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts +3 -1
  20. package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts.map +1 -1
  21. package/dist/processors/observational-memory/observation-turn/turn.d.ts +2 -1
  22. package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +1 -1
  23. package/dist/processors/observational-memory/observational-memory.d.ts +6 -12
  24. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  25. package/dist/processors/observational-memory/observer-agent.d.ts +13 -0
  26. package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -1
  27. package/dist/processors/observational-memory/observer-runner.d.ts.map +1 -1
  28. package/dist/processors/observational-memory/processor.d.ts +2 -0
  29. package/dist/processors/observational-memory/processor.d.ts.map +1 -1
  30. package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -1
  31. package/dist/processors/observational-memory/tracing.d.ts.map +1 -1
  32. package/dist/processors/observational-memory/types.d.ts +23 -13
  33. package/dist/processors/observational-memory/types.d.ts.map +1 -1
  34. package/dist/{src-Ik0ksTOt.cjs → src-CIBCjg2A.cjs} +324 -164
  35. package/dist/{src-Ik0ksTOt.cjs.map → src-CIBCjg2A.cjs.map} +1 -1
  36. package/dist/{src-t_4yoTX9.js → src-kLYHhPqh.js} +324 -164
  37. package/dist/{src-t_4yoTX9.js.map → src-kLYHhPqh.js.map} +1 -1
  38. package/package.json +7 -7
@@ -18926,6 +18926,12 @@ function extractListItemsOnly(content) {
18926
18926
  */
18927
18927
  const MAX_OBSERVATION_LINE_CHARS = 1e4;
18928
18928
  /**
18929
+ * Minimum trimmed line length considered by the duplicate-line degenerate
18930
+ * check. Short lines (blank lines, separators, terse bullets) legitimately
18931
+ * repeat; long identical lines almost never do.
18932
+ */
18933
+ const MIN_DUPLICATE_LINE_CHARS = 24;
18934
+ /**
18929
18935
  * Truncate individual observation lines that exceed the maximum length.
18930
18936
  */
18931
18937
  function sanitizeObservationLines(observations) {
@@ -18963,9 +18969,81 @@ function detectDegenerateRepetition(text) {
18963
18969
  if (totalWindows > 5 && duplicateWindows / totalWindows > .4) return true;
18964
18970
  const lines = text.split("\n");
18965
18971
  for (const line of lines) if (line.length > 5e4) return true;
18972
+ const seenLines = /* @__PURE__ */ new Map();
18973
+ let duplicateLines = 0;
18974
+ let totalCountedLines = 0;
18975
+ for (const line of lines) {
18976
+ const trimmed = line.trim();
18977
+ if (trimmed.length < MIN_DUPLICATE_LINE_CHARS) continue;
18978
+ totalCountedLines++;
18979
+ const count = (seenLines.get(trimmed) ?? 0) + 1;
18980
+ seenLines.set(trimmed, count);
18981
+ if (count > 1) duplicateLines++;
18982
+ }
18983
+ if (totalCountedLines >= 20 && duplicateLines / totalCountedLines > .5) return true;
18966
18984
  return false;
18967
18985
  }
18968
18986
  /**
18987
+ * Build a single-line diagnostic description of output flagged by
18988
+ * {@link detectDegenerateRepetition}. Used when logging or surfacing a
18989
+ * degenerate-output failure so the discarded model output can be inspected —
18990
+ * without it there is no way to tell a real repetition loop apart from a
18991
+ * detector false-positive on legitimately repetitive content.
18992
+ *
18993
+ * Reuses the detector's sampling parameters (200-char windows, ~50 samples)
18994
+ * so the reported duplicate ratio and most-repeated window match what
18995
+ * triggered the detection. Snippets are JSON-escaped so the result stays on
18996
+ * one line.
18997
+ */
18998
+ function describeDegenerateOutput(text, snippetChars = 400) {
18999
+ const windowSize = 200;
19000
+ const step = Math.max(1, Math.floor(text.length / 50));
19001
+ const seen = /* @__PURE__ */ new Map();
19002
+ let duplicateWindows = 0;
19003
+ let totalWindows = 0;
19004
+ for (let i = 0; i + windowSize <= text.length; i += step) {
19005
+ const window = text.slice(i, i + windowSize);
19006
+ totalWindows++;
19007
+ const count = (seen.get(window) ?? 0) + 1;
19008
+ seen.set(window, count);
19009
+ if (count > 1) duplicateWindows++;
19010
+ }
19011
+ let topWindow = "";
19012
+ let topCount = 0;
19013
+ for (const [window, count] of seen) if (count > topCount) {
19014
+ topCount = count;
19015
+ topWindow = window;
19016
+ }
19017
+ let longestLine = 0;
19018
+ const seenLines = /* @__PURE__ */ new Map();
19019
+ let duplicateLines = 0;
19020
+ let totalCountedLines = 0;
19021
+ for (const line of text.split("\n")) {
19022
+ if (line.length > longestLine) longestLine = line.length;
19023
+ const trimmed = line.trim();
19024
+ if (trimmed.length < MIN_DUPLICATE_LINE_CHARS) continue;
19025
+ totalCountedLines++;
19026
+ const count = (seenLines.get(trimmed) ?? 0) + 1;
19027
+ seenLines.set(trimmed, count);
19028
+ if (count > 1) duplicateLines++;
19029
+ }
19030
+ const duplicateRatio = totalWindows > 0 ? (duplicateWindows / totalWindows).toFixed(2) : "n/a";
19031
+ const duplicateLineRatio = totalCountedLines > 0 ? (duplicateLines / totalCountedLines).toFixed(2) : "n/a";
19032
+ const parts = [
19033
+ `length=${text.length}`,
19034
+ `sampledWindows=${totalWindows}`,
19035
+ `duplicateRatio=${duplicateRatio}`,
19036
+ `duplicateLineRatio=${duplicateLineRatio}`,
19037
+ `countedLines=${totalCountedLines}`,
19038
+ `longestLine=${longestLine}`,
19039
+ `topWindowCount=${topCount}`
19040
+ ];
19041
+ if (topCount > 1) parts.push(`topWindow=${JSON.stringify(topWindow)}`);
19042
+ parts.push(`head=${JSON.stringify(text.slice(0, snippetChars))}`);
19043
+ if (text.length > snippetChars * 2) parts.push(`tail=${JSON.stringify(text.slice(-snippetChars))}`);
19044
+ return parts.join(" ");
19045
+ }
19046
+ /**
18969
19047
  * Check if observations contain a Current Task section.
18970
19048
  * Supports both XML format and legacy markdown format.
18971
19049
  */
@@ -19230,7 +19308,19 @@ async function withOmTracingSpan({ phase, model, inputTokens, requestContext, ob
19230
19308
  });
19231
19309
  const childObservabilityContext = (0, _mastra_core_observability.createObservabilityContext)({ currentSpan: span });
19232
19310
  if (!span) return callback(childObservabilityContext);
19233
- return span.executeInContext(() => callback(childObservabilityContext));
19311
+ return span.executeInContext(async () => {
19312
+ try {
19313
+ const result = await callback(childObservabilityContext);
19314
+ span.end();
19315
+ return result;
19316
+ } catch (error) {
19317
+ span.error({
19318
+ error,
19319
+ endSpan: true
19320
+ });
19321
+ throw error;
19322
+ }
19323
+ });
19234
19324
  }
19235
19325
  //#endregion
19236
19326
  //#region src/processors/observational-memory/observer-runner.ts
@@ -19368,13 +19458,13 @@ var ObserverRunner = class {
19368
19458
  let parsed = parseObserverOutput(result.text, activeExtractors);
19369
19459
  let retriedDueToDegenerate = false;
19370
19460
  if (parsed.degenerate) {
19371
- omDebug(`[OM:callObserver] degenerate repetition detected, retrying once`);
19461
+ omDebug(`[OM:callObserver] degenerate repetition detected, retrying once. ${describeDegenerateOutput(result.text, 2e3)}`);
19372
19462
  result = await doGenerate();
19373
19463
  parsed = parseObserverOutput(result.text, activeExtractors);
19374
19464
  retriedDueToDegenerate = true;
19375
19465
  if (parsed.degenerate) {
19376
- omDebug(`[OM:callObserver] degenerate repetition on retry, failing`);
19377
- throw new Error("Observer produced degenerate output after retry");
19466
+ omDebug(`[OM:callObserver] degenerate repetition on retry, failing. ${describeDegenerateOutput(result.text, 2e3)}`);
19467
+ throw new Error(`Observer produced degenerate output after retry. ${describeDegenerateOutput(result.text)}`);
19378
19468
  }
19379
19469
  }
19380
19470
  const structuredExtraction = await extractStructuredValues({
@@ -19518,13 +19608,13 @@ var ObserverRunner = class {
19518
19608
  let parsed = parseMultiThreadObserverOutput(result.text, activeExtractors);
19519
19609
  let retriedDueToDegenerate = false;
19520
19610
  if (parsed.degenerate) {
19521
- omDebug(`[OM:callMultiThreadObserver] degenerate repetition detected, retrying once`);
19611
+ omDebug(`[OM:callMultiThreadObserver] degenerate repetition detected, retrying once. ${describeDegenerateOutput(result.text, 2e3)}`);
19522
19612
  result = await doGenerate();
19523
19613
  parsed = parseMultiThreadObserverOutput(result.text, activeExtractors);
19524
19614
  retriedDueToDegenerate = true;
19525
19615
  if (parsed.degenerate) {
19526
- omDebug(`[OM:callMultiThreadObserver] degenerate repetition on retry, failing`);
19527
- throw new Error("Multi-thread observer produced degenerate output after retry");
19616
+ omDebug(`[OM:callMultiThreadObserver] degenerate repetition on retry, failing. ${describeDegenerateOutput(result.text, 2e3)}`);
19617
+ throw new Error(`Multi-thread observer produced degenerate output after retry. ${describeDegenerateOutput(result.text)}`);
19528
19618
  }
19529
19619
  }
19530
19620
  const structuredExtractionByThread = /* @__PURE__ */ new Map();
@@ -24367,10 +24457,11 @@ ObservationStrategy.create = ((om, opts) => {
24367
24457
  });
24368
24458
  //#endregion
24369
24459
  //#region src/processors/observational-memory/observation-turn/load-memory-context.ts
24370
- async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId }) {
24460
+ async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
24371
24461
  const ctx = await memory.getContext({
24372
24462
  threadId,
24373
- resourceId
24463
+ resourceId,
24464
+ runState
24374
24465
  });
24375
24466
  for (const msg of ctx.messages) if (msg.role !== "system") messageList.add(msg, "memory");
24376
24467
  return ctx;
@@ -24828,10 +24919,11 @@ var ObservationTurn = class {
24828
24919
  * If a MemoryContextProvider is passed, loads historical messages and adds
24829
24920
  * them to the MessageList. Without a provider, only fetches/caches the record.
24830
24921
  */
24831
- async start(memory) {
24922
+ async start(memory, runState) {
24832
24923
  if (this._started) throw new Error("Turn already started");
24833
24924
  this._started = true;
24834
24925
  this._record = await this.om.getOrCreateRecord(this.threadId, this.resourceId);
24926
+ runState?.set(`observational-memory:record:${this.threadId}:${this.resourceId ?? ""}`, this._record);
24835
24927
  this._generationCountAtStart = this._record.generationCount;
24836
24928
  this.memory = memory;
24837
24929
  if (memory) {
@@ -24839,7 +24931,8 @@ var ObservationTurn = class {
24839
24931
  memory,
24840
24932
  messageList: this.messageList,
24841
24933
  threadId: this.threadId,
24842
- resourceId: this.resourceId
24934
+ resourceId: this.resourceId,
24935
+ runState
24843
24936
  });
24844
24937
  this._context = {
24845
24938
  messages: ctx.messages,
@@ -25401,8 +25494,6 @@ var ReflectorRunner = class {
25401
25494
  };
25402
25495
  let reflectedTokens = 0;
25403
25496
  let attemptNumber = 0;
25404
- /** Observations from the previous attempt, used to detect a no-progress ladder. */
25405
- let previousObservations;
25406
25497
  while (currentLevel <= maxLevel) {
25407
25498
  attemptNumber++;
25408
25499
  const isRetry = attemptNumber > 1;
@@ -25467,7 +25558,7 @@ var ReflectorRunner = class {
25467
25558
  finalProviderMetadata = result.providerMetadata ?? finalProviderMetadata;
25468
25559
  parsed = parseReflectorOutput(result.text, observations, activeExtractors);
25469
25560
  if (parsed.degenerate) {
25470
- omDebug(`[OM:callReflector] attempt #${attemptNumber}: degenerate repetition detected, treating as compression failure`);
25561
+ omDebug(`[OM:callReflector] attempt #${attemptNumber}: degenerate repetition detected, treating as compression failure. ${describeDegenerateOutput(result.text, 2e3)}`);
25471
25562
  reflectedTokens = originalTokens;
25472
25563
  } else reflectedTokens = this.tokenCounter.countObservations(parsed.observations);
25473
25564
  omDebug(`[OM:callReflector] attempt #${attemptNumber} parsed: reflectedTokens=${reflectedTokens}, targetThreshold=${targetThreshold}, compressionValid=${validateCompression(reflectedTokens, targetThreshold)}, parsedObsLen=${parsed.observations?.length}, degenerate=${parsed.degenerate ?? false}`);
@@ -25476,11 +25567,6 @@ var ReflectorRunner = class {
25476
25567
  omDebug(`[OM:callReflector] degenerate output persists at maxLevel=${maxLevel}, breaking`);
25477
25568
  break;
25478
25569
  }
25479
- if (!parsed.degenerate && previousObservations !== void 0 && parsed.observations === previousObservations) {
25480
- omDebug(`[OM:callReflector] attempt #${attemptNumber} returned output identical to the previous attempt; escalating cannot help, stopping the ladder`);
25481
- break;
25482
- }
25483
- previousObservations = parsed.observations;
25484
25570
  if (streamContext?.writer) {
25485
25571
  const failedMarker = createObservationFailedMarker({
25486
25572
  cycleId: streamContext.cycleId,
@@ -25564,52 +25650,51 @@ var ReflectorRunner = class {
25564
25650
  this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
25565
25651
  omError("[OM] Failed to set buffering reflection flag", err);
25566
25652
  });
25567
- reflectionHooks?.onReflectionStart?.();
25568
- const asyncOp = this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal).then((outcome) => {
25653
+ const asyncOp = (async () => {
25654
+ let outcome;
25655
+ let reflectionError;
25569
25656
  try {
25570
- reflectionHooks?.onReflectionEnd?.({
25571
- usage: outcome?.usage,
25572
- ...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
25573
- });
25574
- } catch (hookError) {
25575
- omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
25576
- }
25577
- }, async (error) => {
25578
- if (writer) try {
25579
- const failedMarker = createBufferingFailedMarker({
25580
- cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
25581
- operationType: "reflection",
25582
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
25583
- tokensAttempted: observationTokens,
25584
- error: error instanceof Error ? error.message : String(error),
25585
- recordId: record.id,
25586
- threadId: record.threadId ?? ""
25587
- });
25588
- writer.custom({
25589
- ...failedMarker,
25590
- transient: true
25591
- }).catch(() => {});
25592
- await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
25593
- } catch (markerError) {
25594
- omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
25595
- }
25596
- omError("[OM] Async buffered reflection failed", error);
25597
- try {
25598
- reflectionHooks?.onReflectionEnd?.({
25599
- usage: void 0,
25600
- error: error instanceof Error ? error : new Error(String(error))
25657
+ await reflectionHooks?.onReflectionStart?.();
25658
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal);
25659
+ } catch (error) {
25660
+ reflectionError = error instanceof Error ? error : new Error(String(error));
25661
+ if (writer) try {
25662
+ const failedMarker = createBufferingFailedMarker({
25663
+ cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
25664
+ operationType: "reflection",
25665
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
25666
+ tokensAttempted: observationTokens,
25667
+ error: reflectionError.message,
25668
+ recordId: record.id,
25669
+ threadId: record.threadId ?? ""
25670
+ });
25671
+ writer.custom({
25672
+ ...failedMarker,
25673
+ transient: true
25674
+ }).catch(() => {});
25675
+ await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
25676
+ } catch (markerError) {
25677
+ omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
25678
+ }
25679
+ omError("[OM] Async buffered reflection failed", error);
25680
+ BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
25681
+ } finally {
25682
+ try {
25683
+ await reflectionHooks?.onReflectionEnd?.({
25684
+ usage: outcome?.usage,
25685
+ error: reflectionError,
25686
+ ...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
25687
+ });
25688
+ } catch (hookError) {
25689
+ omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
25690
+ }
25691
+ BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
25692
+ unregisterOp(record.id, "bufferingReflection");
25693
+ this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
25694
+ omError("[OM] Failed to clear buffering reflection flag", err);
25601
25695
  });
25602
- } catch (hookError) {
25603
- omError("[OM] onReflectionEnd hook failed after async buffered reflection failure", hookError);
25604
25696
  }
25605
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
25606
- }).finally(() => {
25607
- BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
25608
- unregisterOp(record.id, "bufferingReflection");
25609
- this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
25610
- omError("[OM] Failed to clear buffering reflection flag", err);
25611
- });
25612
- });
25697
+ })();
25613
25698
  BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
25614
25699
  }
25615
25700
  /**
@@ -25910,8 +25995,15 @@ var ReflectorRunner = class {
25910
25995
  let reflectionUsage;
25911
25996
  let reflectionProviderMetadata;
25912
25997
  let reflectionError;
25913
- reflectionHooks?.onReflectionStart?.();
25998
+ let lifecycleError;
25914
25999
  try {
26000
+ try {
26001
+ await reflectionHooks?.onReflectionStart?.();
26002
+ } catch (error) {
26003
+ lifecycleError = error;
26004
+ reflectionError = error instanceof Error ? error : new Error(String(error));
26005
+ throw error;
26006
+ }
25915
26007
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
25916
26008
  const reflectResult = await this.call(record.activeObservations, void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
25917
26009
  reflectionUsage = reflectResult.usage;
@@ -25981,18 +26073,27 @@ var ReflectorRunner = class {
25981
26073
  await this.persistMarkerToStorage(failedMarker, threadId, record.resourceId ?? void 0);
25982
26074
  }
25983
26075
  reflectionError = error instanceof Error ? error : new Error(String(error));
25984
- if (abortSignal?.aborted) throw error;
26076
+ if (lifecycleError !== void 0 || abortSignal?.aborted) throw error;
25985
26077
  omError("[OM] Reflection failed", error);
25986
26078
  } finally {
25987
- await this.storage.setReflectingFlag(record.id, false);
25988
26079
  try {
25989
- reflectionHooks?.onReflectionEnd?.({
26080
+ await this.storage.setReflectingFlag(record.id, false);
26081
+ } finally {
26082
+ unregisterOp(record.id, "reflecting");
26083
+ }
26084
+ let endHookError;
26085
+ try {
26086
+ await reflectionHooks?.onReflectionEnd?.({
25990
26087
  usage: reflectionUsage,
25991
26088
  error: reflectionError,
25992
26089
  ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
25993
26090
  });
25994
- } finally {
25995
- unregisterOp(record.id, "reflecting");
26091
+ } catch (error) {
26092
+ endHookError = error;
26093
+ }
26094
+ if (endHookError !== void 0) {
26095
+ if (lifecycleError === void 0 && !abortSignal?.aborted) throw endHookError;
26096
+ omDebug(`[OM:hooks] onReflectionEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
25996
26097
  }
25997
26098
  }
25998
26099
  }
@@ -26453,6 +26554,8 @@ var ObservationalMemory = class ObservationalMemory {
26453
26554
  onIndexObservations;
26454
26555
  /** Config-level lifecycle hooks fired for every observation/reflection cycle. */
26455
26556
  hooks;
26557
+ /** Execution policy for config-level hooks on manual and turn-synchronous cycles. */
26558
+ hookExecution;
26456
26559
  /** Observer agent runner — handles LLM calls for extracting observations. */
26457
26560
  observer;
26458
26561
  /** Reflector agent runner — handles LLM calls for compressing observations. */
@@ -26559,6 +26662,7 @@ var ObservationalMemory = class ObservationalMemory {
26559
26662
  this.retrievalSearch = typeof config.retrieval === "object" && Boolean(config.retrieval.vector);
26560
26663
  this.onIndexObservations = config.onIndexObservations;
26561
26664
  this.hooks = config.hooks;
26665
+ this.hookExecution = config.hookExecution ?? "non-blocking";
26562
26666
  this.mastra = config.mastra;
26563
26667
  this.memory = config.memory;
26564
26668
  this.curationCadence = config.curationCadence;
@@ -28351,57 +28455,54 @@ ${formattedMessages}
28351
28455
  };
28352
28456
  }
28353
28457
  /**
28354
- * Compose the config-level hooks with optional per-call hooks into a single
28355
- * `ObserveHooks` object, binding call context onto the config-level
28356
- * callbacks. Config-level hooks are guarded so a throwing consumer hook can
28357
- * never fail an observation/reflection cycle; per-call hooks keep their
28358
- * existing payloads and propagation semantics. Returns undefined when
28359
- * neither is configured, so call sites stay zero-cost.
28360
- *
28361
- * Used internally by every pipeline path (manual observe/reflect,
28362
- * turn-engine sync observation, async buffering); public only so the
28363
- * observation turn engine can thread config-level reflection hooks into
28364
- * reflector calls.
28458
+ * Compose config-level hooks with optional per-call hooks and bind context to
28459
+ * config-level callbacks. The configured policy applies unless a background
28460
+ * path explicitly requests non-blocking invocation.
28365
28461
  *
28366
28462
  * @internal
28367
28463
  */
28368
- composeHooks(callHooks, context) {
28464
+ composeHooks(callHooks, context, execution = "configured") {
28369
28465
  const configHooks = this.hooks;
28370
28466
  if (!configHooks) return callHooks;
28371
28467
  if (!callHooks && !Object.keys(configHooks).length) return void 0;
28372
- const fireConfigHook = (name, arg) => {
28468
+ const shouldAwaitConfig = execution === "configured" && this.hookExecution === "await";
28469
+ const invokeConfigHook = async (name, arg) => {
28373
28470
  const hook = configHooks[name];
28374
28471
  if (!hook) return;
28472
+ if (shouldAwaitConfig) {
28473
+ await hook(arg);
28474
+ return;
28475
+ }
28375
28476
  const logHookFailure = (error) => omDebug(`[OM:hooks] config-level ${name} hook failed: ${error instanceof Error ? error.message : String(error)}`);
28376
28477
  try {
28377
- const out = hook(arg);
28378
- if (out && typeof out.then === "function") out.then(void 0, logHookFailure);
28478
+ const result = hook(arg);
28479
+ if (result && typeof result.then === "function") result.then(void 0, logHookFailure);
28379
28480
  } catch (error) {
28380
28481
  logHookFailure(error);
28381
28482
  }
28382
28483
  };
28383
28484
  return {
28384
- onObservationStart: () => {
28385
- fireConfigHook("onObservationStart", context);
28386
- callHooks?.onObservationStart?.();
28485
+ onObservationStart: async () => {
28486
+ await invokeConfigHook("onObservationStart", context);
28487
+ await callHooks?.onObservationStart?.();
28387
28488
  },
28388
- onObservationEnd: (result) => {
28389
- fireConfigHook("onObservationEnd", {
28489
+ onObservationEnd: async (result) => {
28490
+ await invokeConfigHook("onObservationEnd", {
28390
28491
  ...context,
28391
28492
  ...result
28392
28493
  });
28393
- callHooks?.onObservationEnd?.(result);
28494
+ await callHooks?.onObservationEnd?.(result);
28394
28495
  },
28395
- onReflectionStart: () => {
28396
- fireConfigHook("onReflectionStart", context);
28397
- callHooks?.onReflectionStart?.();
28496
+ onReflectionStart: async () => {
28497
+ await invokeConfigHook("onReflectionStart", context);
28498
+ await callHooks?.onReflectionStart?.();
28398
28499
  },
28399
- onReflectionEnd: (result) => {
28400
- fireConfigHook("onReflectionEnd", {
28500
+ onReflectionEnd: async (result) => {
28501
+ await invokeConfigHook("onReflectionEnd", {
28401
28502
  ...context,
28402
28503
  ...result
28403
28504
  });
28404
- callHooks?.onReflectionEnd?.(result);
28505
+ await callHooks?.onReflectionEnd?.(result);
28405
28506
  }
28406
28507
  };
28407
28508
  }
@@ -28414,22 +28515,29 @@ ${formattedMessages}
28414
28515
  * end hook reports `error` for failed cycles even though nothing throws.
28415
28516
  */
28416
28517
  async runBufferedObservationCycle(context, run) {
28417
- const hooks = this.composeHooks(void 0, context);
28418
- hooks?.onObservationStart?.();
28518
+ const hooks = this.composeHooks(void 0, context, "non-blocking");
28419
28519
  let runResult;
28420
28520
  let runError;
28521
+ let lifecycleError;
28421
28522
  try {
28523
+ await hooks?.onObservationStart?.();
28422
28524
  runResult = await run();
28423
28525
  return runResult;
28424
28526
  } catch (error) {
28527
+ lifecycleError = error;
28425
28528
  runError = error instanceof Error ? error : new Error(String(error));
28426
28529
  throw error;
28427
28530
  } finally {
28428
- hooks?.onObservationEnd?.({
28429
- usage: runResult?.usage,
28430
- error: runError ?? runResult?.error,
28431
- ...runResult?.providerMetadata ? { providerMetadata: runResult.providerMetadata } : {}
28432
- });
28531
+ try {
28532
+ await hooks?.onObservationEnd?.({
28533
+ usage: runResult?.usage,
28534
+ error: runError ?? runResult?.error,
28535
+ ...runResult?.providerMetadata ? { providerMetadata: runResult.providerMetadata } : {}
28536
+ });
28537
+ } catch (endHookError) {
28538
+ if (lifecycleError === void 0) throw endHookError;
28539
+ omDebug(`[OM:hooks] async-buffer onObservationEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
28540
+ }
28433
28541
  }
28434
28542
  }
28435
28543
  /**
@@ -28457,18 +28565,21 @@ ${formattedMessages}
28457
28565
  let observed = false;
28458
28566
  let observationUsage;
28459
28567
  let observationProviderMetadata;
28568
+ let observationError;
28569
+ let lifecycleError;
28570
+ let observationStarted = false;
28460
28571
  let generationBefore = -1;
28461
- await this.withLock(lockKey, async () => {
28462
- const freshRecord = await this.getOrCreateRecord(threadId, resourceId);
28463
- generationBefore = freshRecord.generationCount;
28464
- const unobservedMessages = messages ? this.getUnobservedMessages(messages, freshRecord) : await this.loadMessagesFromStorage(threadId, resourceId, freshRecord.lastObservedAt ? new Date(freshRecord.lastObservedAt) : void 0);
28465
- if (!this.meetsObservationThreshold({
28466
- record: freshRecord,
28467
- unobservedTokens: await this.tokenCounter.countMessagesAsync(unobservedMessages)
28468
- })) return;
28469
- hooks?.onObservationStart?.();
28470
- let observationError;
28471
- try {
28572
+ try {
28573
+ await this.withLock(lockKey, async () => {
28574
+ const freshRecord = await this.getOrCreateRecord(threadId, resourceId);
28575
+ generationBefore = freshRecord.generationCount;
28576
+ const unobservedMessages = messages ? this.getUnobservedMessages(messages, freshRecord) : await this.loadMessagesFromStorage(threadId, resourceId, freshRecord.lastObservedAt ? new Date(freshRecord.lastObservedAt) : void 0);
28577
+ if (!this.meetsObservationThreshold({
28578
+ record: freshRecord,
28579
+ unobservedTokens: await this.tokenCounter.countMessagesAsync(unobservedMessages)
28580
+ })) return;
28581
+ observationStarted = true;
28582
+ await hooks?.onObservationStart?.();
28472
28583
  const result = await ObservationStrategy.create(this, {
28473
28584
  record: freshRecord,
28474
28585
  threadId,
@@ -28486,17 +28597,22 @@ ${formattedMessages}
28486
28597
  observed = result.observed;
28487
28598
  observationUsage = result.usage;
28488
28599
  observationProviderMetadata = result.providerMetadata;
28489
- } catch (error) {
28490
- observationError = error instanceof Error ? error : new Error(String(error));
28491
- throw error;
28492
- } finally {
28493
- hooks?.onObservationEnd?.({
28494
- usage: observationUsage,
28495
- error: observationError,
28496
- ...observationProviderMetadata ? { providerMetadata: observationProviderMetadata } : {}
28497
- });
28498
- }
28499
- });
28600
+ });
28601
+ } catch (error) {
28602
+ lifecycleError = error;
28603
+ observationError = error instanceof Error ? error : new Error(String(error));
28604
+ }
28605
+ if (observationStarted) try {
28606
+ await hooks?.onObservationEnd?.({
28607
+ usage: observationUsage,
28608
+ error: observationError,
28609
+ ...observationProviderMetadata ? { providerMetadata: observationProviderMetadata } : {}
28610
+ });
28611
+ } catch (endHookError) {
28612
+ if (lifecycleError === void 0) throw endHookError;
28613
+ omDebug(`[OM:hooks] onObservationEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
28614
+ }
28615
+ if (lifecycleError !== void 0) throw lifecycleError;
28500
28616
  const record = await this.getOrCreateRecord(threadId, resourceId);
28501
28617
  const reflected = record.generationCount > generationBefore && generationBefore >= 0;
28502
28618
  if (observed) this.maybeTriggerCadenceCuration(threadId, resourceId, record, requestContext).catch((error) => {
@@ -28570,11 +28686,18 @@ ${formattedMessages}
28570
28686
  resourceId,
28571
28687
  trigger: "manual"
28572
28688
  });
28573
- hooks?.onReflectionStart?.();
28574
28689
  let reflectionUsage;
28575
28690
  let reflectionProviderMetadata;
28576
28691
  let reflectionError;
28692
+ let lifecycleError;
28577
28693
  try {
28694
+ try {
28695
+ await hooks?.onReflectionStart?.();
28696
+ } catch (error) {
28697
+ lifecycleError = error;
28698
+ reflectionError = error instanceof Error ? error : new Error(String(error));
28699
+ throw error;
28700
+ }
28578
28701
  const thread = await this.storage.getThreadById({ threadId });
28579
28702
  const previousOmMetadata = (0, _mastra_core_memory.getThreadOMMetadata)(thread?.metadata);
28580
28703
  const priorExtractedValues = getPriorExtractedValues(previousOmMetadata, this.reflectionConfig.extractors);
@@ -28612,6 +28735,7 @@ ${formattedMessages}
28612
28735
  };
28613
28736
  } catch (error) {
28614
28737
  reflectionError = error instanceof Error ? error : new Error(String(error));
28738
+ if (lifecycleError !== void 0) throw error;
28615
28739
  omError("[OM] reflect() failed", error);
28616
28740
  return {
28617
28741
  reflected: false,
@@ -28619,13 +28743,25 @@ ${formattedMessages}
28619
28743
  usage: void 0
28620
28744
  };
28621
28745
  } finally {
28622
- hooks?.onReflectionEnd?.({
28623
- usage: reflectionUsage,
28624
- error: reflectionError,
28625
- ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
28626
- });
28627
- await this.storage.setReflectingFlag(record.id, false);
28628
- unregisterOp(record.id, "reflecting");
28746
+ try {
28747
+ await this.storage.setReflectingFlag(record.id, false);
28748
+ } finally {
28749
+ unregisterOp(record.id, "reflecting");
28750
+ }
28751
+ let endHookError;
28752
+ try {
28753
+ await hooks?.onReflectionEnd?.({
28754
+ usage: reflectionUsage,
28755
+ error: reflectionError,
28756
+ ...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
28757
+ });
28758
+ } catch (error) {
28759
+ endHookError = error;
28760
+ }
28761
+ if (endHookError !== void 0) {
28762
+ if (lifecycleError === void 0) throw endHookError;
28763
+ omDebug(`[OM:hooks] onReflectionEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
28764
+ }
28629
28765
  }
28630
28766
  }
28631
28767
  /**
@@ -28921,7 +29057,9 @@ var ObservationalMemoryProcessor = class {
28921
29057
  return messageList;
28922
29058
  }
28923
29059
  const { threadId, resourceId } = context;
28924
- const readOnly = (0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly;
29060
+ const memoryContext = (0, _mastra_core_memory.parseMemoryRequestContext)(requestContext);
29061
+ const runState = memoryContext?.runState?.();
29062
+ const readOnly = memoryContext?.memoryConfig?.readOnly;
28925
29063
  const actorModelContext = model?.modelId ? {
28926
29064
  provider: model.provider,
28927
29065
  modelId: model.modelId,
@@ -28938,7 +29076,8 @@ var ObservationalMemoryProcessor = class {
28938
29076
  memory: this.memory,
28939
29077
  messageList,
28940
29078
  threadId,
28941
- resourceId
29079
+ resourceId,
29080
+ runState
28942
29081
  });
28943
29082
  const systemMessages = ctx.omRecord ? await this.engine.buildContextSystemMessages({
28944
29083
  threadId,
@@ -28979,7 +29118,7 @@ var ObservationalMemoryProcessor = class {
28979
29118
  this.turn.sendStateSignal = args.sendStateSignal;
28980
29119
  this.turn.agent = args.agent;
28981
29120
  this.turn.requestContext = requestContext;
28982
- await this.turn.start(this.memory);
29121
+ await this.turn.start(this.memory, runState);
28983
29122
  if (stepNumber === 0 && this.temporalMarkers) await insertTemporalGapMarkers({
28984
29123
  messageList,
28985
29124
  sendSignal: args.sendSignal
@@ -30149,14 +30288,18 @@ ${workingMemory}`;
30149
30288
  if (!this.threadConfig.workingMemory?.enabled) return null;
30150
30289
  return extractWorkingMemoryContent(text)?.trim() ?? null;
30151
30290
  }
30152
- async getWorkingMemory({ threadId, resourceId, memoryConfig }) {
30291
+ async getWorkingMemory({ threadId, resourceId, memoryConfig, runState }) {
30153
30292
  const config = this.getMergedThreadConfig(memoryConfig || {});
30154
30293
  if (!config.workingMemory?.enabled) return null;
30155
30294
  const scope = config.workingMemory.scope || "resource";
30156
30295
  let workingMemoryData = null;
30157
30296
  if (scope === "resource" && !resourceId) throw new Error("Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.");
30158
- if (scope === "resource" && resourceId) workingMemoryData = (await (await this.getMemoryStore()).getResourceById({ resourceId }))?.workingMemory || null;
30159
- else workingMemoryData = (await this.getThreadById({ threadId }))?.metadata?.workingMemory;
30297
+ if (scope === "resource" && resourceId) {
30298
+ const loadWorkingMemory = async () => {
30299
+ return (await (await this.getMemoryStore()).getResourceById({ resourceId }))?.workingMemory || null;
30300
+ };
30301
+ workingMemoryData = runState ? await runState.load(`working-memory:resource:${resourceId}`, loadWorkingMemory) : await loadWorkingMemory();
30302
+ } else workingMemoryData = (runState?.threadLoaded ? runState.thread : await this.getThreadById({ threadId }))?.metadata?.workingMemory;
30160
30303
  if (!workingMemoryData) return null;
30161
30304
  return workingMemoryData;
30162
30305
  }
@@ -30188,16 +30331,18 @@ ${workingMemory}`;
30188
30331
  content: (config.workingMemory.template || this.defaultWorkingMemoryTemplate).trim()
30189
30332
  };
30190
30333
  }
30191
- async getSystemMessage({ threadId, resourceId, memoryConfig }) {
30334
+ async getSystemMessage({ threadId, resourceId, memoryConfig, runState }) {
30192
30335
  const config = this.getMergedThreadConfig(memoryConfig);
30193
30336
  this.assertWorkingMemoryStateSignalsCompatibility(config);
30194
30337
  if (!config.workingMemory?.enabled) return null;
30195
30338
  if (config.workingMemory?.useStateSignals) return null;
30196
- const workingMemoryTemplate = await this.getWorkingMemoryTemplate({ memoryConfig });
30339
+ const loadTemplate = () => this.getWorkingMemoryTemplate({ memoryConfig });
30340
+ const workingMemoryTemplate = runState ? await runState.load("working-memory:template", loadTemplate) : await loadTemplate();
30197
30341
  const workingMemoryData = await this.getWorkingMemory({
30198
30342
  threadId,
30199
30343
  resourceId,
30200
- memoryConfig: config
30344
+ memoryConfig: config,
30345
+ runState
30201
30346
  });
30202
30347
  if (!workingMemoryTemplate) return null;
30203
30348
  const workingMemoryConfig = config.workingMemory;
@@ -30230,7 +30375,7 @@ ${workingMemory}`;
30230
30375
  * ```
30231
30376
  */
30232
30377
  async getContext(opts) {
30233
- const { threadId, resourceId, memoryConfig } = opts;
30378
+ const { threadId, resourceId, memoryConfig, runState } = opts;
30234
30379
  const config = this.getMergedThreadConfig(memoryConfig);
30235
30380
  const memoryStore = await this.getMemoryStore();
30236
30381
  const systemParts = [];
@@ -30240,10 +30385,14 @@ ${workingMemory}`;
30240
30385
  let otherThreadsContext;
30241
30386
  const omEngine = await this.omEngine;
30242
30387
  if (omEngine) {
30243
- omRecord = await omEngine.getRecord(threadId, resourceId);
30388
+ const loadOmRecord = () => omEngine.getRecord(threadId, resourceId);
30389
+ omRecord = runState ? await runState.load(`observational-memory:record:${threadId}:${resourceId ?? ""}`, loadOmRecord) : await loadOmRecord();
30244
30390
  if (omRecord?.activeObservations) {
30245
30391
  hasObservations = true;
30246
- if (omEngine.scope === "resource" && resourceId) otherThreadsContext = await omEngine.getOtherThreadsContext(resourceId, threadId);
30392
+ if (omEngine.scope === "resource" && resourceId) {
30393
+ const loadOtherThreadsContext = () => omEngine.getOtherThreadsContext(resourceId, threadId);
30394
+ otherThreadsContext = runState ? await runState.load(`observational-memory:other-threads:${resourceId}:${threadId}:${omRecord.lastObservedAt ?? ""}`, loadOtherThreadsContext) : await loadOtherThreadsContext();
30395
+ }
30247
30396
  const obsSystemMessage = await omEngine.buildContextSystemMessage({
30248
30397
  threadId,
30249
30398
  resourceId,
@@ -30271,30 +30420,41 @@ ${workingMemory}`;
30271
30420
  const workingMemoryMessage = await this.getSystemMessage({
30272
30421
  threadId,
30273
30422
  resourceId,
30274
- memoryConfig: config
30423
+ memoryConfig: config,
30424
+ runState
30275
30425
  });
30276
30426
  if (workingMemoryMessage) systemParts.push(workingMemoryMessage);
30277
30427
  let messages;
30278
30428
  if (omEngine && omRecord) {
30279
30429
  const dateFilter = omRecord.lastObservedAt ? { dateRange: { start: new Date(new Date(omRecord.lastObservedAt).getTime() + 1) } } : void 0;
30280
- if (omEngine.scope === "resource" && resourceId) messages = (await memoryStore.listMessagesByResourceId({
30281
- resourceId,
30282
- orderBy: {
30283
- field: "createdAt",
30284
- direction: "ASC"
30285
- },
30286
- perPage: false,
30287
- filter: dateFilter
30288
- })).messages;
30289
- else messages = (await memoryStore.listMessages({
30290
- threadId,
30291
- orderBy: {
30292
- field: "createdAt",
30293
- direction: "ASC"
30294
- },
30295
- perPage: false,
30296
- filter: dateFilter
30297
- })).messages;
30430
+ const boundary = omRecord.lastObservedAt ? new Date(omRecord.lastObservedAt).toISOString() : "";
30431
+ if (omEngine.scope === "resource" && resourceId) {
30432
+ const loadMessages = async () => {
30433
+ return (await memoryStore.listMessagesByResourceId({
30434
+ resourceId,
30435
+ orderBy: {
30436
+ field: "createdAt",
30437
+ direction: "ASC"
30438
+ },
30439
+ perPage: false,
30440
+ filter: dateFilter
30441
+ })).messages;
30442
+ };
30443
+ messages = runState ? await runState.load(`observational-memory:messages:resource:${resourceId}:${boundary}`, loadMessages) : await loadMessages();
30444
+ } else {
30445
+ const loadMessages = async () => {
30446
+ return (await memoryStore.listMessages({
30447
+ threadId,
30448
+ orderBy: {
30449
+ field: "createdAt",
30450
+ direction: "ASC"
30451
+ },
30452
+ perPage: false,
30453
+ filter: dateFilter
30454
+ })).messages;
30455
+ };
30456
+ messages = runState ? await runState.load(`observational-memory:messages:thread:${threadId}:${boundary}`, loadMessages) : await loadMessages();
30457
+ }
30298
30458
  } else {
30299
30459
  const lastMessages = config.lastMessages;
30300
30460
  if (lastMessages === false) messages = [];
@@ -31599,4 +31759,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
31599
31759
  }
31600
31760
  });
31601
31761
 
31602
- //# sourceMappingURL=src-Ik0ksTOt.cjs.map
31762
+ //# sourceMappingURL=src-CIBCjg2A.cjs.map