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

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.
@@ -39859,7 +39859,8 @@ var ObservationalMemoryProcessor = class {
39859
39859
  ctx = await step.prepare();
39860
39860
  } catch (error) {
39861
39861
  const err = error instanceof Error ? error : new Error(String(error));
39862
- const abortMessage = abortSignal?.aborted ? "Agent execution was aborted" : `Encountered error during memory observation: ${err.message}`;
39862
+ const abortReason = abortSignal?.reason;
39863
+ 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}`;
39863
39864
  const failedTurn = this.turn;
39864
39865
  await failedTurn.end().catch(() => {});
39865
39866
  if (this.turn === failedTurn) this.turn = void 0;
@@ -40168,7 +40169,6 @@ function normalizeObservationalMemoryConfig(config) {
40168
40169
  function hasWorkingMemoryExtractor(extractors) {
40169
40170
  return !!extractors?.some((extractor) => extractor.slug === "working-memory");
40170
40171
  }
40171
- const CHARS_PER_TOKEN = 4;
40172
40172
  const DEFAULT_MESSAGE_RANGE = {
40173
40173
  before: 1,
40174
40174
  after: 1
@@ -40311,6 +40311,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
40311
40311
  });
40312
40312
  this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig);
40313
40313
  this.threadConfig = mergedConfig;
40314
+ (0, _mastra_core_memory.resolveMaxChunkChars)({ maxChunkChars: this.configuredMaxChunkChars });
40314
40315
  const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory);
40315
40316
  if (omConfig?.retrieval && typeof omConfig.retrieval === "object" && omConfig.retrieval.vector) {
40316
40317
  if (!this.vector) throw new Error("`retrieval: { vector: true }` requires a vector store. Pass a `vector` option to your Memory instance.");
@@ -40826,28 +40827,9 @@ ${workingMemory}`;
40826
40827
  release();
40827
40828
  }
40828
40829
  }
40830
+ /** Splits text into chunks of at most `tokenSize` English tokens, measured as characters. */
40829
40831
  chunkText(text, tokenSize = 4096) {
40830
- const charSize = tokenSize * CHARS_PER_TOKEN;
40831
- const chunks = [];
40832
- let currentChunk = "";
40833
- const words = text.split(/\s+/);
40834
- for (const word of words) {
40835
- if (word.length > charSize) {
40836
- if (currentChunk) {
40837
- chunks.push(currentChunk);
40838
- currentChunk = "";
40839
- }
40840
- for (let i = 0; i < word.length; i += charSize) chunks.push(word.slice(i, i + charSize));
40841
- continue;
40842
- }
40843
- const wordWithSpace = currentChunk ? " " + word : word;
40844
- if (currentChunk.length + wordWithSpace.length > charSize) {
40845
- if (currentChunk) chunks.push(currentChunk);
40846
- currentChunk = word;
40847
- } else currentChunk += wordWithSpace;
40848
- }
40849
- if (currentChunk) chunks.push(currentChunk);
40850
- return chunks;
40832
+ return (0, _mastra_core_memory.chunkMessageText)(text, tokenSize * _mastra_core_memory.MESSAGE_EMBEDDING_CHARS_PER_TOKEN);
40851
40833
  }
40852
40834
  hasher = (0, xxhash_wasm.default)();
