@mastra/memory 1.37.1 → 1.38.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.
@@ -19804,21 +19804,22 @@ function safeSlice(str, end) {
19804
19804
  return str.slice(0, safeEnd);
19805
19805
  }
19806
19806
  //#endregion
19807
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/tokenx/1.3.0/09093cdaeebfe25c39ba9052d6277b45fc99abf5e14e859f60f338f5c5160afd/node_modules/tokenx/dist/index.mjs
19807
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/tokenx/1.6.0/394289cb1bed8c542941f77748eea1a31bd3419018d0fb2ac7029ece2458cdd1/node_modules/tokenx/dist/index.mjs
19808
19808
  const PATTERNS = {
19809
19809
  whitespace: /^\s+$/,
19810
- cjk: /[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u303F\uFF00-\uFFEF\u30A0-\u30FF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,
19811
- numeric: /^\d+(?:[.,]\d+)*$/,
19812
- punctuation: /[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_-]/,
19813
- alphanumeric: /^[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]+$/
19810
+ structuredWhitespace: /\n\s/,
19811
+ cjk: /[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u30FF\uFF00-\uFFEF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,
19812
+ numeric: /^\d+$/,
19813
+ punctuation: /[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/
19814
19814
  };
19815
- const TOKEN_SPLIT_PATTERN = /* @__PURE__ */ new RegExp(`(\\s+|${PATTERNS.punctuation.source}+)`);
19815
+ const TOKEN_SPLIT_PATTERN = new RegExp(`(\\s+|${PATTERNS.punctuation.source}+)`);
19816
19816
  const DEFAULT_CHARS_PER_TOKEN = 6;
19817
19817
  const SHORT_TOKEN_THRESHOLD = 3;
19818
+ const KANA_CHARS_PER_TOKEN = 1.35;
19818
19819
  const DEFAULT_LANGUAGE_CONFIGS = [
19819
19820
  {
19820
19821
  pattern: /[äöüßẞ]/i,
19821
- averageCharsPerToken: 3
19822
+ averageCharsPerToken: 2.6
19822
19823
  },
19823
19824
  {
19824
19825
  pattern: /[éèêëàâîïôûùüÿçœæáíóúñ]/i,
@@ -19826,39 +19827,75 @@ const DEFAULT_LANGUAGE_CONFIGS = [
19826
19827
  },
19827
19828
  {
19828
19829
  pattern: /[ąćęłńóśźżěščřžýůúďťň]/i,
19829
- averageCharsPerToken: 3.5
19830
+ averageCharsPerToken: 2.5
19831
+ },
19832
+ {
19833
+ pattern: /[\u0430-\u044F\u0451]/i,
19834
+ averageCharsPerToken: 4
19835
+ },
19836
+ {
19837
+ pattern: /[\u03AC-\u03CE]/i,
19838
+ averageCharsPerToken: 2.75
19839
+ },
19840
+ {
19841
+ pattern: /^\p{Extended_Pictographic}[\p{Extended_Pictographic}\p{Emoji_Component}]*$/u,
19842
+ averageCharsPerToken: .75
19830
19843
  }
19831
19844
  ];
19832
19845
  /**
19833
- * Estimates the number of tokens in a text string using heuristic rules.
19846
+ * Walks a text as (segment, estimated token count) pairs. The segments
19847
+ * concatenate back to the original text; whitespace segments count zero
19848
+ * tokens unless they carry structure (indentation or blank lines).
19834
19849
  */
19835
- function estimateTokenCount(text, options = {}) {
19836
- if (!text) return 0;
19837
- const { defaultCharsPerToken = DEFAULT_CHARS_PER_TOKEN, languageConfigs = DEFAULT_LANGUAGE_CONFIGS } = options;
19838
- const segments = text.split(TOKEN_SPLIT_PATTERN).filter(Boolean);
19839
- let tokenCount = 0;
19840
- for (const segment of segments) tokenCount += estimateSegmentTokens(segment, languageConfigs, defaultCharsPerToken);
19841
- return tokenCount;
19850
+ function* walkSegments(text, options = {}) {
19851
+ if (!text) return;
19852
+ const resolvedOptions = resolveOptions(options);
19853
+ for (const segment of text.split(TOKEN_SPLIT_PATTERN)) if (segment) yield {
19854
+ segment,
19855
+ tokenCount: estimateSegmentTokens(segment, resolvedOptions)
19856
+ };
19842
19857
  }
19843
- function estimateSegmentTokens(segment, languageConfigs, defaultCharsPerToken) {
19844
- if (PATTERNS.whitespace.test(segment)) return 0;
19845
- if (PATTERNS.cjk.test(segment)) return getCharacterCount(segment);
19846
- if (PATTERNS.numeric.test(segment)) return 1;
19858
+ function resolveOptions(options) {
19859
+ return {
19860
+ defaultCharsPerToken: options.defaultCharsPerToken ?? DEFAULT_CHARS_PER_TOKEN,
19861
+ languageConfigs: options.languageConfigs ?? DEFAULT_LANGUAGE_CONFIGS
19862
+ };
19863
+ }
19864
+ function estimateSegmentTokens(segment, { languageConfigs, defaultCharsPerToken }) {
19865
+ if (PATTERNS.whitespace.test(segment)) return PATTERNS.structuredWhitespace.test(segment) ? 1 : 0;
19866
+ const languageCharsPerToken = getLanguageSpecificCharsPerToken(segment, languageConfigs);
19867
+ if (languageCharsPerToken !== void 0) return Math.ceil(getCharacterCount(segment) / languageCharsPerToken);
19868
+ if (PATTERNS.cjk.test(segment)) return estimateCjkTokens(segment);
19869
+ if (PATTERNS.numeric.test(segment)) return Math.ceil(segment.length / 3);
19847
19870
  if (segment.length <= SHORT_TOKEN_THRESHOLD) return 1;
19848
- if (PATTERNS.punctuation.test(segment)) return segment.length > 1 ? Math.ceil(segment.length / 2) : 1;
19849
- if (PATTERNS.alphanumeric.test(segment)) {
19850
- const charsPerToken$1 = getLanguageSpecificCharsPerToken(segment, languageConfigs) ?? defaultCharsPerToken;
19851
- return Math.ceil(segment.length / charsPerToken$1);
19852
- }
19853
- const charsPerToken = getLanguageSpecificCharsPerToken(segment, languageConfigs) ?? defaultCharsPerToken;
19854
- return Math.ceil(segment.length / charsPerToken);
19871
+ if (PATTERNS.punctuation.test(segment)) return Math.ceil(segment.length / 2);
19872
+ return Math.ceil(segment.length / defaultCharsPerToken);
19855
19873
  }
19856
19874
  function getLanguageSpecificCharsPerToken(segment, languageConfigs) {
19857
- for (const config of languageConfigs) if (config.pattern.test(segment)) return config.averageCharsPerToken;
19875
+ for (const config of languageConfigs) if (segment.search(config.pattern) !== -1) return config.averageCharsPerToken;
19858
19876
  }
19859
19877
  function getCharacterCount(text) {
19860
19878
  return Array.from(text).length;
19861
19879
  }
19880
+ function estimateCjkTokens(segment) {
19881
+ let kanaCount = 0;
19882
+ let otherCount = 0;
19883
+ for (const character of segment) {
19884
+ const codePoint = character.codePointAt(0);
19885
+ if (codePoint >= 12352 && codePoint <= 12543) kanaCount++;
19886
+ else otherCount++;
19887
+ }
19888
+ return otherCount + Math.ceil(kanaCount / KANA_CHARS_PER_TOKEN);
19889
+ }
19890
+ /**
19891
+ * Estimates the number of tokens in a text string using heuristic rules
19892
+ */
19893
+ function estimateTokenCount(text, options = {}) {
19894
+ if (!text) return 0;
19895
+ let tokenCount = 0;
19896
+ for (const segmentEstimate of walkSegments(text, options)) tokenCount += segmentEstimate.tokenCount;
19897
+ return tokenCount;
19898
+ }
19862
19899
  //#endregion
19863
19900
  //#region src/processors/observational-memory/tool-argument-helpers.ts
19864
19901
  const DEFAULT_OBSERVER_TOOL_ARGUMENT_MAX_TOKENS = 2e3;
@@ -22379,7 +22416,7 @@ const IMAGE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
22379
22416
  "heif",
22380
22417
  "avif"
22381
22418
  ]);
22382
- const TOKEN_ESTIMATE_CACHE_VERSION = 7;
22419
+ const TOKEN_ESTIMATE_CACHE_VERSION = 8;
22383
22420
  /**
22384
22421
  * Cache `source` marker for token estimates supplied by the caller via
22385
22422
  * `part.providerMetadata.mastra.tokenEstimate`. Pipelines that strip the real
@@ -23823,6 +23860,7 @@ async function summarizeConversation(opts) {
23823
23860
  providerOptions: OBSERVATIONAL_MEMORY_DEFAULTS.observation.providerOptions,
23824
23861
  maxTokensPerBatch: OBSERVATIONAL_MEMORY_DEFAULTS.observation.maxTokensPerBatch,
23825
23862
  bufferOnIdle: false,
23863
+ observeOnContextOverflow: false,
23826
23864
  observeAttachments: "auto",
23827
23865
  instruction: opts.instructions,
23828
23866
  threadTitle: false,
@@ -31317,6 +31355,7 @@ var ObservationalMemory = class ObservationalMemory {
31317
31355
  maxTokensPerBatch: config.observation?.maxTokensPerBatch ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.maxTokensPerBatch,
31318
31356
  bufferTokens: asyncBufferingDisabled ? void 0 : resolveBufferTokens(config.observation?.bufferTokens ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.bufferTokens, config.observation?.messageTokens ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.messageTokens),
31319
31357
  bufferOnIdle: config.observation?.bufferOnIdle ?? false,
31358
+ observeOnContextOverflow: config.observation?.observeOnContextOverflow ?? true,
31320
31359
  bufferActivation: asyncBufferingDisabled ? void 0 : config.observation?.bufferActivation ?? OBSERVATIONAL_MEMORY_DEFAULTS.observation.bufferActivation,
31321
31360
  activateAfterIdle: parseActivationTTLConfig(observationActivateAfterIdle, observationActivateAfterIdlePath),
31322
31361
  activateOnProviderChange: config.observation?.activateOnProviderChange ?? config.activateOnProviderChange ?? false,
@@ -33337,7 +33376,9 @@ ${formattedMessages}
33337
33376
  recordInsideLock = freshRecord;
33338
33377
  generationBefore = freshRecord.generationCount;
33339
33378
  const unobservedMessages = messages ? this.getUnobservedMessages(messages, freshRecord) : await this.loadMessagesFromStorage(threadId, resourceId, freshRecord.lastObservedAt ? new Date(freshRecord.lastObservedAt) : void 0);
33340
- if (!this.meetsObservationThreshold({
33379
+ if (opts.force) {
33380
+ if (unobservedMessages.length === 0) return;
33381
+ } else if (!this.meetsObservationThreshold({
33341
33382
  record: freshRecord,
33342
33383
  unobservedTokens: await this.tokenCounter.countMessagesAsync(unobservedMessages)
33343
33384
  })) return;
@@ -33645,6 +33686,55 @@ ${formattedMessages}
33645
33686
  }
33646
33687
  };
33647
33688
  //#endregion
33689
+ //#region src/processors/observational-memory/context-overflow.ts
33690
+ /**
33691
+ * Detects provider errors that reject a request for exceeding the model's context window.
33692
+ *
33693
+ * Providers report this with different codes and wording, so this matches the known shapes
33694
+ * (OpenAI and OpenAI-compatible APIs, Anthropic, Google, Bedrock, xAI, Mistral, local servers)
33695
+ * against the error's message, code, response body and causes.
33696
+ */
33697
+ const CONTEXT_OVERFLOW_PATTERNS = [
33698
+ /context[_ ]length[_ ]exceeded/i,
33699
+ /maximum context length/i,
33700
+ /maximum prompt length/i,
33701
+ /prompt is too long/i,
33702
+ /input is too long/i,
33703
+ /exceed\w*\b[^.]{0,40}\bcontext (?:window|length|limit|size)/i,
33704
+ /input token count[^.]{0,40}exceeds the maximum/i,
33705
+ /reduce the length of the (?:messages|prompt|input)/i
33706
+ ];
33707
+ const MAX_CAUSE_DEPTH = 4;
33708
+ function collectErrorText(error, depth = 0) {
33709
+ if (depth > MAX_CAUSE_DEPTH || error == null) return [];
33710
+ if (typeof error === "string") return [error];
33711
+ if (typeof error !== "object") return [];
33712
+ const record = error;
33713
+ const texts = [];
33714
+ for (const key of [
33715
+ "message",
33716
+ "code",
33717
+ "type",
33718
+ "responseBody"
33719
+ ]) {
33720
+ const value = record[key];
33721
+ if (typeof value === "string") texts.push(value);
33722
+ }
33723
+ if (record.data && typeof record.data === "object") texts.push(...collectErrorText(record.data.error ?? record.data, depth + 1));
33724
+ if (record.error && typeof record.error === "object") texts.push(...collectErrorText(record.error, depth + 1));
33725
+ texts.push(...collectErrorText(record.cause, depth + 1));
33726
+ return texts;
33727
+ }
33728
+ function isRateLimited(error, depth = 0) {
33729
+ if (depth > MAX_CAUSE_DEPTH || error == null || typeof error !== "object") return false;
33730
+ const record = error;
33731
+ return record.statusCode === 429 || isRateLimited(record.cause, depth + 1);
33732
+ }
33733
+ function isContextOverflowError(error) {
33734
+ if (isRateLimited(error)) return false;
33735
+ return collectErrorText(error).some((text) => CONTEXT_OVERFLOW_PATTERNS.some((pattern) => pattern.test(text)));
33736
+ }
33737
+ //#endregion
33648
33738
  //#region src/processors/observational-memory/temporal-markers.ts
33649
33739
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
33650
33740
  function getTemporalGapReminderText(gapText, timestamp) {
@@ -33755,6 +33845,8 @@ function getOmObservabilityContext(args) {
33755
33845
  }
33756
33846
  /** Key used to store gateway detection result in per-processor state. */
33757
33847
  const GATEWAY_STATE_KEY = "__isGatewayModel";
33848
+ /** Step number OM last recovered from a context-overflow error, so each step retries at most once. */
33849
+ const CONTEXT_OVERFLOW_STEP_KEY = "__omContextOverflowStep";
33758
33850
  /** Check if the model is routed through a Mastra gateway (duck-type check to avoid cross-package instanceof issues). */
33759
33851
  function isMastraGatewayModel(model) {
33760
33852
  return typeof model === "object" && model !== null && "gatewayId" in model && model.gatewayId === "mastra";
@@ -33994,6 +34086,42 @@ var ObservationalMemoryProcessor = class {
33994
34086
  return messageList;
33995
34087
  });
33996
34088
  }
34089
+ async processAPIError(args) {
34090
+ const { error, messageList, requestContext, stepNumber, state } = args;
34091
+ if (!this.engine.getObservationConfig().observeOnContextOverflow) return;
34092
+ if (state[GATEWAY_STATE_KEY]) return;
34093
+ if (state[CONTEXT_OVERFLOW_STEP_KEY] === stepNumber) return;
34094
+ if (!isContextOverflowError(error)) return;
34095
+ const context = this.engine.getThreadContext(requestContext, messageList);
34096
+ if (!context) return;
34097
+ if (parseMemoryRequestContext(requestContext)?.memoryConfig?.readOnly) return;
34098
+ state[CONTEXT_OVERFLOW_STEP_KEY] = stepNumber;
34099
+ omDebug(`[OM:processAPIError] context overflow at step ${stepNumber} — observing pending messages`);
34100
+ const { threadId, resourceId } = context;
34101
+ await this.engine.waitForBuffering(threadId, resourceId);
34102
+ const messages = getObservableMessages(messageList);
34103
+ const { activated } = await this.engine.activate({
34104
+ threadId,
34105
+ resourceId,
34106
+ messages,
34107
+ messageList,
34108
+ writer: args.writer
34109
+ });
34110
+ const { observed } = await this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, () => this.engine.observe({
34111
+ threadId,
34112
+ resourceId,
34113
+ messages: getObservableMessages(messageList),
34114
+ messageList,
34115
+ force: true,
34116
+ agent: args.agent,
34117
+ sendSignal: args.sendSignal,
34118
+ sendStateSignal: args.sendStateSignal,
34119
+ requestContext,
34120
+ writer: args.writer,
34121
+ observabilityContext: getOmObservabilityContext(args)
34122
+ }));
34123
+ return { retry: activated || observed };
34124
+ }
33997
34125
  get config() {
33998
34126
  return this.engine.config;
33999
34127
  }
@@ -35447,6 +35575,7 @@ ${workingMemory}`;
35447
35575
  providerOptions: omConfig.observation.providerOptions,
35448
35576
  bufferTokens: omConfig.observation.bufferTokens,
35449
35577
  bufferOnIdle: omConfig.observation.bufferOnIdle,
35578
+ observeOnContextOverflow: omConfig.observation.observeOnContextOverflow,
35450
35579
  bufferActivation: omConfig.observation.bufferActivation,
35451
35580
  blockAfter: omConfig.observation.blockAfter,
35452
35581
  previousObserverTokens: omConfig.observation.previousObserverTokens,
@@ -36525,6 +36654,17 @@ Notes:
36525
36654
  return processors;
36526
36655
  }
36527
36656
  /**
36657
+ * Extends the base implementation to add ObservationalMemory as an error processor.
36658
+ * OM uses processAPIError to observe pending messages and retry when the provider
36659
+ * rejects a request for exceeding the model's context window.
36660
+ */
36661
+ async getErrorProcessors(configuredProcessors = [], context) {
36662
+ const processors = await super.getErrorProcessors(configuredProcessors, context);
36663
+ const om = await this.createOMProcessor(configuredProcessors, context);
36664
+ if (om) processors.push(om);
36665
+ return processors;
36666
+ }
36667
+ /**
36528
36668
  * Creates an ObservationalMemory processor wrapping the shared engine.
36529
36669
  * Returns null if OM is not configured, not supported, or already present
36530
36670
  * in the user's configured processors.
@@ -36577,4 +36717,4 @@ Notes:
36577
36717
  //#endregion
36578
36718
  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
36719
 
36580
- //# sourceMappingURL=src-DWoBX5f9.js.map
36720
+ //# sourceMappingURL=src-CTyZJ6A-.js.map