@mastra/memory 1.42.0-alpha.2 → 1.42.0-alpha.4

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 (44) hide show
  1. package/dist/docs/SKILL.md +1 -1
  2. package/dist/docs/assets/SOURCE_MAP.json +84 -84
  3. package/dist/docs/references/docs-agents-human-in-the-loop.md +2 -2
  4. package/dist/docs/references/docs-agents-networks.md +1 -1
  5. package/dist/docs/references/docs-guides-context-engineering.md +3 -3
  6. package/dist/docs/references/docs-harness-background-tasks.md +2 -2
  7. package/dist/docs/references/docs-harness-goals.md +2 -2
  8. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  9. package/dist/docs/references/docs-memory-memory-processors.md +8 -8
  10. package/dist/docs/references/docs-memory-message-history.md +3 -3
  11. package/dist/docs/references/docs-memory-observational-memory.md +1 -1
  12. package/dist/docs/references/docs-memory-semantic-recall.md +2 -2
  13. package/dist/docs/references/docs-memory-working-memory.md +3 -2
  14. package/dist/docs/references/docs-signals-overview.md +1 -1
  15. package/dist/docs/references/docs-storage.md +12 -12
  16. package/dist/docs/references/docs-subagents.md +26 -3
  17. package/dist/docs/references/integrations-channels-github.md +1 -1
  18. package/dist/docs/references/integrations-channels-ring.md +2 -2
  19. package/dist/docs/references/integrations-databases-aurora-dsql.md +1 -1
  20. package/dist/docs/references/integrations-databases-elasticsearch.md +1 -1
  21. package/dist/docs/references/integrations-databases-libsql.md +6 -0
  22. package/dist/docs/references/integrations-databases-mongodb.md +1 -1
  23. package/dist/docs/references/integrations-databases-oracledb.md +1 -1
  24. package/dist/docs/references/integrations-databases-postgresql.md +9 -1
  25. package/dist/docs/references/integrations-databases-redis.md +1 -1
  26. package/dist/docs/references/integrations-databases-upstash.md +1 -1
  27. package/dist/docs/references/reference-memory-memory-class.md +3 -3
  28. package/dist/docs/references/reference-memory-observational-memory.md +7 -3
  29. package/dist/docs/references/reference-processors-token-limiter-processor.md +3 -3
  30. package/dist/index.cjs +1 -1
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +1 -1
  33. package/dist/processors/index.cjs +1 -1
  34. package/dist/processors/index.js +1 -1
  35. package/dist/processors/observational-memory/cache-boundary.d.ts +21 -0
  36. package/dist/processors/observational-memory/constants.d.ts +1 -1
  37. package/dist/processors/observational-memory/date-utils.d.ts +4 -0
  38. package/dist/processors/observational-memory/observational-memory.d.ts +1 -0
  39. package/dist/processors/observational-memory/processor.d.ts +3 -1
  40. package/dist/processors/observational-memory/thresholds.d.ts +2 -0
  41. package/dist/processors/observational-memory/types.d.ts +5 -0
  42. package/dist/{src-Bv05c6Nj.js → src-CVekC2V9.js} +102 -25
  43. package/dist/{src-D2dL-xVG.cjs → src-DaOrkH_R.cjs} +102 -25
  44. package/package.json +2 -2
@@ -24232,7 +24232,7 @@ KNOWLEDGE UPDATES: When asked about current state (e.g., "where do I currently..
24232
24232
 
24233
24233
  USER STATEMENTS VS ASSISTANT SUGGESTIONS: Treat what the user said about their own life, plans, decisions, and dates as authoritative, unless data or their own later messages say otherwise. Treat what the assistant said, such as proposed schedules, example dates, and recommendations, as suggestions rather than facts about what happened, unless the user adopted or confirmed them. What the assistant did, such as editing a file, running a command, or calling a tool, is a record of what happened.
24234
24234
 
24235
- PLANNED ACTIONS: If the user stated they planned to do something (e.g., "I'm going to...", "I'm looking forward to...", "I will...") and the date they planned to do it is now in the past (check the relative time like "3 weeks ago"), assume they completed the action unless there's evidence they didn't. For example, if someone said "I'll start my new diet on Monday" and that was 2 weeks ago, assume they started the diet.
24235
+ PLANNED ACTIONS: If the user stated they planned to do something (e.g., "I'm going to...", "I'm looking forward to...", "I will...") and the date they planned to do it is now in the past (compare the absolute dates; use relative-time hints when available), assume they completed the action unless there's evidence they didn't. For example, if someone said "I'll start my new diet on Monday" and that was 2 weeks ago, assume they started the diet.
24236
24236
 
24237
24237
  MOST RECENT USER INPUT: Treat the most recent user message as the highest-priority signal for what to do next. Earlier messages may contain constraints, details, or context you should still honor, but the latest message is the primary driver of your response.
24238
24238
 
@@ -25718,15 +25718,8 @@ function isFutureIntentObservation(line) {
25718
25718
  /\babout\s+to\b/i
25719
25719
  ].some((pattern) => pattern.test(line));
25720
25720
  }
