@mastra/memory 1.41.1-alpha.0 → 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.
@@ -6,7 +6,7 @@ import { toJSONSchema } from "zod/v4/core";
6
6
  import { Agent, MessageList } from "@mastra/core/agent";
7
7
  import { ErrorCategory, ErrorDomain, MastraError, classifyProviderError } from "@mastra/core/error";
8
8
  import { coreFeatures } from "@mastra/core/features";
9
- import { MastraMemory, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, setThreadOMMetadata } from "@mastra/core/memory";
9
+ import { MESSAGE_EMBEDDING_CHARS_PER_TOKEN, MastraMemory, buildMessageEmbeddingRows, chunkMessageText, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, resolveMaxChunkChars, setThreadOMMetadata, upsertMessageVectors } from "@mastra/core/memory";
10
10
  import * as coreObservability from "@mastra/core/observability";
11
11
  import { EntityType, SpanType, createObservabilityContext, getOrCreateSpan } from "@mastra/core/observability";
12
12
  import { MessageHistory, MessageHistory as MessageHistory$1, SemanticRecall, TokenLimiterProcessor, WorkingMemory } from "@mastra/core/processors";
@@ -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
@@ -39838,7 +39874,8 @@ var ObservationalMemoryProcessor = class {
39838
39874
  ctx = await step.prepare();
39839
39875
  } catch (error) {
39840
39876
  const err = error instanceof Error ? error : new Error(String(error));
39841
- const abortMessage = abortSignal?.aborted ? "Agent execution was aborted" : `Encountered error during memory observation: ${err.message}`;
39877
+ const abortReason = abortSignal?.reason;
39878
+ const abortMessage = abortSignal?.aborted ? abortReason instanceof Error && abortReason.name !== "AbortError" ? `Agent execution was aborted: ${abortReason.message}` : "Agent execution was aborted" : `Encountered error during memory observation: ${err.message}`;
39842
39879
  const failedTurn = this.turn;
39843
39880
  await failedTurn.end().catch(() => {});
39844
39881
  if (this.turn === failedTurn) this.turn = void 0;
@@ -40147,7 +40184,6 @@ function normalizeObservationalMemoryConfig(config) {
40147
40184
  function hasWorkingMemoryExtractor(extractors) {
40148
40185
  return !!extractors?.some((extractor) => extractor.slug === "working-memory");
40149
40186
  }
40150
- const CHARS_PER_TOKEN = 4;
40151
40187
  const DEFAULT_MESSAGE_RANGE = {
40152
40188
  before: 1,
40153
40189
  after: 1
@@ -40290,6 +40326,7 @@ var Memory = class Memory extends MastraMemory {
40290
40326
  });
40291
40327
  this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig);
40292
40328
  this.threadConfig = mergedConfig;
40329
+ resolveMaxChunkChars({ maxChunkChars: this.configuredMaxChunkChars });
40293
40330
  const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory);
40294
40331
  if (omConfig?.retrieval && typeof omConfig.retrieval === "object" && omConfig.retrieval.vector) {
40295
40332
  if (!this.vector) throw new Error("`retrieval: { vector: true }` requires a vector store. Pass a `vector` option to your Memory instance.");
@@ -40722,7 +40759,7 @@ var Memory = class Memory extends MastraMemory {
40722
40759
  const config = this.getMergedThreadConfig(memoryConfig || {});
40723
40760
  this.assertWorkingMemoryStateSignalsCompatibility(config);
40724
40761
  if (!config.workingMemory?.enabled) throw new Error("Working memory is not enabled for this memory instance");
40725
- const mutexKey = memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`;
40762
+ const mutexKey = (config.workingMemory.scope || "resource") === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
40726
40763
  const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new Mutex();
40727
40764
  this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
40728
40765
  const release = await mutex.acquire();
@@ -40805,28 +40842,9 @@ ${workingMemory}`;
40805
40842
  release();
40806
40843
  }
40807
40844
  }
