@mastra/memory 1.0.0-beta.3 → 1.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @mastra/memory
2
2
 
3
+ ## 1.0.0-beta.4
4
+
5
+ ### Patch Changes
6
+
7
+ - Fix connection pool exhaustion when saving many messages with semantic recall enabled. Instead of calling vector.upsert() for each message individually (which acquires a separate DB connection), all embeddings are now batched into a single upsert call. ([#10954](https://github.com/mastra-ai/mastra/pull/10954))
8
+
9
+ - Updated dependencies [[`0d41fe2`](https://github.com/mastra-ai/mastra/commit/0d41fe245355dfc66d61a0d9c85d9400aac351ff), [`6b3ba91`](https://github.com/mastra-ai/mastra/commit/6b3ba91494cc10394df96782f349a4f7b1e152cc), [`7907fd1`](https://github.com/mastra-ai/mastra/commit/7907fd1c5059813b7b870b81ca71041dc807331b)]:
10
+ - @mastra/core@1.0.0-beta.8
11
+
3
12
  ## 1.0.0-beta.3
4
13
 
5
14
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -552,7 +552,8 @@ ${workingMemory}`;
552
552
  messages: dbMessages
553
553
  });
554
554
  if (this.vector && config.semanticRecall) {
555
- let indexName;
555
+ const embeddingData = [];
556
+ let dimension;
556
557
  await Promise.all(
557
558
  updatedMessages.map(async (message) => {
558
559
  let textForEmbedding = null;
@@ -563,19 +564,11 @@ ${workingMemory}`;
563
564
  if (joined) textForEmbedding = joined;
564
565
  }
565
566
  if (!textForEmbedding) return;
566
- const { embeddings, chunks, dimension } = await this.embedMessageContent(textForEmbedding);
567
- if (typeof indexName === `undefined`) {
568
- indexName = this.createEmbeddingIndex(dimension, config).then((result2) => result2.indexName);
569
- }
570
- if (typeof this.vector === `undefined`) {
571
- throw new Error(
572
- `Tried to upsert embeddings to index ${indexName} but this Memory instance doesn't have an attached vector db.`
573
- );
574
- }
575
- await this.vector.upsert({
576
- indexName: await indexName,
577
- vectors: embeddings,
578
- metadata: chunks.map(() => ({
567
+ const result2 = await this.embedMessageContent(textForEmbedding);
568
+ dimension = result2.dimension;
569
+ embeddingData.push({
570
+ embeddings: result2.embeddings,
571
+ metadata: result2.chunks.map(() => ({
579
572
  message_id: message.id,
580
573
  thread_id: message.threadId,
581
574
  resource_id: message.resourceId
@@ -583,6 +576,23 @@ ${workingMemory}`;
583
576
  });
584
577
  })
585
578
  );
579
+ if (embeddingData.length > 0 && dimension !== void 0) {
580
+ if (typeof this.vector === `undefined`) {
581
+ throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
582
+ }
583
+ const { indexName } = await this.createEmbeddingIndex(dimension, config);
584
+ const allVectors = [];
585
+ const allMetadata = [];
586
+ for (const data of embeddingData) {
587
+ allVectors.push(...data.embeddings);
588
+ allMetadata.push(...data.metadata);
589
+ }
590
+ await this.vector.upsert({
591
+ indexName,
592
+ vectors: allVectors,
593
+ metadata: allMetadata
594
+ });
595
+ }
586
596
  }
587
597
  return result;
588
598
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tools/working-memory.ts","../src/index.ts"],"names":["z","ZodObject","convertSchemaToZod","createTool","MastraMemory","MessageList","Mutex","xxhash","embedManyV5","embedMany","result","zodToJsonSchema","generateEmptyFromSchema"],"mappings":";;;;;;;;;;;;;;;;;;;;AAcO,SAAS,sBAAA,CACd,UACA,MAAA,EACyB;AACzB,EAAA,IAAI,CAAC,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,EAAU;AAC7C,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,MAAA,GAAkC,EAAE,GAAG,QAAA,EAAS;AAEtD,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,EAAG;AACrC,IAAA,MAAM,WAAA,GAAc,OAAO,GAAG,CAAA;AAC9B,IAAA,MAAM,aAAA,GAAgB,OAAO,GAAG,CAAA;AAGhC,IAAA,IAAI,gBAA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AO,IAAA,CAAK,OAAA,CAAQ,cAAA,CAAe,EAAE,UAAU,CAAA;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAa,eAAe,KAAA,EAA0C;AAEpE,IAAA,IAAI,UAAA;AAEJ,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACzB,MAAA,MAAM,IAAI,MAAM,mEAAmE,CAAA;AAAA,IACrF;AAEA,IAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,MAAA;AAAA,IACF;AAEA,IAAA,UAAA,GAAa,KAAA,CAAM,IAAI,CAAA,IAAA,KAAQ;AAC7B,MAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,QAAA,OAAO,IAAA;AAAA,MACT,WAAW,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,IAAY,QAAQ,IAAA,EAAM;AAC3D,QAAA,OAAO,IAAA,CAAK,EAAA;AAAA,MACd,CAAA,MAAO;AACL,QAAA,MAAM,IAAI,MAAM,2EAA2E,CAAA;AAAA,MAC7F;AAAA,IACF,CAAC,CAAA;AAGD,IAAA,MAAM,UAAA,GAAa,WAAW,MAAA,CAAO,CAAA,EAAA,KAAM,CAAC,EAAA,IAAM,OAAO,OAAO,QAAQ,CAAA;AACxE,IAAA,IAAI,UAAA,CAAW,SAAS,CAAA,EAAG;AACzB,MAAA,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAAA,IAC7D;AAGA,IAAA,MAAM,IAAA,CAAK,OAAA,CAAQ,cAAA,CAAe,UAAU,CAAA;AAAA,EAK9C;AACF","file":"index.cjs","sourcesContent":["import type { MemoryConfig } from '@mastra/core/memory';\nimport { createTool } from '@mastra/core/tools';\nimport { convertSchemaToZod } from '@mastra/schema-compat';\nimport type { Schema } from '@mastra/schema-compat';\nimport { z, ZodObject } from 'zod';\nimport type { ZodType } from 'zod';\n\n/**\n * Deep merges two objects, with special handling for null values (delete) and arrays (replace).\n * - Object properties are recursively merged\n * - null values in the update will delete the corresponding property\n * - Arrays are replaced entirely (not merged element-by-element)\n * - Primitive values are overwritten\n */\nexport function deepMergeWorkingMemory(\n existing: Record<string, unknown> | null | undefined,\n update: Record<string, unknown>,\n): Record<string, unknown> {\n if (!existing || typeof existing !== 'object') {\n return update;\n }\n\n const result: Record<string, unknown> = { ...existing };\n\n for (const key of Object.keys(update)) {\n const updateValue = update[key];\n const existingValue = result[key];\n\n // null means delete the property\n if (updateValue === null) {\n delete result[key];\n }\n // Arrays are replaced entirely (too complex to diff/merge arrays of objects)\n else if (Array.isArray(updateValue)) {\n result[key] = updateValue;\n }\n // Recursively merge nested objects\n else if (\n typeof updateValue === 'object' &&\n updateValue !== null &&\n typeof existingValue === 'object' &&\n existingValue !== null &&\n !Array.isArray(existingValue)\n ) {\n result[key] = deepMergeWorkingMemory(\n existingValue as Record<string, unknown>,\n updateValue as Record<string, unknown>,\n );\n }\n // Primitive values or new properties: just set them\n else {\n result[key] = updateValue;\n }\n }\n\n return result;\n}\n\nexport const updateWorkingMemoryTool = (memoryConfig?: MemoryConfig) => {\n const schema = memoryConfig?.workingMemory?.schema;\n\n let inputSchema: ZodType = z.object({\n memory: z\n .string()\n .describe(`The Markdown formatted working memory content to store. This MUST be a string. Never pass an object.`),\n });\n\n if (schema) {\n inputSchema = z.object({\n memory:\n schema instanceof ZodObject\n ? schema\n : (convertSchemaToZod({ jsonSchema: schema } as Schema).describe(\n `The JSON formatted working memory content to store.`,\n ) as ZodObject<any>),\n });\n }\n\n // For schema-based working memory, we use merge semantics\n // For template-based (Markdown), we use replace semantics (existing behavior)\n const usesMergeSemantics = Boolean(schema);\n\n const description = schema\n ? `Update the working memory with new information. Data is merged with existing memory - you only need to include fields you want to add or update. Set a field to null to remove it. Arrays are replaced entirely when provided.`\n : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;\n\n return createTool({\n id: 'update-working-memory',\n description,\n inputSchema,\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n let workingMemory: string;\n\n if (usesMergeSemantics) {\n // Schema-based: fetch existing, merge, save\n const existingRaw = await memory.getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n });\n\n let existingData: Record<string, unknown> | null = null;\n if (existingRaw) {\n try {\n existingData = typeof existingRaw === 'string' ? JSON.parse(existingRaw) : existingRaw;\n } catch {\n // If existing data is not valid JSON, start fresh\n existingData = null;\n }\n }\n\n let newData: unknown;\n if (typeof inputData.memory === 'string') {\n try {\n newData = JSON.parse(inputData.memory);\n } catch (parseError) {\n const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(\n `Failed to parse working memory input as JSON: ${errorMessage}. ` +\n `Raw input: ${inputData.memory.length > 500 ? inputData.memory.slice(0, 500) + '...' : inputData.memory}`,\n );\n }\n } else {\n newData = inputData.memory;\n }\n const mergedData = deepMergeWorkingMemory(existingData, newData as Record<string, unknown>);\n workingMemory = JSON.stringify(mergedData);\n } else {\n // Template-based (Markdown): use existing replace semantics\n workingMemory = typeof inputData.memory === 'string' ? inputData.memory : JSON.stringify(inputData.memory);\n }\n\n // Use the updateWorkingMemory method which handles both thread and resource scope\n await memory.updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n });\n\n return { success: true };\n },\n });\n};\n\nexport const __experimental_updateWorkingMemoryToolVNext = (config: MemoryConfig) => {\n return createTool({\n id: 'update-working-memory',\n description: 'Update the working memory with new information.',\n inputSchema: z.object({\n newMemory: z\n .string()\n .optional()\n .describe(\n `The ${config.workingMemory?.schema ? 'JSON' : 'Markdown'} formatted working memory content to store`,\n ),\n searchString: z\n .string()\n .optional()\n .describe(\n \"The working memory string to find. Will be replaced with the newMemory string. If this is omitted or doesn't exist, the newMemory string will be appended to the end of your working memory. Replacing single lines at a time is encouraged for greater accuracy. If updateReason is not 'append-new-memory', this search string must be provided or the tool call will be rejected.\",\n ),\n updateReason: z\n .enum(['append-new-memory', 'clarify-existing-memory', 'replace-irrelevant-memory'])\n .optional()\n .describe(\n \"The reason you're updating working memory. Passing any value other than 'append-new-memory' requires a searchString to be provided. Defaults to append-new-memory\",\n ),\n }),\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig: config,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n const workingMemory = inputData.newMemory || '';\n if (!inputData.updateReason) inputData.updateReason = `append-new-memory`;\n\n if (\n inputData.searchString &&\n config.workingMemory?.scope === `resource` &&\n inputData.updateReason === `replace-irrelevant-memory`\n ) {\n // don't allow replacements due to something not being relevant to the current conversation\n // if there's no searchString, then we will append.\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason === `append-new-memory` && inputData.searchString) {\n // do not find/replace when append-new-memory is selected\n // some models get confused and pass a search string even when they don't want to replace it.\n // TODO: maybe they're trying to add new info after the search string?\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason !== `append-new-memory` && !inputData.searchString) {\n return {\n success: false,\n reason: `updateReason was ${inputData.updateReason} but no searchString was provided. Unable to replace undefined with \"${inputData.newMemory}\"`,\n };\n }\n\n // Use the new updateWorkingMemory method which handles both thread and resource scope\n const result = await memory!.__experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory: workingMemory,\n searchString: inputData.searchString,\n memoryConfig: config,\n });\n\n if (result) {\n return result;\n }\n\n return { success: true };\n },\n });\n};\n","import { MessageList } from '@mastra/core/agent';\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory } from '@mastra/core/memory';\nimport type {\n MastraMessageV1,\n MemoryConfig,\n SharedMemoryConfig,\n StorageThreadType,\n WorkingMemoryTemplate,\n MessageDeleteInput,\n} from '@mastra/core/memory';\nimport type {\n StorageListThreadsByResourceIdOutput,\n StorageListThreadsByResourceIdInput,\n StorageListMessagesInput,\n} from '@mastra/core/storage';\nimport type { ToolAction } from '@mastra/core/tools';\nimport { generateEmptyFromSchema } from '@mastra/core/utils';\nimport { zodToJsonSchema } from '@mastra/schema-compat/zod-to-json';\nimport { embedMany } from 'ai';\nimport type { TextPart } from 'ai';\nimport { embedMany as embedManyV5 } from 'ai-v5';\nimport { Mutex } from 'async-mutex';\nimport type { JSONSchema7 } from 'json-schema';\nimport xxhash from 'xxhash-wasm';\nimport { ZodObject } from 'zod';\nimport type { ZodTypeAny } from 'zod';\nimport {\n updateWorkingMemoryTool,\n __experimental_updateWorkingMemoryToolVNext,\n deepMergeWorkingMemory,\n} from './tools/working-memory';\n\n// Re-export for testing purposes\nexport { deepMergeWorkingMemory };\n\n// Average characters per token based on OpenAI's tokenization\nconst CHARS_PER_TOKEN = 4;\n\nconst DEFAULT_MESSAGE_RANGE = { before: 1, after: 1 } as const;\nconst DEFAULT_TOP_K = 4;\n\nconst isZodObject = (v: ZodTypeAny): v is ZodObject<any, any, any> => v instanceof ZodObject;\n\n/**\n * Concrete implementation of MastraMemory that adds support for thread configuration\n * and message injection.\n */\nexport class Memory extends MastraMemory {\n constructor(config: SharedMemoryConfig = {}) {\n super({ name: 'Memory', ...config });\n\n const mergedConfig = this.getMergedThreadConfig({\n workingMemory: config.options?.workingMemory || {\n // these defaults are now set inside @mastra/core/memory in getMergedThreadConfig.\n // In a future release we can remove it from this block - for now if we remove it\n // and someone bumps @mastra/memory without bumping @mastra/core the defaults wouldn't exist yet\n enabled: false,\n template: this.defaultWorkingMemoryTemplate,\n },\n });\n this.threadConfig = mergedConfig;\n }\n\n protected async validateThreadIsOwnedByResource(threadId: string, resourceId: string, config: MemoryConfig) {\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n const thread = await this.storage.getThreadById({ threadId });\n\n // For resource-scoped semantic recall, we don't need to validate that the specific thread exists\n // because we're searching across all threads for the resource\n if (!thread && !resourceScope) {\n throw new Error(`No thread found with id ${threadId}`);\n }\n\n // If thread exists, validate it belongs to the correct resource\n if (thread && thread.resourceId !== resourceId) {\n throw new Error(\n `Thread with id ${threadId} is for resource with id ${thread.resourceId} but resource ${resourceId} was queried.`,\n );\n }\n }\n\n protected checkStorageFeatureSupport(config: MemoryConfig) {\n const resourceScope =\n (typeof config.semanticRecall === 'object' && config.semanticRecall.scope !== 'thread') ||\n // resource scope is now default\n config.semanticRecall === true;\n\n if (resourceScope && !this.storage.supports.selectByIncludeResourceScope) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support semanticRecall: { scope: \"resource\" } yet and currently only supports per-thread semantic recall.`,\n );\n }\n\n if (\n config.workingMemory?.enabled &&\n config.workingMemory.scope === `resource` &&\n !this.storage.supports.resourceWorkingMemory\n ) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support workingMemory: { scope: \"resource\" } yet and currently only supports per-thread working memory. Supported adapters: LibSQL, PostgreSQL, Upstash.`,\n );\n }\n }\n\n async recall(\n args: StorageListMessagesInput & {\n threadConfig?: MemoryConfig;\n vectorSearchString?: string;\n threadId: string;\n },\n ): Promise<{ messages: MastraDBMessage[] }> {\n const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, filter } = args;\n const config = this.getMergedThreadConfig(threadConfig || {});\n if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);\n\n // Use perPage from args if provided, otherwise use threadConfig.lastMessages\n const perPage = perPageArg !== undefined ? perPageArg : config.lastMessages;\n\n // When limiting messages (perPage !== false) without explicit orderBy, we need to:\n // 1. Query DESC to get the NEWEST messages (not oldest)\n // 2. Reverse results to restore chronological order for the LLM\n // Without this fix, \"lastMessages: 64\" returns the OLDEST 64 messages, not the last 64.\n const shouldGetNewestAndReverse = !orderBy && perPage !== false;\n const effectiveOrderBy = shouldGetNewestAndReverse\n ? { field: 'createdAt' as const, direction: 'DESC' as const }\n : orderBy;\n\n const vectorResults: {\n id: string;\n score: number;\n metadata?: Record<string, any>;\n vector?: number[];\n }[] = [];\n\n this.logger.debug(`Memory recall() with:`, {\n threadId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n threadConfig,\n });\n\n this.checkStorageFeatureSupport(config);\n\n const defaultRange = DEFAULT_MESSAGE_RANGE;\n const defaultTopK = DEFAULT_TOP_K;\n\n const vectorConfig =\n typeof config?.semanticRecall === `boolean`\n ? {\n topK: defaultTopK,\n messageRange: defaultRange,\n }\n : {\n topK: config?.semanticRecall?.topK ?? defaultTopK,\n messageRange: config?.semanticRecall?.messageRange ?? defaultRange,\n };\n\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n // Guard: If resource-scoped semantic recall is enabled but no resourceId is provided, throw an error\n if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {\n throw new Error(\n `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`,\n );\n }\n\n if (config?.semanticRecall && vectorSearchString && this.vector) {\n const { embeddings, dimension } = await this.embedMessageContent(vectorSearchString!);\n const { indexName } = await this.createEmbeddingIndex(dimension, config);\n\n await Promise.all(\n embeddings.map(async embedding => {\n if (typeof this.vector === `undefined`) {\n throw new Error(\n `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`,\n );\n }\n\n vectorResults.push(\n ...(await this.vector.query({\n indexName,\n queryVector: embedding,\n topK: vectorConfig.topK,\n filter: resourceScope\n ? {\n resource_id: resourceId,\n }\n : {\n thread_id: threadId,\n },\n })),\n );\n }),\n );\n }\n\n // Get raw messages from storage\n const paginatedResult = await this.storage.listMessages({\n threadId,\n resourceId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n filter,\n ...(vectorResults?.length\n ? {\n include: vectorResults.map(r => ({\n id: r.metadata?.message_id,\n threadId: r.metadata?.thread_id,\n withNextMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.after,\n withPreviousMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.before,\n })),\n }\n : {}),\n });\n // Reverse to restore chronological order if we queried DESC to get newest messages\n const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;\n\n const list = new MessageList({ threadId, resourceId }).add(rawMessages, 'memory');\n\n // Always return mastra-db format (V2)\n const messages = list.get.all.db();\n\n return { messages };\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n return this.storage.getThreadById({ threadId });\n }\n\n async listThreadsByResourceId(\n args: StorageListThreadsByResourceIdInput,\n ): Promise<StorageListThreadsByResourceIdOutput> {\n return this.storage.listThreadsByResourceId(args);\n }\n\n private async handleWorkingMemoryFromMetadata({\n workingMemory,\n resourceId,\n memoryConfig,\n }: {\n workingMemory: string;\n resourceId: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (config.workingMemory?.enabled) {\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // For resource scope, update the resource's working memory\n if (scope === 'resource' && resourceId) {\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n }\n // For thread scope, the metadata is already saved with the thread\n }\n }\n\n async saveThread({\n thread,\n memoryConfig,\n }: {\n thread: StorageThreadType;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const savedThread = await this.storage.saveThread({ thread });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (thread.metadata?.workingMemory && typeof thread.metadata.workingMemory === 'string' && thread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: thread.metadata.workingMemory,\n resourceId: thread.resourceId,\n memoryConfig,\n });\n }\n\n return savedThread;\n }\n\n async updateThread({\n id,\n title,\n metadata,\n memoryConfig,\n }: {\n id: string;\n title: string;\n metadata: Record<string, unknown>;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const updatedThread = await this.storage.updateThread({\n id,\n title,\n metadata,\n });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (metadata?.workingMemory && typeof metadata.workingMemory === 'string' && updatedThread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: metadata.workingMemory as string,\n resourceId: updatedThread.resourceId,\n memoryConfig,\n });\n }\n\n return updatedThread;\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.storage.deleteThread({ threadId });\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n }\n\n private updateWorkingMemoryMutexes = new Map<string, Mutex>();\n /**\n * @warning experimental! can be removed or changed at any time\n */\n async __experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory,\n searchString,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n searchString?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<{ success: boolean; reason: string }> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n // If the agent calls the update working memory tool multiple times simultaneously\n // each call could overwrite the other call\n // so get an in memory mutex to make sure this.getWorkingMemory() returns up to date data each time\n const mutexKey =\n memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`;\n const mutex = this.updateWorkingMemoryMutexes.has(mutexKey)\n ? this.updateWorkingMemoryMutexes.get(mutexKey)!\n : new Mutex();\n this.updateWorkingMemoryMutexes.set(mutexKey, mutex);\n const release = await mutex.acquire();\n\n try {\n const existingWorkingMemory = (await this.getWorkingMemory({ threadId, resourceId, memoryConfig })) || '';\n const template = await this.getWorkingMemoryTemplate({ memoryConfig });\n\n let reason = '';\n if (existingWorkingMemory) {\n if (searchString && existingWorkingMemory?.includes(searchString)) {\n workingMemory = existingWorkingMemory.replace(searchString, workingMemory);\n reason = `found and replaced searchString with newMemory`;\n } else if (\n existingWorkingMemory.includes(workingMemory) ||\n template?.content?.trim() === workingMemory.trim()\n ) {\n return {\n success: false,\n reason: `attempted to insert duplicate data into working memory. this entry was skipped`,\n };\n } else {\n if (searchString) {\n reason = `attempted to replace working memory string that doesn't exist. Appending to working memory instead.`;\n } else {\n reason = `appended newMemory to end of working memory`;\n }\n\n workingMemory =\n existingWorkingMemory +\n `\n${workingMemory}`;\n }\n } else if (workingMemory === template?.content) {\n return {\n success: false,\n reason: `try again when you have data to add. newMemory was equal to the working memory template`,\n };\n } else {\n reason = `started new working memory`;\n }\n\n // remove empty template insertions which models sometimes duplicate\n workingMemory = template?.content ? workingMemory.replaceAll(template?.content, '') : workingMemory;\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n\n if (reason) {\n return { success: true, reason };\n }\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n\n return { success: true, reason };\n } catch (e) {\n this.logger.error(e instanceof Error ? e.stack || e.message : JSON.stringify(e));\n return { success: false, reason: 'Tool error.' };\n } finally {\n release();\n }\n }\n\n protected chunkText(text: string, tokenSize = 4096) {\n // Convert token size to character size with some buffer\n const charSize = tokenSize * CHARS_PER_TOKEN;\n const chunks: string[] = [];\n let currentChunk = '';\n\n // Split text into words to avoid breaking words\n const words = text.split(/\\s+/);\n\n for (const word of words) {\n // Add space before word unless it's the first word in the chunk\n const wordWithSpace = currentChunk ? ' ' + word : word;\n\n // If adding this word would exceed the chunk size, start a new chunk\n if (currentChunk.length + wordWithSpace.length > charSize) {\n chunks.push(currentChunk);\n currentChunk = word;\n } else {\n currentChunk += wordWithSpace;\n }\n }\n\n // Add the final chunk if not empty\n if (currentChunk) {\n chunks.push(currentChunk);\n }\n\n return chunks;\n }\n\n private hasher = xxhash();\n\n // embedding is computationally expensive so cache content -> embeddings/chunks\n private embeddingCache = new Map<\n number,\n {\n chunks: string[];\n embeddings: Awaited<ReturnType<typeof embedMany>>['embeddings'];\n dimension: number | undefined;\n }\n >();\n private firstEmbed: Promise<any> | undefined;\n protected async embedMessageContent(content: string) {\n // use fast xxhash for lower memory usage. if we cache by content string we will store all messages in memory for the life of the process\n const key = (await this.hasher).h32(content);\n const cached = this.embeddingCache.get(key);\n if (cached) return cached;\n const chunks = this.chunkText(content);\n\n if (typeof this.embedder === `undefined`) {\n throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);\n }\n // for fastembed multiple initial calls to embed will fail if the model hasn't been downloaded yet.\n const isFastEmbed = this.embedder.provider === `fastembed`;\n if (isFastEmbed && this.firstEmbed instanceof Promise) {\n // so wait for the first one\n await this.firstEmbed;\n }\n\n const promise = (this.embedder.specificationVersion === `v2` ? embedManyV5 : embedMany)({\n values: chunks,\n maxRetries: 3,\n // @ts-ignore\n model: this.embedder,\n });\n\n if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;\n const { embeddings } = await promise;\n\n const result = {\n embeddings,\n chunks,\n dimension: embeddings[0]?.length,\n };\n this.embeddingCache.set(key, result);\n return result;\n }\n\n async saveMessages({\n messages,\n memoryConfig,\n }: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig | undefined;\n }): Promise<{ messages: MastraDBMessage[] }> {\n // Then strip working memory tags from all messages\n const updatedMessages = messages\n .map(m => {\n return this.updateMessageToHideWorkingMemoryV2(m);\n })\n .filter((m): m is MastraDBMessage => Boolean(m));\n\n const config = this.getMergedThreadConfig(memoryConfig);\n\n // Convert messages to MastraDBMessage format if needed\n const dbMessages = new MessageList({\n generateMessageId: () => this.generateId(),\n })\n .add(updatedMessages, 'memory')\n .get.all.db();\n\n const result = await this.storage.saveMessages({\n messages: dbMessages,\n });\n\n if (this.vector && config.semanticRecall) {\n let indexName: Promise<string>;\n await Promise.all(\n updatedMessages.map(async message => {\n let textForEmbedding: string | null = null;\n\n if (\n message.content.content &&\n typeof message.content.content === 'string' &&\n message.content.content.trim() !== ''\n ) {\n textForEmbedding = message.content.content;\n } else if (message.content.parts && message.content.parts.length > 0) {\n // Extract text from all text parts, concatenate\n const joined = message.content.parts\n .filter(part => part.type === 'text')\n .map(part => (part as TextPart).text)\n .join(' ')\n .trim();\n if (joined) textForEmbedding = joined;\n }\n\n if (!textForEmbedding) return;\n\n const { embeddings, chunks, dimension } = await this.embedMessageContent(textForEmbedding);\n\n if (typeof indexName === `undefined`) {\n indexName = this.createEmbeddingIndex(dimension, config).then(result => result.indexName);\n }\n\n if (typeof this.vector === `undefined`) {\n throw new Error(\n `Tried to upsert embeddings to index ${indexName} but this Memory instance doesn't have an attached vector db.`,\n );\n }\n\n await this.vector.upsert({\n indexName: await indexName,\n vectors: embeddings,\n metadata: chunks.map(() => ({\n message_id: message.id,\n thread_id: message.threadId,\n resource_id: message.resourceId,\n })),\n });\n }),\n );\n }\n\n return result;\n }\n protected updateMessageToHideWorkingMemory(message: MastraMessageV1): MastraMessageV1 | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n if (typeof message?.content === `string`) {\n return {\n ...message,\n content: message.content.replace(workingMemoryRegex, ``).trim(),\n };\n } else if (Array.isArray(message?.content)) {\n // Filter out updateWorkingMemory tool-call/result content items\n const filteredContent = message.content.filter(\n content =>\n (content.type !== 'tool-call' && content.type !== 'tool-result') ||\n content.toolName !== 'updateWorkingMemory',\n );\n const newContent = filteredContent.map(content => {\n if (content.type === 'text') {\n return {\n ...content,\n text: content.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return { ...content };\n }) as MastraMessageV1['content'];\n if (!newContent.length) return null;\n return { ...message, content: newContent };\n } else {\n return { ...message };\n }\n }\n protected updateMessageToHideWorkingMemoryV2(message: MastraDBMessage): MastraDBMessage | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n const newMessage = { ...message, content: { ...message.content } }; // Deep copy message and content\n\n if (newMessage.content.content && typeof newMessage.content.content === 'string') {\n newMessage.content.content = newMessage.content.content.replace(workingMemoryRegex, '').trim();\n }\n\n if (newMessage.content.parts) {\n newMessage.content.parts = newMessage.content.parts\n .filter(part => {\n if (part.type === 'tool-invocation') {\n return part.toolInvocation.toolName !== 'updateWorkingMemory';\n }\n return true;\n })\n .map(part => {\n if (part.type === 'text') {\n return {\n ...part,\n text: part.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return part;\n });\n\n // If all parts were filtered out (e.g., only contained updateWorkingMemory tool calls) we need to skip the whole message, it was only working memory tool calls/results\n if (newMessage.content.parts.length === 0) {\n return null;\n }\n }\n\n return newMessage;\n }\n\n protected parseWorkingMemory(text: string): string | null {\n if (!this.threadConfig.workingMemory?.enabled) return null;\n\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n const matches = text.match(workingMemoryRegex);\n const match = matches?.[0];\n\n if (match) {\n return match.replace(/<\\/?working_memory>/g, '').trim();\n }\n\n return null;\n }\n\n public async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n let workingMemoryData: string | null = null;\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Get working memory from resource table\n const resource = await this.storage.getResourceById({ resourceId });\n workingMemoryData = resource?.workingMemory || null;\n } else {\n // Get working memory from thread metadata (default behavior)\n const thread = await this.storage.getThreadById({ threadId });\n workingMemoryData = thread?.metadata?.workingMemory as string;\n }\n\n if (!workingMemoryData) {\n return null;\n }\n\n return workingMemoryData;\n }\n\n /**\n * Gets the working memory template for the current memory configuration.\n * Supports both ZodObject and JSONSchema7 schemas.\n *\n * @param memoryConfig - The memory configuration containing the working memory settings\n * @returns The working memory template with format and content, or null if working memory is disabled\n */\n public async getWorkingMemoryTemplate({\n memoryConfig,\n }: {\n memoryConfig?: MemoryConfig;\n }): Promise<WorkingMemoryTemplate | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n // Get thread from storage\n if (config.workingMemory?.schema) {\n try {\n const schema = config.workingMemory.schema;\n let convertedSchema: JSONSchema7;\n\n if (isZodObject(schema as ZodTypeAny)) {\n convertedSchema = zodToJsonSchema(schema as ZodTypeAny);\n } else {\n convertedSchema = schema as JSONSchema7;\n }\n\n return { format: 'json', content: JSON.stringify(convertedSchema) };\n } catch (error) {\n this.logger.error('Error converting schema', error);\n throw error;\n }\n }\n\n // Return working memory from metadata\n const memory = config.workingMemory.template || this.defaultWorkingMemoryTemplate;\n return { format: 'markdown', content: memory.trim() };\n }\n\n public async getSystemMessage({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n const workingMemoryTemplate = await this.getWorkingMemoryTemplate({ memoryConfig });\n const workingMemoryData = await this.getWorkingMemory({ threadId, resourceId, memoryConfig: config });\n\n if (!workingMemoryTemplate) {\n return null;\n }\n\n return this.isVNextWorkingMemoryConfig(memoryConfig)\n ? this.__experimental_getWorkingMemoryToolInstructionVNext({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n })\n : this.getWorkingMemoryToolInstruction({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n });\n }\n\n public defaultWorkingMemoryTemplate = `\n# User Information\n- **First Name**: \n- **Last Name**: \n- **Location**: \n- **Occupation**: \n- **Interests**: \n- **Goals**: \n- **Events**: \n- **Facts**: \n- **Projects**: \n`;\n\n protected getWorkingMemoryToolInstruction({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n const emptyWorkingMemoryTemplateObject =\n template.format === 'json' ? generateEmptyFromSchema(template.content) : null;\n const hasEmptyWorkingMemoryTemplateObject =\n emptyWorkingMemoryTemplateObject && Object.keys(emptyWorkingMemoryTemplateObject).length > 0;\n\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool. If information might be referenced again - store it!\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n${\n template.format !== 'json'\n ? `5. IMPORTANT: When calling updateWorkingMemory, the only valid parameter is the memory field. DO NOT pass an object.\n6. IMPORTANT: ALWAYS pass the data you want to store in the memory field as a string. DO NOT pass an object.\n7. IMPORTANT: Data must only be sent as a string no matter which format is used.`\n : ''\n}\n\n\n${\n template.format !== 'json'\n ? `<working_memory_template>\n${template.content}\n</working_memory_template>`\n : ''\n}\n\n${hasEmptyWorkingMemoryTemplateObject ? 'When working with json data, the object format below represents the template:' : ''}\n${hasEmptyWorkingMemoryTemplateObject ? JSON.stringify(emptyWorkingMemoryTemplateObject) : ''}\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- Do not remove empty sections - you must include the empty sections along with the ones you're filling in\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the entire ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it.\n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.`;\n }\n\n protected __experimental_getWorkingMemoryToolInstructionVNext({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool.\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n5. If your memory has not changed, you do not need to call the updateWorkingMemory tool. By default it will persist and be available for you in future interactions\n6. Information not being relevant to the current conversation is not a valid reason to replace or remove working memory information. Your working memory spans across multiple conversations and may be needed again later, even if it's not currently relevant.\n\n<working_memory_template>\n${template.content}\n</working_memory_template>\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n${\n template.content !== this.defaultWorkingMemoryTemplate\n ? `- Only store information if it's in the working memory template, do not store other information unless the user asks you to remember it, as that non-template information may be irrelevant`\n : `- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n`\n}\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it. \n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information if that information is not already stored.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.\n`;\n }\n\n private isVNextWorkingMemoryConfig(config?: MemoryConfig): boolean {\n if (!config?.workingMemory) return false;\n\n const isMDWorkingMemory =\n !(`schema` in config.workingMemory) &&\n (typeof config.workingMemory.template === `string` || config.workingMemory.template) &&\n config.workingMemory;\n\n return Boolean(isMDWorkingMemory && isMDWorkingMemory.version === `vnext`);\n }\n\n public listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any>> {\n const mergedConfig = this.getMergedThreadConfig(config);\n if (mergedConfig.workingMemory?.enabled) {\n return {\n updateWorkingMemory: this.isVNextWorkingMemoryConfig(mergedConfig)\n ? // use the new experimental tool\n __experimental_updateWorkingMemoryToolVNext(mergedConfig)\n : updateWorkingMemoryTool(mergedConfig),\n };\n }\n return {};\n }\n\n /**\n * Updates the metadata of a list of messages\n * @param messages - The list of messages to update\n * @returns The list of updated messages\n */\n public async updateMessages({\n messages,\n }: {\n messages: Partial<MastraDBMessage> & { id: string }[];\n }): Promise<MastraDBMessage[]> {\n if (messages.length === 0) return [];\n\n // TODO: Possibly handle updating the vector db here when a message is updated.\n\n return this.storage.updateMessages({ messages });\n }\n\n /**\n * Deletes one or more messages\n * @param input - Must be an array containing either:\n * - Message ID strings\n * - Message objects with 'id' properties\n * @returns Promise that resolves when all messages are deleted\n */\n public async deleteMessages(input: MessageDeleteInput): Promise<void> {\n // Normalize input to array of IDs\n let messageIds: string[];\n\n if (!Array.isArray(input)) {\n throw new Error('Invalid input: must be an array of message IDs or message objects');\n }\n\n if (input.length === 0) {\n return; // No-op for empty array\n }\n\n messageIds = input.map(item => {\n if (typeof item === 'string') {\n return item;\n } else if (item && typeof item === 'object' && 'id' in item) {\n return item.id;\n } else {\n throw new Error('Invalid input: array items must be strings or objects with an id property');\n }\n });\n\n // Validate all IDs are non-empty strings\n const invalidIds = messageIds.filter(id => !id || typeof id !== 'string');\n if (invalidIds.length > 0) {\n throw new Error('All message IDs must be non-empty strings');\n }\n\n // Delete from storage\n await this.storage.deleteMessages(messageIds);\n\n // TODO: Delete from vector store if semantic recall is enabled\n // This would require getting the messages first to know their threadId/resourceId\n // and then querying the vector store to delete associated embeddings\n }\n}\n\n// Re-export memory processors from @mastra/core for backward compatibility\nexport { SemanticRecall, WorkingMemory, MessageHistory } from '@mastra/core/processors';\n"]}
1
+ {"version":3,"sources":["../src/tools/working-memory.ts","../src/index.ts"],"names":["z","ZodObject","convertSchemaToZod","createTool","MastraMemory","MessageList","Mutex","xxhash","embedManyV5","embedMany","result","zodToJsonSchema","generateEmptyFromSchema"],"mappings":";;;;;;;;;;;;;;;;;;;;AAcO,SAAS,sBAAA,CACd,UACA,MAAA,EACyB;AACzB,EAAA,IAAI,CAAC,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,EAAU;AAC7C,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,MAAA,GAAkC,EAAE,GAAG,QAAA,EAAS;AAEtD,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,EAAG;AACrC,IAAA,MAAM,WAAA,GAAc,OAAO,GAAG,CAAA;AAC9B,IAAA,MAAM,aAAA,GAAgB,OAAO,GAAG,CAAA;AAGhC,IAAA,IAAI,gBAAgB,IAAA,EAAM;AACxB,MAAA,OAAO,OAAO,GAAG,CAAA;AAAA,IACnB,CAAA,MAAA,IAES,KAAA,CAAM,OAAA,CAAQ,WAAW,CAAA,EAAG;AACnC,MAAA,MAAA,CAAO,GAAG,CAAA,GAAI,WAAA;AAAA,IAChB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index.cjs","sourcesContent":["import type { MemoryConfig } from '@mastra/core/memory';\nimport { createTool } from '@mastra/core/tools';\nimport { convertSchemaToZod } from '@mastra/schema-compat';\nimport type { Schema } from '@mastra/schema-compat';\nimport { z, ZodObject } from 'zod';\nimport type { ZodType } from 'zod';\n\n/**\n * Deep merges two objects, with special handling for null values (delete) and arrays (replace).\n * - Object properties are recursively merged\n * - null values in the update will delete the corresponding property\n * - Arrays are replaced entirely (not merged element-by-element)\n * - Primitive values are overwritten\n */\nexport function deepMergeWorkingMemory(\n existing: Record<string, unknown> | null | undefined,\n update: Record<string, unknown>,\n): Record<string, unknown> {\n if (!existing || typeof existing !== 'object') {\n return update;\n }\n\n const result: Record<string, unknown> = { ...existing };\n\n for (const key of Object.keys(update)) {\n const updateValue = update[key];\n const existingValue = result[key];\n\n // null means delete the property\n if (updateValue === null) {\n delete result[key];\n }\n // Arrays are replaced entirely (too complex to diff/merge arrays of objects)\n else if (Array.isArray(updateValue)) {\n result[key] = updateValue;\n }\n // Recursively merge nested objects\n else if (\n typeof updateValue === 'object' &&\n updateValue !== null &&\n typeof existingValue === 'object' &&\n existingValue !== null &&\n !Array.isArray(existingValue)\n ) {\n result[key] = deepMergeWorkingMemory(\n existingValue as Record<string, unknown>,\n updateValue as Record<string, unknown>,\n );\n }\n // Primitive values or new properties: just set them\n else {\n result[key] = updateValue;\n }\n }\n\n return result;\n}\n\nexport const updateWorkingMemoryTool = (memoryConfig?: MemoryConfig) => {\n const schema = memoryConfig?.workingMemory?.schema;\n\n let inputSchema: ZodType = z.object({\n memory: z\n .string()\n .describe(`The Markdown formatted working memory content to store. This MUST be a string. Never pass an object.`),\n });\n\n if (schema) {\n inputSchema = z.object({\n memory:\n schema instanceof ZodObject\n ? schema\n : (convertSchemaToZod({ jsonSchema: schema } as Schema).describe(\n `The JSON formatted working memory content to store.`,\n ) as ZodObject<any>),\n });\n }\n\n // For schema-based working memory, we use merge semantics\n // For template-based (Markdown), we use replace semantics (existing behavior)\n const usesMergeSemantics = Boolean(schema);\n\n const description = schema\n ? `Update the working memory with new information. Data is merged with existing memory - you only need to include fields you want to add or update. Set a field to null to remove it. Arrays are replaced entirely when provided.`\n : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;\n\n return createTool({\n id: 'update-working-memory',\n description,\n inputSchema,\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n let workingMemory: string;\n\n if (usesMergeSemantics) {\n // Schema-based: fetch existing, merge, save\n const existingRaw = await memory.getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n });\n\n let existingData: Record<string, unknown> | null = null;\n if (existingRaw) {\n try {\n existingData = typeof existingRaw === 'string' ? JSON.parse(existingRaw) : existingRaw;\n } catch {\n // If existing data is not valid JSON, start fresh\n existingData = null;\n }\n }\n\n let newData: unknown;\n if (typeof inputData.memory === 'string') {\n try {\n newData = JSON.parse(inputData.memory);\n } catch (parseError) {\n const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(\n `Failed to parse working memory input as JSON: ${errorMessage}. ` +\n `Raw input: ${inputData.memory.length > 500 ? inputData.memory.slice(0, 500) + '...' : inputData.memory}`,\n );\n }\n } else {\n newData = inputData.memory;\n }\n const mergedData = deepMergeWorkingMemory(existingData, newData as Record<string, unknown>);\n workingMemory = JSON.stringify(mergedData);\n } else {\n // Template-based (Markdown): use existing replace semantics\n workingMemory = typeof inputData.memory === 'string' ? inputData.memory : JSON.stringify(inputData.memory);\n }\n\n // Use the updateWorkingMemory method which handles both thread and resource scope\n await memory.updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n });\n\n return { success: true };\n },\n });\n};\n\nexport const __experimental_updateWorkingMemoryToolVNext = (config: MemoryConfig) => {\n return createTool({\n id: 'update-working-memory',\n description: 'Update the working memory with new information.',\n inputSchema: z.object({\n newMemory: z\n .string()\n .optional()\n .describe(\n `The ${config.workingMemory?.schema ? 'JSON' : 'Markdown'} formatted working memory content to store`,\n ),\n searchString: z\n .string()\n .optional()\n .describe(\n \"The working memory string to find. Will be replaced with the newMemory string. If this is omitted or doesn't exist, the newMemory string will be appended to the end of your working memory. Replacing single lines at a time is encouraged for greater accuracy. If updateReason is not 'append-new-memory', this search string must be provided or the tool call will be rejected.\",\n ),\n updateReason: z\n .enum(['append-new-memory', 'clarify-existing-memory', 'replace-irrelevant-memory'])\n .optional()\n .describe(\n \"The reason you're updating working memory. Passing any value other than 'append-new-memory' requires a searchString to be provided. Defaults to append-new-memory\",\n ),\n }),\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig: config,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n const workingMemory = inputData.newMemory || '';\n if (!inputData.updateReason) inputData.updateReason = `append-new-memory`;\n\n if (\n inputData.searchString &&\n config.workingMemory?.scope === `resource` &&\n inputData.updateReason === `replace-irrelevant-memory`\n ) {\n // don't allow replacements due to something not being relevant to the current conversation\n // if there's no searchString, then we will append.\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason === `append-new-memory` && inputData.searchString) {\n // do not find/replace when append-new-memory is selected\n // some models get confused and pass a search string even when they don't want to replace it.\n // TODO: maybe they're trying to add new info after the search string?\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason !== `append-new-memory` && !inputData.searchString) {\n return {\n success: false,\n reason: `updateReason was ${inputData.updateReason} but no searchString was provided. Unable to replace undefined with \"${inputData.newMemory}\"`,\n };\n }\n\n // Use the new updateWorkingMemory method which handles both thread and resource scope\n const result = await memory!.__experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory: workingMemory,\n searchString: inputData.searchString,\n memoryConfig: config,\n });\n\n if (result) {\n return result;\n }\n\n return { success: true };\n },\n });\n};\n","import { MessageList } from '@mastra/core/agent';\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory } from '@mastra/core/memory';\nimport type {\n MastraMessageV1,\n MemoryConfig,\n SharedMemoryConfig,\n StorageThreadType,\n WorkingMemoryTemplate,\n MessageDeleteInput,\n} from '@mastra/core/memory';\nimport type {\n StorageListThreadsByResourceIdOutput,\n StorageListThreadsByResourceIdInput,\n StorageListMessagesInput,\n} from '@mastra/core/storage';\nimport type { ToolAction } from '@mastra/core/tools';\nimport { generateEmptyFromSchema } from '@mastra/core/utils';\nimport { zodToJsonSchema } from '@mastra/schema-compat/zod-to-json';\nimport { embedMany } from 'ai';\nimport type { TextPart } from 'ai';\nimport { embedMany as embedManyV5 } from 'ai-v5';\nimport { Mutex } from 'async-mutex';\nimport type { JSONSchema7 } from 'json-schema';\nimport xxhash from 'xxhash-wasm';\nimport { ZodObject } from 'zod';\nimport type { ZodTypeAny } from 'zod';\nimport {\n updateWorkingMemoryTool,\n __experimental_updateWorkingMemoryToolVNext,\n deepMergeWorkingMemory,\n} from './tools/working-memory';\n\n// Re-export for testing purposes\nexport { deepMergeWorkingMemory };\n\n// Average characters per token based on OpenAI's tokenization\nconst CHARS_PER_TOKEN = 4;\n\nconst DEFAULT_MESSAGE_RANGE = { before: 1, after: 1 } as const;\nconst DEFAULT_TOP_K = 4;\n\nconst isZodObject = (v: ZodTypeAny): v is ZodObject<any, any, any> => v instanceof ZodObject;\n\n/**\n * Concrete implementation of MastraMemory that adds support for thread configuration\n * and message injection.\n */\nexport class Memory extends MastraMemory {\n constructor(config: SharedMemoryConfig = {}) {\n super({ name: 'Memory', ...config });\n\n const mergedConfig = this.getMergedThreadConfig({\n workingMemory: config.options?.workingMemory || {\n // these defaults are now set inside @mastra/core/memory in getMergedThreadConfig.\n // In a future release we can remove it from this block - for now if we remove it\n // and someone bumps @mastra/memory without bumping @mastra/core the defaults wouldn't exist yet\n enabled: false,\n template: this.defaultWorkingMemoryTemplate,\n },\n });\n this.threadConfig = mergedConfig;\n }\n\n protected async validateThreadIsOwnedByResource(threadId: string, resourceId: string, config: MemoryConfig) {\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n const thread = await this.storage.getThreadById({ threadId });\n\n // For resource-scoped semantic recall, we don't need to validate that the specific thread exists\n // because we're searching across all threads for the resource\n if (!thread && !resourceScope) {\n throw new Error(`No thread found with id ${threadId}`);\n }\n\n // If thread exists, validate it belongs to the correct resource\n if (thread && thread.resourceId !== resourceId) {\n throw new Error(\n `Thread with id ${threadId} is for resource with id ${thread.resourceId} but resource ${resourceId} was queried.`,\n );\n }\n }\n\n protected checkStorageFeatureSupport(config: MemoryConfig) {\n const resourceScope =\n (typeof config.semanticRecall === 'object' && config.semanticRecall.scope !== 'thread') ||\n // resource scope is now default\n config.semanticRecall === true;\n\n if (resourceScope && !this.storage.supports.selectByIncludeResourceScope) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support semanticRecall: { scope: \"resource\" } yet and currently only supports per-thread semantic recall.`,\n );\n }\n\n if (\n config.workingMemory?.enabled &&\n config.workingMemory.scope === `resource` &&\n !this.storage.supports.resourceWorkingMemory\n ) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support workingMemory: { scope: \"resource\" } yet and currently only supports per-thread working memory. Supported adapters: LibSQL, PostgreSQL, Upstash.`,\n );\n }\n }\n\n async recall(\n args: StorageListMessagesInput & {\n threadConfig?: MemoryConfig;\n vectorSearchString?: string;\n threadId: string;\n },\n ): Promise<{ messages: MastraDBMessage[] }> {\n const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, filter } = args;\n const config = this.getMergedThreadConfig(threadConfig || {});\n if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);\n\n // Use perPage from args if provided, otherwise use threadConfig.lastMessages\n const perPage = perPageArg !== undefined ? perPageArg : config.lastMessages;\n\n // When limiting messages (perPage !== false) without explicit orderBy, we need to:\n // 1. Query DESC to get the NEWEST messages (not oldest)\n // 2. Reverse results to restore chronological order for the LLM\n // Without this fix, \"lastMessages: 64\" returns the OLDEST 64 messages, not the last 64.\n const shouldGetNewestAndReverse = !orderBy && perPage !== false;\n const effectiveOrderBy = shouldGetNewestAndReverse\n ? { field: 'createdAt' as const, direction: 'DESC' as const }\n : orderBy;\n\n const vectorResults: {\n id: string;\n score: number;\n metadata?: Record<string, any>;\n vector?: number[];\n }[] = [];\n\n this.logger.debug(`Memory recall() with:`, {\n threadId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n threadConfig,\n });\n\n this.checkStorageFeatureSupport(config);\n\n const defaultRange = DEFAULT_MESSAGE_RANGE;\n const defaultTopK = DEFAULT_TOP_K;\n\n const vectorConfig =\n typeof config?.semanticRecall === `boolean`\n ? {\n topK: defaultTopK,\n messageRange: defaultRange,\n }\n : {\n topK: config?.semanticRecall?.topK ?? defaultTopK,\n messageRange: config?.semanticRecall?.messageRange ?? defaultRange,\n };\n\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n // Guard: If resource-scoped semantic recall is enabled but no resourceId is provided, throw an error\n if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {\n throw new Error(\n `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`,\n );\n }\n\n if (config?.semanticRecall && vectorSearchString && this.vector) {\n const { embeddings, dimension } = await this.embedMessageContent(vectorSearchString!);\n const { indexName } = await this.createEmbeddingIndex(dimension, config);\n\n await Promise.all(\n embeddings.map(async embedding => {\n if (typeof this.vector === `undefined`) {\n throw new Error(\n `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`,\n );\n }\n\n vectorResults.push(\n ...(await this.vector.query({\n indexName,\n queryVector: embedding,\n topK: vectorConfig.topK,\n filter: resourceScope\n ? {\n resource_id: resourceId,\n }\n : {\n thread_id: threadId,\n },\n })),\n );\n }),\n );\n }\n\n // Get raw messages from storage\n const paginatedResult = await this.storage.listMessages({\n threadId,\n resourceId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n filter,\n ...(vectorResults?.length\n ? {\n include: vectorResults.map(r => ({\n id: r.metadata?.message_id,\n threadId: r.metadata?.thread_id,\n withNextMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.after,\n withPreviousMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.before,\n })),\n }\n : {}),\n });\n // Reverse to restore chronological order if we queried DESC to get newest messages\n const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;\n\n const list = new MessageList({ threadId, resourceId }).add(rawMessages, 'memory');\n\n // Always return mastra-db format (V2)\n const messages = list.get.all.db();\n\n return { messages };\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n return this.storage.getThreadById({ threadId });\n }\n\n async listThreadsByResourceId(\n args: StorageListThreadsByResourceIdInput,\n ): Promise<StorageListThreadsByResourceIdOutput> {\n return this.storage.listThreadsByResourceId(args);\n }\n\n private async handleWorkingMemoryFromMetadata({\n workingMemory,\n resourceId,\n memoryConfig,\n }: {\n workingMemory: string;\n resourceId: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (config.workingMemory?.enabled) {\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // For resource scope, update the resource's working memory\n if (scope === 'resource' && resourceId) {\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n }\n // For thread scope, the metadata is already saved with the thread\n }\n }\n\n async saveThread({\n thread,\n memoryConfig,\n }: {\n thread: StorageThreadType;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const savedThread = await this.storage.saveThread({ thread });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (thread.metadata?.workingMemory && typeof thread.metadata.workingMemory === 'string' && thread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: thread.metadata.workingMemory,\n resourceId: thread.resourceId,\n memoryConfig,\n });\n }\n\n return savedThread;\n }\n\n async updateThread({\n id,\n title,\n metadata,\n memoryConfig,\n }: {\n id: string;\n title: string;\n metadata: Record<string, unknown>;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const updatedThread = await this.storage.updateThread({\n id,\n title,\n metadata,\n });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (metadata?.workingMemory && typeof metadata.workingMemory === 'string' && updatedThread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: metadata.workingMemory as string,\n resourceId: updatedThread.resourceId,\n memoryConfig,\n });\n }\n\n return updatedThread;\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.storage.deleteThread({ threadId });\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n }\n\n private updateWorkingMemoryMutexes = new Map<string, Mutex>();\n /**\n * @warning experimental! can be removed or changed at any time\n */\n async __experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory,\n searchString,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n searchString?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<{ success: boolean; reason: string }> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n // If the agent calls the update working memory tool multiple times simultaneously\n // each call could overwrite the other call\n // so get an in memory mutex to make sure this.getWorkingMemory() returns up to date data each time\n const mutexKey =\n memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`;\n const mutex = this.updateWorkingMemoryMutexes.has(mutexKey)\n ? this.updateWorkingMemoryMutexes.get(mutexKey)!\n : new Mutex();\n this.updateWorkingMemoryMutexes.set(mutexKey, mutex);\n const release = await mutex.acquire();\n\n try {\n const existingWorkingMemory = (await this.getWorkingMemory({ threadId, resourceId, memoryConfig })) || '';\n const template = await this.getWorkingMemoryTemplate({ memoryConfig });\n\n let reason = '';\n if (existingWorkingMemory) {\n if (searchString && existingWorkingMemory?.includes(searchString)) {\n workingMemory = existingWorkingMemory.replace(searchString, workingMemory);\n reason = `found and replaced searchString with newMemory`;\n } else if (\n existingWorkingMemory.includes(workingMemory) ||\n template?.content?.trim() === workingMemory.trim()\n ) {\n return {\n success: false,\n reason: `attempted to insert duplicate data into working memory. this entry was skipped`,\n };\n } else {\n if (searchString) {\n reason = `attempted to replace working memory string that doesn't exist. Appending to working memory instead.`;\n } else {\n reason = `appended newMemory to end of working memory`;\n }\n\n workingMemory =\n existingWorkingMemory +\n `\n${workingMemory}`;\n }\n } else if (workingMemory === template?.content) {\n return {\n success: false,\n reason: `try again when you have data to add. newMemory was equal to the working memory template`,\n };\n } else {\n reason = `started new working memory`;\n }\n\n // remove empty template insertions which models sometimes duplicate\n workingMemory = template?.content ? workingMemory.replaceAll(template?.content, '') : workingMemory;\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n\n if (reason) {\n return { success: true, reason };\n }\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n\n return { success: true, reason };\n } catch (e) {\n this.logger.error(e instanceof Error ? e.stack || e.message : JSON.stringify(e));\n return { success: false, reason: 'Tool error.' };\n } finally {\n release();\n }\n }\n\n protected chunkText(text: string, tokenSize = 4096) {\n // Convert token size to character size with some buffer\n const charSize = tokenSize * CHARS_PER_TOKEN;\n const chunks: string[] = [];\n let currentChunk = '';\n\n // Split text into words to avoid breaking words\n const words = text.split(/\\s+/);\n\n for (const word of words) {\n // Add space before word unless it's the first word in the chunk\n const wordWithSpace = currentChunk ? ' ' + word : word;\n\n // If adding this word would exceed the chunk size, start a new chunk\n if (currentChunk.length + wordWithSpace.length > charSize) {\n chunks.push(currentChunk);\n currentChunk = word;\n } else {\n currentChunk += wordWithSpace;\n }\n }\n\n // Add the final chunk if not empty\n if (currentChunk) {\n chunks.push(currentChunk);\n }\n\n return chunks;\n }\n\n private hasher = xxhash();\n\n // embedding is computationally expensive so cache content -> embeddings/chunks\n private embeddingCache = new Map<\n number,\n {\n chunks: string[];\n embeddings: Awaited<ReturnType<typeof embedMany>>['embeddings'];\n dimension: number | undefined;\n }\n >();\n private firstEmbed: Promise<any> | undefined;\n protected async embedMessageContent(content: string) {\n // use fast xxhash for lower memory usage. if we cache by content string we will store all messages in memory for the life of the process\n const key = (await this.hasher).h32(content);\n const cached = this.embeddingCache.get(key);\n if (cached) return cached;\n const chunks = this.chunkText(content);\n\n if (typeof this.embedder === `undefined`) {\n throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);\n }\n // for fastembed multiple initial calls to embed will fail if the model hasn't been downloaded yet.\n const isFastEmbed = this.embedder.provider === `fastembed`;\n if (isFastEmbed && this.firstEmbed instanceof Promise) {\n // so wait for the first one\n await this.firstEmbed;\n }\n\n const promise = (this.embedder.specificationVersion === `v2` ? embedManyV5 : embedMany)({\n values: chunks,\n maxRetries: 3,\n // @ts-ignore\n model: this.embedder,\n });\n\n if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;\n const { embeddings } = await promise;\n\n const result = {\n embeddings,\n chunks,\n dimension: embeddings[0]?.length,\n };\n this.embeddingCache.set(key, result);\n return result;\n }\n\n async saveMessages({\n messages,\n memoryConfig,\n }: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig | undefined;\n }): Promise<{ messages: MastraDBMessage[] }> {\n // Then strip working memory tags from all messages\n const updatedMessages = messages\n .map(m => {\n return this.updateMessageToHideWorkingMemoryV2(m);\n })\n .filter((m): m is MastraDBMessage => Boolean(m));\n\n const config = this.getMergedThreadConfig(memoryConfig);\n\n // Convert messages to MastraDBMessage format if needed\n const dbMessages = new MessageList({\n generateMessageId: () => this.generateId(),\n })\n .add(updatedMessages, 'memory')\n .get.all.db();\n\n const result = await this.storage.saveMessages({\n messages: dbMessages,\n });\n\n if (this.vector && config.semanticRecall) {\n // Collect all embeddings first (embedding is CPU-bound, doesn't use pool connections)\n const embeddingData: Array<{\n embeddings: number[][];\n metadata: Array<{ message_id: string; thread_id: string | undefined; resource_id: string | undefined }>;\n }> = [];\n let dimension: number | undefined;\n\n // Process embeddings concurrently - this doesn't use DB connections\n await Promise.all(\n updatedMessages.map(async message => {\n let textForEmbedding: string | null = null;\n\n if (\n message.content.content &&\n typeof message.content.content === 'string' &&\n message.content.content.trim() !== ''\n ) {\n textForEmbedding = message.content.content;\n } else if (message.content.parts && message.content.parts.length > 0) {\n // Extract text from all text parts, concatenate\n const joined = message.content.parts\n .filter(part => part.type === 'text')\n .map(part => (part as TextPart).text)\n .join(' ')\n .trim();\n if (joined) textForEmbedding = joined;\n }\n\n if (!textForEmbedding) return;\n\n const result = await this.embedMessageContent(textForEmbedding);\n dimension = result.dimension;\n\n embeddingData.push({\n embeddings: result.embeddings,\n metadata: result.chunks.map(() => ({\n message_id: message.id,\n thread_id: message.threadId,\n resource_id: message.resourceId,\n })),\n });\n }),\n );\n\n // Batch all vectors into a single upsert call to avoid pool exhaustion\n if (embeddingData.length > 0 && dimension !== undefined) {\n if (typeof this.vector === `undefined`) {\n throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);\n }\n\n const { indexName } = await this.createEmbeddingIndex(dimension, config);\n\n // Flatten all embeddings and metadata into single arrays\n const allVectors: number[][] = [];\n const allMetadata: Array<{\n message_id: string;\n thread_id: string | undefined;\n resource_id: string | undefined;\n }> = [];\n\n for (const data of embeddingData) {\n allVectors.push(...data.embeddings);\n allMetadata.push(...data.metadata);\n }\n\n await this.vector.upsert({\n indexName,\n vectors: allVectors,\n metadata: allMetadata,\n });\n }\n }\n\n return result;\n }\n protected updateMessageToHideWorkingMemory(message: MastraMessageV1): MastraMessageV1 | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n if (typeof message?.content === `string`) {\n return {\n ...message,\n content: message.content.replace(workingMemoryRegex, ``).trim(),\n };\n } else if (Array.isArray(message?.content)) {\n // Filter out updateWorkingMemory tool-call/result content items\n const filteredContent = message.content.filter(\n content =>\n (content.type !== 'tool-call' && content.type !== 'tool-result') ||\n content.toolName !== 'updateWorkingMemory',\n );\n const newContent = filteredContent.map(content => {\n if (content.type === 'text') {\n return {\n ...content,\n text: content.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return { ...content };\n }) as MastraMessageV1['content'];\n if (!newContent.length) return null;\n return { ...message, content: newContent };\n } else {\n return { ...message };\n }\n }\n protected updateMessageToHideWorkingMemoryV2(message: MastraDBMessage): MastraDBMessage | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n const newMessage = { ...message, content: { ...message.content } }; // Deep copy message and content\n\n if (newMessage.content.content && typeof newMessage.content.content === 'string') {\n newMessage.content.content = newMessage.content.content.replace(workingMemoryRegex, '').trim();\n }\n\n if (newMessage.content.parts) {\n newMessage.content.parts = newMessage.content.parts\n .filter(part => {\n if (part.type === 'tool-invocation') {\n return part.toolInvocation.toolName !== 'updateWorkingMemory';\n }\n return true;\n })\n .map(part => {\n if (part.type === 'text') {\n return {\n ...part,\n text: part.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return part;\n });\n\n // If all parts were filtered out (e.g., only contained updateWorkingMemory tool calls) we need to skip the whole message, it was only working memory tool calls/results\n if (newMessage.content.parts.length === 0) {\n return null;\n }\n }\n\n return newMessage;\n }\n\n protected parseWorkingMemory(text: string): string | null {\n if (!this.threadConfig.workingMemory?.enabled) return null;\n\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n const matches = text.match(workingMemoryRegex);\n const match = matches?.[0];\n\n if (match) {\n return match.replace(/<\\/?working_memory>/g, '').trim();\n }\n\n return null;\n }\n\n public async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n let workingMemoryData: string | null = null;\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Get working memory from resource table\n const resource = await this.storage.getResourceById({ resourceId });\n workingMemoryData = resource?.workingMemory || null;\n } else {\n // Get working memory from thread metadata (default behavior)\n const thread = await this.storage.getThreadById({ threadId });\n workingMemoryData = thread?.metadata?.workingMemory as string;\n }\n\n if (!workingMemoryData) {\n return null;\n }\n\n return workingMemoryData;\n }\n\n /**\n * Gets the working memory template for the current memory configuration.\n * Supports both ZodObject and JSONSchema7 schemas.\n *\n * @param memoryConfig - The memory configuration containing the working memory settings\n * @returns The working memory template with format and content, or null if working memory is disabled\n */\n public async getWorkingMemoryTemplate({\n memoryConfig,\n }: {\n memoryConfig?: MemoryConfig;\n }): Promise<WorkingMemoryTemplate | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n // Get thread from storage\n if (config.workingMemory?.schema) {\n try {\n const schema = config.workingMemory.schema;\n let convertedSchema: JSONSchema7;\n\n if (isZodObject(schema as ZodTypeAny)) {\n convertedSchema = zodToJsonSchema(schema as ZodTypeAny);\n } else {\n convertedSchema = schema as JSONSchema7;\n }\n\n return { format: 'json', content: JSON.stringify(convertedSchema) };\n } catch (error) {\n this.logger.error('Error converting schema', error);\n throw error;\n }\n }\n\n // Return working memory from metadata\n const memory = config.workingMemory.template || this.defaultWorkingMemoryTemplate;\n return { format: 'markdown', content: memory.trim() };\n }\n\n public async getSystemMessage({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n const workingMemoryTemplate = await this.getWorkingMemoryTemplate({ memoryConfig });\n const workingMemoryData = await this.getWorkingMemory({ threadId, resourceId, memoryConfig: config });\n\n if (!workingMemoryTemplate) {\n return null;\n }\n\n return this.isVNextWorkingMemoryConfig(memoryConfig)\n ? this.__experimental_getWorkingMemoryToolInstructionVNext({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n })\n : this.getWorkingMemoryToolInstruction({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n });\n }\n\n public defaultWorkingMemoryTemplate = `\n# User Information\n- **First Name**: \n- **Last Name**: \n- **Location**: \n- **Occupation**: \n- **Interests**: \n- **Goals**: \n- **Events**: \n- **Facts**: \n- **Projects**: \n`;\n\n protected getWorkingMemoryToolInstruction({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n const emptyWorkingMemoryTemplateObject =\n template.format === 'json' ? generateEmptyFromSchema(template.content) : null;\n const hasEmptyWorkingMemoryTemplateObject =\n emptyWorkingMemoryTemplateObject && Object.keys(emptyWorkingMemoryTemplateObject).length > 0;\n\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool. If information might be referenced again - store it!\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n${\n template.format !== 'json'\n ? `5. IMPORTANT: When calling updateWorkingMemory, the only valid parameter is the memory field. DO NOT pass an object.\n6. IMPORTANT: ALWAYS pass the data you want to store in the memory field as a string. DO NOT pass an object.\n7. IMPORTANT: Data must only be sent as a string no matter which format is used.`\n : ''\n}\n\n\n${\n template.format !== 'json'\n ? `<working_memory_template>\n${template.content}\n</working_memory_template>`\n : ''\n}\n\n${hasEmptyWorkingMemoryTemplateObject ? 'When working with json data, the object format below represents the template:' : ''}\n${hasEmptyWorkingMemoryTemplateObject ? JSON.stringify(emptyWorkingMemoryTemplateObject) : ''}\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- Do not remove empty sections - you must include the empty sections along with the ones you're filling in\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the entire ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it.\n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.`;\n }\n\n protected __experimental_getWorkingMemoryToolInstructionVNext({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool.\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n5. If your memory has not changed, you do not need to call the updateWorkingMemory tool. By default it will persist and be available for you in future interactions\n6. Information not being relevant to the current conversation is not a valid reason to replace or remove working memory information. Your working memory spans across multiple conversations and may be needed again later, even if it's not currently relevant.\n\n<working_memory_template>\n${template.content}\n</working_memory_template>\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n${\n template.content !== this.defaultWorkingMemoryTemplate\n ? `- Only store information if it's in the working memory template, do not store other information unless the user asks you to remember it, as that non-template information may be irrelevant`\n : `- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n`\n}\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it. \n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information if that information is not already stored.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.\n`;\n }\n\n private isVNextWorkingMemoryConfig(config?: MemoryConfig): boolean {\n if (!config?.workingMemory) return false;\n\n const isMDWorkingMemory =\n !(`schema` in config.workingMemory) &&\n (typeof config.workingMemory.template === `string` || config.workingMemory.template) &&\n config.workingMemory;\n\n return Boolean(isMDWorkingMemory && isMDWorkingMemory.version === `vnext`);\n }\n\n public listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any>> {\n const mergedConfig = this.getMergedThreadConfig(config);\n if (mergedConfig.workingMemory?.enabled) {\n return {\n updateWorkingMemory: this.isVNextWorkingMemoryConfig(mergedConfig)\n ? // use the new experimental tool\n __experimental_updateWorkingMemoryToolVNext(mergedConfig)\n : updateWorkingMemoryTool(mergedConfig),\n };\n }\n return {};\n }\n\n /**\n * Updates the metadata of a list of messages\n * @param messages - The list of messages to update\n * @returns The list of updated messages\n */\n public async updateMessages({\n messages,\n }: {\n messages: Partial<MastraDBMessage> & { id: string }[];\n }): Promise<MastraDBMessage[]> {\n if (messages.length === 0) return [];\n\n // TODO: Possibly handle updating the vector db here when a message is updated.\n\n return this.storage.updateMessages({ messages });\n }\n\n /**\n * Deletes one or more messages\n * @param input - Must be an array containing either:\n * - Message ID strings\n * - Message objects with 'id' properties\n * @returns Promise that resolves when all messages are deleted\n */\n public async deleteMessages(input: MessageDeleteInput): Promise<void> {\n // Normalize input to array of IDs\n let messageIds: string[];\n\n if (!Array.isArray(input)) {\n throw new Error('Invalid input: must be an array of message IDs or message objects');\n }\n\n if (input.length === 0) {\n return; // No-op for empty array\n }\n\n messageIds = input.map(item => {\n if (typeof item === 'string') {\n return item;\n } else if (item && typeof item === 'object' && 'id' in item) {\n return item.id;\n } else {\n throw new Error('Invalid input: array items must be strings or objects with an id property');\n }\n });\n\n // Validate all IDs are non-empty strings\n const invalidIds = messageIds.filter(id => !id || typeof id !== 'string');\n if (invalidIds.length > 0) {\n throw new Error('All message IDs must be non-empty strings');\n }\n\n // Delete from storage\n await this.storage.deleteMessages(messageIds);\n\n // TODO: Delete from vector store if semantic recall is enabled\n // This would require getting the messages first to know their threadId/resourceId\n // and then querying the vector store to delete associated embeddings\n }\n}\n\n// Re-export memory processors from @mastra/core for backward compatibility\nexport { SemanticRecall, WorkingMemory, MessageHistory } from '@mastra/core/processors';\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,YAA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AG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;IAalF;;;;OAIG;IACU,cAAc,CAAC,EAC1B,QAAQ,GACT,EAAE;QACD,QAAQ,EAAE,OAAO,CAAC,eAAe,CAAC,GAAG;YAAE,EAAE,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC;KACvD,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;IAQ9B;;;;;;OAMG;IACU,cAAc,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;CAmCtE;AAGD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC"}
package/dist/index.js CHANGED
@@ -546,7 +546,8 @@ ${workingMemory}`;
546
546
  messages: dbMessages
547
547
  });
548
548
  if (this.vector && config.semanticRecall) {
549
- let indexName;
549
+ const embeddingData = [];
550
+ let dimension;
550
551
  await Promise.all(
551
552
  updatedMessages.map(async (message) => {
552
553
  let textForEmbedding = null;
@@ -557,19 +558,11 @@ ${workingMemory}`;
557
558
  if (joined) textForEmbedding = joined;
558
559
  }
559
560
  if (!textForEmbedding) return;
560
- const { embeddings, chunks, dimension } = await this.embedMessageContent(textForEmbedding);
561
- if (typeof indexName === `undefined`) {
562
- indexName = this.createEmbeddingIndex(dimension, config).then((result2) => result2.indexName);
563
- }
564
- if (typeof this.vector === `undefined`) {
565
- throw new Error(
566
- `Tried to upsert embeddings to index ${indexName} but this Memory instance doesn't have an attached vector db.`
567
- );
568
- }
569
- await this.vector.upsert({
570
- indexName: await indexName,
571
- vectors: embeddings,
572
- metadata: chunks.map(() => ({
561
+ const result2 = await this.embedMessageContent(textForEmbedding);
562
+ dimension = result2.dimension;
563
+ embeddingData.push({
564
+ embeddings: result2.embeddings,
565
+ metadata: result2.chunks.map(() => ({
573
566
  message_id: message.id,
574
567
  thread_id: message.threadId,
575
568
  resource_id: message.resourceId
@@ -577,6 +570,23 @@ ${workingMemory}`;
577
570
  });
578
571
  })
579
572
  );
573
+ if (embeddingData.length > 0 && dimension !== void 0) {
574
+ if (typeof this.vector === `undefined`) {
575
+ throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
576
+ }
577
+ const { indexName } = await this.createEmbeddingIndex(dimension, config);
578
+ const allVectors = [];
579
+ const allMetadata = [];
580
+ for (const data of embeddingData) {
581
+ allVectors.push(...data.embeddings);
582
+ allMetadata.push(...data.metadata);
583
+ }
584
+ await this.vector.upsert({
585
+ indexName,
586
+ vectors: allVectors,
587
+ metadata: allMetadata
588
+ });
589
+ }
580
590
  }
581
591
  return result;
582
592
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tools/working-memory.ts","../src/index.ts"],"names":["ZodObject","embedManyV5","embedMany","result"],"mappings":";;;;;;;;;;;;;;AAcO,SAAS,sBAAA,CACd,UACA,MAAA,EACyB;AACzB,EAAA,IAAI,CAAC,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,EAAU;AAC7C,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,MAAA,GAAkC,EAAE,GAAG,QAAA,EAAS;AAEtD,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,EAAG;AACrC,IAAA,MAAM,WAAA,GAAc,OAAO,GAAG,CAAA;AAC9B,IAAA,MAAM,aAAA,GAAgB,OAAO,GAAG,CAAA;AAGhC,IAAA,IAAI,gBAAgB,IAAA,EAAM;AACxB,MAAA,OAAO,OAAO,GAAG,CAAA;AAAA,IACnB,CAAA,MAAA,IAES,KAAA,CAAM,OAAA,CAAQ,WAAW,CAAA,EAAG;AACnC,MAAA,MAAA,CAAO,GAAG,CAAA,GAAI,WAAA;AAAA,IAChB,CAAA,MAAA,IAGE,OAAO,WAAA,KAAgB,QAAA,IACvB,gBAAgB,IAAA,IAChB,OAAO,aAAA,KAAkB,QAAA,IACzB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AAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,MAAA;AAAA,IACF;AAEA,IAAA,UAAA,GAAa,KAAA,CAAM,IAAI,CAAA,IAAA,KAAQ;AAC7B,MAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,QAAA,OAAO,IAAA;AAAA,MACT,WAAW,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,IAAY,QAAQ,IAAA,EAAM;AAC3D,QAAA,OAAO,IAAA,CAAK,EAAA;AAAA,MACd,CAAA,MAAO;AACL,QAAA,MAAM,IAAI,MAAM,2EAA2E,CAAA;AAAA,MAC7F;AAAA,IACF,CAAC,CAAA;AAGD,IAAA,MAAM,UAAA,GAAa,WAAW,MAAA,CAAO,CAAA,EAAA,KAAM,CAAC,EAAA,IAAM,OAAO,OAAO,QAAQ,CAAA;AACxE,IAAA,IAAI,UAAA,CAAW,SAAS,CAAA,EAAG;AACzB,MAAA,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAAA,IAC7D;AAGA,IAAA,MAAM,IAAA,CAAK,OAAA,CAAQ,cAAA,CAAe,UAAU,CAAA;AAAA,EAK9C;AACF","file":"index.js","sourcesContent":["import type { MemoryConfig } from '@mastra/core/memory';\nimport { createTool } from '@mastra/core/tools';\nimport { convertSchemaToZod } from '@mastra/schema-compat';\nimport type { Schema } from '@mastra/schema-compat';\nimport { z, ZodObject } from 'zod';\nimport type { ZodType } from 'zod';\n\n/**\n * Deep merges two objects, with special handling for null values (delete) and arrays (replace).\n * - Object properties are recursively merged\n * - null values in the update will delete the corresponding property\n * - Arrays are replaced entirely (not merged element-by-element)\n * - Primitive values are overwritten\n */\nexport function deepMergeWorkingMemory(\n existing: Record<string, unknown> | null | undefined,\n update: Record<string, unknown>,\n): Record<string, unknown> {\n if (!existing || typeof existing !== 'object') {\n return update;\n }\n\n const result: Record<string, unknown> = { ...existing };\n\n for (const key of Object.keys(update)) {\n const updateValue = update[key];\n const existingValue = result[key];\n\n // null means delete the property\n if (updateValue === null) {\n delete result[key];\n }\n // Arrays are replaced entirely (too complex to diff/merge arrays of objects)\n else if (Array.isArray(updateValue)) {\n result[key] = updateValue;\n }\n // Recursively merge nested objects\n else if (\n typeof updateValue === 'object' &&\n updateValue !== null &&\n typeof existingValue === 'object' &&\n existingValue !== null &&\n !Array.isArray(existingValue)\n ) {\n result[key] = deepMergeWorkingMemory(\n existingValue as Record<string, unknown>,\n updateValue as Record<string, unknown>,\n );\n }\n // Primitive values or new properties: just set them\n else {\n result[key] = updateValue;\n }\n }\n\n return result;\n}\n\nexport const updateWorkingMemoryTool = (memoryConfig?: MemoryConfig) => {\n const schema = memoryConfig?.workingMemory?.schema;\n\n let inputSchema: ZodType = z.object({\n memory: z\n .string()\n .describe(`The Markdown formatted working memory content to store. This MUST be a string. Never pass an object.`),\n });\n\n if (schema) {\n inputSchema = z.object({\n memory:\n schema instanceof ZodObject\n ? schema\n : (convertSchemaToZod({ jsonSchema: schema } as Schema).describe(\n `The JSON formatted working memory content to store.`,\n ) as ZodObject<any>),\n });\n }\n\n // For schema-based working memory, we use merge semantics\n // For template-based (Markdown), we use replace semantics (existing behavior)\n const usesMergeSemantics = Boolean(schema);\n\n const description = schema\n ? `Update the working memory with new information. Data is merged with existing memory - you only need to include fields you want to add or update. Set a field to null to remove it. Arrays are replaced entirely when provided.`\n : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;\n\n return createTool({\n id: 'update-working-memory',\n description,\n inputSchema,\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n let workingMemory: string;\n\n if (usesMergeSemantics) {\n // Schema-based: fetch existing, merge, save\n const existingRaw = await memory.getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n });\n\n let existingData: Record<string, unknown> | null = null;\n if (existingRaw) {\n try {\n existingData = typeof existingRaw === 'string' ? JSON.parse(existingRaw) : existingRaw;\n } catch {\n // If existing data is not valid JSON, start fresh\n existingData = null;\n }\n }\n\n let newData: unknown;\n if (typeof inputData.memory === 'string') {\n try {\n newData = JSON.parse(inputData.memory);\n } catch (parseError) {\n const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(\n `Failed to parse working memory input as JSON: ${errorMessage}. ` +\n `Raw input: ${inputData.memory.length > 500 ? inputData.memory.slice(0, 500) + '...' : inputData.memory}`,\n );\n }\n } else {\n newData = inputData.memory;\n }\n const mergedData = deepMergeWorkingMemory(existingData, newData as Record<string, unknown>);\n workingMemory = JSON.stringify(mergedData);\n } else {\n // Template-based (Markdown): use existing replace semantics\n workingMemory = typeof inputData.memory === 'string' ? inputData.memory : JSON.stringify(inputData.memory);\n }\n\n // Use the updateWorkingMemory method which handles both thread and resource scope\n await memory.updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n });\n\n return { success: true };\n },\n });\n};\n\nexport const __experimental_updateWorkingMemoryToolVNext = (config: MemoryConfig) => {\n return createTool({\n id: 'update-working-memory',\n description: 'Update the working memory with new information.',\n inputSchema: z.object({\n newMemory: z\n .string()\n .optional()\n .describe(\n `The ${config.workingMemory?.schema ? 'JSON' : 'Markdown'} formatted working memory content to store`,\n ),\n searchString: z\n .string()\n .optional()\n .describe(\n \"The working memory string to find. Will be replaced with the newMemory string. If this is omitted or doesn't exist, the newMemory string will be appended to the end of your working memory. Replacing single lines at a time is encouraged for greater accuracy. If updateReason is not 'append-new-memory', this search string must be provided or the tool call will be rejected.\",\n ),\n updateReason: z\n .enum(['append-new-memory', 'clarify-existing-memory', 'replace-irrelevant-memory'])\n .optional()\n .describe(\n \"The reason you're updating working memory. Passing any value other than 'append-new-memory' requires a searchString to be provided. Defaults to append-new-memory\",\n ),\n }),\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig: config,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n const workingMemory = inputData.newMemory || '';\n if (!inputData.updateReason) inputData.updateReason = `append-new-memory`;\n\n if (\n inputData.searchString &&\n config.workingMemory?.scope === `resource` &&\n inputData.updateReason === `replace-irrelevant-memory`\n ) {\n // don't allow replacements due to something not being relevant to the current conversation\n // if there's no searchString, then we will append.\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason === `append-new-memory` && inputData.searchString) {\n // do not find/replace when append-new-memory is selected\n // some models get confused and pass a search string even when they don't want to replace it.\n // TODO: maybe they're trying to add new info after the search string?\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason !== `append-new-memory` && !inputData.searchString) {\n return {\n success: false,\n reason: `updateReason was ${inputData.updateReason} but no searchString was provided. Unable to replace undefined with \"${inputData.newMemory}\"`,\n };\n }\n\n // Use the new updateWorkingMemory method which handles both thread and resource scope\n const result = await memory!.__experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory: workingMemory,\n searchString: inputData.searchString,\n memoryConfig: config,\n });\n\n if (result) {\n return result;\n }\n\n return { success: true };\n },\n });\n};\n","import { MessageList } from '@mastra/core/agent';\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory } from '@mastra/core/memory';\nimport type {\n MastraMessageV1,\n MemoryConfig,\n SharedMemoryConfig,\n StorageThreadType,\n WorkingMemoryTemplate,\n MessageDeleteInput,\n} from '@mastra/core/memory';\nimport type {\n StorageListThreadsByResourceIdOutput,\n StorageListThreadsByResourceIdInput,\n StorageListMessagesInput,\n} from '@mastra/core/storage';\nimport type { ToolAction } from '@mastra/core/tools';\nimport { generateEmptyFromSchema } from '@mastra/core/utils';\nimport { zodToJsonSchema } from '@mastra/schema-compat/zod-to-json';\nimport { embedMany } from 'ai';\nimport type { TextPart } from 'ai';\nimport { embedMany as embedManyV5 } from 'ai-v5';\nimport { Mutex } from 'async-mutex';\nimport type { JSONSchema7 } from 'json-schema';\nimport xxhash from 'xxhash-wasm';\nimport { ZodObject } from 'zod';\nimport type { ZodTypeAny } from 'zod';\nimport {\n updateWorkingMemoryTool,\n __experimental_updateWorkingMemoryToolVNext,\n deepMergeWorkingMemory,\n} from './tools/working-memory';\n\n// Re-export for testing purposes\nexport { deepMergeWorkingMemory };\n\n// Average characters per token based on OpenAI's tokenization\nconst CHARS_PER_TOKEN = 4;\n\nconst DEFAULT_MESSAGE_RANGE = { before: 1, after: 1 } as const;\nconst DEFAULT_TOP_K = 4;\n\nconst isZodObject = (v: ZodTypeAny): v is ZodObject<any, any, any> => v instanceof ZodObject;\n\n/**\n * Concrete implementation of MastraMemory that adds support for thread configuration\n * and message injection.\n */\nexport class Memory extends MastraMemory {\n constructor(config: SharedMemoryConfig = {}) {\n super({ name: 'Memory', ...config });\n\n const mergedConfig = this.getMergedThreadConfig({\n workingMemory: config.options?.workingMemory || {\n // these defaults are now set inside @mastra/core/memory in getMergedThreadConfig.\n // In a future release we can remove it from this block - for now if we remove it\n // and someone bumps @mastra/memory without bumping @mastra/core the defaults wouldn't exist yet\n enabled: false,\n template: this.defaultWorkingMemoryTemplate,\n },\n });\n this.threadConfig = mergedConfig;\n }\n\n protected async validateThreadIsOwnedByResource(threadId: string, resourceId: string, config: MemoryConfig) {\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n const thread = await this.storage.getThreadById({ threadId });\n\n // For resource-scoped semantic recall, we don't need to validate that the specific thread exists\n // because we're searching across all threads for the resource\n if (!thread && !resourceScope) {\n throw new Error(`No thread found with id ${threadId}`);\n }\n\n // If thread exists, validate it belongs to the correct resource\n if (thread && thread.resourceId !== resourceId) {\n throw new Error(\n `Thread with id ${threadId} is for resource with id ${thread.resourceId} but resource ${resourceId} was queried.`,\n );\n }\n }\n\n protected checkStorageFeatureSupport(config: MemoryConfig) {\n const resourceScope =\n (typeof config.semanticRecall === 'object' && config.semanticRecall.scope !== 'thread') ||\n // resource scope is now default\n config.semanticRecall === true;\n\n if (resourceScope && !this.storage.supports.selectByIncludeResourceScope) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support semanticRecall: { scope: \"resource\" } yet and currently only supports per-thread semantic recall.`,\n );\n }\n\n if (\n config.workingMemory?.enabled &&\n config.workingMemory.scope === `resource` &&\n !this.storage.supports.resourceWorkingMemory\n ) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support workingMemory: { scope: \"resource\" } yet and currently only supports per-thread working memory. Supported adapters: LibSQL, PostgreSQL, Upstash.`,\n );\n }\n }\n\n async recall(\n args: StorageListMessagesInput & {\n threadConfig?: MemoryConfig;\n vectorSearchString?: string;\n threadId: string;\n },\n ): Promise<{ messages: MastraDBMessage[] }> {\n const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, filter } = args;\n const config = this.getMergedThreadConfig(threadConfig || {});\n if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);\n\n // Use perPage from args if provided, otherwise use threadConfig.lastMessages\n const perPage = perPageArg !== undefined ? perPageArg : config.lastMessages;\n\n // When limiting messages (perPage !== false) without explicit orderBy, we need to:\n // 1. Query DESC to get the NEWEST messages (not oldest)\n // 2. Reverse results to restore chronological order for the LLM\n // Without this fix, \"lastMessages: 64\" returns the OLDEST 64 messages, not the last 64.\n const shouldGetNewestAndReverse = !orderBy && perPage !== false;\n const effectiveOrderBy = shouldGetNewestAndReverse\n ? { field: 'createdAt' as const, direction: 'DESC' as const }\n : orderBy;\n\n const vectorResults: {\n id: string;\n score: number;\n metadata?: Record<string, any>;\n vector?: number[];\n }[] = [];\n\n this.logger.debug(`Memory recall() with:`, {\n threadId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n threadConfig,\n });\n\n this.checkStorageFeatureSupport(config);\n\n const defaultRange = DEFAULT_MESSAGE_RANGE;\n const defaultTopK = DEFAULT_TOP_K;\n\n const vectorConfig =\n typeof config?.semanticRecall === `boolean`\n ? {\n topK: defaultTopK,\n messageRange: defaultRange,\n }\n : {\n topK: config?.semanticRecall?.topK ?? defaultTopK,\n messageRange: config?.semanticRecall?.messageRange ?? defaultRange,\n };\n\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n // Guard: If resource-scoped semantic recall is enabled but no resourceId is provided, throw an error\n if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {\n throw new Error(\n `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`,\n );\n }\n\n if (config?.semanticRecall && vectorSearchString && this.vector) {\n const { embeddings, dimension } = await this.embedMessageContent(vectorSearchString!);\n const { indexName } = await this.createEmbeddingIndex(dimension, config);\n\n await Promise.all(\n embeddings.map(async embedding => {\n if (typeof this.vector === `undefined`) {\n throw new Error(\n `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`,\n );\n }\n\n vectorResults.push(\n ...(await this.vector.query({\n indexName,\n queryVector: embedding,\n topK: vectorConfig.topK,\n filter: resourceScope\n ? {\n resource_id: resourceId,\n }\n : {\n thread_id: threadId,\n },\n })),\n );\n }),\n );\n }\n\n // Get raw messages from storage\n const paginatedResult = await this.storage.listMessages({\n threadId,\n resourceId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n filter,\n ...(vectorResults?.length\n ? {\n include: vectorResults.map(r => ({\n id: r.metadata?.message_id,\n threadId: r.metadata?.thread_id,\n withNextMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.after,\n withPreviousMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.before,\n })),\n }\n : {}),\n });\n // Reverse to restore chronological order if we queried DESC to get newest messages\n const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;\n\n const list = new MessageList({ threadId, resourceId }).add(rawMessages, 'memory');\n\n // Always return mastra-db format (V2)\n const messages = list.get.all.db();\n\n return { messages };\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n return this.storage.getThreadById({ threadId });\n }\n\n async listThreadsByResourceId(\n args: StorageListThreadsByResourceIdInput,\n ): Promise<StorageListThreadsByResourceIdOutput> {\n return this.storage.listThreadsByResourceId(args);\n }\n\n private async handleWorkingMemoryFromMetadata({\n workingMemory,\n resourceId,\n memoryConfig,\n }: {\n workingMemory: string;\n resourceId: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (config.workingMemory?.enabled) {\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // For resource scope, update the resource's working memory\n if (scope === 'resource' && resourceId) {\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n }\n // For thread scope, the metadata is already saved with the thread\n }\n }\n\n async saveThread({\n thread,\n memoryConfig,\n }: {\n thread: StorageThreadType;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const savedThread = await this.storage.saveThread({ thread });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (thread.metadata?.workingMemory && typeof thread.metadata.workingMemory === 'string' && thread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: thread.metadata.workingMemory,\n resourceId: thread.resourceId,\n memoryConfig,\n });\n }\n\n return savedThread;\n }\n\n async updateThread({\n id,\n title,\n metadata,\n memoryConfig,\n }: {\n id: string;\n title: string;\n metadata: Record<string, unknown>;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const updatedThread = await this.storage.updateThread({\n id,\n title,\n metadata,\n });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (metadata?.workingMemory && typeof metadata.workingMemory === 'string' && updatedThread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: metadata.workingMemory as string,\n resourceId: updatedThread.resourceId,\n memoryConfig,\n });\n }\n\n return updatedThread;\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.storage.deleteThread({ threadId });\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n }\n\n private updateWorkingMemoryMutexes = new Map<string, Mutex>();\n /**\n * @warning experimental! can be removed or changed at any time\n */\n async __experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory,\n searchString,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n searchString?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<{ success: boolean; reason: string }> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n // If the agent calls the update working memory tool multiple times simultaneously\n // each call could overwrite the other call\n // so get an in memory mutex to make sure this.getWorkingMemory() returns up to date data each time\n const mutexKey =\n memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`;\n const mutex = this.updateWorkingMemoryMutexes.has(mutexKey)\n ? this.updateWorkingMemoryMutexes.get(mutexKey)!\n : new Mutex();\n this.updateWorkingMemoryMutexes.set(mutexKey, mutex);\n const release = await mutex.acquire();\n\n try {\n const existingWorkingMemory = (await this.getWorkingMemory({ threadId, resourceId, memoryConfig })) || '';\n const template = await this.getWorkingMemoryTemplate({ memoryConfig });\n\n let reason = '';\n if (existingWorkingMemory) {\n if (searchString && existingWorkingMemory?.includes(searchString)) {\n workingMemory = existingWorkingMemory.replace(searchString, workingMemory);\n reason = `found and replaced searchString with newMemory`;\n } else if (\n existingWorkingMemory.includes(workingMemory) ||\n template?.content?.trim() === workingMemory.trim()\n ) {\n return {\n success: false,\n reason: `attempted to insert duplicate data into working memory. this entry was skipped`,\n };\n } else {\n if (searchString) {\n reason = `attempted to replace working memory string that doesn't exist. Appending to working memory instead.`;\n } else {\n reason = `appended newMemory to end of working memory`;\n }\n\n workingMemory =\n existingWorkingMemory +\n `\n${workingMemory}`;\n }\n } else if (workingMemory === template?.content) {\n return {\n success: false,\n reason: `try again when you have data to add. newMemory was equal to the working memory template`,\n };\n } else {\n reason = `started new working memory`;\n }\n\n // remove empty template insertions which models sometimes duplicate\n workingMemory = template?.content ? workingMemory.replaceAll(template?.content, '') : workingMemory;\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n\n if (reason) {\n return { success: true, reason };\n }\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n\n return { success: true, reason };\n } catch (e) {\n this.logger.error(e instanceof Error ? e.stack || e.message : JSON.stringify(e));\n return { success: false, reason: 'Tool error.' };\n } finally {\n release();\n }\n }\n\n protected chunkText(text: string, tokenSize = 4096) {\n // Convert token size to character size with some buffer\n const charSize = tokenSize * CHARS_PER_TOKEN;\n const chunks: string[] = [];\n let currentChunk = '';\n\n // Split text into words to avoid breaking words\n const words = text.split(/\\s+/);\n\n for (const word of words) {\n // Add space before word unless it's the first word in the chunk\n const wordWithSpace = currentChunk ? ' ' + word : word;\n\n // If adding this word would exceed the chunk size, start a new chunk\n if (currentChunk.length + wordWithSpace.length > charSize) {\n chunks.push(currentChunk);\n currentChunk = word;\n } else {\n currentChunk += wordWithSpace;\n }\n }\n\n // Add the final chunk if not empty\n if (currentChunk) {\n chunks.push(currentChunk);\n }\n\n return chunks;\n }\n\n private hasher = xxhash();\n\n // embedding is computationally expensive so cache content -> embeddings/chunks\n private embeddingCache = new Map<\n number,\n {\n chunks: string[];\n embeddings: Awaited<ReturnType<typeof embedMany>>['embeddings'];\n dimension: number | undefined;\n }\n >();\n private firstEmbed: Promise<any> | undefined;\n protected async embedMessageContent(content: string) {\n // use fast xxhash for lower memory usage. if we cache by content string we will store all messages in memory for the life of the process\n const key = (await this.hasher).h32(content);\n const cached = this.embeddingCache.get(key);\n if (cached) return cached;\n const chunks = this.chunkText(content);\n\n if (typeof this.embedder === `undefined`) {\n throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);\n }\n // for fastembed multiple initial calls to embed will fail if the model hasn't been downloaded yet.\n const isFastEmbed = this.embedder.provider === `fastembed`;\n if (isFastEmbed && this.firstEmbed instanceof Promise) {\n // so wait for the first one\n await this.firstEmbed;\n }\n\n const promise = (this.embedder.specificationVersion === `v2` ? embedManyV5 : embedMany)({\n values: chunks,\n maxRetries: 3,\n // @ts-ignore\n model: this.embedder,\n });\n\n if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;\n const { embeddings } = await promise;\n\n const result = {\n embeddings,\n chunks,\n dimension: embeddings[0]?.length,\n };\n this.embeddingCache.set(key, result);\n return result;\n }\n\n async saveMessages({\n messages,\n memoryConfig,\n }: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig | undefined;\n }): Promise<{ messages: MastraDBMessage[] }> {\n // Then strip working memory tags from all messages\n const updatedMessages = messages\n .map(m => {\n return this.updateMessageToHideWorkingMemoryV2(m);\n })\n .filter((m): m is MastraDBMessage => Boolean(m));\n\n const config = this.getMergedThreadConfig(memoryConfig);\n\n // Convert messages to MastraDBMessage format if needed\n const dbMessages = new MessageList({\n generateMessageId: () => this.generateId(),\n })\n .add(updatedMessages, 'memory')\n .get.all.db();\n\n const result = await this.storage.saveMessages({\n messages: dbMessages,\n });\n\n if (this.vector && config.semanticRecall) {\n let indexName: Promise<string>;\n await Promise.all(\n updatedMessages.map(async message => {\n let textForEmbedding: string | null = null;\n\n if (\n message.content.content &&\n typeof message.content.content === 'string' &&\n message.content.content.trim() !== ''\n ) {\n textForEmbedding = message.content.content;\n } else if (message.content.parts && message.content.parts.length > 0) {\n // Extract text from all text parts, concatenate\n const joined = message.content.parts\n .filter(part => part.type === 'text')\n .map(part => (part as TextPart).text)\n .join(' ')\n .trim();\n if (joined) textForEmbedding = joined;\n }\n\n if (!textForEmbedding) return;\n\n const { embeddings, chunks, dimension } = await this.embedMessageContent(textForEmbedding);\n\n if (typeof indexName === `undefined`) {\n indexName = this.createEmbeddingIndex(dimension, config).then(result => result.indexName);\n }\n\n if (typeof this.vector === `undefined`) {\n throw new Error(\n `Tried to upsert embeddings to index ${indexName} but this Memory instance doesn't have an attached vector db.`,\n );\n }\n\n await this.vector.upsert({\n indexName: await indexName,\n vectors: embeddings,\n metadata: chunks.map(() => ({\n message_id: message.id,\n thread_id: message.threadId,\n resource_id: message.resourceId,\n })),\n });\n }),\n );\n }\n\n return result;\n }\n protected updateMessageToHideWorkingMemory(message: MastraMessageV1): MastraMessageV1 | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n if (typeof message?.content === `string`) {\n return {\n ...message,\n content: message.content.replace(workingMemoryRegex, ``).trim(),\n };\n } else if (Array.isArray(message?.content)) {\n // Filter out updateWorkingMemory tool-call/result content items\n const filteredContent = message.content.filter(\n content =>\n (content.type !== 'tool-call' && content.type !== 'tool-result') ||\n content.toolName !== 'updateWorkingMemory',\n );\n const newContent = filteredContent.map(content => {\n if (content.type === 'text') {\n return {\n ...content,\n text: content.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return { ...content };\n }) as MastraMessageV1['content'];\n if (!newContent.length) return null;\n return { ...message, content: newContent };\n } else {\n return { ...message };\n }\n }\n protected updateMessageToHideWorkingMemoryV2(message: MastraDBMessage): MastraDBMessage | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n const newMessage = { ...message, content: { ...message.content } }; // Deep copy message and content\n\n if (newMessage.content.content && typeof newMessage.content.content === 'string') {\n newMessage.content.content = newMessage.content.content.replace(workingMemoryRegex, '').trim();\n }\n\n if (newMessage.content.parts) {\n newMessage.content.parts = newMessage.content.parts\n .filter(part => {\n if (part.type === 'tool-invocation') {\n return part.toolInvocation.toolName !== 'updateWorkingMemory';\n }\n return true;\n })\n .map(part => {\n if (part.type === 'text') {\n return {\n ...part,\n text: part.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return part;\n });\n\n // If all parts were filtered out (e.g., only contained updateWorkingMemory tool calls) we need to skip the whole message, it was only working memory tool calls/results\n if (newMessage.content.parts.length === 0) {\n return null;\n }\n }\n\n return newMessage;\n }\n\n protected parseWorkingMemory(text: string): string | null {\n if (!this.threadConfig.workingMemory?.enabled) return null;\n\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n const matches = text.match(workingMemoryRegex);\n const match = matches?.[0];\n\n if (match) {\n return match.replace(/<\\/?working_memory>/g, '').trim();\n }\n\n return null;\n }\n\n public async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n let workingMemoryData: string | null = null;\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Get working memory from resource table\n const resource = await this.storage.getResourceById({ resourceId });\n workingMemoryData = resource?.workingMemory || null;\n } else {\n // Get working memory from thread metadata (default behavior)\n const thread = await this.storage.getThreadById({ threadId });\n workingMemoryData = thread?.metadata?.workingMemory as string;\n }\n\n if (!workingMemoryData) {\n return null;\n }\n\n return workingMemoryData;\n }\n\n /**\n * Gets the working memory template for the current memory configuration.\n * Supports both ZodObject and JSONSchema7 schemas.\n *\n * @param memoryConfig - The memory configuration containing the working memory settings\n * @returns The working memory template with format and content, or null if working memory is disabled\n */\n public async getWorkingMemoryTemplate({\n memoryConfig,\n }: {\n memoryConfig?: MemoryConfig;\n }): Promise<WorkingMemoryTemplate | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n // Get thread from storage\n if (config.workingMemory?.schema) {\n try {\n const schema = config.workingMemory.schema;\n let convertedSchema: JSONSchema7;\n\n if (isZodObject(schema as ZodTypeAny)) {\n convertedSchema = zodToJsonSchema(schema as ZodTypeAny);\n } else {\n convertedSchema = schema as JSONSchema7;\n }\n\n return { format: 'json', content: JSON.stringify(convertedSchema) };\n } catch (error) {\n this.logger.error('Error converting schema', error);\n throw error;\n }\n }\n\n // Return working memory from metadata\n const memory = config.workingMemory.template || this.defaultWorkingMemoryTemplate;\n return { format: 'markdown', content: memory.trim() };\n }\n\n public async getSystemMessage({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n const workingMemoryTemplate = await this.getWorkingMemoryTemplate({ memoryConfig });\n const workingMemoryData = await this.getWorkingMemory({ threadId, resourceId, memoryConfig: config });\n\n if (!workingMemoryTemplate) {\n return null;\n }\n\n return this.isVNextWorkingMemoryConfig(memoryConfig)\n ? this.__experimental_getWorkingMemoryToolInstructionVNext({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n })\n : this.getWorkingMemoryToolInstruction({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n });\n }\n\n public defaultWorkingMemoryTemplate = `\n# User Information\n- **First Name**: \n- **Last Name**: \n- **Location**: \n- **Occupation**: \n- **Interests**: \n- **Goals**: \n- **Events**: \n- **Facts**: \n- **Projects**: \n`;\n\n protected getWorkingMemoryToolInstruction({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n const emptyWorkingMemoryTemplateObject =\n template.format === 'json' ? generateEmptyFromSchema(template.content) : null;\n const hasEmptyWorkingMemoryTemplateObject =\n emptyWorkingMemoryTemplateObject && Object.keys(emptyWorkingMemoryTemplateObject).length > 0;\n\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool. If information might be referenced again - store it!\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n${\n template.format !== 'json'\n ? `5. IMPORTANT: When calling updateWorkingMemory, the only valid parameter is the memory field. DO NOT pass an object.\n6. IMPORTANT: ALWAYS pass the data you want to store in the memory field as a string. DO NOT pass an object.\n7. IMPORTANT: Data must only be sent as a string no matter which format is used.`\n : ''\n}\n\n\n${\n template.format !== 'json'\n ? `<working_memory_template>\n${template.content}\n</working_memory_template>`\n : ''\n}\n\n${hasEmptyWorkingMemoryTemplateObject ? 'When working with json data, the object format below represents the template:' : ''}\n${hasEmptyWorkingMemoryTemplateObject ? JSON.stringify(emptyWorkingMemoryTemplateObject) : ''}\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- Do not remove empty sections - you must include the empty sections along with the ones you're filling in\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the entire ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it.\n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.`;\n }\n\n protected __experimental_getWorkingMemoryToolInstructionVNext({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool.\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n5. If your memory has not changed, you do not need to call the updateWorkingMemory tool. By default it will persist and be available for you in future interactions\n6. Information not being relevant to the current conversation is not a valid reason to replace or remove working memory information. Your working memory spans across multiple conversations and may be needed again later, even if it's not currently relevant.\n\n<working_memory_template>\n${template.content}\n</working_memory_template>\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n${\n template.content !== this.defaultWorkingMemoryTemplate\n ? `- Only store information if it's in the working memory template, do not store other information unless the user asks you to remember it, as that non-template information may be irrelevant`\n : `- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n`\n}\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it. \n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information if that information is not already stored.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.\n`;\n }\n\n private isVNextWorkingMemoryConfig(config?: MemoryConfig): boolean {\n if (!config?.workingMemory) return false;\n\n const isMDWorkingMemory =\n !(`schema` in config.workingMemory) &&\n (typeof config.workingMemory.template === `string` || config.workingMemory.template) &&\n config.workingMemory;\n\n return Boolean(isMDWorkingMemory && isMDWorkingMemory.version === `vnext`);\n }\n\n public listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any>> {\n const mergedConfig = this.getMergedThreadConfig(config);\n if (mergedConfig.workingMemory?.enabled) {\n return {\n updateWorkingMemory: this.isVNextWorkingMemoryConfig(mergedConfig)\n ? // use the new experimental tool\n __experimental_updateWorkingMemoryToolVNext(mergedConfig)\n : updateWorkingMemoryTool(mergedConfig),\n };\n }\n return {};\n }\n\n /**\n * Updates the metadata of a list of messages\n * @param messages - The list of messages to update\n * @returns The list of updated messages\n */\n public async updateMessages({\n messages,\n }: {\n messages: Partial<MastraDBMessage> & { id: string }[];\n }): Promise<MastraDBMessage[]> {\n if (messages.length === 0) return [];\n\n // TODO: Possibly handle updating the vector db here when a message is updated.\n\n return this.storage.updateMessages({ messages });\n }\n\n /**\n * Deletes one or more messages\n * @param input - Must be an array containing either:\n * - Message ID strings\n * - Message objects with 'id' properties\n * @returns Promise that resolves when all messages are deleted\n */\n public async deleteMessages(input: MessageDeleteInput): Promise<void> {\n // Normalize input to array of IDs\n let messageIds: string[];\n\n if (!Array.isArray(input)) {\n throw new Error('Invalid input: must be an array of message IDs or message objects');\n }\n\n if (input.length === 0) {\n return; // No-op for empty array\n }\n\n messageIds = input.map(item => {\n if (typeof item === 'string') {\n return item;\n } else if (item && typeof item === 'object' && 'id' in item) {\n return item.id;\n } else {\n throw new Error('Invalid input: array items must be strings or objects with an id property');\n }\n });\n\n // Validate all IDs are non-empty strings\n const invalidIds = messageIds.filter(id => !id || typeof id !== 'string');\n if (invalidIds.length > 0) {\n throw new Error('All message IDs must be non-empty strings');\n }\n\n // Delete from storage\n await this.storage.deleteMessages(messageIds);\n\n // TODO: Delete from vector store if semantic recall is enabled\n // This would require getting the messages first to know their threadId/resourceId\n // and then querying the vector store to delete associated embeddings\n }\n}\n\n// Re-export memory processors from @mastra/core for backward compatibility\nexport { SemanticRecall, WorkingMemory, MessageHistory } from '@mastra/core/processors';\n"]}
1
+ {"version":3,"sources":["../src/tools/working-memory.ts","../src/index.ts"],"names":["ZodObject","embedManyV5","embedMany","result"],"mappings":";;;;;;;;;;;;;;AAcO,SAAS,sBAAA,CACd,UACA,MAAA,EACyB;AACzB,EAAA,IAAI,CAAC,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,EAAU;AAC7C,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,MAAA,GAAkC,EAAE,GAAG,QAAA,EAAS;AAEtD,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,EAAG;AACrC,IAAA,MAAM,WAAA,GAAc,OAAO,GAAG,CAAA;AAC9B,IAAA,MAAM,aAAA,GAAgB,OAAO,GAAG,CAAA;AAGhC,IAAA,IAAI,gBAAgB,IAAA,EAAM;AACxB,MAAA,OAAO,OAAO,GAAG,CAAA;AAAA,IACnB,CAAA,MAAA,IAES,KAAA,CAAM,OAAA,CAAQ,WAAW,CAAA,EAAG;AACnC,MAAA,MAAA,CAAO,GAAG,CAAA,GAAI,WAAA;AAAA,IAChB,CAAA,MAAA,IAGE,OAAO,WAAA,KAAgB,QAAA,IACvB,gBAAgB,IAAA,IAChB,OAAO,aAAA,KAAkB,QAAA,IACzB,kBAAkB,IAAA,IAClB,CAAC,KAAA,CAAM,OAAA,CAAQ,aAAa,CAAA,EAC5B;AACA,MAAA,MAAA,CAAO,GAAG,CAAA,GAAI,sBAAA;AAAA,QACZ,aAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAA,MAEK;AACH,MAAA,MAAA,CAAO,GAAG,CAAA,GAAI,WAAA;AAAA,IAChB;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;AAEO,IAAM,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A,CAAQ,KAAK,CAAA,EAAG;AACzB,MAAA,MAAM,IAAI,MAAM,mEAAmE,CAAA;AAAA,IACrF;AAEA,IAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,MAAA;AAAA,IACF;AAEA,IAAA,UAAA,GAAa,KAAA,CAAM,IAAI,CAAA,IAAA,KAAQ;AAC7B,MAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,QAAA,OAAO,IAAA;AAAA,MACT,WAAW,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,IAAY,QAAQ,IAAA,EAAM;AAC3D,QAAA,OAAO,IAAA,CAAK,EAAA;AAAA,MACd,CAAA,MAAO;AACL,QAAA,MAAM,IAAI,MAAM,2EAA2E,CAAA;AAAA,MAC7F;AAAA,IACF,CAAC,CAAA;AAGD,IAAA,MAAM,UAAA,GAAa,WAAW,MAAA,CAAO,CAAA,EAAA,KAAM,CAAC,EAAA,IAAM,OAAO,OAAO,QAAQ,CAAA;AACxE,IAAA,IAAI,UAAA,CAAW,SAAS,CAAA,EAAG;AACzB,MAAA,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAAA,IAC7D;AAGA,IAAA,MAAM,IAAA,CAAK,OAAA,CAAQ,cAAA,CAAe,UAAU,CAAA;AAAA,EAK9C;AACF","file":"index.js","sourcesContent":["import type { MemoryConfig } from '@mastra/core/memory';\nimport { createTool } from '@mastra/core/tools';\nimport { convertSchemaToZod } from '@mastra/schema-compat';\nimport type { Schema } from '@mastra/schema-compat';\nimport { z, ZodObject } from 'zod';\nimport type { ZodType } from 'zod';\n\n/**\n * Deep merges two objects, with special handling for null values (delete) and arrays (replace).\n * - Object properties are recursively merged\n * - null values in the update will delete the corresponding property\n * - Arrays are replaced entirely (not merged element-by-element)\n * - Primitive values are overwritten\n */\nexport function deepMergeWorkingMemory(\n existing: Record<string, unknown> | null | undefined,\n update: Record<string, unknown>,\n): Record<string, unknown> {\n if (!existing || typeof existing !== 'object') {\n return update;\n }\n\n const result: Record<string, unknown> = { ...existing };\n\n for (const key of Object.keys(update)) {\n const updateValue = update[key];\n const existingValue = result[key];\n\n // null means delete the property\n if (updateValue === null) {\n delete result[key];\n }\n // Arrays are replaced entirely (too complex to diff/merge arrays of objects)\n else if (Array.isArray(updateValue)) {\n result[key] = updateValue;\n }\n // Recursively merge nested objects\n else if (\n typeof updateValue === 'object' &&\n updateValue !== null &&\n typeof existingValue === 'object' &&\n existingValue !== null &&\n !Array.isArray(existingValue)\n ) {\n result[key] = deepMergeWorkingMemory(\n existingValue as Record<string, unknown>,\n updateValue as Record<string, unknown>,\n );\n }\n // Primitive values or new properties: just set them\n else {\n result[key] = updateValue;\n }\n }\n\n return result;\n}\n\nexport const updateWorkingMemoryTool = (memoryConfig?: MemoryConfig) => {\n const schema = memoryConfig?.workingMemory?.schema;\n\n let inputSchema: ZodType = z.object({\n memory: z\n .string()\n .describe(`The Markdown formatted working memory content to store. This MUST be a string. Never pass an object.`),\n });\n\n if (schema) {\n inputSchema = z.object({\n memory:\n schema instanceof ZodObject\n ? schema\n : (convertSchemaToZod({ jsonSchema: schema } as Schema).describe(\n `The JSON formatted working memory content to store.`,\n ) as ZodObject<any>),\n });\n }\n\n // For schema-based working memory, we use merge semantics\n // For template-based (Markdown), we use replace semantics (existing behavior)\n const usesMergeSemantics = Boolean(schema);\n\n const description = schema\n ? `Update the working memory with new information. Data is merged with existing memory - you only need to include fields you want to add or update. Set a field to null to remove it. Arrays are replaced entirely when provided.`\n : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;\n\n return createTool({\n id: 'update-working-memory',\n description,\n inputSchema,\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n let workingMemory: string;\n\n if (usesMergeSemantics) {\n // Schema-based: fetch existing, merge, save\n const existingRaw = await memory.getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n });\n\n let existingData: Record<string, unknown> | null = null;\n if (existingRaw) {\n try {\n existingData = typeof existingRaw === 'string' ? JSON.parse(existingRaw) : existingRaw;\n } catch {\n // If existing data is not valid JSON, start fresh\n existingData = null;\n }\n }\n\n let newData: unknown;\n if (typeof inputData.memory === 'string') {\n try {\n newData = JSON.parse(inputData.memory);\n } catch (parseError) {\n const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(\n `Failed to parse working memory input as JSON: ${errorMessage}. ` +\n `Raw input: ${inputData.memory.length > 500 ? inputData.memory.slice(0, 500) + '...' : inputData.memory}`,\n );\n }\n } else {\n newData = inputData.memory;\n }\n const mergedData = deepMergeWorkingMemory(existingData, newData as Record<string, unknown>);\n workingMemory = JSON.stringify(mergedData);\n } else {\n // Template-based (Markdown): use existing replace semantics\n workingMemory = typeof inputData.memory === 'string' ? inputData.memory : JSON.stringify(inputData.memory);\n }\n\n // Use the updateWorkingMemory method which handles both thread and resource scope\n await memory.updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n });\n\n return { success: true };\n },\n });\n};\n\nexport const __experimental_updateWorkingMemoryToolVNext = (config: MemoryConfig) => {\n return createTool({\n id: 'update-working-memory',\n description: 'Update the working memory with new information.',\n inputSchema: z.object({\n newMemory: z\n .string()\n .optional()\n .describe(\n `The ${config.workingMemory?.schema ? 'JSON' : 'Markdown'} formatted working memory content to store`,\n ),\n searchString: z\n .string()\n .optional()\n .describe(\n \"The working memory string to find. Will be replaced with the newMemory string. If this is omitted or doesn't exist, the newMemory string will be appended to the end of your working memory. Replacing single lines at a time is encouraged for greater accuracy. If updateReason is not 'append-new-memory', this search string must be provided or the tool call will be rejected.\",\n ),\n updateReason: z\n .enum(['append-new-memory', 'clarify-existing-memory', 'replace-irrelevant-memory'])\n .optional()\n .describe(\n \"The reason you're updating working memory. Passing any value other than 'append-new-memory' requires a searchString to be provided. Defaults to append-new-memory\",\n ),\n }),\n execute: async (inputData, context) => {\n const threadId = context?.agent?.threadId;\n const resourceId = context?.agent?.resourceId;\n\n // Memory can be accessed via context.memory (when agent is part of Mastra instance)\n // or context.memory (when agent is standalone with memory passed directly)\n const memory = (context as any)?.memory;\n\n if (!threadId || !memory || !resourceId) {\n throw new Error('Thread ID, Memory instance, and resourceId are required for working memory updates');\n }\n\n let thread = await memory.getThreadById({ threadId });\n\n if (!thread) {\n thread = await memory.createThread({\n threadId,\n resourceId,\n memoryConfig: config,\n });\n }\n\n if (thread.resourceId && thread.resourceId !== resourceId) {\n throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);\n }\n\n const workingMemory = inputData.newMemory || '';\n if (!inputData.updateReason) inputData.updateReason = `append-new-memory`;\n\n if (\n inputData.searchString &&\n config.workingMemory?.scope === `resource` &&\n inputData.updateReason === `replace-irrelevant-memory`\n ) {\n // don't allow replacements due to something not being relevant to the current conversation\n // if there's no searchString, then we will append.\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason === `append-new-memory` && inputData.searchString) {\n // do not find/replace when append-new-memory is selected\n // some models get confused and pass a search string even when they don't want to replace it.\n // TODO: maybe they're trying to add new info after the search string?\n inputData.searchString = undefined;\n }\n\n if (inputData.updateReason !== `append-new-memory` && !inputData.searchString) {\n return {\n success: false,\n reason: `updateReason was ${inputData.updateReason} but no searchString was provided. Unable to replace undefined with \"${inputData.newMemory}\"`,\n };\n }\n\n // Use the new updateWorkingMemory method which handles both thread and resource scope\n const result = await memory!.__experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory: workingMemory,\n searchString: inputData.searchString,\n memoryConfig: config,\n });\n\n if (result) {\n return result;\n }\n\n return { success: true };\n },\n });\n};\n","import { MessageList } from '@mastra/core/agent';\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory } from '@mastra/core/memory';\nimport type {\n MastraMessageV1,\n MemoryConfig,\n SharedMemoryConfig,\n StorageThreadType,\n WorkingMemoryTemplate,\n MessageDeleteInput,\n} from '@mastra/core/memory';\nimport type {\n StorageListThreadsByResourceIdOutput,\n StorageListThreadsByResourceIdInput,\n StorageListMessagesInput,\n} from '@mastra/core/storage';\nimport type { ToolAction } from '@mastra/core/tools';\nimport { generateEmptyFromSchema } from '@mastra/core/utils';\nimport { zodToJsonSchema } from '@mastra/schema-compat/zod-to-json';\nimport { embedMany } from 'ai';\nimport type { TextPart } from 'ai';\nimport { embedMany as embedManyV5 } from 'ai-v5';\nimport { Mutex } from 'async-mutex';\nimport type { JSONSchema7 } from 'json-schema';\nimport xxhash from 'xxhash-wasm';\nimport { ZodObject } from 'zod';\nimport type { ZodTypeAny } from 'zod';\nimport {\n updateWorkingMemoryTool,\n __experimental_updateWorkingMemoryToolVNext,\n deepMergeWorkingMemory,\n} from './tools/working-memory';\n\n// Re-export for testing purposes\nexport { deepMergeWorkingMemory };\n\n// Average characters per token based on OpenAI's tokenization\nconst CHARS_PER_TOKEN = 4;\n\nconst DEFAULT_MESSAGE_RANGE = { before: 1, after: 1 } as const;\nconst DEFAULT_TOP_K = 4;\n\nconst isZodObject = (v: ZodTypeAny): v is ZodObject<any, any, any> => v instanceof ZodObject;\n\n/**\n * Concrete implementation of MastraMemory that adds support for thread configuration\n * and message injection.\n */\nexport class Memory extends MastraMemory {\n constructor(config: SharedMemoryConfig = {}) {\n super({ name: 'Memory', ...config });\n\n const mergedConfig = this.getMergedThreadConfig({\n workingMemory: config.options?.workingMemory || {\n // these defaults are now set inside @mastra/core/memory in getMergedThreadConfig.\n // In a future release we can remove it from this block - for now if we remove it\n // and someone bumps @mastra/memory without bumping @mastra/core the defaults wouldn't exist yet\n enabled: false,\n template: this.defaultWorkingMemoryTemplate,\n },\n });\n this.threadConfig = mergedConfig;\n }\n\n protected async validateThreadIsOwnedByResource(threadId: string, resourceId: string, config: MemoryConfig) {\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n const thread = await this.storage.getThreadById({ threadId });\n\n // For resource-scoped semantic recall, we don't need to validate that the specific thread exists\n // because we're searching across all threads for the resource\n if (!thread && !resourceScope) {\n throw new Error(`No thread found with id ${threadId}`);\n }\n\n // If thread exists, validate it belongs to the correct resource\n if (thread && thread.resourceId !== resourceId) {\n throw new Error(\n `Thread with id ${threadId} is for resource with id ${thread.resourceId} but resource ${resourceId} was queried.`,\n );\n }\n }\n\n protected checkStorageFeatureSupport(config: MemoryConfig) {\n const resourceScope =\n (typeof config.semanticRecall === 'object' && config.semanticRecall.scope !== 'thread') ||\n // resource scope is now default\n config.semanticRecall === true;\n\n if (resourceScope && !this.storage.supports.selectByIncludeResourceScope) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support semanticRecall: { scope: \"resource\" } yet and currently only supports per-thread semantic recall.`,\n );\n }\n\n if (\n config.workingMemory?.enabled &&\n config.workingMemory.scope === `resource` &&\n !this.storage.supports.resourceWorkingMemory\n ) {\n throw new Error(\n `Memory error: Attached storage adapter \"${this.storage.name || 'unknown'}\" doesn't support workingMemory: { scope: \"resource\" } yet and currently only supports per-thread working memory. Supported adapters: LibSQL, PostgreSQL, Upstash.`,\n );\n }\n }\n\n async recall(\n args: StorageListMessagesInput & {\n threadConfig?: MemoryConfig;\n vectorSearchString?: string;\n threadId: string;\n },\n ): Promise<{ messages: MastraDBMessage[] }> {\n const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, filter } = args;\n const config = this.getMergedThreadConfig(threadConfig || {});\n if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);\n\n // Use perPage from args if provided, otherwise use threadConfig.lastMessages\n const perPage = perPageArg !== undefined ? perPageArg : config.lastMessages;\n\n // When limiting messages (perPage !== false) without explicit orderBy, we need to:\n // 1. Query DESC to get the NEWEST messages (not oldest)\n // 2. Reverse results to restore chronological order for the LLM\n // Without this fix, \"lastMessages: 64\" returns the OLDEST 64 messages, not the last 64.\n const shouldGetNewestAndReverse = !orderBy && perPage !== false;\n const effectiveOrderBy = shouldGetNewestAndReverse\n ? { field: 'createdAt' as const, direction: 'DESC' as const }\n : orderBy;\n\n const vectorResults: {\n id: string;\n score: number;\n metadata?: Record<string, any>;\n vector?: number[];\n }[] = [];\n\n this.logger.debug(`Memory recall() with:`, {\n threadId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n threadConfig,\n });\n\n this.checkStorageFeatureSupport(config);\n\n const defaultRange = DEFAULT_MESSAGE_RANGE;\n const defaultTopK = DEFAULT_TOP_K;\n\n const vectorConfig =\n typeof config?.semanticRecall === `boolean`\n ? {\n topK: defaultTopK,\n messageRange: defaultRange,\n }\n : {\n topK: config?.semanticRecall?.topK ?? defaultTopK,\n messageRange: config?.semanticRecall?.messageRange ?? defaultRange,\n };\n\n const resourceScope =\n (typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope !== `thread`) ||\n config.semanticRecall === true;\n\n // Guard: If resource-scoped semantic recall is enabled but no resourceId is provided, throw an error\n if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {\n throw new Error(\n `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`,\n );\n }\n\n if (config?.semanticRecall && vectorSearchString && this.vector) {\n const { embeddings, dimension } = await this.embedMessageContent(vectorSearchString!);\n const { indexName } = await this.createEmbeddingIndex(dimension, config);\n\n await Promise.all(\n embeddings.map(async embedding => {\n if (typeof this.vector === `undefined`) {\n throw new Error(\n `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`,\n );\n }\n\n vectorResults.push(\n ...(await this.vector.query({\n indexName,\n queryVector: embedding,\n topK: vectorConfig.topK,\n filter: resourceScope\n ? {\n resource_id: resourceId,\n }\n : {\n thread_id: threadId,\n },\n })),\n );\n }),\n );\n }\n\n // Get raw messages from storage\n const paginatedResult = await this.storage.listMessages({\n threadId,\n resourceId,\n perPage,\n page,\n orderBy: effectiveOrderBy,\n filter,\n ...(vectorResults?.length\n ? {\n include: vectorResults.map(r => ({\n id: r.metadata?.message_id,\n threadId: r.metadata?.thread_id,\n withNextMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.after,\n withPreviousMessages:\n typeof vectorConfig.messageRange === 'number'\n ? vectorConfig.messageRange\n : vectorConfig.messageRange.before,\n })),\n }\n : {}),\n });\n // Reverse to restore chronological order if we queried DESC to get newest messages\n const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;\n\n const list = new MessageList({ threadId, resourceId }).add(rawMessages, 'memory');\n\n // Always return mastra-db format (V2)\n const messages = list.get.all.db();\n\n return { messages };\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n return this.storage.getThreadById({ threadId });\n }\n\n async listThreadsByResourceId(\n args: StorageListThreadsByResourceIdInput,\n ): Promise<StorageListThreadsByResourceIdOutput> {\n return this.storage.listThreadsByResourceId(args);\n }\n\n private async handleWorkingMemoryFromMetadata({\n workingMemory,\n resourceId,\n memoryConfig,\n }: {\n workingMemory: string;\n resourceId: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (config.workingMemory?.enabled) {\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // For resource scope, update the resource's working memory\n if (scope === 'resource' && resourceId) {\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n }\n // For thread scope, the metadata is already saved with the thread\n }\n }\n\n async saveThread({\n thread,\n memoryConfig,\n }: {\n thread: StorageThreadType;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const savedThread = await this.storage.saveThread({ thread });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (thread.metadata?.workingMemory && typeof thread.metadata.workingMemory === 'string' && thread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: thread.metadata.workingMemory,\n resourceId: thread.resourceId,\n memoryConfig,\n });\n }\n\n return savedThread;\n }\n\n async updateThread({\n id,\n title,\n metadata,\n memoryConfig,\n }: {\n id: string;\n title: string;\n metadata: Record<string, unknown>;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType> {\n const updatedThread = await this.storage.updateThread({\n id,\n title,\n metadata,\n });\n\n // Check if metadata contains workingMemory and working memory is enabled\n if (metadata?.workingMemory && typeof metadata.workingMemory === 'string' && updatedThread.resourceId) {\n await this.handleWorkingMemoryFromMetadata({\n workingMemory: metadata.workingMemory as string,\n resourceId: updatedThread.resourceId,\n memoryConfig,\n });\n }\n\n return updatedThread;\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.storage.deleteThread({ threadId });\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfig;\n }): Promise<void> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n }\n\n private updateWorkingMemoryMutexes = new Map<string, Mutex>();\n /**\n * @warning experimental! can be removed or changed at any time\n */\n async __experimental_updateWorkingMemoryVNext({\n threadId,\n resourceId,\n workingMemory,\n searchString,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n searchString?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<{ success: boolean; reason: string }> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n\n if (!config.workingMemory?.enabled) {\n throw new Error('Working memory is not enabled for this memory instance');\n }\n\n this.checkStorageFeatureSupport(config);\n\n // If the agent calls the update working memory tool multiple times simultaneously\n // each call could overwrite the other call\n // so get an in memory mutex to make sure this.getWorkingMemory() returns up to date data each time\n const mutexKey =\n memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`;\n const mutex = this.updateWorkingMemoryMutexes.has(mutexKey)\n ? this.updateWorkingMemoryMutexes.get(mutexKey)!\n : new Mutex();\n this.updateWorkingMemoryMutexes.set(mutexKey, mutex);\n const release = await mutex.acquire();\n\n try {\n const existingWorkingMemory = (await this.getWorkingMemory({ threadId, resourceId, memoryConfig })) || '';\n const template = await this.getWorkingMemoryTemplate({ memoryConfig });\n\n let reason = '';\n if (existingWorkingMemory) {\n if (searchString && existingWorkingMemory?.includes(searchString)) {\n workingMemory = existingWorkingMemory.replace(searchString, workingMemory);\n reason = `found and replaced searchString with newMemory`;\n } else if (\n existingWorkingMemory.includes(workingMemory) ||\n template?.content?.trim() === workingMemory.trim()\n ) {\n return {\n success: false,\n reason: `attempted to insert duplicate data into working memory. this entry was skipped`,\n };\n } else {\n if (searchString) {\n reason = `attempted to replace working memory string that doesn't exist. Appending to working memory instead.`;\n } else {\n reason = `appended newMemory to end of working memory`;\n }\n\n workingMemory =\n existingWorkingMemory +\n `\n${workingMemory}`;\n }\n } else if (workingMemory === template?.content) {\n return {\n success: false,\n reason: `try again when you have data to add. newMemory was equal to the working memory template`,\n };\n } else {\n reason = `started new working memory`;\n }\n\n // remove empty template insertions which models sometimes duplicate\n workingMemory = template?.content ? workingMemory.replaceAll(template?.content, '') : workingMemory;\n\n const scope = config.workingMemory.scope || 'resource';\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Update working memory in resource table\n await this.storage.updateResource({\n resourceId,\n workingMemory,\n });\n\n if (reason) {\n return { success: true, reason };\n }\n } else {\n // Update working memory in thread metadata (existing behavior)\n const thread = await this.storage.getThreadById({ threadId });\n if (!thread) {\n throw new Error(`Thread ${threadId} not found`);\n }\n\n await this.storage.updateThread({\n id: threadId,\n title: thread.title || 'Untitled Thread',\n metadata: {\n ...thread.metadata,\n workingMemory,\n },\n });\n }\n\n return { success: true, reason };\n } catch (e) {\n this.logger.error(e instanceof Error ? e.stack || e.message : JSON.stringify(e));\n return { success: false, reason: 'Tool error.' };\n } finally {\n release();\n }\n }\n\n protected chunkText(text: string, tokenSize = 4096) {\n // Convert token size to character size with some buffer\n const charSize = tokenSize * CHARS_PER_TOKEN;\n const chunks: string[] = [];\n let currentChunk = '';\n\n // Split text into words to avoid breaking words\n const words = text.split(/\\s+/);\n\n for (const word of words) {\n // Add space before word unless it's the first word in the chunk\n const wordWithSpace = currentChunk ? ' ' + word : word;\n\n // If adding this word would exceed the chunk size, start a new chunk\n if (currentChunk.length + wordWithSpace.length > charSize) {\n chunks.push(currentChunk);\n currentChunk = word;\n } else {\n currentChunk += wordWithSpace;\n }\n }\n\n // Add the final chunk if not empty\n if (currentChunk) {\n chunks.push(currentChunk);\n }\n\n return chunks;\n }\n\n private hasher = xxhash();\n\n // embedding is computationally expensive so cache content -> embeddings/chunks\n private embeddingCache = new Map<\n number,\n {\n chunks: string[];\n embeddings: Awaited<ReturnType<typeof embedMany>>['embeddings'];\n dimension: number | undefined;\n }\n >();\n private firstEmbed: Promise<any> | undefined;\n protected async embedMessageContent(content: string) {\n // use fast xxhash for lower memory usage. if we cache by content string we will store all messages in memory for the life of the process\n const key = (await this.hasher).h32(content);\n const cached = this.embeddingCache.get(key);\n if (cached) return cached;\n const chunks = this.chunkText(content);\n\n if (typeof this.embedder === `undefined`) {\n throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);\n }\n // for fastembed multiple initial calls to embed will fail if the model hasn't been downloaded yet.\n const isFastEmbed = this.embedder.provider === `fastembed`;\n if (isFastEmbed && this.firstEmbed instanceof Promise) {\n // so wait for the first one\n await this.firstEmbed;\n }\n\n const promise = (this.embedder.specificationVersion === `v2` ? embedManyV5 : embedMany)({\n values: chunks,\n maxRetries: 3,\n // @ts-ignore\n model: this.embedder,\n });\n\n if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;\n const { embeddings } = await promise;\n\n const result = {\n embeddings,\n chunks,\n dimension: embeddings[0]?.length,\n };\n this.embeddingCache.set(key, result);\n return result;\n }\n\n async saveMessages({\n messages,\n memoryConfig,\n }: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig | undefined;\n }): Promise<{ messages: MastraDBMessage[] }> {\n // Then strip working memory tags from all messages\n const updatedMessages = messages\n .map(m => {\n return this.updateMessageToHideWorkingMemoryV2(m);\n })\n .filter((m): m is MastraDBMessage => Boolean(m));\n\n const config = this.getMergedThreadConfig(memoryConfig);\n\n // Convert messages to MastraDBMessage format if needed\n const dbMessages = new MessageList({\n generateMessageId: () => this.generateId(),\n })\n .add(updatedMessages, 'memory')\n .get.all.db();\n\n const result = await this.storage.saveMessages({\n messages: dbMessages,\n });\n\n if (this.vector && config.semanticRecall) {\n // Collect all embeddings first (embedding is CPU-bound, doesn't use pool connections)\n const embeddingData: Array<{\n embeddings: number[][];\n metadata: Array<{ message_id: string; thread_id: string | undefined; resource_id: string | undefined }>;\n }> = [];\n let dimension: number | undefined;\n\n // Process embeddings concurrently - this doesn't use DB connections\n await Promise.all(\n updatedMessages.map(async message => {\n let textForEmbedding: string | null = null;\n\n if (\n message.content.content &&\n typeof message.content.content === 'string' &&\n message.content.content.trim() !== ''\n ) {\n textForEmbedding = message.content.content;\n } else if (message.content.parts && message.content.parts.length > 0) {\n // Extract text from all text parts, concatenate\n const joined = message.content.parts\n .filter(part => part.type === 'text')\n .map(part => (part as TextPart).text)\n .join(' ')\n .trim();\n if (joined) textForEmbedding = joined;\n }\n\n if (!textForEmbedding) return;\n\n const result = await this.embedMessageContent(textForEmbedding);\n dimension = result.dimension;\n\n embeddingData.push({\n embeddings: result.embeddings,\n metadata: result.chunks.map(() => ({\n message_id: message.id,\n thread_id: message.threadId,\n resource_id: message.resourceId,\n })),\n });\n }),\n );\n\n // Batch all vectors into a single upsert call to avoid pool exhaustion\n if (embeddingData.length > 0 && dimension !== undefined) {\n if (typeof this.vector === `undefined`) {\n throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);\n }\n\n const { indexName } = await this.createEmbeddingIndex(dimension, config);\n\n // Flatten all embeddings and metadata into single arrays\n const allVectors: number[][] = [];\n const allMetadata: Array<{\n message_id: string;\n thread_id: string | undefined;\n resource_id: string | undefined;\n }> = [];\n\n for (const data of embeddingData) {\n allVectors.push(...data.embeddings);\n allMetadata.push(...data.metadata);\n }\n\n await this.vector.upsert({\n indexName,\n vectors: allVectors,\n metadata: allMetadata,\n });\n }\n }\n\n return result;\n }\n protected updateMessageToHideWorkingMemory(message: MastraMessageV1): MastraMessageV1 | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n if (typeof message?.content === `string`) {\n return {\n ...message,\n content: message.content.replace(workingMemoryRegex, ``).trim(),\n };\n } else if (Array.isArray(message?.content)) {\n // Filter out updateWorkingMemory tool-call/result content items\n const filteredContent = message.content.filter(\n content =>\n (content.type !== 'tool-call' && content.type !== 'tool-result') ||\n content.toolName !== 'updateWorkingMemory',\n );\n const newContent = filteredContent.map(content => {\n if (content.type === 'text') {\n return {\n ...content,\n text: content.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return { ...content };\n }) as MastraMessageV1['content'];\n if (!newContent.length) return null;\n return { ...message, content: newContent };\n } else {\n return { ...message };\n }\n }\n protected updateMessageToHideWorkingMemoryV2(message: MastraDBMessage): MastraDBMessage | null {\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n\n const newMessage = { ...message, content: { ...message.content } }; // Deep copy message and content\n\n if (newMessage.content.content && typeof newMessage.content.content === 'string') {\n newMessage.content.content = newMessage.content.content.replace(workingMemoryRegex, '').trim();\n }\n\n if (newMessage.content.parts) {\n newMessage.content.parts = newMessage.content.parts\n .filter(part => {\n if (part.type === 'tool-invocation') {\n return part.toolInvocation.toolName !== 'updateWorkingMemory';\n }\n return true;\n })\n .map(part => {\n if (part.type === 'text') {\n return {\n ...part,\n text: part.text.replace(workingMemoryRegex, '').trim(),\n };\n }\n return part;\n });\n\n // If all parts were filtered out (e.g., only contained updateWorkingMemory tool calls) we need to skip the whole message, it was only working memory tool calls/results\n if (newMessage.content.parts.length === 0) {\n return null;\n }\n }\n\n return newMessage;\n }\n\n protected parseWorkingMemory(text: string): string | null {\n if (!this.threadConfig.workingMemory?.enabled) return null;\n\n const workingMemoryRegex = /<working_memory>([^]*?)<\\/working_memory>/g;\n const matches = text.match(workingMemoryRegex);\n const match = matches?.[0];\n\n if (match) {\n return match.replace(/<\\/?working_memory>/g, '').trim();\n }\n\n return null;\n }\n\n public async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig || {});\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n this.checkStorageFeatureSupport(config);\n\n const scope = config.workingMemory.scope || 'resource';\n let workingMemoryData: string | null = null;\n\n // Guard: If resource-scoped working memory is enabled but no resourceId is provided, throw an error\n if (scope === 'resource' && !resourceId) {\n throw new Error(\n `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. ` +\n `Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`,\n );\n }\n\n if (scope === 'resource' && resourceId) {\n // Get working memory from resource table\n const resource = await this.storage.getResourceById({ resourceId });\n workingMemoryData = resource?.workingMemory || null;\n } else {\n // Get working memory from thread metadata (default behavior)\n const thread = await this.storage.getThreadById({ threadId });\n workingMemoryData = thread?.metadata?.workingMemory as string;\n }\n\n if (!workingMemoryData) {\n return null;\n }\n\n return workingMemoryData;\n }\n\n /**\n * Gets the working memory template for the current memory configuration.\n * Supports both ZodObject and JSONSchema7 schemas.\n *\n * @param memoryConfig - The memory configuration containing the working memory settings\n * @returns The working memory template with format and content, or null if working memory is disabled\n */\n public async getWorkingMemoryTemplate({\n memoryConfig,\n }: {\n memoryConfig?: MemoryConfig;\n }): Promise<WorkingMemoryTemplate | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n // Get thread from storage\n if (config.workingMemory?.schema) {\n try {\n const schema = config.workingMemory.schema;\n let convertedSchema: JSONSchema7;\n\n if (isZodObject(schema as ZodTypeAny)) {\n convertedSchema = zodToJsonSchema(schema as ZodTypeAny);\n } else {\n convertedSchema = schema as JSONSchema7;\n }\n\n return { format: 'json', content: JSON.stringify(convertedSchema) };\n } catch (error) {\n this.logger.error('Error converting schema', error);\n throw error;\n }\n }\n\n // Return working memory from metadata\n const memory = config.workingMemory.template || this.defaultWorkingMemoryTemplate;\n return { format: 'markdown', content: memory.trim() };\n }\n\n public async getSystemMessage({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n const config = this.getMergedThreadConfig(memoryConfig);\n if (!config.workingMemory?.enabled) {\n return null;\n }\n\n const workingMemoryTemplate = await this.getWorkingMemoryTemplate({ memoryConfig });\n const workingMemoryData = await this.getWorkingMemory({ threadId, resourceId, memoryConfig: config });\n\n if (!workingMemoryTemplate) {\n return null;\n }\n\n return this.isVNextWorkingMemoryConfig(memoryConfig)\n ? this.__experimental_getWorkingMemoryToolInstructionVNext({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n })\n : this.getWorkingMemoryToolInstruction({\n template: workingMemoryTemplate,\n data: workingMemoryData,\n });\n }\n\n public defaultWorkingMemoryTemplate = `\n# User Information\n- **First Name**: \n- **Last Name**: \n- **Location**: \n- **Occupation**: \n- **Interests**: \n- **Goals**: \n- **Events**: \n- **Facts**: \n- **Projects**: \n`;\n\n protected getWorkingMemoryToolInstruction({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n const emptyWorkingMemoryTemplateObject =\n template.format === 'json' ? generateEmptyFromSchema(template.content) : null;\n const hasEmptyWorkingMemoryTemplateObject =\n emptyWorkingMemoryTemplateObject && Object.keys(emptyWorkingMemoryTemplateObject).length > 0;\n\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool. If information might be referenced again - store it!\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n${\n template.format !== 'json'\n ? `5. IMPORTANT: When calling updateWorkingMemory, the only valid parameter is the memory field. DO NOT pass an object.\n6. IMPORTANT: ALWAYS pass the data you want to store in the memory field as a string. DO NOT pass an object.\n7. IMPORTANT: Data must only be sent as a string no matter which format is used.`\n : ''\n}\n\n\n${\n template.format !== 'json'\n ? `<working_memory_template>\n${template.content}\n</working_memory_template>`\n : ''\n}\n\n${hasEmptyWorkingMemoryTemplateObject ? 'When working with json data, the object format below represents the template:' : ''}\n${hasEmptyWorkingMemoryTemplateObject ? JSON.stringify(emptyWorkingMemoryTemplateObject) : ''}\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- Do not remove empty sections - you must include the empty sections along with the ones you're filling in\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the entire ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it.\n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.`;\n }\n\n protected __experimental_getWorkingMemoryToolInstructionVNext({\n template,\n data,\n }: {\n template: WorkingMemoryTemplate;\n data: string | null;\n }) {\n return `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore and update any conversation-relevant information by calling the updateWorkingMemory tool.\n\nGuidelines:\n1. Store anything that could be useful later in the conversation\n2. Update proactively when information changes, no matter how small\n3. Use ${template.format === 'json' ? 'JSON' : 'Markdown'} format for all data\n4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for \"information about yourself\"\n5. If your memory has not changed, you do not need to call the updateWorkingMemory tool. By default it will persist and be available for you in future interactions\n6. Information not being relevant to the current conversation is not a valid reason to replace or remove working memory information. Your working memory spans across multiple conversations and may be needed again later, even if it's not currently relevant.\n\n<working_memory_template>\n${template.content}\n</working_memory_template>\n\n<working_memory_data>\n${data}\n</working_memory_data>\n\nNotes:\n- Update memory whenever referenced information changes\n${\n template.content !== this.defaultWorkingMemoryTemplate\n ? `- Only store information if it's in the working memory template, do not store other information unless the user asks you to remember it, as that non-template information may be irrelevant`\n : `- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)\n`\n}\n- This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history\n- REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the ${template.format === 'json' ? 'JSON' : 'Markdown'} content. The system will store it for you. The user will not see it. \n- IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information if that information is not already stored.\n- IMPORTANT: Preserve the ${template.format === 'json' ? 'JSON' : 'Markdown'} formatting structure above while updating the content.\n`;\n }\n\n private isVNextWorkingMemoryConfig(config?: MemoryConfig): boolean {\n if (!config?.workingMemory) return false;\n\n const isMDWorkingMemory =\n !(`schema` in config.workingMemory) &&\n (typeof config.workingMemory.template === `string` || config.workingMemory.template) &&\n config.workingMemory;\n\n return Boolean(isMDWorkingMemory && isMDWorkingMemory.version === `vnext`);\n }\n\n public listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any>> {\n const mergedConfig = this.getMergedThreadConfig(config);\n if (mergedConfig.workingMemory?.enabled) {\n return {\n updateWorkingMemory: this.isVNextWorkingMemoryConfig(mergedConfig)\n ? // use the new experimental tool\n __experimental_updateWorkingMemoryToolVNext(mergedConfig)\n : updateWorkingMemoryTool(mergedConfig),\n };\n }\n return {};\n }\n\n /**\n * Updates the metadata of a list of messages\n * @param messages - The list of messages to update\n * @returns The list of updated messages\n */\n public async updateMessages({\n messages,\n }: {\n messages: Partial<MastraDBMessage> & { id: string }[];\n }): Promise<MastraDBMessage[]> {\n if (messages.length === 0) return [];\n\n // TODO: Possibly handle updating the vector db here when a message is updated.\n\n return this.storage.updateMessages({ messages });\n }\n\n /**\n * Deletes one or more messages\n * @param input - Must be an array containing either:\n * - Message ID strings\n * - Message objects with 'id' properties\n * @returns Promise that resolves when all messages are deleted\n */\n public async deleteMessages(input: MessageDeleteInput): Promise<void> {\n // Normalize input to array of IDs\n let messageIds: string[];\n\n if (!Array.isArray(input)) {\n throw new Error('Invalid input: must be an array of message IDs or message objects');\n }\n\n if (input.length === 0) {\n return; // No-op for empty array\n }\n\n messageIds = input.map(item => {\n if (typeof item === 'string') {\n return item;\n } else if (item && typeof item === 'object' && 'id' in item) {\n return item.id;\n } else {\n throw new Error('Invalid input: array items must be strings or objects with an id property');\n }\n });\n\n // Validate all IDs are non-empty strings\n const invalidIds = messageIds.filter(id => !id || typeof id !== 'string');\n if (invalidIds.length > 0) {\n throw new Error('All message IDs must be non-empty strings');\n }\n\n // Delete from storage\n await this.storage.deleteMessages(messageIds);\n\n // TODO: Delete from vector store if semantic recall is enabled\n // This would require getting the messages first to know their threadId/resourceId\n // and then querying the vector store to delete associated embeddings\n }\n}\n\n// Re-export memory processors from @mastra/core for backward compatibility\nexport { SemanticRecall, WorkingMemory, MessageHistory } from '@mastra/core/processors';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/memory",
3
- "version": "1.0.0-beta.3",
3
+ "version": "1.0.0-beta.4",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -49,9 +49,9 @@
49
49
  "typescript": "^5.8.3",
50
50
  "typescript-eslint": "^8.38.0",
51
51
  "vitest": "4.0.12",
52
- "@internal/lint": "0.0.53",
53
52
  "@internal/types-builder": "0.0.28",
54
- "@mastra/core": "1.0.0-beta.6"
53
+ "@internal/lint": "0.0.53",
54
+ "@mastra/core": "1.0.0-beta.8"
55
55
  },
56
56
  "peerDependencies": {
57
57
  "@mastra/core": ">=1.0.0-0 <2.0.0-0",