25721
- /**
25722
- * Expand inline estimated dates with relative time.
25723
- * Matches patterns like "(estimated May 27-28, 2023)" or "(meaning May 30, 2023 at 3:00 PM)"
25724
- * and expands them to "(meaning May 30, 2023 - 3 weeks ago)". Notes without a year are left alone.
25725
- */
25726
- function expandInlineEstimatedDates(observations, currentDate, timeZone) {
25727
- const inlineDateRegex = /\((estimated|meaning)\s([^()]*)\)/gi;
25728
- const today = calendarDayIn(currentDate, timeZone);
25729
- return observations.replace(inlineDateRegex, (match, prefix, noteText, offset) => {
25721
+ function expandInlineEstimatedDatesForDay(observations, today) {
25722
+ return observations.replace(/\((estimated|meaning)\s([^()]*)\)/gi, (match, prefix, noteText, offset) => {
25730
25723
  const dateContent = noteText.trimStart();
25731
25724
  const span = findDateSpan(dateContent);
25732
25725
  if (!span) return match;
@@ -25737,14 +25730,8 @@ function expandInlineEstimatedDates(observations, currentDate, timeZone) {
25737
25730
  return `(${prefix} ${dateContent} - ${relative})`;
25738
25731
  });
25739
25732
  }
25740
- /**
25741
- * Annotates dates written into observation text, e.g. "exam on January 10, 2024" becomes
25742
- * "exam on January 10, 2024 (5 months ago)". Only dates that state their year are annotated;
25743
- * "Date:" headers and "(meaning/estimated …)" notes are handled separately and skipped here.
25744
- */
25745
- function annotateObservationTextDates(observations, currentDate, timeZone) {
25733
+ function annotateObservationTextDatesForDay(observations, today) {
25746
25734
  const regex = new RegExp(String.raw`^Date:.*$|\((?:[Ee]stimated|[Mm]eaning)\b[^()]*\)|${FREE_TEXT_DATE.source}`, "gm");
25747
- const today = calendarDayIn(currentDate, timeZone);
25748
25735
  return observations.replace(regex, (match, offset) => {
25749
25736
  if (match.startsWith("Date:") || match.startsWith("(")) return match;
25750
25737
  const span = parseDateSpan(match);
@@ -25762,8 +25749,16 @@ function annotateObservationTextDates(observations, currentDate, timeZone) {
25762
25749
  * `currentDate`'s calendar date in that zone, so the result doesn't depend on the zone of the process rendering it.
25763
25750
  */
25764
25751
  function addRelativeTimeToObservations(observations, currentDate, timeZone) {
25765
- const today = calendarDayIn(currentDate, timeZone);
25766
- const withInlineDates = annotateObservationTextDates(expandInlineEstimatedDates(observations, currentDate, timeZone), currentDate, timeZone);
25752
+ return addRelativeTimeForDay(observations, calendarDayIn(currentDate, timeZone));
25753
+ }
25754
+ function addRelativeTimeForDay(observations, today) {
25755
+ return formatObservationDateHeaders(annotateObservationTextDatesForDay(expandInlineEstimatedDatesForDay(observations, today), today), today);
25756
+ }
25757
+ /** Preserve only clock-independent gaps in the cacheable observation text. */
25758
+ function addObservationDateGaps(observations) {
25759
+ return formatObservationDateHeaders(observations);
25760
+ }
25761
+ function formatObservationDateHeaders(withInlineDates, today) {
25767
25762
  const dateHeaderRegex = /^(Date:[ \t]*)(.*)$/gm;
25768
25763
  const dates = [];
25769
25764
  let regexMatch;
@@ -25789,12 +25784,35 @@ function addRelativeTimeToObservations(observations, currentDate, timeZone) {
25789
25784
  const gap = formatGapBetweenDates(prev.span.end, curr.span.start);
25790
25785
  if (gap) result += `\n${gap}\n\n`;
25791
25786
  }
25792
- result += `${curr.prefix}${curr.dateStr} (${relativeSpan(curr.span, today)})`;
25787
+ result += today === void 0 ? curr.match : `${curr.prefix}${curr.dateStr} (${relativeSpan(curr.span, today)})`;
25793
25788
  lastIndex = curr.index + curr.match.length;
25794
25789
  }
25795
25790
  result += withInlineDates.slice(lastIndex);
25796
25791
  return result;
25797
25792
  }
25793
+ /** Live cues are bounded and separate from the absolute observation prefix. */
25794
+ function buildObservationDateHints(observations, currentDate, timeZone) {
25795
+ const today = calendarDayIn(currentDate, timeZone);
25796
+ const opening = `<observation-date-hints>\nToday is ${(/* @__PURE__ */ new Date(today * DAY_MS)).toISOString().slice(0, 10)} in the observation time zone (${resolveTimeZone(timeZone) ?? "process local"}). These live annotations refer to the absolute observations above; they are not additional observations.`;
25797
+ const closing = "\n</observation-date-hints>";
25798
+ const omission = "\nAdditional date cues omitted. Interpret remaining absolute dates against today; past planned actions likely already happened.";
25799
+ const lines = [];
25800
+ let remaining = 8e3 - opening.length - 26 - 126;
25801
+ let omitted = false;
25802
+ for (const line of observations.split("\n")) {
25803
+ if (!/\d{4}/.test(line)) continue;
25804
+ const annotated = addRelativeTimeForDay(line, today);
25805
+ if (annotated === line) continue;
25806
+ if (lines.length >= 64 || annotated.length + 1 > remaining) {
25807
+ omitted = true;
25808
+ break;
25809
+ }
25810
+ lines.push(annotated);
25811
+ remaining -= annotated.length + 1;
25812
+ }
25813
+ if (!lines.length && !omitted) return void 0;
25814
+ return `${opening}${lines.map((line) => `\n${line}`).join("")}${omitted ? omission : ""}${closing}`;
25815
+ }
25798
25816
  function formatTemporalGap(diffMs) {
25799
25817
  if (diffMs < 6e5) return null;
25800
25818
  const minute = 6e4;
@@ -33679,11 +33697,16 @@ function calculateDynamicThreshold(threshold, currentObservationTokens) {
33679
33697
  * Resolve bufferTokens config value.
33680
33698
  * Values in (0, 1) are treated as ratios of the message threshold.
33681
33699
  * e.g. bufferTokens: 0.25 with messageTokens: 20_000 → 5_000
33700
+ * Ratios resolve to at least 1 and below the threshold, so tiny thresholds
33701
+ * (e.g. messageTokens: 2) don't round to 0 or up to the threshold itself.
33682
33702
  */
33683
33703
  function resolveBufferTokens(bufferTokens, messageTokens) {
33684
33704
  if (bufferTokens === false) return void 0;
33685
33705
  if (bufferTokens === void 0) return void 0;
33686
- if (bufferTokens > 0 && bufferTokens < 1) return Math.round(getMaxThreshold(messageTokens) * bufferTokens);
33706
+ if (bufferTokens > 0 && bufferTokens < 1) {
33707
+ const threshold = getMaxThreshold(messageTokens);
33708
+ return Math.max(1, Math.min(Math.round(threshold * bufferTokens), threshold - 1));
33709
+ }
33687
33710
  return bufferTokens;
33688
33711
  }
33689
33712
  /**
@@ -38063,6 +38086,7 @@ let hasWarnedResourceScopeDeprecation = false;
38063
38086
  var ObservationalMemory = class ObservationalMemory {
38064
38087
  storage;
38065
38088
  tokenCounter;
38089
+ liveDateHints;
38066
38090
  scope;
38067
38091
  /** Whether retrieval-mode observation groups are enabled. */
38068
38092
  retrieval;
@@ -38195,6 +38219,7 @@ var ObservationalMemory = class ObservationalMemory {
38195
38219
  if (config.model && config.reflection?.model) throw new Error("Cannot set both `model` and `reflection.model`. Use `model` to set both agents, or set each individually.");
38196
38220
  this.shouldObscureThreadIds = config.obscureThreadIds || false;
38197
38221
  this.storage = config.storage;
38222
+ this.liveDateHints = config.liveDateHints ?? true;
38198
38223
  this.scope = config.scope ?? "thread";
38199
38224
  this.retrieval = Boolean(config.retrieval);
38200
38225
  this.retrievalScope = typeof config.retrieval === "object" ? config.retrieval.scope ?? "resource" : "resource";
@@ -38533,7 +38558,10 @@ var ObservationalMemory = class ObservationalMemory {
38533
38558
  const observationThreshold = getMaxThreshold(this.observationConfig.messageTokens);
38534
38559
  if (this.observationConfig.bufferTokens !== void 0) {
38535
38560
  if (this.observationConfig.bufferTokens <= 0) throw new Error(`observation.bufferTokens must be > 0, got ${this.observationConfig.bufferTokens}`);
38536
- if (this.observationConfig.bufferTokens >= observationThreshold) throw new Error(`observation.bufferTokens (${this.observationConfig.bufferTokens}) must be less than messageTokens (${observationThreshold})`);
38561
+ if (this.observationConfig.bufferTokens >= observationThreshold) {
38562
+ if (observationThreshold < 2) throw new Error(`observation.messageTokens must be at least 2 when async buffering is enabled, got ${observationThreshold}. Set observation: { bufferTokens: false } to use a smaller messageTokens.`);
38563
+ throw new Error(`observation.bufferTokens (${this.observationConfig.bufferTokens}) must be less than messageTokens (${observationThreshold})`);
38564
+ }
38537
38565
  }
38538
38566
  if (this.observationConfig.bufferActivation !== void 0) {
38539
38567
  if (this.observationConfig.bufferActivation <= 0) throw new Error(`observation.bufferActivation must be > 0, got ${this.observationConfig.bufferActivation}`);
@@ -38983,11 +39011,14 @@ var ObservationalMemory = class ObservationalMemory {
38983
39011
  * the message for the current thread.
38984
39012
  */
38985
39013
  formatObservationsForContext(observations, currentTask, suggestedResponse, extractedValues, unobservedContextBlocks, currentDate, retrieval = false, timeZone) {
38986
- let optimized = retrieval ? renderObservationGroupsForReflection(observations, { includeReflectionKind: true }) ?? optimizeObservationsForContext(observations) : optimizeObservationsForContext(observations);
38987
- if (currentDate) optimized = addRelativeTimeToObservations(optimized, currentDate, timeZone);
39014
+ const optimized = retrieval ? renderObservationGroupsForReflection(observations, { includeReflectionKind: true }) ?? optimizeObservationsForContext(observations) : optimizeObservationsForContext(observations);
39015
+ const dateHints = this.liveDateHints && currentDate ? buildObservationDateHints(optimized, currentDate, timeZone) : void 0;
39016
+ const stableObservations = currentDate ? addObservationDateGaps(optimized) : optimized;
38988
39017
  const messages = [`${getObservationContextPrompt(this.scope)}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}${retrieval ? `\n\n${getRetrievalInstructions(this.retrievalScope, this.retrievalInstructions, this.retrievalSearch, this.storage.supportsObservationalMemoryHistorySearch === true)}` : ""}`];
38989
39018
  if (unobservedContextBlocks) messages.push(`The following content is from OTHER conversations different from the current conversation, they're here for reference, but they're not necessarily your focus:\nSTART_OTHER_CONVERSATIONS_BLOCK\n${unobservedContextBlocks}\nEND_OTHER_CONVERSATIONS_BLOCK`);
38990
- for (const chunk of this.splitObservationContextChunks(optimized)) messages.push(`<observations>\n${chunk}\n</observations>`);
39019
+ const observationChunks = this.splitObservationContextChunks(stableObservations);
39020
+ for (const chunk of observationChunks) messages.push(`<observations>\n${chunk}\n</observations>`);
39021
+ if (observationChunks.length > 0 && dateHints) messages.push(dateHints);
38991
39022
  if (currentTask) messages.push(`<current-task>\n${currentTask}\n</current-task>`);
38992
39023
  if (suggestedResponse) messages.push(`<suggested-response>\n${suggestedResponse}\n</suggested-response>`);
38993
39024
  messages.push(...buildExtractedValueContextSections([...this.observationConfig.extractors, ...this.reflectionConfig.extractors], extractedValues));
@@ -40725,6 +40756,44 @@ ${formattedMessages}
40725
40756
  });
40726
40757
  }
40727
40758
  };
40759
+ // src/processors/observational-memory/cache-boundary.ts
40760
+ /**
40761
+ * Hints where the stable part of memory's context ends: the last observation chunk.
40762
+ *
40763
+ * Memory renders each observation chunk as its own closed `<observations>` block, newest last, and puts what
40764
+ * changes more often (date hints, the current task, the suggested response) after them. An update that only adds
40765
+ * chunks leaves every earlier message unchanged, so a prompt cache that ends on the last chunk stays valid.
40766
+ *
40767
+ * The hint is `providerOptions.mastra.cacheBoundary: true`, set on the prompt of one model call only, so it is never
40768
+ * stored. Provider adapters never forward `providerOptions.mastra`; a model adapter that supports prompt caching can
40769
+ * turn it into a real cache mark within its own limits.
40770
+ *
40771
+ * Chat Completions endpoints (`*.chat`) get no hint: core merges their leading system messages into one and skips the
40772
+ * merge when an earlier message carries `providerOptions`. Only a chunk memory rendered itself is hinted: `rendered` is the
40773
+ * text of the system messages memory tagged in the message list this step, so an instruction that only looks like a
40774
+ * chunk is never hinted. Returns `undefined` when nothing is hinted.
40775
+ */
40776
+ function markObservationCacheBoundary(prompt, apiProviderId, rendered) {
40777
+ if (!apiProviderId || apiProviderId.endsWith(".chat")) return void 0;
40778
+ const chunks = new Set(rendered?.filter((content) => typeof content === "string" && isObservationChunk(content)));
40779
+ if (chunks.size === 0) return void 0;
40780
+ let boundary = -1;
40781
+ prompt.forEach((message, index) => {
40782
+ if (message.role === "system" && chunks.has(message.content)) boundary = index;
40783
+ });
40784
+ if (boundary < 0) return void 0;
40785
+ return prompt.map((message, index) => index === boundary ? {
40786
+ ...message,
40787
+ providerOptions: {
40788
+ ...message.providerOptions,
40789
+ mastra: {
40790
+ ...message.providerOptions?.mastra,
40791
+ cacheBoundary: true
40792
+ }
40793
+ }
40794
+ } : message);
40795
+ }
40796
+ const isObservationChunk = (content) => content.startsWith("<observations>\n") && content.endsWith("\n</observations>");
40728
40797
  // src/processors/observational-memory/temporal-markers.ts
40729
40798
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
40730
40799
  function getTemporalGapReminderText(gapText, timestamp) {
@@ -41146,6 +41215,13 @@ var ObservationalMemoryProcessor = class {
41146
41215
  return messageList;
41147
41216
  });
41148
41217
  }
41218
+ /** Hints memory's cache boundary on this model call's prompt only, so the hint is never stored. */
41219
+ processLLMRequest({ prompt, model, apiProviderId, messageList }) {
41220
+ const provider = apiProviderId ?? (typeof model?.provider === "string" ? model.provider : void 0);
41221
+ const rendered = messageList?.getSystemMessages("observational-memory").map((message) => message.content);
41222
+ const hinted = markObservationCacheBoundary(prompt, provider, rendered);
41223
+ return hinted ? { prompt: hinted } : void 0;
41224
+ }
41149
41225
  async processOutputResult(args) {
41150
41226
  const { messageList, requestContext, state: _state } = args;
41151
41227
  const state = _state ?? {};
@@ -42632,6 +42708,7 @@ ${workingMemory}`;
42632
42708
  return new OMClass({
42633
42709
  storage: memoryStore,
42634
42710
  memory: this,
42711
+ liveDateHints: omConfig.liveDateHints,
42635
42712
  scope: omConfig.scope,
42636
42713
  retrieval: omConfig.retrieval,
42637
42714
  activateAfterIdle: omConfig.activateAfterIdle,
@@ -24254,7 +24254,7 @@ KNOWLEDGE UPDATES: When asked about current state (e.g., "where do I currently..
24254
24254
 
24255
24255
  USER STATEMENTS VS ASSISTANT SUGGESTIONS: Treat what the user said about their own life, plans, decisions, and dates as authoritative, unless data or their own later messages say otherwise. Treat what the assistant said, such as proposed schedules, example dates, and recommendations, as suggestions rather than facts about what happened, unless the user adopted or confirmed them. What the assistant did, such as editing a file, running a command, or calling a tool, is a record of what happened.
24256
24256
 
24257
- PLANNED ACTIONS: If the user stated they planned to do something (e.g., "I'm going to...", "I'm looking forward to...", "I will...") and the date they planned to do it is now in the past (check the relative time like "3 weeks ago"), assume they completed the action unless there's evidence they didn't. For example, if someone said "I'll start my new diet on Monday" and that was 2 weeks ago, assume they started the diet.
24257
+ PLANNED ACTIONS: If the user stated they planned to do something (e.g., "I'm going to...", "I'm looking forward to...", "I will...") and the date they planned to do it is now in the past (compare the absolute dates; use relative-time hints when available), assume they completed the action unless there's evidence they didn't. For example, if someone said "I'll start my new diet on Monday" and that was 2 weeks ago, assume they started the diet.
24258
24258
 
24259
24259
  MOST RECENT USER INPUT: Treat the most recent user message as the highest-priority signal for what to do next. Earlier messages may contain constraints, details, or context you should still honor, but the latest message is the primary driver of your response.
24260
24260
 
@@ -25740,15 +25740,8 @@ function isFutureIntentObservation(line) {
25740
25740
  /\babout\s+to\b/i
25741
25741
  ].some((pattern) => pattern.test(line));
25742
25742
  }
25743
- /**
25744
- * Expand inline estimated dates with relative time.
25745
- * Matches patterns like "(estimated May 27-28, 2023)" or "(meaning May 30, 2023 at 3:00 PM)"
25746
- * and expands them to "(meaning May 30, 2023 - 3 weeks ago)". Notes without a year are left alone.
25747
- */
25748
- function expandInlineEstimatedDates(observations, currentDate, timeZone) {
25749
- const inlineDateRegex = /\((estimated|meaning)\s([^()]*)\)/gi;
25750
- const today = calendarDayIn(currentDate, timeZone);
25751
- return observations.replace(inlineDateRegex, (match, prefix, noteText, offset) => {
25743
+ function expandInlineEstimatedDatesForDay(observations, today) {
25744
+ return observations.replace(/\((estimated|meaning)\s([^()]*)\)/gi, (match, prefix, noteText, offset) => {
25752
25745
  const dateContent = noteText.trimStart();
25753
25746
  const span = findDateSpan(dateContent);
25754
25747
  if (!span) return match;
@@ -25759,14 +25752,8 @@ function expandInlineEstimatedDates(observations, currentDate, timeZone) {
25759
25752
  return `(${prefix} ${dateContent} - ${relative})`;
25760
25753
  });
25761
25754
  }
25762
- /**
25763
- * Annotates dates written into observation text, e.g. "exam on January 10, 2024" becomes
25764
- * "exam on January 10, 2024 (5 months ago)". Only dates that state their year are annotated;
25765
- * "Date:" headers and "(meaning/estimated …)" notes are handled separately and skipped here.
25766
- */
25767
- function annotateObservationTextDates(observations, currentDate, timeZone) {
25755
+ function annotateObservationTextDatesForDay(observations, today) {
25768
25756
  const regex = new RegExp(String.raw`^Date:.*$|\((?:[Ee]stimated|[Mm]eaning)\b[^()]*\)|${FREE_TEXT_DATE.source}`, "gm");
25769
- const today = calendarDayIn(currentDate, timeZone);
25770
25757
  return observations.replace(regex, (match, offset) => {
25771
25758
  if (match.startsWith("Date:") || match.startsWith("(")) return match;
25772
25759
  const span = parseDateSpan(match);
@@ -25784,8 +25771,16 @@ function annotateObservationTextDates(observations, currentDate, timeZone) {
25784
25771
  * `currentDate`'s calendar date in that zone, so the result doesn't depend on the zone of the process rendering it.
25785
25772
  */
25786
25773
  function addRelativeTimeToObservations(observations, currentDate, timeZone) {
25787
- const today = calendarDayIn(currentDate, timeZone);
25788
- const withInlineDates = annotateObservationTextDates(expandInlineEstimatedDates(observations, currentDate, timeZone), currentDate, timeZone);
25774
+ return addRelativeTimeForDay(observations, calendarDayIn(currentDate, timeZone));
25775
+ }
25776
+ function addRelativeTimeForDay(observations, today) {
25777
+ return formatObservationDateHeaders(annotateObservationTextDatesForDay(expandInlineEstimatedDatesForDay(observations, today), today), today);
25778
+ }
25779
+ /** Preserve only clock-independent gaps in the cacheable observation text. */
25780
+ function addObservationDateGaps(observations) {
25781
+ return formatObservationDateHeaders(observations);
25782
+ }
25783
+ function formatObservationDateHeaders(withInlineDates, today) {
25789
25784
  const dateHeaderRegex = /^(Date:[ \t]*)(.*)$/gm;
25790
25785
  const dates = [];
25791
25786
  let regexMatch;
@@ -25811,12 +25806,35 @@ function addRelativeTimeToObservations(observations, currentDate, timeZone) {
25811
25806
  const gap = formatGapBetweenDates(prev.span.end, curr.span.start);
25812
25807
  if (gap) result += `\n${gap}\n\n`;
25813
25808
  }
25814
- result += `${curr.prefix}${curr.dateStr} (${relativeSpan(curr.span, today)})`;
25809
+ result += today === void 0 ? curr.match : `${curr.prefix}${curr.dateStr} (${relativeSpan(curr.span, today)})`;
25815
25810
  lastIndex = curr.index + curr.match.length;
25816
25811
  }
25817
25812
  result += withInlineDates.slice(lastIndex);
25818
25813
  return result;
25819
25814
  }
25815
+ /** Live cues are bounded and separate from the absolute observation prefix. */
25816
+ function buildObservationDateHints(observations, currentDate, timeZone) {
25817
+ const today = calendarDayIn(currentDate, timeZone);
25818
+ const opening = `<observation-date-hints>\nToday is ${(/* @__PURE__ */ new Date(today * DAY_MS)).toISOString().slice(0, 10)} in the observation time zone (${resolveTimeZone(timeZone) ?? "process local"}). These live annotations refer to the absolute observations above; they are not additional observations.`;
25819
+ const closing = "\n</observation-date-hints>";
25820
+ const omission = "\nAdditional date cues omitted. Interpret remaining absolute dates against today; past planned actions likely already happened.";
25821
+ const lines = [];
25822
+ let remaining = 8e3 - opening.length - 26 - 126;
25823
+ let omitted = false;
25824
+ for (const line of observations.split("\n")) {
25825
+ if (!/\d{4}/.test(line)) continue;
25826
+ const annotated = addRelativeTimeForDay(line, today);
25827
+ if (annotated === line) continue;
25828
+ if (lines.length >= 64 || annotated.length + 1 > remaining) {
25829
+ omitted = true;
25830
+ break;
25831
+ }
25832
+ lines.push(annotated);
25833
+ remaining -= annotated.length + 1;
25834
+ }
25835
+ if (!lines.length && !omitted) return void 0;
25836
+ return `${opening}${lines.map((line) => `\n${line}`).join("")}${omitted ? omission : ""}${closing}`;
25837
+ }
25820
25838
  function formatTemporalGap(diffMs) {
25821
25839
  if (diffMs < 6e5) return null;
25822
25840
  const minute = 6e4;
@@ -33701,11 +33719,16 @@ function calculateDynamicThreshold(threshold, currentObservationTokens) {
33701
33719
  * Resolve bufferTokens config value.
33702
33720
  * Values in (0, 1) are treated as ratios of the message threshold.
33703
33721
  * e.g. bufferTokens: 0.25 with messageTokens: 20_000 → 5_000
33722
+ * Ratios resolve to at least 1 and below the threshold, so tiny thresholds
33723
+ * (e.g. messageTokens: 2) don't round to 0 or up to the threshold itself.
33704
33724
  */
33705
33725
  function resolveBufferTokens(bufferTokens, messageTokens) {
33706
33726
  if (bufferTokens === false) return void 0;
33707
33727
  if (bufferTokens === void 0) return void 0;
33708
- if (bufferTokens > 0 && bufferTokens < 1) return Math.round(getMaxThreshold(messageTokens) * bufferTokens);
33728
+ if (bufferTokens > 0 && bufferTokens < 1) {
33729
+ const threshold = getMaxThreshold(messageTokens);
33730
+ return Math.max(1, Math.min(Math.round(threshold * bufferTokens), threshold - 1));
33731
+ }
33709
33732
  return bufferTokens;
33710
33733
  }
33711
33734
  /**
@@ -38085,6 +38108,7 @@ let hasWarnedResourceScopeDeprecation = false;
38085
38108
  var ObservationalMemory = class ObservationalMemory {
38086
38109
  storage;
38087
38110
  tokenCounter;
38111
+ liveDateHints;
38088
38112
  scope;
38089
38113
  /** Whether retrieval-mode observation groups are enabled. */
38090
38114
  retrieval;
@@ -38217,6 +38241,7 @@ var ObservationalMemory = class ObservationalMemory {
38217
38241
  if (config.model && config.reflection?.model) throw new Error("Cannot set both `model` and `reflection.model`. Use `model` to set both agents, or set each individually.");
38218
38242
  this.shouldObscureThreadIds = config.obscureThreadIds || false;
38219
38243
  this.storage = config.storage;
38244
+ this.liveDateHints = config.liveDateHints ?? true;
38220
38245
  this.scope = config.scope ?? "thread";
38221
38246
  this.retrieval = Boolean(config.retrieval);
38222
38247
  this.retrievalScope = typeof config.retrieval === "object" ? config.retrieval.scope ?? "resource" : "resource";
@@ -38555,7 +38580,10 @@ var ObservationalMemory = class ObservationalMemory {
38555
38580
  const observationThreshold = getMaxThreshold(this.observationConfig.messageTokens);
38556
38581
  if (this.observationConfig.bufferTokens !== void 0) {
38557
38582
  if (this.observationConfig.bufferTokens <= 0) throw new Error(`observation.bufferTokens must be > 0, got ${this.observationConfig.bufferTokens}`);
38558
- if (this.observationConfig.bufferTokens >= observationThreshold) throw new Error(`observation.bufferTokens (${this.observationConfig.bufferTokens}) must be less than messageTokens (${observationThreshold})`);
38583
+ if (this.observationConfig.bufferTokens >= observationThreshold) {
38584
+ if (observationThreshold < 2) throw new Error(`observation.messageTokens must be at least 2 when async buffering is enabled, got ${observationThreshold}. Set observation: { bufferTokens: false } to use a smaller messageTokens.`);
38585
+ throw new Error(`observation.bufferTokens (${this.observationConfig.bufferTokens}) must be less than messageTokens (${observationThreshold})`);
38586
+ }
38559
38587
  }
38560
38588
  if (this.observationConfig.bufferActivation !== void 0) {
38561
38589
  if (this.observationConfig.bufferActivation <= 0) throw new Error(`observation.bufferActivation must be > 0, got ${this.observationConfig.bufferActivation}`);
@@ -39005,11 +39033,14 @@ var ObservationalMemory = class ObservationalMemory {
39005
39033
  * the message for the current thread.
39006
39034
  */
39007
39035
  formatObservationsForContext(observations, currentTask, suggestedResponse, extractedValues, unobservedContextBlocks, currentDate, retrieval = false, timeZone) {
39008
- let optimized = retrieval ? renderObservationGroupsForReflection(observations, { includeReflectionKind: true }) ?? optimizeObservationsForContext(observations) : optimizeObservationsForContext(observations);
39009
- if (currentDate) optimized = addRelativeTimeToObservations(optimized, currentDate, timeZone);
39036
+ const optimized = retrieval ? renderObservationGroupsForReflection(observations, { includeReflectionKind: true }) ?? optimizeObservationsForContext(observations) : optimizeObservationsForContext(observations);
39037
+ const dateHints = this.liveDateHints && currentDate ? buildObservationDateHints(optimized, currentDate, timeZone) : void 0;
39038
+ const stableObservations = currentDate ? addObservationDateGaps(optimized) : optimized;
39010
39039
  const messages = [`${getObservationContextPrompt(this.scope)}\n\n${OBSERVATION_CONTEXT_INSTRUCTIONS}${retrieval ? `\n\n${getRetrievalInstructions(this.retrievalScope, this.retrievalInstructions, this.retrievalSearch, this.storage.supportsObservationalMemoryHistorySearch === true)}` : ""}`];
39011
39040
  if (unobservedContextBlocks) messages.push(`The following content is from OTHER conversations different from the current conversation, they're here for reference, but they're not necessarily your focus:\nSTART_OTHER_CONVERSATIONS_BLOCK\n${unobservedContextBlocks}\nEND_OTHER_CONVERSATIONS_BLOCK`);
39012
- for (const chunk of this.splitObservationContextChunks(optimized)) messages.push(`<observations>\n${chunk}\n</observations>`);
39041
+ const observationChunks = this.splitObservationContextChunks(stableObservations);
39042
+ for (const chunk of observationChunks) messages.push(`<observations>\n${chunk}\n</observations>`);
39043
+ if (observationChunks.length > 0 && dateHints) messages.push(dateHints);
39013
39044
  if (currentTask) messages.push(`<current-task>\n${currentTask}\n</current-task>`);
39014
39045
  if (suggestedResponse) messages.push(`<suggested-response>\n${suggestedResponse}\n</suggested-response>`);
39015
39046
  messages.push(...buildExtractedValueContextSections([...this.observationConfig.extractors, ...this.reflectionConfig.extractors], extractedValues));
@@ -40747,6 +40778,44 @@ ${formattedMessages}
40747
40778
  });
40748
40779
  }
40749
40780
  };
40781
+ // src/processors/observational-memory/cache-boundary.ts
40782
+ /**
40783
+ * Hints where the stable part of memory's context ends: the last observation chunk.
40784
+ *
40785
+ * Memory renders each observation chunk as its own closed `<observations>` block, newest last, and puts what
40786
+ * changes more often (date hints, the current task, the suggested response) after them. An update that only adds
40787
+ * chunks leaves every earlier message unchanged, so a prompt cache that ends on the last chunk stays valid.
40788
+ *
40789
+ * The hint is `providerOptions.mastra.cacheBoundary: true`, set on the prompt of one model call only, so it is never
40790
+ * stored. Provider adapters never forward `providerOptions.mastra`; a model adapter that supports prompt caching can
40791
+ * turn it into a real cache mark within its own limits.
40792
+ *
40793
+ * Chat Completions endpoints (`*.chat`) get no hint: core merges their leading system messages into one and skips the
40794
+ * merge when an earlier message carries `providerOptions`. Only a chunk memory rendered itself is hinted: `rendered` is the
40795
+ * text of the system messages memory tagged in the message list this step, so an instruction that only looks like a
40796
+ * chunk is never hinted. Returns `undefined` when nothing is hinted.
40797
+ */
40798
+ function markObservationCacheBoundary(prompt, apiProviderId, rendered) {
40799
+ if (!apiProviderId || apiProviderId.endsWith(".chat")) return void 0;
40800
+ const chunks = new Set(rendered?.filter((content) => typeof content === "string" && isObservationChunk(content)));
40801
+ if (chunks.size === 0) return void 0;
40802
+ let boundary = -1;
40803
+ prompt.forEach((message, index) => {
40804
+ if (message.role === "system" && chunks.has(message.content)) boundary = index;
40805
+ });
40806
+ if (boundary < 0) return void 0;
40807
+ return prompt.map((message, index) => index === boundary ? {
40808
+ ...message,
40809
+ providerOptions: {
40810
+ ...message.providerOptions,
40811
+ mastra: {
40812
+ ...message.providerOptions?.mastra,
40813
+ cacheBoundary: true
40814
+ }
40815
+ }
40816
+ } : message);
40817
+ }
40818
+ const isObservationChunk = (content) => content.startsWith("<observations>\n") && content.endsWith("\n</observations>");
40750
40819
  // src/processors/observational-memory/temporal-markers.ts
40751
40820
  const TEMPORAL_GAP_REMINDER_TYPE = "temporal-gap";
40752
40821
  function getTemporalGapReminderText(gapText, timestamp) {
@@ -41168,6 +41237,13 @@ var ObservationalMemoryProcessor = class {
41168
41237
  return messageList;
41169
41238
  });
41170
41239
  }
41240
+ /** Hints memory's cache boundary on this model call's prompt only, so the hint is never stored. */
41241
+ processLLMRequest({ prompt, model, apiProviderId, messageList }) {
41242
+ const provider = apiProviderId ?? (typeof model?.provider === "string" ? model.provider : void 0);
41243
+ const rendered = messageList?.getSystemMessages("observational-memory").map((message) => message.content);
41244
+ const hinted = markObservationCacheBoundary(prompt, provider, rendered);
41245
+ return hinted ? { prompt: hinted } : void 0;
41246
+ }
41171
41247
  async processOutputResult(args) {
41172
41248
  const { messageList, requestContext, state: _state } = args;
41173
41249
  const state = _state ?? {};
@@ -42654,6 +42730,7 @@ ${workingMemory}`;
42654
42730
  return new OMClass({
42655
42731
  storage: memoryStore,
42656
42732
  memory: this,
42733
+ liveDateHints: omConfig.liveDateHints,
42657
42734
  scope: omConfig.scope,
42658
42735
  retrieval: omConfig.retrieval,
42659
42736
  activateAfterIdle: omConfig.activateAfterIdle,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/memory",
3
- "version": "1.42.0-alpha.2",
3
+ "version": "1.42.0-alpha.4",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -73,7 +73,7 @@
73
73
  "@internal/ai-v7": "0.0.99",
74
74
  "@internal/lint": "0.0.152",
75
75
  "@internal/types-builder": "0.0.127",
76
- "@mastra/core": "1.87.0-alpha.11"
76
+ "@mastra/core": "1.87.0-alpha.13"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "@mastra/core": ">=1.85.1-0 <2.0.0-0"