40845
+ /** Splits text into chunks of at most `tokenSize` English tokens, measured as characters. */
40808
40846
  chunkText(text, tokenSize = 4096) {
40809
- const charSize = tokenSize * CHARS_PER_TOKEN;
40810
- const chunks = [];
40811
- let currentChunk = "";
40812
- const words = text.split(/\s+/);
40813
- for (const word of words) {
40814
- if (word.length > charSize) {
40815
- if (currentChunk) {
40816
- chunks.push(currentChunk);
40817
- currentChunk = "";
40818
- }
40819
- for (let i = 0; i < word.length; i += charSize) chunks.push(word.slice(i, i + charSize));
40820
- continue;
40821
- }
40822
- const wordWithSpace = currentChunk ? " " + word : word;
40823
- if (currentChunk.length + wordWithSpace.length > charSize) {
40824
- if (currentChunk) chunks.push(currentChunk);
40825
- currentChunk = word;
40826
- } else currentChunk += wordWithSpace;
40827
- }
40828
- if (currentChunk) chunks.push(currentChunk);
40829
- return chunks;
40847
+ return chunkMessageText(text, tokenSize * MESSAGE_EMBEDDING_CHARS_PER_TOKEN);
40830
40848
  }
40831
40849
  hasher = xxhash();
40832
40850
  embeddingCache = new LRUCache({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
@@ -40842,11 +40860,23 @@ ${workingMemory}`;
40842
40860
  return cached;
40843
40861
  }
40844
40862
  const chunks = this.chunkText(content);
40863
+ const { embeddings, usage } = await this.embedValues(chunks);
40864
+ const result = {
40865
+ embeddings,
40866
+ chunks,
40867
+ usage,
40868
+ dimension: embeddings[0]?.length
40869
+ };
40870
+ this.embeddingCache.set(key, result);
40871
+ return result;
40872
+ }
40873
+ /** Sends texts to the embedder through the AI SDK version that matches its spec. */
40874
+ async embedValues(values) {
40845
40875
  if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40846
40876
  const isFastEmbed = this.embedder.provider === `fastembed`;
40847
40877
  if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
40848
40878
  const options = {
40849
- values: chunks,
40879
+ values,
40850
40880
  maxRetries: 3
40851
40881
  };
40852
40882
  const model = this.embedder;
@@ -40881,106 +40911,87 @@ ${workingMemory}`;
40881
40911
  }
40882
40912
  if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;
40883
40913
  const { embeddings, usage } = await promise;
40884
- const result = {
40914
+ return {
40885
40915
  embeddings,
40886
- chunks,
40887
- usage,
40888
- dimension: embeddings[0]?.length
40916
+ usage
40889
40917
  };
40890
- this.embeddingCache.set(key, result);
40891
- return result;
40892
40918
  }
40893
- async saveMessages({ messages, memoryConfig, observabilityContext }) {
40919
+ /**
40920
+ * Metadata of each thread, spread onto that thread's vector rows so `semanticRecall.filter`
40921
+ * can match thread attributes.
40922
+ */
40923
+ async loadThreadMetadata(threadIds) {
40924
+ const memoryStore = await this.getMemoryStore();
40925
+ const metadataByThread = /* @__PURE__ */ new Map();
40926
+ await Promise.all(threadIds.map(async (threadId) => {
40927
+ try {
40928
+ const thread = await memoryStore.getThreadById({ threadId });
40929
+ if (thread?.metadata) metadataByThread.set(threadId, thread.metadata);
40930
+ } catch (error) {
40931
+ const message = error instanceof Error ? error.message : String(error);
40932
+ throw new Error(`Could not fetch metadata for thread ${threadId} while writing semantic recall embeddings: ${message}`);
40933
+ }
40934
+ }));
40935
+ return metadataByThread;
40936
+ }
40937
+ /**
40938
+ * Embeds messages into vector rows in the shared format, without writing them. Every
40939
+ * message-vector write in this class builds its rows here.
40940
+ */
40941
+ async buildMessageVectorRows({ items, embeddedMessages }) {
40942
+ if (items.length === 0) return {
40943
+ ids: [],
40944
+ metadata: [],
40945
+ embeddedEntries: []
40946
+ };
40947
+ if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40948
+ return buildMessageEmbeddingRows({
40949
+ items,
40950
+ embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
40951
+ maxChunkChars: resolveMaxChunkChars({
40952
+ maxChunkChars: this.configuredMaxChunkChars,
40953
+ embedder: this.embedder
40954
+ }),
40955
+ loadThreadMetadata: (threadIds) => this.loadThreadMetadata(threadIds),
40956
+ embeddedMessages,
40957
+ indexName: embeddedMessages ? this.getEmbeddingIndexName(this.isSelfEmbedding ? void 0 : await this.getEmbeddingDimension()) : void 0
40958
+ });
40959
+ }
40960
+ /** Writes rows from {@link buildMessageVectorRows} into the message index for `config`. */
40961
+ async writeMessageVectorRows({ rows, config, embeddedMessages }) {
40962
+ if (!this.vector || rows.ids.length === 0) return;
40963
+ const { indexName } = await this.createEmbeddingIndex(rows.dimension, config);
40964
+ await upsertMessageVectors(this.vector, indexName, rows, embeddedMessages);
40965
+ }
40966
+ /**
40967
+ * Embeds messages and writes their vector rows.
40968
+ *
40969
+ * @returns Tokens billed by the embedder, if any.
40970
+ */
40971
+ async writeMessageVectors(args) {
40972
+ if (!this.vector) return void 0;
40973
+ const rows = await this.buildMessageVectorRows(args);
40974
+ await this.writeMessageVectorRows({
40975
+ ...args,
40976
+ rows
40977
+ });
40978
+ return rows.usage;
40979
+ }
40980
+ async saveMessages({ messages, memoryConfig, observabilityContext, embeddedMessages }) {
40894
40981
  const span = this.createMemorySpan("save", observabilityContext, void 0, { messageCount: messages.length });
40895
40982
  try {
40896
40983
  const updatedMessages = this.prepareMessagesForPersistence(messages);
40897
40984
  const config = this.getMergedThreadConfig(memoryConfig);
40898
40985
  const dbMessages = new MessageList({ generateMessageId: () => this.generateId() }).add(updatedMessages, "memory").get.all.db();
40899
- const memoryStore = await this.getMemoryStore();
40900
- const result = await memoryStore.saveMessages({ messages: dbMessages });
40901
- let totalTokens = 0;
40902
- if (this.vector && config.semanticRecall) {
40903
- const messagesByThread = /* @__PURE__ */ new Map();
40904
- updatedMessages.forEach((message) => {
40905
- if (message.threadId) {
40906
- if (!messagesByThread.has(message.threadId)) messagesByThread.set(message.threadId, []);
40907
- messagesByThread.get(message.threadId).push(message);
40908
- }
40909
- });
40910
- const threadMetadataMap = /* @__PURE__ */ new Map();
40911
- await Promise.all(Array.from(messagesByThread.keys()).map(async (threadId) => {
40912
- try {
40913
- const thread = await memoryStore.getThreadById({ threadId });
40914
- if (thread?.metadata) threadMetadataMap.set(threadId, thread.metadata);
40915
- } catch (error) {
40916
- const message = error instanceof Error ? error.message : String(error);
40917
- throw new Error(`Could not fetch metadata for thread ${threadId} while saving semantic recall embeddings: ${message}`);
40918
- }
40919
- }));
40920
- const embeddingData = [];
40921
- let dimension;
40922
- await Promise.all(updatedMessages.map(async (message) => {
40923
- let textForEmbedding = null;
40924
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
40925
- else if (message.content.parts && message.content.parts.length > 0) {
40926
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
40927
- if (joined) textForEmbedding = joined;
40928
- }
40929
- if (!textForEmbedding) return;
40930
- let embeddings = [];
40931
- let documents;
40932
- let chunks;
40933
- if (this.isSelfEmbedding) {
40934
- chunks = this.chunkText(textForEmbedding);
40935
- documents = chunks;
40936
- } else {
40937
- const result = await this.embedMessageContent(textForEmbedding);
40938
- dimension = result.dimension;
40939
- if (result.usage?.tokens) totalTokens += result.usage.tokens;
40940
- embeddings = result.embeddings;
40941
- chunks = result.chunks;
40942
- }
40943
- const threadMetadata = message.threadId ? threadMetadataMap.get(message.threadId) || {} : {};
40944
- embeddingData.push({
40945
- embeddings,
40946
- documents,
40947
- metadata: chunks.map(() => ({
40948
- ...threadMetadata,
40949
- message_id: message.id,
40950
- thread_id: message.threadId,
40951
- resource_id: message.resourceId,
40952
- role: message.role,
40953
- content: textForEmbedding,
40954
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
40955
- }))
40956
- });
40957
- }));
40958
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
40959
- if (typeof this.vector === `undefined`) throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
40960
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
40961
- const allVectors = [];
40962
- const allMetadata = [];
40963
- const allDocuments = [];
40964
- for (const data of embeddingData) {
40965
- allVectors.push(...data.embeddings);
40966
- if (data.documents) allDocuments.push(...data.documents);
40967
- allMetadata.push(...data.metadata);
40968
- }
40969
- if (this.isSelfEmbedding) await this.vector.upsert({
40970
- indexName,
40971
- documents: allDocuments,
40972
- metadata: allMetadata
40973
- });
40974
- else await this.vector.upsert({
40975
- indexName,
40976
- vectors: allVectors,
40977
- metadata: allMetadata
40978
- });
40979
- }
40980
- }
40986
+ const result = await (await this.getMemoryStore()).saveMessages({ messages: dbMessages });
40987
+ const usage = this.vector && config.semanticRecall ? await this.writeMessageVectors({
40988
+ items: updatedMessages.map((message) => ({ message })),
40989
+ config,
40990
+ embeddedMessages
40991
+ }) : void 0;
40981
40992
  const saveResult = {
40982
40993
  ...result,
40983
- usage: totalTokens > 0 ? { tokens: totalTokens } : void 0
40994
+ usage
40984
40995
  };
40985
40996
  span?.end({
40986
40997
  output: { success: true },
@@ -41703,51 +41714,6 @@ Notes:
41703
41714
  return collected;
41704
41715
  }
41705
41716
  /**
41706
- * Index a list of messages directly (without querying storage).
41707
- * Used by observe-time indexing to vectorize newly-observed messages.
41708
- */
41709
- async indexMessagesList(messages) {
41710
- if (!this.vector || !this.embedder) return;
41711
- const embeddingData = [];
41712
- let dimension;
41713
- await Promise.all(messages.map(async (message) => {
41714
- let textForEmbedding = null;
41715
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
41716
- else if (message.content.parts && message.content.parts.length > 0) {
41717
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
41718
- if (joined) textForEmbedding = joined;
41719
- }
41720
- if (!textForEmbedding) return;
41721
- const embedResult = await this.embedMessageContent(textForEmbedding);
41722
- dimension = embedResult.dimension;
41723
- embeddingData.push({
41724
- embeddings: embedResult.embeddings,
41725
- metadata: embedResult.chunks.map(() => ({
41726
- message_id: message.id,
41727
- thread_id: message.threadId,
41728
- resource_id: message.resourceId,
41729
- role: message.role,
41730
- content: textForEmbedding,
41731
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
41732
- }))
41733
- });
41734
- }));
41735
- if (embeddingData.length > 0 && dimension !== void 0) {
41736
- const { indexName } = await this.createEmbeddingIndex(dimension);
41737
- const allVectors = [];
41738
- const allMetadata = [];
41739
- for (const data of embeddingData) {
41740
- allVectors.push(...data.embeddings);
41741
- allMetadata.push(...data.metadata);
41742
- }
41743
- await this.vector.upsert({
41744
- indexName,
41745
- vectors: allVectors,
41746
- metadata: allMetadata
41747
- });
41748
- }
41749
- }
41750
- /**
41751
41717
  * Check whether retrieval search (vector-based) is enabled.
41752
41718
  * Returns true when `retrieval: { vector: true }` and Memory has a vector store plus either an
41753
41719
  * embedder or a store that generates embeddings itself.
@@ -41853,43 +41819,19 @@ Notes:
41853
41819
  const messagesWithTextUpdates = [...textForEmbeddingById.keys()].map((id) => ({ id }));
41854
41820
  if (messagesWithTextUpdates.length > 0) {
41855
41821
  const existingMessagesMap = new Map(existing.messages.map((m) => [m.id, m]));
41856
- const embeddingData = [];
41857
- let dimension;
41858
- const messageIdsWithNewEmbeddings = /* @__PURE__ */ new Set();
41859
- const messageIdsWithClearedContent = /* @__PURE__ */ new Set();
41860
- await Promise.all(messagesWithTextUpdates.map(async (message) => {
41861
- const existingMessage = existingMessagesMap.get(message.id);
41862
- if (!existingMessage) return;
41863
- const textForEmbedding = textForEmbeddingById.get(message.id) ?? null;
41864
- if (textForEmbedding) {
41865
- let embeddings = [];
41866
- let documents;
41867
- let chunks;
41868
- if (this.isSelfEmbedding) {
41869
- chunks = this.chunkText(textForEmbedding);
41870
- documents = chunks;
41871
- } else {
41872
- const result = await this.embedMessageContent(textForEmbedding);
41873
- dimension = result.dimension;
41874
- embeddings = result.embeddings;
41875
- chunks = result.chunks;
41876
- }
41877
- embeddingData.push({
41878
- embeddings,
41879
- documents,
41880
- metadata: chunks.map(() => ({
41881
- message_id: message.id,
41882
- thread_id: existingMessage.threadId,
41883
- resource_id: existingMessage.resourceId,
41884
- role: existingMessage.role,
41885
- content: textForEmbedding,
41886
- created_at: existingMessage.createdAt instanceof Date ? existingMessage.createdAt.toISOString() : String(existingMessage.createdAt)
41887
- }))
41888
- });
41889
- messageIdsWithNewEmbeddings.add(message.id);
41890
- } else messageIdsWithClearedContent.add(message.id);
41891
- }));
41892
- const messageIdsNeedingDeletion = /* @__PURE__ */ new Set([...messageIdsWithClearedContent, ...messageIdsWithNewEmbeddings]);
41822
+ const messageIdsNeedingDeletion = /* @__PURE__ */ new Set();
41823
+ const items = [];
41824
+ for (const { id } of messagesWithTextUpdates) {
41825
+ const existingMessage = existingMessagesMap.get(id);
41826
+ if (!existingMessage) continue;
41827
+ messageIdsNeedingDeletion.add(id);
41828
+ const text = textForEmbeddingById.get(id);
41829
+ if (text) items.push({
41830
+ message: existingMessage,
41831
+ text
41832
+ });
41833
+ }
41834
+ const rows = await this.buildMessageVectorRows({ items });
41893
41835
  if (messageIdsNeedingDeletion.size > 0) try {
41894
41836
  const memoryIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
41895
41837
  const idsToDelete = [...messageIdsNeedingDeletion];
@@ -41912,27 +41854,10 @@ Notes:
41912
41854
  } catch {
41913
41855
  this.logger.debug("Failed to clean up old vectors during message update");
41914
41856
  }
41915
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
41916
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
41917
- const allVectors = [];
41918
- const allMetadata = [];
41919
- const allDocuments = [];
41920
- for (const data of embeddingData) {
41921
- allVectors.push(...data.embeddings);
41922
- if (data.documents) allDocuments.push(...data.documents);
41923
- allMetadata.push(...data.metadata);
41924
- }
41925
- if (this.isSelfEmbedding) await this.vector.upsert({
41926
- indexName,
41927
- documents: allDocuments,
41928
- metadata: allMetadata
41929
- });
41930
- else await this.vector.upsert({
41931
- indexName,
41932
- vectors: allVectors,
41933
- metadata: allMetadata
41934
- });
41935
- }
41857
+ await this.writeMessageVectorRows({
41858
+ rows,
41859
+ config
41860
+ });
41936
41861
  }
41937
41862
  }
41938
41863
  return memoryStore.updateMessages({ messages });
@@ -42197,6 +42122,7 @@ Notes:
42197
42122
  threadId,
42198
42123
  perPage: false
42199
42124
  });
