@mastra/memory 1.41.1-alpha.1 → 1.41.1-alpha.3

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.
@@ -23878,6 +23878,9 @@ Observation groups with range IDs and your recall tool allows you to think back
23878
23878
  ${custom}`;
23879
23879
  }
23880
23880
  // src/processors/observational-memory/extractor.ts
23881
+ /** Sentinel a required inline section uses to signal that no update is needed. */
23882
+ const UNCHANGED_EXTRACTOR_VALUE = "UNCHANGED";
23883
+ const UNCHANGED_PATTERN = new RegExp(`^[\\s\`'"*]*${UNCHANGED_EXTRACTOR_VALUE}[\\s\`'"*.!]*$`, "i");
23881
23884
  const BUILT_IN_SLUGS = /* @__PURE__ */ new Set([
23882
23885
  "current-task",
23883
23886
  "suggested-response",
@@ -23943,11 +23946,16 @@ var Extractor = class Extractor {
23943
23946
  metadataKeyPath;
23944
23947
  onExtracted;
23945
23948
  retryStructuredExtractionOnEmptyObject;
23949
+ /**
23950
+ * @internal Require this inline section in single-thread observer calls. A missing section is recorded as an
23951
+ * extraction failure, and `UNCHANGED` is skipped rather than stored. Batched multi-thread calls treat it as optional.
23952
+ */
23953
+ required;
23946
23954
  /** @internal */
23947
23955
  internal;
23948
23956
  instructionsConfig;
23949
23957
  schemaConfig;
23950
- constructor(config, internal = false) {
23958
+ constructor(config, internal = false, required = false) {
23951
23959
  const name = config.name.trim();
23952
23960
  const instructions = typeof config.instructions === "string" ? config.instructions.trim() : void 0;
23953
23961
  const slug = slugifyExtractorName(name);
@@ -23970,6 +23978,7 @@ var Extractor = class Extractor {
23970
23978
  this.metadataKeyPath = isHook ? false : config.metadataKeyPath ?? `extracted.${slug}`;
23971
23979
  this.onExtracted = config.onExtracted;
23972
23980
  this.retryStructuredExtractionOnEmptyObject = config.retryStructuredExtractionOnEmptyObject ?? false;
23981
+ this.required = required;
23973
23982
  this.internal = internal;
23974
23983
  }
23975
23984
  async resolve(context) {
@@ -23985,7 +23994,7 @@ var Extractor = class Extractor {
23985
23994
  metadataKeyPath: this.metadataKeyPath,
23986
23995
  onExtracted: this.onExtracted,
23987
23996
  retryStructuredExtractionOnEmptyObject: this.retryStructuredExtractionOnEmptyObject
23988
- }, this.internal);
23997
+ }, this.internal, this.required);
23989
23998
  }
23990
23999
  };
23991
24000
  async function resolveExtractors(extractors, context) {
@@ -24040,6 +24049,7 @@ function parseExtractedValues(output, extractors) {
24040
24049
  const values = {};
24041
24050
  const failures = [];
24042
24051
  const inlineExtractors = extractors.filter((extractor) => extractor.mode === "inline");
24052
+ const unchangedSlugs = /* @__PURE__ */ new Set();
24043
24053
  const regex = new RegExp(`<${EXTRACTED_VALUES_TAG}>([\\s\\S]*?)<\\/${EXTRACTED_VALUES_TAG}>`, "gi");
24044
24054
  const matches = [...output.matchAll(regex)];
24045
24055
  for (const match of matches) try {
@@ -24049,6 +24059,10 @@ function parseExtractedValues(output, extractors) {
24049
24059
  if (!Object.prototype.hasOwnProperty.call(extractedValues, extractor.slug)) continue;
24050
24060
  const rawValue = extractedValues[extractor.slug];
24051
24061
  if (rawValue === void 0 || rawValue === null || rawValue === "") continue;
24062
+ if (extractor.required && typeof rawValue === "string" && UNCHANGED_PATTERN.test(rawValue)) {
24063
+ unchangedSlugs.add(extractor.slug);
24064
+ continue;
24065
+ }
24052
24066
  const parsed = extractor.schema.safeParse(rawValue);
24053
24067
  if (parsed.success) values[extractor.slug] = parsed.data;
24054
24068
  else failures.push({
@@ -24063,10 +24077,17 @@ function parseExtractedValues(output, extractors) {
24063
24077
  });
24064
24078
  }
24065
24079
  for (const extractor of inlineExtractors) {
24066
- if (Object.prototype.hasOwnProperty.call(values, extractor.slug)) continue;
24080
+ if (Object.prototype.hasOwnProperty.call(values, extractor.slug) || unchangedSlugs.has(extractor.slug)) continue;
24067
24081
  const tagRegex = new RegExp(`<${extractor.slug}>([\\s\\S]*?)<\\/${extractor.slug}>`, "gi");
24068
24082
  const rawValue = [...output.matchAll(tagRegex)].at(-1)?.[1]?.trim();
24069
- if (!rawValue) continue;
24083
+ if (!rawValue) {
24084
+ if (extractor.required) failures.push({
24085
+ slug: extractor.slug,
24086
+ error: `Observer output did not include the required <${extractor.slug}> section`
24087
+ });
24088
+ continue;
24089
+ }
24090
+ if (extractor.required && UNCHANGED_PATTERN.test(rawValue)) continue;
24070
24091
  try {
24071
24092
  values[extractor.slug] = parseExtractorValue(extractor, rawValue);
24072
24093
  } catch (error) {
@@ -24087,13 +24108,21 @@ function stripExtractorSections(output, extractors) {
24087
24108
  for (const extractor of inlineExtractors) stripped = stripped.replace(new RegExp(`[ \\t]*<${extractor.slug}>[\\s\\S]*?<\\/${extractor.slug}>\\s*`, "gi"), "");
24088
24109
  return stripped;
24089
24110
  }
24111
+ /**
24112
+ * Batched multi-thread observer calls share one output across threads, so a per-thread required
24113
+ * section would duplicate resource-level values and record spurious failures. Treat them as optional there.
24114
+ */
24115
+ function withoutRequiredSections(extractors) {
24116
+ return extractors.map((extractor) => extractor.required ? Object.assign(Object.create(Object.getPrototypeOf(extractor)), extractor, { required: false }) : extractor);
24117
+ }
24090
24118
  function buildExtractorOutputSections(extractors) {
24091
24119
  const inlineExtractors = extractors.filter((extractor) => extractor.mode === "inline");
24092
24120
  if (inlineExtractors.length === 0) return "";
24093
- return `Additional optional XML sections:\nIf the observations include information relevant to any of these tags, output that tag after <observations> and include the relevant information.\n${inlineExtractors.map((extractor) => `<${extractor.slug}>
24121
+ const sections = inlineExtractors.map((extractor) => `<${extractor.slug}>
24094
24122
  ${extractor.instructions}
24095
- Include this section when the observations contain relevant information for <${extractor.slug}>. Write only that information inside the tag.
24096
- </${extractor.slug}>`).join("\n\n")}`;
24123
+ ${extractor.required ? `This section is REQUIRED: always output <${extractor.slug}>. If nothing needs to change, write exactly ${UNCHANGED_EXTRACTOR_VALUE} inside the tag.` : `Include this section when the observations contain relevant information for <${extractor.slug}>. Write only that information inside the tag.`}
24124
+ </${extractor.slug}>`).join("\n\n");
24125
+ return `${inlineExtractors.some((extractor) => extractor.required) ? "Additional XML sections:\nOutput these tags after <observations>, following the instructions in each tag." : "Additional optional XML sections:\nIf the observations include information relevant to any of these tags, output that tag after <observations> and include the relevant information."}\n${sections}`;
24097
24126
  }
24098
24127
  function renderPriorValue(value) {
24099
24128
  return typeof value === "string" ? value : JSON.stringify(value);
@@ -27630,6 +27659,11 @@ var ObserverRunner = class {
27630
27659
  });
27631
27660
  const extractedValues = mergeExtractedValues(parsed.extractedValues, structuredExtraction.values);
27632
27661
  const extractionFailures = mergeExtractionFailures(parsed.extractionFailures, structuredExtraction.failures);
27662
+ const failedSlugs = activeExtractors.filter((extractor) => extractor.mode === "inline" && extractor.required).map((extractor) => extractor.slug).filter((slug) => parsed.extractionFailures?.some((failure) => failure.slug === slug));
27663
+ if (failedSlugs.length > 0) this.mastra?.getLogger?.().warn("OM observer could not extract required sections", {
27664
+ failedSlugs,
27665
+ threadId: messagesToObserve[0]?.threadId
27666
+ });
27633
27667
  const builtIns = getBuiltInExtractedValues(extractedValues);
27634
27668
  const systemPrompt = buildObserverSystemPrompt(false, this.observationConfig.instruction, this.observationConfig.threadTitle, activeExtractors);
27635
27669
  this.lastExchange = {
@@ -27762,10 +27796,11 @@ var ObserverRunner = class {
27762
27796
  usage: totalUsage
27763
27797
  };
27764
27798
  }
27765
- const agent = this.createAgent(resolvedModel.model, true, void 0, activeExtractors);
27799
+ const batchExtractors = withoutRequiredSections(activeExtractors);
27800
+ const agent = this.createAgent(resolvedModel.model, true, void 0, batchExtractors);
27766
27801
  const internalRequestContext = withOmInternalThreadId(requestContext, agent.id);
27767
27802
  const multiThreadAttachmentFilter = this.resolveAttachmentFilter(resolvedModel.model, requestContext);
27768
- const observerMessages = [buildMultiThreadObserverRequestMessage(existingObservations, messagesByThread, threadOrder, priorMetadataByThread, wasTruncated, this.observationConfig.threadTitle, activeExtractors, {
27803
+ const observerMessages = [buildMultiThreadObserverRequestMessage(existingObservations, messagesByThread, threadOrder, priorMetadataByThread, wasTruncated, this.observationConfig.threadTitle, batchExtractors, {
27769
27804
  attachmentFilter: multiThreadAttachmentFilter,
27770
27805
  timeZone
27771
27806
  })];
@@ -27821,12 +27856,12 @@ var ObserverRunner = class {
27821
27856
  });
27822
27857
  };
27823
27858
  let result = await doGenerate();
27824
- let parsed = parseMultiThreadObserverOutput(result.text, activeExtractors);
27859
+ let parsed = parseMultiThreadObserverOutput(result.text, batchExtractors);
27825
27860
  let retriedDueToDegenerate = false;
27826
27861
  if (parsed.degenerate) {
27827
27862
  omDebug(`[OM:callMultiThreadObserver] degenerate repetition detected, retrying once. ${describeDegenerateOutput(result.text, 2e3)}`);
27828
27863
  result = await doGenerate();
27829
- parsed = parseMultiThreadObserverOutput(result.text, activeExtractors);
27864
+ parsed = parseMultiThreadObserverOutput(result.text, batchExtractors);
27830
27865
  retriedDueToDegenerate = true;
27831
27866
  if (parsed.degenerate) {
27832
27867
  omDebug(`[OM:callMultiThreadObserver] degenerate repetition on retry, failing. ${describeDegenerateOutput(result.text, 2e3)}`);
@@ -27837,7 +27872,7 @@ var ObserverRunner = class {
27837
27872
  const aggregatedExtractedValues = mergeExtractedValues(...Array.from(parsed.threads, ([threadId, threadResult]) => mergeExtractedValues(threadResult.extractedValues, structuredExtractionByThread.get(threadId)?.values)));
27838
27873
  const aggregatedExtractionFailures = mergeExtractionFailures(...Array.from(parsed.threads, ([threadId, threadResult]) => mergeExtractionFailures(threadResult.extractionFailures, structuredExtractionByThread.get(threadId)?.failures)));
27839
27874
  const aggregatedBuiltIns = getBuiltInExtractedValues(aggregatedExtractedValues);
27840
- const systemPrompt = buildObserverSystemPrompt(true, this.observationConfig.instruction, this.observationConfig.threadTitle, activeExtractors);
27875
+ const systemPrompt = buildObserverSystemPrompt(true, this.observationConfig.instruction, this.observationConfig.threadTitle, batchExtractors);
27841
27876
  this.lastExchange = {
27842
27877
  systemPrompt,
27843
27878
  observerMessages,
@@ -27869,7 +27904,7 @@ var ObserverRunner = class {
27869
27904
  threadTitle: builtIns.threadTitle ?? threadResult.threadTitle,
27870
27905
  extractedValues,
27871
27906
  extractionFailures,
27872
- extractors: activeExtractors
27907
+ extractors: batchExtractors
27873
27908
  });
27874
27909
  }
27875
27910
  for (const threadId of results.keys()) for (const msg of messagesByThread.get(threadId) ?? []) this.observedMessageIds.add(msg.id);
@@ -27908,7 +27943,8 @@ function assertRecognizedObserverOutput(output, label, isRecognized) {
27908
27943
  function hasSingleThreadObserverContent(text, extractors) {
27909
27944
  if (/^[ \t]*<observations>/im.test(text)) return true;
27910
27945
  const parsed = parseObserverOutput(text, extractors);
27911
- return Boolean(parsed.degenerate || parsed.observations || parsed.currentTask || parsed.suggestedContinuation || parsed.threadTitle || Object.keys(parsed.extractedValues ?? {}).length || parsed.extractionFailures?.length);
27946
+ const requiredSlugs = new Set(extractors.filter((extractor) => extractor.mode === "inline" && extractor.required).map((extractor) => extractor.slug));
27947
+ return Boolean(parsed.degenerate || parsed.observations || parsed.currentTask || parsed.suggestedContinuation || parsed.threadTitle || Object.keys(parsed.extractedValues ?? {}).length || parsed.extractionFailures?.some((failure) => !requiredSlugs.has(failure.slug)));
27912
27948
  }
27913
27949
  /**
27914
27950
  * Multi-thread replies carry every recognised section inside `<thread>` blocks, so a reply
@@ -29811,7 +29847,7 @@ var WorkingMemoryExtractor = class extends Extractor {
29811
29847
  });
29812
29848
  return document;
29813
29849
  }
29814
- });
29850
+ }, false, true);
29815
29851
  }
29816
29852
  };
29817
29853
  // src/removed-subconscious.ts
@@ -30190,6 +30226,31 @@ function wrapInObservationGroup(observations, range, id = generateAnchorId(), _s
30190
30226
  const content = observations.trim();
30191
30227
  return `<observation-group id="${id}" range="${range}"${kind ? ` kind="${kind}"` : ""}>\n${content}\n</observation-group>`;
30192
30228
  }
30229
+ function isObservationGroupOpeningLine(line) {
30230
+ const trimmed = line.trimStart();
30231
+ return trimmed.startsWith(OBSERVATION_GROUP_OPEN) && /\s/.test(trimmed[18] ?? "");
30232
+ }
30233
+ /**
30234
+ * Moves a cut of `cut` leading lines so it never splits an observation group. A cut inside a group
30235
+ * moves back to just before the group's opening tag (and the blank lines that separate it from the
30236
+ * previous group). When nothing precedes that group, the cut moves forward to just after its closing
30237
+ * tag instead, so the whole group is cut. A cut outside every group, and observations without group
30238
+ * tags, are returned unchanged.
30239
+ */
30240
+ function alignLineCutToObservationGroups(lines, cut) {
30241
+ let openingLine = -1;
30242
+ for (let i = 0; i < cut; i++) {
30243
+ const line = lines[i];
30244
+ if (isObservationGroupOpeningLine(line)) openingLine = i;
30245
+ else if (line.trim() === OBSERVATION_GROUP_CLOSE) openingLine = -1;
30246
+ }
30247
+ if (openingLine === -1) return cut;
30248
+ let before = openingLine;
30249
+ while (before > 0 && lines[before - 1].trim() === "") before--;
30250
+ if (before > 0) return before;
30251
+ for (let i = cut; i < lines.length; i++) if (lines[i].trim() === OBSERVATION_GROUP_CLOSE) return i + 1;
30252
+ return cut;
30253
+ }
30193
30254
  function parseObservationGroups(observations) {
30194
30255
  if (!observations) return [];
30195
30256
  const groups = [];
@@ -36013,7 +36074,7 @@ var ReflectorRunner = class {
36013
36074
  const totalLines = allLines.length;
36014
36075
  const avgTokensPerLine = totalLines > 0 ? observationTokens / totalLines : 0;
36015
36076
  const activationPointTokens = reflectThreshold * bufferActivation;
36016
- const linesToReflect = avgTokensPerLine > 0 ? Math.min(Math.floor(activationPointTokens / avgTokensPerLine), totalLines) : totalLines;
36077
+ const linesToReflect = alignLineCutToObservationGroups(allLines, avgTokensPerLine > 0 ? Math.min(Math.floor(activationPointTokens / avgTokensPerLine), totalLines) : totalLines);
36017
36078
  const hookContext = {
36018
36079
  threadId: currentRecord.threadId ?? void 0,
36019
36080
  resourceId: currentRecord.resourceId ?? void 0,
@@ -40723,7 +40784,7 @@ var Memory = class Memory extends MastraMemory {
40723
40784
  const config = this.getMergedThreadConfig(memoryConfig || {});
40724
40785
  this.assertWorkingMemoryStateSignalsCompatibility(config);
40725
40786
  if (!config.workingMemory?.enabled) throw new Error("Working memory is not enabled for this memory instance");
40726
- const mutexKey = memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`;
40787
+ const mutexKey = (config.workingMemory.scope || "resource") === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
40727
40788
  const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new Mutex();
40728
40789
  this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
40729
40790
  const release = await mutex.acquire();
@@ -42437,4 +42498,4 @@ Notes:
42437
42498
  };
42438
42499
  export { summarizeConversation as A, injectAnchorIds as B, wrapInObservationGroup as C, WorkingMemoryExtractor as D, Subconscious as E, extractCurrentTask as F, OBSERVATION_CONTEXT_INSTRUCTIONS as G, stripEphemeralAnchorIds as H, formatMessagesForObserver as I, OBSERVATION_CONTINUATION_HINT as J, OBSERVATION_CONTEXT_PROMPT as K, hasCurrentTaskSection as L, OBSERVER_SYSTEM_PROMPT as M, buildObserverPrompt as N, deepMergeWorkingMemory as O, buildObserverSystemPrompt as P, optimizeObservationsForContext as R, stripObservationGroups as S, StaleKnowledgeSemanticIndexError as T, Extractor as U, parseAnchorId as V, OBSERVATIONAL_MEMORY_DEFAULTS as W, getObservationContextPrompt as Y, combineObservationGroupRanges as _, extractWorkingMemoryContent as a, reconcileObservationGroupsFromReflection as b, getObservationsAsOf as c, AUTO_MODEL_BY_PROVIDER as d, resolveAutoModelId as f, ModelByInputTokens as g, WorkingMemoryStateProcessor as h, WorkingMemory as i, TokenCounter as j, SUMMARIZE_THREAD_DEFAULTS 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, OBSERVATION_CONTEXT_PROMPT_THREAD as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, deriveObservationGroupProvenance as v, KnowledgeSemanticIndexCoordinator as w, renderObservationGroupsForReflection as x, parseObservationGroups as y, parseObserverOutput as z };
42439
42500
 
42440
- //# sourceMappingURL=src-BL6KZcyR.js.map
42501
+ //# sourceMappingURL=src-KIKQ7ztT.js.map