@mastra/memory 1.41.1-alpha.1 → 1.41.1-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.
@@ -23899,6 +23899,9 @@ Observation groups with range IDs and your recall tool allows you to think back
23899
23899
  ${custom}`;
23900
23900
  }
23901
23901
  // src/processors/observational-memory/extractor.ts
23902
+ /** Sentinel a required inline section uses to signal that no update is needed. */
23903
+ const UNCHANGED_EXTRACTOR_VALUE = "UNCHANGED";
23904
+ const UNCHANGED_PATTERN = new RegExp(`^[\\s\`'"*]*${UNCHANGED_EXTRACTOR_VALUE}[\\s\`'"*.!]*$`, "i");
23902
23905
  const BUILT_IN_SLUGS = /* @__PURE__ */ new Set([
23903
23906
  "current-task",
23904
23907
  "suggested-response",
@@ -23964,11 +23967,16 @@ var Extractor = class Extractor {
23964
23967
  metadataKeyPath;
23965
23968
  onExtracted;
23966
23969
  retryStructuredExtractionOnEmptyObject;
23970
+ /**
23971
+ * @internal Require this inline section in single-thread observer calls. A missing section is recorded as an
23972
+ * extraction failure, and `UNCHANGED` is skipped rather than stored. Batched multi-thread calls treat it as optional.
23973
+ */
23974
+ required;
23967
23975
  /** @internal */
23968
23976
  internal;
23969
23977
  instructionsConfig;
23970
23978
  schemaConfig;
23971
- constructor(config, internal = false) {
23979
+ constructor(config, internal = false, required = false) {
23972
23980
  const name = config.name.trim();
23973
23981
  const instructions = typeof config.instructions === "string" ? config.instructions.trim() : void 0;
23974
23982
  const slug = slugifyExtractorName(name);
@@ -23991,6 +23999,7 @@ var Extractor = class Extractor {
23991
23999
  this.metadataKeyPath = isHook ? false : config.metadataKeyPath ?? `extracted.${slug}`;
23992
24000
  this.onExtracted = config.onExtracted;
23993
24001
  this.retryStructuredExtractionOnEmptyObject = config.retryStructuredExtractionOnEmptyObject ?? false;
24002
+ this.required = required;
23994
24003
  this.internal = internal;
23995
24004
  }
23996
24005
  async resolve(context) {
@@ -24006,7 +24015,7 @@ var Extractor = class Extractor {
24006
24015
  metadataKeyPath: this.metadataKeyPath,
24007
24016
  onExtracted: this.onExtracted,
24008
24017
  retryStructuredExtractionOnEmptyObject: this.retryStructuredExtractionOnEmptyObject
24009
- }, this.internal);
24018
+ }, this.internal, this.required);
24010
24019
  }
24011
24020
  };
24012
24021
  async function resolveExtractors(extractors, context) {
@@ -24061,6 +24070,7 @@ function parseExtractedValues(output, extractors) {
24061
24070
  const values = {};
24062
24071
  const failures = [];
24063
24072
  const inlineExtractors = extractors.filter((extractor) => extractor.mode === "inline");
24073
+ const unchangedSlugs = /* @__PURE__ */ new Set();
24064
24074
  const regex = new RegExp(`<${EXTRACTED_VALUES_TAG}>([\\s\\S]*?)<\\/${EXTRACTED_VALUES_TAG}>`, "gi");
24065
24075
  const matches = [...output.matchAll(regex)];
24066
24076
  for (const match of matches) try {
@@ -24070,6 +24080,10 @@ function parseExtractedValues(output, extractors) {
24070
24080
  if (!Object.prototype.hasOwnProperty.call(extractedValues, extractor.slug)) continue;
24071
24081
  const rawValue = extractedValues[extractor.slug];
24072
24082
  if (rawValue === void 0 || rawValue === null || rawValue === "") continue;
24083
+ if (extractor.required && typeof rawValue === "string" && UNCHANGED_PATTERN.test(rawValue)) {
24084
+ unchangedSlugs.add(extractor.slug);
24085
+ continue;
24086
+ }
24073
24087
  const parsed = extractor.schema.safeParse(rawValue);
24074
24088
  if (parsed.success) values[extractor.slug] = parsed.data;
24075
24089
  else failures.push({
@@ -24084,10 +24098,17 @@ function parseExtractedValues(output, extractors) {
24084
24098
  });
24085
24099
  }
24086
24100
  for (const extractor of inlineExtractors) {
24087
- if (Object.prototype.hasOwnProperty.call(values, extractor.slug)) continue;
24101
+ if (Object.prototype.hasOwnProperty.call(values, extractor.slug) || unchangedSlugs.has(extractor.slug)) continue;
24088
24102
  const tagRegex = new RegExp(`<${extractor.slug}>([\\s\\S]*?)<\\/${extractor.slug}>`, "gi");
24089
24103
  const rawValue = [...output.matchAll(tagRegex)].at(-1)?.[1]?.trim();
24090
- if (!rawValue) continue;
24104
+ if (!rawValue) {
24105
+ if (extractor.required) failures.push({
24106
+ slug: extractor.slug,
24107
+ error: `Observer output did not include the required <${extractor.slug}> section`
24108
+ });
24109
+ continue;
24110
+ }
24111
+ if (extractor.required && UNCHANGED_PATTERN.test(rawValue)) continue;
24091
24112
  try {
24092
24113
  values[extractor.slug] = parseExtractorValue(extractor, rawValue);
24093
24114
  } catch (error) {
@@ -24108,13 +24129,21 @@ function stripExtractorSections(output, extractors) {
24108
24129
  for (const extractor of inlineExtractors) stripped = stripped.replace(new RegExp(`[ \\t]*<${extractor.slug}>[\\s\\S]*?<\\/${extractor.slug}>\\s*`, "gi"), "");
24109
24130
  return stripped;
24110
24131
  }
24132
+ /**
24133
+ * Batched multi-thread observer calls share one output across threads, so a per-thread required
24134
+ * section would duplicate resource-level values and record spurious failures. Treat them as optional there.
24135
+ */
24136
+ function withoutRequiredSections(extractors) {
24137
+ return extractors.map((extractor) => extractor.required ? Object.assign(Object.create(Object.getPrototypeOf(extractor)), extractor, { required: false }) : extractor);
24138
+ }
24111
24139
  function buildExtractorOutputSections(extractors) {
24112
24140
  const inlineExtractors = extractors.filter((extractor) => extractor.mode === "inline");
24113
24141
  if (inlineExtractors.length === 0) return "";
24114
- 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}>
24142
+ const sections = inlineExtractors.map((extractor) => `<${extractor.slug}>
24115
24143
  ${extractor.instructions}
24116
- Include this section when the observations contain relevant information for <${extractor.slug}>. Write only that information inside the tag.
24117
- </${extractor.slug}>`).join("\n\n")}`;
24144
+ ${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.`}
24145
+ </${extractor.slug}>`).join("\n\n");
24146
+ 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}`;
24118
24147
  }
24119
24148
  function renderPriorValue(value) {
24120
24149
  return typeof value === "string" ? value : JSON.stringify(value);
@@ -27651,6 +27680,11 @@ var ObserverRunner = class {
27651
27680
  });
27652
27681
  const extractedValues = mergeExtractedValues(parsed.extractedValues, structuredExtraction.values);
27653
27682
  const extractionFailures = mergeExtractionFailures(parsed.extractionFailures, structuredExtraction.failures);
27683
+ const failedSlugs = activeExtractors.filter((extractor) => extractor.mode === "inline" && extractor.required).map((extractor) => extractor.slug).filter((slug) => parsed.extractionFailures?.some((failure) => failure.slug === slug));
27684
+ if (failedSlugs.length > 0) this.mastra?.getLogger?.().warn("OM observer could not extract required sections", {
27685
+ failedSlugs,
27686
+ threadId: messagesToObserve[0]?.threadId
27687
+ });
27654
27688
  const builtIns = getBuiltInExtractedValues(extractedValues);
27655
27689
  const systemPrompt = buildObserverSystemPrompt(false, this.observationConfig.instruction, this.observationConfig.threadTitle, activeExtractors);
27656
27690
  this.lastExchange = {
@@ -27783,10 +27817,11 @@ var ObserverRunner = class {
27783
27817
  usage: totalUsage
27784
27818
  };
27785
27819
  }
27786
- const agent = this.createAgent(resolvedModel.model, true, void 0, activeExtractors);
27820
+ const batchExtractors = withoutRequiredSections(activeExtractors);
27821
+ const agent = this.createAgent(resolvedModel.model, true, void 0, batchExtractors);
27787
27822
  const internalRequestContext = withOmInternalThreadId(requestContext, agent.id);
27788
27823
  const multiThreadAttachmentFilter = this.resolveAttachmentFilter(resolvedModel.model, requestContext);
27789
- const observerMessages = [buildMultiThreadObserverRequestMessage(existingObservations, messagesByThread, threadOrder, priorMetadataByThread, wasTruncated, this.observationConfig.threadTitle, activeExtractors, {
27824
+ const observerMessages = [buildMultiThreadObserverRequestMessage(existingObservations, messagesByThread, threadOrder, priorMetadataByThread, wasTruncated, this.observationConfig.threadTitle, batchExtractors, {
27790
27825
  attachmentFilter: multiThreadAttachmentFilter,
27791
27826
  timeZone
27792
27827
  })];
@@ -27842,12 +27877,12 @@ var ObserverRunner = class {
27842
27877
  });
27843
27878
  };
27844
27879
  let result = await doGenerate();
27845
- let parsed = parseMultiThreadObserverOutput(result.text, activeExtractors);
27880
+ let parsed = parseMultiThreadObserverOutput(result.text, batchExtractors);
27846
27881
  let retriedDueToDegenerate = false;
27847
27882
  if (parsed.degenerate) {
27848
27883
  omDebug(`[OM:callMultiThreadObserver] degenerate repetition detected, retrying once. ${describeDegenerateOutput(result.text, 2e3)}`);
27849
27884
  result = await doGenerate();
27850
- parsed = parseMultiThreadObserverOutput(result.text, activeExtractors);
27885
+ parsed = parseMultiThreadObserverOutput(result.text, batchExtractors);
27851
27886
  retriedDueToDegenerate = true;
27852
27887
  if (parsed.degenerate) {
27853
27888
  omDebug(`[OM:callMultiThreadObserver] degenerate repetition on retry, failing. ${describeDegenerateOutput(result.text, 2e3)}`);
@@ -27858,7 +27893,7 @@ var ObserverRunner = class {
27858
27893
  const aggregatedExtractedValues = mergeExtractedValues(...Array.from(parsed.threads, ([threadId, threadResult]) => mergeExtractedValues(threadResult.extractedValues, structuredExtractionByThread.get(threadId)?.values)));
27859
27894
  const aggregatedExtractionFailures = mergeExtractionFailures(...Array.from(parsed.threads, ([threadId, threadResult]) => mergeExtractionFailures(threadResult.extractionFailures, structuredExtractionByThread.get(threadId)?.failures)));
27860
27895
  const aggregatedBuiltIns = getBuiltInExtractedValues(aggregatedExtractedValues);
27861
- const systemPrompt = buildObserverSystemPrompt(true, this.observationConfig.instruction, this.observationConfig.threadTitle, activeExtractors);
27896
+ const systemPrompt = buildObserverSystemPrompt(true, this.observationConfig.instruction, this.observationConfig.threadTitle, batchExtractors);
27862
27897
  this.lastExchange = {
27863
27898
  systemPrompt,
27864
27899
  observerMessages,
@@ -27890,7 +27925,7 @@ var ObserverRunner = class {
27890
27925
  threadTitle: builtIns.threadTitle ?? threadResult.threadTitle,
27891
27926
  extractedValues,
27892
27927
  extractionFailures,
27893
- extractors: activeExtractors
27928
+ extractors: batchExtractors
27894
27929
  });
27895
27930
  }
27896
27931
  for (const threadId of results.keys()) for (const msg of messagesByThread.get(threadId) ?? []) this.observedMessageIds.add(msg.id);
@@ -27929,7 +27964,8 @@ function assertRecognizedObserverOutput(output, label, isRecognized) {
27929
27964
  function hasSingleThreadObserverContent(text, extractors) {
27930
27965
  if (/^[ \t]*<observations>/im.test(text)) return true;
27931
27966
  const parsed = parseObserverOutput(text, extractors);
27932
- return Boolean(parsed.degenerate || parsed.observations || parsed.currentTask || parsed.suggestedContinuation || parsed.threadTitle || Object.keys(parsed.extractedValues ?? {}).length || parsed.extractionFailures?.length);
27967
+ const requiredSlugs = new Set(extractors.filter((extractor) => extractor.mode === "inline" && extractor.required).map((extractor) => extractor.slug));
27968
+ 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)));
27933
27969
  }
27934
27970
  /**
27935
27971
  * Multi-thread replies carry every recognised section inside `<thread>` blocks, so a reply
@@ -29832,7 +29868,7 @@ var WorkingMemoryExtractor = class extends Extractor {
29832
29868
  });
29833
29869
  return document;
29834
29870
  }
29835
- });
29871
+ }, false, true);
29836
29872
  }
29837
29873
  };
29838
29874
  // src/removed-subconscious.ts
@@ -40744,7 +40780,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
40744
40780
  const config = this.getMergedThreadConfig(memoryConfig || {});
40745
40781
  this.assertWorkingMemoryStateSignalsCompatibility(config);
40746
40782
  if (!config.workingMemory?.enabled) throw new Error("Working memory is not enabled for this memory instance");
40747
- const mutexKey = memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`;
40783
+ const mutexKey = (config.workingMemory.scope || "resource") === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
40748
40784
  const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new async_mutex.Mutex();
40749
40785
  this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
40750
40786
  const release = await mutex.acquire();
@@ -42733,4 +42769,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
42733
42769
  }
42734
42770
  });
42735
42771
 
42736
- //# sourceMappingURL=src-Bo9Kpfk_.cjs.map
42772
+ //# sourceMappingURL=src-DrWCcSnW.cjs.map