@mastra/memory 1.37.1-alpha.3 → 1.38.0-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.
Files changed (29) hide show
  1. package/dist/docs/SKILL.md +2 -2
  2. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  3. package/dist/docs/references/docs-harness-background-tasks.md +13 -10
  4. package/dist/docs/references/docs-memory-overview.md +31 -0
  5. package/dist/docs/references/integrations-databases-redis.md +3 -23
  6. package/dist/docs/references/integrations-databases-valkey.md +2 -0
  7. package/dist/docs/references/reference-memory-observational-memory.md +13 -0
  8. package/dist/index.cjs +1 -1
  9. package/dist/index.d.ts +7 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/processors/index.cjs +1 -1
  13. package/dist/processors/index.js +1 -1
  14. package/dist/processors/observational-memory/context-overflow.d.ts +2 -0
  15. package/dist/processors/observational-memory/context-overflow.d.ts.map +1 -0
  16. package/dist/processors/observational-memory/observational-memory.d.ts +5 -0
  17. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  18. package/dist/processors/observational-memory/processor.d.ts +2 -1
  19. package/dist/processors/observational-memory/processor.d.ts.map +1 -1
  20. package/dist/processors/observational-memory/summarize.d.ts.map +1 -1
  21. package/dist/processors/observational-memory/types.d.ts +14 -0
  22. package/dist/processors/observational-memory/types.d.ts.map +1 -1
  23. package/dist/{src-BU8L6v1o.cjs → src-BfhwVNr7.cjs} +105 -2
  24. package/dist/src-BfhwVNr7.cjs.map +1 -0
  25. package/dist/{src-DWoBX5f9.js → src-CnLuefUv.js} +105 -2
  26. package/dist/src-CnLuefUv.js.map +1 -0
  27. package/package.json +8 -8
  28. package/dist/src-BU8L6v1o.cjs.map +0 -1
  29. package/dist/src-DWoBX5f9.js.map +0 -1