42125
+ const rows = await this.buildMessageVectorRows({ items: messages.map((message) => ({ message })) });
42200
42126
  const messageIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
42201
42127
  await Promise.all(messageIndexes.map(async (indexName) => {
42202
42128
  await this.vector.deleteVectors({
@@ -42204,7 +42130,10 @@ Notes:
42204
42130
  filter: { thread_id: threadId }
42205
42131
  });
42206
42132
  }));
42207
- if (messages.length > 0) await this.embedClonedMessages(messages, config);
42133
+ await this.writeMessageVectorRows({
42134
+ rows,
42135
+ config
42136
+ });
42208
42137
  } catch (error) {
42209
42138
  this.logger.error("Failed to migrate semantic-recall vectors during thread transfer", {
42210
42139
  threadId,
@@ -42352,67 +42281,15 @@ Notes:
42352
42281
  return cloned;
42353
42282
  }
42354
42283
  /**
42355
- * Embed cloned messages for semantic recall.
42356
- * This is similar to the embedding logic in saveMessages but operates on already-saved messages.
42284
+ * Embed cloned messages for semantic recall. Cloned messages have new ids, so they get rows of
42285
+ * their own next to the source thread's rows.
42357
42286
  */
42358
42287
  async embedClonedMessages(messages, config) {
42359
42288
  if (!this.vector || !this.embedder && !this.isSelfEmbedding) return;
42360
- const embeddingData = [];
42361
- let dimension;
42362
- await Promise.all(messages.map(async (message) => {
42363
- let textForEmbedding = null;
42364
- if (message.content?.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
42365
- else if (message.content?.parts && message.content.parts.length > 0) {
42366
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
42367
- if (joined) textForEmbedding = joined;
42368
- }
42369
- if (!textForEmbedding) return;
42370
- let embeddings = [];
42371
- let documents;
42372
- let chunks;
42373
- if (this.isSelfEmbedding) {
42374
- chunks = this.chunkText(textForEmbedding);
42375
- documents = chunks;
42376
- } else {
42377
- const result = await this.embedMessageContent(textForEmbedding);
42378
- dimension = result.dimension;
42379
- embeddings = result.embeddings;
42380
- chunks = result.chunks;
42381
- }
42382
- embeddingData.push({
42383
- embeddings,
42384
- documents,
42385
- metadata: chunks.map(() => ({
42386
- message_id: message.id,
42387
- thread_id: message.threadId,
42388
- resource_id: message.resourceId,
42389
- role: message.role,
42390
- content: textForEmbedding,
42391
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
42392
- }))
42393
- });
42394
- }));
42395
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
42396
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
42397
- const allVectors = [];
42398
- const allMetadata = [];
42399
- const allDocuments = [];
42400
- for (const data of embeddingData) {
42401
- allVectors.push(...data.embeddings);
42402
- if (data.documents) allDocuments.push(...data.documents);
42403
- allMetadata.push(...data.metadata);
42404
- }
42405
- if (this.isSelfEmbedding) await this.vector.upsert({
42406
- indexName,
42407
- documents: allDocuments,
42408
- metadata: allMetadata
42409
- });
42410
- else await this.vector.upsert({
42411
- indexName,
42412
- vectors: allVectors,
42413
- metadata: allMetadata
42414
- });
42415
- }
42289
+ await this.writeMessageVectors({
42290
+ items: messages.map((message) => ({ message })),
42291
+ config
42292
+ });
42416
42293
  }
42417
42294
  /**
42418
42295
  * Get the clone metadata from a thread if it was cloned from another thread.
@@ -42596,4 +42473,4 @@ Notes:
42596
42473
  };
42597
42474
  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 };
42598
42475
 
42599
- //# sourceMappingURL=src-BIae5T_v.js.map
42476
+ //# sourceMappingURL=src-wMl-5Ms8.js.map