40853
40835
  embeddingCache = new lru_cache.LRUCache({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
@@ -40863,11 +40845,23 @@ ${workingMemory}`;
40863
40845
  return cached;
40864
40846
  }
40865
40847
  const chunks = this.chunkText(content);
40848
+ const { embeddings, usage } = await this.embedValues(chunks);
40849
+ const result = {
40850
+ embeddings,
40851
+ chunks,
40852
+ usage,
40853
+ dimension: embeddings[0]?.length
40854
+ };
40855
+ this.embeddingCache.set(key, result);
40856
+ return result;
40857
+ }
40858
+ /** Sends texts to the embedder through the AI SDK version that matches its spec. */
40859
+ async embedValues(values) {
40866
40860
  if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40867
40861
  const isFastEmbed = this.embedder.provider === `fastembed`;
40868
40862
  if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
40869
40863
  const options = {
40870
- values: chunks,
40864
+ values,
40871
40865
  maxRetries: 3
40872
40866
  };
40873
40867
  const model = this.embedder;
@@ -40902,106 +40896,87 @@ ${workingMemory}`;
40902
40896
  }
40903
40897
  if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;
40904
40898
  const { embeddings, usage } = await promise;
40905
- const result = {
40899
+ return {
40906
40900
  embeddings,
40907
- chunks,
40908
- usage,
40909
- dimension: embeddings[0]?.length
40901
+ usage
40910
40902
  };
40911
- this.embeddingCache.set(key, result);
40912
- return result;
40913
40903
  }
40914
- async saveMessages({ messages, memoryConfig, observabilityContext }) {
40904
+ /**
40905
+ * Metadata of each thread, spread onto that thread's vector rows so `semanticRecall.filter`
40906
+ * can match thread attributes.
40907
+ */
40908
+ async loadThreadMetadata(threadIds) {
40909
+ const memoryStore = await this.getMemoryStore();
40910
+ const metadataByThread = /* @__PURE__ */ new Map();
40911
+ await Promise.all(threadIds.map(async (threadId) => {
40912
+ try {
40913
+ const thread = await memoryStore.getThreadById({ threadId });
40914
+ if (thread?.metadata) metadataByThread.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 writing semantic recall embeddings: ${message}`);
40918
+ }
40919
+ }));
40920
+ return metadataByThread;
40921
+ }
40922
+ /**
40923
+ * Embeds messages into vector rows in the shared format, without writing them. Every
40924
+ * message-vector write in this class builds its rows here.
40925
+ */
40926
+ async buildMessageVectorRows({ items, embeddedMessages }) {
40927
+ if (items.length === 0) return {
40928
+ ids: [],
40929
+ metadata: [],
40930
+ embeddedEntries: []
40931
+ };
40932
+ if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40933
+ return (0, _mastra_core_memory.buildMessageEmbeddingRows)({
40934
+ items,
40935
+ embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
40936
+ maxChunkChars: (0, _mastra_core_memory.resolveMaxChunkChars)({
40937
+ maxChunkChars: this.configuredMaxChunkChars,
40938
+ embedder: this.embedder
40939
+ }),
40940
+ loadThreadMetadata: (threadIds) => this.loadThreadMetadata(threadIds),
40941
+ embeddedMessages,
40942
+ indexName: embeddedMessages ? this.getEmbeddingIndexName(this.isSelfEmbedding ? void 0 : await this.getEmbeddingDimension()) : void 0
40943
+ });
40944
+ }
40945
+ /** Writes rows from {@link buildMessageVectorRows} into the message index for `config`. */
40946
+ async writeMessageVectorRows({ rows, config, embeddedMessages }) {
40947
+ if (!this.vector || rows.ids.length === 0) return;
40948
+ const { indexName } = await this.createEmbeddingIndex(rows.dimension, config);
40949
+ await (0, _mastra_core_memory.upsertMessageVectors)(this.vector, indexName, rows, embeddedMessages);
40950
+ }
40951
+ /**
40952
+ * Embeds messages and writes their vector rows.
40953
+ *
40954
+ * @returns Tokens billed by the embedder, if any.
40955
+ */
40956
+ async writeMessageVectors(args) {
40957
+ if (!this.vector) return void 0;
40958
+ const rows = await this.buildMessageVectorRows(args);
40959
+ await this.writeMessageVectorRows({
40960
+ ...args,
40961
+ rows
40962
+ });
40963
+ return rows.usage;
40964
+ }
40965
+ async saveMessages({ messages, memoryConfig, observabilityContext, embeddedMessages }) {
40915
40966
  const span = this.createMemorySpan("save", observabilityContext, void 0, { messageCount: messages.length });
40916
40967
  try {
40917
40968
  const updatedMessages = this.prepareMessagesForPersistence(messages);
40918
40969
  const config = this.getMergedThreadConfig(memoryConfig);
40919
40970
  const dbMessages = new _mastra_core_agent.MessageList({ generateMessageId: () => this.generateId() }).add(updatedMessages, "memory").get.all.db();
40920
- const memoryStore = await this.getMemoryStore();
40921
- const result = await memoryStore.saveMessages({ messages: dbMessages });
40922
- let totalTokens = 0;
40923
- if (this.vector && config.semanticRecall) {
40924
- const messagesByThread = /* @__PURE__ */ new Map();
40925
- updatedMessages.forEach((message) => {
40926
- if (message.threadId) {
40927
- if (!messagesByThread.has(message.threadId)) messagesByThread.set(message.threadId, []);
40928
- messagesByThread.get(message.threadId).push(message);
40929
- }
40930
- });
40931
- const threadMetadataMap = /* @__PURE__ */ new Map();
40932
- await Promise.all(Array.from(messagesByThread.keys()).map(async (threadId) => {
40933
- try {
40934
- const thread = await memoryStore.getThreadById({ threadId });
40935
- if (thread?.metadata) threadMetadataMap.set(threadId, thread.metadata);
40936
- } catch (error) {
40937
- const message = error instanceof Error ? error.message : String(error);
40938
- throw new Error(`Could not fetch metadata for thread ${threadId} while saving semantic recall embeddings: ${message}`);
40939
- }
40940
- }));
40941
- const embeddingData = [];
40942
- let dimension;
40943
- await Promise.all(updatedMessages.map(async (message) => {
40944
- let textForEmbedding = null;
40945
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
40946
- else if (message.content.parts && message.content.parts.length > 0) {
40947
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
40948
- if (joined) textForEmbedding = joined;
40949
- }
40950
- if (!textForEmbedding) return;
40951
- let embeddings = [];
40952
- let documents;
40953
- let chunks;
40954
- if (this.isSelfEmbedding) {
40955
- chunks = this.chunkText(textForEmbedding);
40956
- documents = chunks;
40957
- } else {
40958
- const result = await this.embedMessageContent(textForEmbedding);
40959
- dimension = result.dimension;
40960
- if (result.usage?.tokens) totalTokens += result.usage.tokens;
40961
- embeddings = result.embeddings;
40962
- chunks = result.chunks;
40963
- }
40964
- const threadMetadata = message.threadId ? threadMetadataMap.get(message.threadId) || {} : {};
40965
- embeddingData.push({
40966
- embeddings,
40967
- documents,
40968
- metadata: chunks.map(() => ({
40969
- ...threadMetadata,
40970
- message_id: message.id,
40971
- thread_id: message.threadId,
40972
- resource_id: message.resourceId,
40973
- role: message.role,
40974
- content: textForEmbedding,
40975
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
40976
- }))
40977
- });
40978
- }));
40979
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
40980
- if (typeof this.vector === `undefined`) throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
40981
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
40982
- const allVectors = [];
40983
- const allMetadata = [];
40984
- const allDocuments = [];
40985
- for (const data of embeddingData) {
40986
- allVectors.push(...data.embeddings);
40987
- if (data.documents) allDocuments.push(...data.documents);
40988
- allMetadata.push(...data.metadata);
40989
- }
40990
- if (this.isSelfEmbedding) await this.vector.upsert({
40991
- indexName,
40992
- documents: allDocuments,
40993
- metadata: allMetadata
40994
- });
40995
- else await this.vector.upsert({
40996
- indexName,
40997
- vectors: allVectors,
40998
- metadata: allMetadata
40999
- });
41000
- }
41001
- }
40971
+ const result = await (await this.getMemoryStore()).saveMessages({ messages: dbMessages });
40972
+ const usage = this.vector && config.semanticRecall ? await this.writeMessageVectors({
40973
+ items: updatedMessages.map((message) => ({ message })),
40974
+ config,
40975
+ embeddedMessages
40976
+ }) : void 0;
41002
40977
  const saveResult = {
41003
40978
  ...result,
41004
- usage: totalTokens > 0 ? { tokens: totalTokens } : void 0
40979
+ usage
41005
40980
  };
41006
40981
  span?.end({
41007
40982
  output: { success: true },
@@ -41724,51 +41699,6 @@ Notes:
41724
41699
  return collected;
41725
41700
  }
41726
41701
  /**
41727
- * Index a list of messages directly (without querying storage).
41728
- * Used by observe-time indexing to vectorize newly-observed messages.
41729
- */
41730
- async indexMessagesList(messages) {
41731
- if (!this.vector || !this.embedder) return;
41732
- const embeddingData = [];
41733
- let dimension;
41734
- await Promise.all(messages.map(async (message) => {
41735
- let textForEmbedding = null;
41736
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
41737
- else if (message.content.parts && message.content.parts.length > 0) {
41738
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
41739
- if (joined) textForEmbedding = joined;
41740
- }
41741
- if (!textForEmbedding) return;
41742
- const embedResult = await this.embedMessageContent(textForEmbedding);
41743
- dimension = embedResult.dimension;
41744
- embeddingData.push({
41745
- embeddings: embedResult.embeddings,
41746
- metadata: embedResult.chunks.map(() => ({
41747
- message_id: message.id,
41748
- thread_id: message.threadId,
41749
- resource_id: message.resourceId,
41750
- role: message.role,
41751
- content: textForEmbedding,
41752
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
41753
- }))
41754
- });
41755
- }));
41756
- if (embeddingData.length > 0 && dimension !== void 0) {
41757
- const { indexName } = await this.createEmbeddingIndex(dimension);
41758
- const allVectors = [];
41759
- const allMetadata = [];
41760
- for (const data of embeddingData) {
41761
- allVectors.push(...data.embeddings);
41762
- allMetadata.push(...data.metadata);
41763
- }
41764
- await this.vector.upsert({
41765
- indexName,
41766
- vectors: allVectors,
41767
- metadata: allMetadata
41768
- });
41769
- }
41770
- }
41771
- /**
41772
41702
  * Check whether retrieval search (vector-based) is enabled.
41773
41703
  * Returns true when `retrieval: { vector: true }` and Memory has a vector store plus either an
41774
41704
  * embedder or a store that generates embeddings itself.
@@ -41874,43 +41804,19 @@ Notes:
41874
41804
  const messagesWithTextUpdates = [...textForEmbeddingById.keys()].map((id) => ({ id }));
41875
41805
  if (messagesWithTextUpdates.length > 0) {
41876
41806
  const existingMessagesMap = new Map(existing.messages.map((m) => [m.id, m]));
41877
- const embeddingData = [];
41878
- let dimension;
41879
- const messageIdsWithNewEmbeddings = /* @__PURE__ */ new Set();
41880
- const messageIdsWithClearedContent = /* @__PURE__ */ new Set();
41881
- await Promise.all(messagesWithTextUpdates.map(async (message) => {
41882
- const existingMessage = existingMessagesMap.get(message.id);
41883
- if (!existingMessage) return;
41884
- const textForEmbedding = textForEmbeddingById.get(message.id) ?? null;
41885
- if (textForEmbedding) {
41886
- let embeddings = [];
41887
- let documents;
41888
- let chunks;
41889
- if (this.isSelfEmbedding) {
41890
- chunks = this.chunkText(textForEmbedding);
41891
- documents = chunks;
41892
- } else {
41893
- const result = await this.embedMessageContent(textForEmbedding);
41894
- dimension = result.dimension;
41895
- embeddings = result.embeddings;
41896
- chunks = result.chunks;
41897
- }
41898
- embeddingData.push({
41899
- embeddings,
41900
- documents,
41901
- metadata: chunks.map(() => ({
41902
- message_id: message.id,
41903
- thread_id: existingMessage.threadId,
41904
- resource_id: existingMessage.resourceId,
41905
- role: existingMessage.role,
41906
- content: textForEmbedding,
41907
- created_at: existingMessage.createdAt instanceof Date ? existingMessage.createdAt.toISOString() : String(existingMessage.createdAt)
41908
- }))
41909
- });
41910
- messageIdsWithNewEmbeddings.add(message.id);
41911
- } else messageIdsWithClearedContent.add(message.id);
41912
- }));
41913
- const messageIdsNeedingDeletion = /* @__PURE__ */ new Set([...messageIdsWithClearedContent, ...messageIdsWithNewEmbeddings]);
41807
+ const messageIdsNeedingDeletion = /* @__PURE__ */ new Set();
41808
+ const items = [];
41809
+ for (const { id } of messagesWithTextUpdates) {
41810
+ const existingMessage = existingMessagesMap.get(id);
41811
+ if (!existingMessage) continue;
41812
+ messageIdsNeedingDeletion.add(id);
41813
+ const text = textForEmbeddingById.get(id);
41814
+ if (text) items.push({
41815
+ message: existingMessage,
41816
+ text
41817
+ });
41818
+ }
41819
+ const rows = await this.buildMessageVectorRows({ items });
41914
41820
  if (messageIdsNeedingDeletion.size > 0) try {
41915
41821
  const memoryIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
41916
41822
  const idsToDelete = [...messageIdsNeedingDeletion];
@@ -41933,27 +41839,10 @@ Notes:
41933
41839
  } catch {
41934
41840
  this.logger.debug("Failed to clean up old vectors during message update");
41935
41841
  }
41936
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
41937
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
41938
- const allVectors = [];
41939
- const allMetadata = [];
41940
- const allDocuments = [];
41941
- for (const data of embeddingData) {
41942
- allVectors.push(...data.embeddings);
41943
- if (data.documents) allDocuments.push(...data.documents);
41944
- allMetadata.push(...data.metadata);
41945
- }
41946
- if (this.isSelfEmbedding) await this.vector.upsert({
41947
- indexName,
41948
- documents: allDocuments,
41949
- metadata: allMetadata
41950
- });
41951
- else await this.vector.upsert({
41952
- indexName,
41953
- vectors: allVectors,
41954
- metadata: allMetadata
41955
- });
41956
- }
41842
+ await this.writeMessageVectorRows({
41843
+ rows,
41844
+ config
41845
+ });
41957
41846
  }
41958
41847
  }
41959
41848
  return memoryStore.updateMessages({ messages });
@@ -42218,6 +42107,7 @@ Notes:
42218
42107
  threadId,
42219
42108
  perPage: false
42220
42109
  });
42110
+ const rows = await this.buildMessageVectorRows({ items: messages.map((message) => ({ message })) });
42221
42111
  const messageIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
42222
42112
  await Promise.all(messageIndexes.map(async (indexName) => {
42223
42113
  await this.vector.deleteVectors({
@@ -42225,7 +42115,10 @@ Notes:
42225
42115
  filter: { thread_id: threadId }
42226
42116
  });
42227
42117
  }));
42228
- if (messages.length > 0) await this.embedClonedMessages(messages, config);
42118
+ await this.writeMessageVectorRows({
42119
+ rows,
42120
+ config
42121
+ });
42229
42122
  } catch (error) {
42230
42123
  this.logger.error("Failed to migrate semantic-recall vectors during thread transfer", {
42231
42124
  threadId,
@@ -42373,67 +42266,15 @@ Notes:
42373
42266
  return cloned;
42374
42267
  }
42375
42268
  /**
42376
- * Embed cloned messages for semantic recall.
42377
- * This is similar to the embedding logic in saveMessages but operates on already-saved messages.
42269
+ * Embed cloned messages for semantic recall. Cloned messages have new ids, so they get rows of
42270
+ * their own next to the source thread's rows.
42378
42271
  */
42379
42272
  async embedClonedMessages(messages, config) {
42380
42273
  if (!this.vector || !this.embedder && !this.isSelfEmbedding) return;
42381
- const embeddingData = [];
42382
- let dimension;
42383
- await Promise.all(messages.map(async (message) => {
42384
- let textForEmbedding = null;
42385
- if (message.content?.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
42386
- else if (message.content?.parts && message.content.parts.length > 0) {
42387
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
42388
- if (joined) textForEmbedding = joined;
42389
- }
42390
- if (!textForEmbedding) return;
42391
- let embeddings = [];
42392
- let documents;
42393
- let chunks;
42394
- if (this.isSelfEmbedding) {
42395
- chunks = this.chunkText(textForEmbedding);
42396
- documents = chunks;
42397
- } else {
42398
- const result = await this.embedMessageContent(textForEmbedding);
42399
- dimension = result.dimension;
42400
- embeddings = result.embeddings;
42401
- chunks = result.chunks;
42402
- }
42403
- embeddingData.push({
42404
- embeddings,
42405
- documents,
42406
- metadata: chunks.map(() => ({
42407
- message_id: message.id,
42408
- thread_id: message.threadId,
42409
- resource_id: message.resourceId,
42410
- role: message.role,
42411
- content: textForEmbedding,
42412
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
42413
- }))
42414
- });
42415
- }));
42416
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
42417
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
42418
- const allVectors = [];
42419
- const allMetadata = [];
42420
- const allDocuments = [];
42421
- for (const data of embeddingData) {
42422
- allVectors.push(...data.embeddings);
42423
- if (data.documents) allDocuments.push(...data.documents);
42424
- allMetadata.push(...data.metadata);
42425
- }
42426
- if (this.isSelfEmbedding) await this.vector.upsert({
42427
- indexName,
42428
- documents: allDocuments,
42429
- metadata: allMetadata
42430
- });
42431
- else await this.vector.upsert({
42432
- indexName,
42433
- vectors: allVectors,
42434
- metadata: allMetadata
42435
- });
42436
- }
42274
+ await this.writeMessageVectors({
42275
+ items: messages.map((message) => ({ message })),
42276
+ config
42277
+ });
42437
42278
  }
42438
42279
  /**
42439
42280
  * Get the clone metadata from a thread if it was cloned from another thread.
@@ -42892,4 +42733,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
42892
42733
  }
42893
42734
  });
42894
42735
 
42895
- //# sourceMappingURL=src-BbbBzTaj.cjs.map
42736
+ //# sourceMappingURL=src-Bo9Kpfk_.cjs.map