@@ -23823,6 +23823,7 @@ async function summarizeConversation(opts) {
23823
23823
  providerOptions: OBSERVATIONAL_MEMORY_DEFAULTS.observation.providerOptions,
23824
23824
  maxTokensPerBatch: OBSERVATIONAL_MEMORY_DEFAULTS.observation.maxTokensPerBatch,
23825
23825
  bufferOnIdle: false,
23826
+ observeOnContextOverflow: false,
23826
23827
  observeAttachments: "auto",
23827
23828
  instruction: opts.instructions,
23828
23829
  threadTitle: false,
@@ -31317,6 +31318,7 @@ var ObservationalMemory = class ObservationalMemory {
31317
31318
  maxTokensPerBatch: config.observation?.maxTokensPerBatch ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.maxTokensPerBatch,
31318
31319
  bufferTokens: asyncBufferingDisabled ? void 0 : resolveBufferTokens(config.observation?.bufferTokens ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.bufferTokens, config.observation?.messageTokens ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.messageTokens),
31319
31320
  bufferOnIdle: config.observation?.bufferOnIdle ?? false,
31321
+ observeOnContextOverflow: config.observation?.observeOnContextOverflow ?? true,
31320
31322
  bufferActivation: asyncBufferingDisabled ? void 0 : config.observation?.bufferActivation ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.bufferActivation,
31321
31323
  activateAfterIdle: parseActivationTTLConfig(observationActivateAfterIdle, observationActivateAfterIdlePath),
31322
31324
  activateOnProviderChange: config.observation?.activateOnProviderChange ?? config.activateOnProviderChange ?? false,
@@ -33337,7 +33339,9 @@ ${formattedMessages}
33337
33339
  recordInsideLock = freshRecord;
33338
33340
  generationBefore = freshRecord.generationCount;
33339
33341
  const unobservedMessages = messages ? this.getUnobservedMessages(messages, freshRecord) : await this.loadMessagesFromStorage(threadId, resourceId, freshRecord.lastObservedAt ? new Date(freshRecord.lastObservedAt) : void 0);
33340
- if (!this.meetsObservationThreshold({
33342
+ if (opts.force) {
33343
+ if (unobservedMessages.length === 0) return;
33344
+ } else if (!this.meetsObservationThreshold({
33341
33345
  record: freshRecord,
33342
33346
  unobservedTokens: await this.tokenCounter.countMessagesAsync(unobservedMessages)
33343
33347
  })) return;
@@ -33645,6 +33649,55 @@ ${formattedMessages}
33645
33649
  }
33646
33650
  };
33647
33651
  //#endregion
33652
+ //#region src/processors/observational-memory/context-overflow.ts
33653
+ /**
33654
+ * Detects provider errors that reject a request for exceeding the model's context window.
33655
+ *
33656
+ * Providers report this with different codes and wording, so this matches the known shapes
33657
+ * (OpenAI and OpenAI-compatible APIs, Anthropic, Google, Bedrock, xAI, Mistral, local servers)
33658
+ * against the error's message, code, response body and causes.
33659
+ */
33660
+ const CONTEXT_OVERFLOW_PATTERNS = [
33661
+ /context[_ ]length[_ ]exceeded/i,
33662
+ /maximum context length/i,
33663
+ /maximum prompt length/i,
33664
+ /prompt is too long/i,
33665
+ /input is too long/i,
33666
+ /exceed\w*\b[^.]{0,40}\bcontext (?:window|length|limit|size)/i,
33667
+ /input token count[^.]{0,40}exceeds the maximum/i,
33668
+ /reduce the length of the (?:messages|prompt|input)/i
33669
+ ];
33670
+ const MAX_CAUSE_DEPTH = 4;
33671
+ function collectErrorText(error, depth = 0) {
33672
+ if (depth > MAX_CAUSE_DEPTH || error == null) return [];
33673
+ if (typeof error === "string") return [error];
33674
+ if (typeof error !== "object") return [];
33675
+ const record = error;
33676
+ const texts = [];
33677
+ for (const key of [
33678
+ "message",
33679
+ "code",
33680
+ "type",
33681
+ "responseBody"
33682
+ ]) {
33683
+ const value = record[key];
33684
+ if (typeof value === "string") texts.push(value);
33685
+ }
33686
+ if (record.data && typeof record.data === "object") texts.push(...collectErrorText(record.data.error ?? record.data, depth + 1));
33687
+ if (record.error && typeof record.error === "object") texts.push(...collectErrorText(record.error, depth + 1));
33688
+ texts.push(...collectErrorText(record.cause, depth + 1));
33689
+ return texts;
33690
+ }
33691
+ function isRateLimited(error, depth = 0) {
33692
+ if (depth > MAX_CAUSE_DEPTH || error == null || typeof error !== "object") return false;
33693
+ const record = error;
33694
+ return record.statusCode === 429 || isRateLimited(record.cause, depth + 1);
33695
+ }
33696
+ function isContextOverflowError(error) {
33697
+ if (isRateLimited(error)) return false;
33698
+ return collectErrorText(error).some((text) => CONTEXT_OVERFLOW_PATTERNS.some((pattern) => pattern.test(text)));
33699
+ }
33700
+ //#endregion
33648
33701
  //#region src/processors/observational-memory/temporal-markers.ts
33649
33702
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
33650
33703
  function getTemporalGapReminderText(gapText, timestamp) {
@@ -33755,6 +33808,8 @@ function getOmObservabilityContext(args) {
33755
33808
  }
33756
33809
  /** Key used to store gateway detection result in per-processor state. */
33757
33810
  const GATEWAY_STATE_KEY = "__isGatewayModel";
33811
+ /** Step number OM last recovered from a context-overflow error, so each step retries at most once. */
33812
+ const CONTEXT_OVERFLOW_STEP_KEY = "__omContextOverflowStep";
33758
33813
  /** Check if the model is routed through a Mastra gateway (duck-type check to avoid cross-package instanceof issues). */
33759
33814
  function isMastraGatewayModel(model) {
33760
33815
  return typeof model === "object" && model !== null && "gatewayId" in model && model.gatewayId === "mastra";
@@ -33994,6 +34049,42 @@ var ObservationalMemoryProcessor = class {
33994
34049
  return messageList;
33995
34050
  });
33996
34051
  }
34052
+ async processAPIError(args) {
34053
+ const { error, messageList, requestContext, stepNumber, state } = args;
34054
+ if (!this.engine.getObservationConfig().observeOnContextOverflow) return;
34055
+ if (state[GATEWAY_STATE_KEY]) return;
34056
+ if (state[CONTEXT_OVERFLOW_STEP_KEY] === stepNumber) return;
34057
+ if (!isContextOverflowError(error)) return;
34058
+ const context = this.engine.getThreadContext(requestContext, messageList);
34059
+ if (!context) return;
34060
+ if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
34061
+ state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
34062
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
34063
+ const { threadId, resourceId } = context;
34064
+ await this.engine.waitForBuffering(threadId, resourceId);
34065
+ const messages = getObservableMessages(messageList);
34066
+ const { activated } = await this.engine.activate({
34067
+ threadId,
34068
+ resourceId,
34069
+ messages,
34070
+ messageList,
34071
+ writer: args.writer
34072
+ });
34073
+ const { observed } = await this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, () => this.engine.observe({
34074
+ threadId,
34075
+ resourceId,
34076
+ messages: getObservableMessages(messageList),
34077
+ messageList,
34078
+ force: true,
34079
+ agent: args.agent,
34080
+ sendSignal: args.sendSignal,
34081
+ sendStateSignal: args.sendStateSignal,
34082
+ requestContext,
34083
+ writer: args.writer,
34084
+ observabilityContext: getOmObservabilityContext(args)
34085
+ }));
34086
+ return { retry: activated || observed };
34087
+ }
33997
34088
  get config() {
33998
34089
  return this.engine.config;
33999
34090
  }
@@ -35447,6 +35538,7 @@ ${workingMemory}`;
35447
35538
  providerOptions: omConfig.observation.providerOptions,
35448
35539
  bufferTokens: omConfig.observation.bufferTokens,
35449
35540
  bufferOnIdle: omConfig.observation.bufferOnIdle,
35541
+ observeOnContextOverflow: omConfig.observation.observeOnContextOverflow,
35450
35542
  bufferActivation: omConfig.observation.bufferActivation,
35451
35543
  blockAfter: omConfig.observation.blockAfter,
35452
35544
  previousObserverTokens: omConfig.observation.previousObserverTokens,
@@ -36525,6 +36617,17 @@ Notes:
36525
36617
  return processors;
36526
36618
  }
36527
36619
  /**
36620
+ * Extends the base implementation to add ObservationalMemory as an error processor.
36621
+ * OM uses processAPIError to observe pending messages and retry when the provider
36622
+ * rejects a request for exceeding the model's context window.
36623
+ */
36624
+ async getErrorProcessors(configuredProcessors = [], context) {
36625
+ const processors = await super.getErrorProcessors(configuredProcessors, context);
36626
+ const om = await this.createOMProcessor(configuredProcessors, context);
36627
+ if (om) processors.push(om);
36628
+ return processors;
36629
+ }
36630
+ /**
36528
36631
  * Creates an ObservationalMemory processor wrapping the shared engine.
36529
36632
  * Returns null if OM is not configured, not supported, or already present
36530
36633
  * in the user's configured processors.
@@ -36577,4 +36680,4 @@ Notes:
36577
36680
  //#endregion
36578
36681
  export { renderSubconsciousActivity as $, buildObserverSystemPrompt as A, OBSERVATION_CONTEXT_INSTRUCTIONS as B, WorkingMemoryExtractor as C, TokenCounter as D, summarizeConversation as E, parseObserverOutput as F, Subconscious as G, OBSERVATION_CONTEXT_PROMPT_THREAD as H, injectAnchorIds as I, SubconsciousRemindExtractor as J, KnowledgeSemanticIndexCoordinator as K, parseAnchorId as L, formatMessagesForObserver as M, hasCurrentTaskSection as N, OBSERVER_SYSTEM_PROMPT as O, optimizeObservationsForContext as P, publishSubconsciousActivity as Q, stripEphemeralAnchorIds as R, wrapInObservationGroup as S, SUMMARIZE_THREAD_DEFAULTS as T, OBSERVATION_CONTINUATION_HINT as U, OBSERVATION_CONTEXT_PROMPT as V, getObservationContextPrompt as W, SUBCONSCIOUS_ACTIVITY_STATE_ID as X, ModelByInputTokens as Y, buildSubconsciousActivitySnapshot as Z, deriveObservationGroupProvenance as _, extractWorkingMemoryContent as a, renderObservationGroupsForReflection as b, getObservationsAsOf as c, AUTO_MODEL_BY_PROVIDER as d, Extractor as et, resolveAutoModelId as f, combineObservationGroupRanges as g, WorkingMemoryStateProcessor as h, WorkingMemory as i, extractCurrentTask as j, buildObserverPrompt as k, ObservationalMemoryProcessor as l, WORKING_MEMORY_STATE_PROCESSOR_ID as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, WORKING_MEMORY_STATE_ID as p, StaleKnowledgeSemanticIndexError as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, parseObservationGroups as v, deepMergeWorkingMemory as w, stripObservationGroups as x, reconcileObservationGroupsFromReflection as y, OBSERVATIONAL_MEMORY_DEFAULTS as z };
36579
36682
 
36580
- //# sourceMappingURL=src-DWoBX5f9.js.map
36683
+ //# sourceMappingURL=src-CnLuefUv.js.map