@mastra/memory 0.15.11 → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +307 -26
- package/dist/index.cjs +90 -160
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +16 -43
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +90 -160
- package/dist/index.js.map +1 -1
- package/dist/tools/working-memory.d.ts +2 -14
- package/dist/tools/working-memory.d.ts.map +1 -1
- package/package.json +13 -22
package/dist/index.cjs.map
CHANGED
|
@@ -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":";;;;;;;;;;;;;;;;;;;AAOO,IAAM,uBAAA,GAA0B,CAAC,YAAA,KAAgC;AACtE,EAAA,MAAM,MAAA,GAAS,cAAc,aAAA,EAAe,MAAA;AAE5C,EAAA,IAAI,WAAA,GAAuBA,MAAE,MAAA,CAAO;AAAA,IAClC,MAAA,EAAQA,KAAA,CACL,MAAA,EAAO,CACP,SAAS,CAAA,oGAAA,CAAsG;AAAA,GACnH,CAAA;AAED,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,WAAA,GAAcA,MAAE,MAAA,CAAO;AAAA,MACrB,MAAA,EACE,kBAAkBC,aAAA,GACd,MAAA,GACCC,gCAAmB,EAAE,UAAA,EAAY,MAAA,EAAkB,CAAA,CAAE,QAAA;AAAA,QACpD,CAAA,mDAAA;AAAA;AACF,KACP,CAAA;AAAA,EACH;AAEA,EAAA,OAAOC,gBAAA,CAAW;AAAA,IAChB,EAAA,EAAI,uBAAA;AAAA,IACJ,WAAA,EAAa,CAAA,0FAAA,EAA6F,MAAA,GAAS,wEAAA,GAA2E,EAAE,CAAA,CAAA;AAAA,IAChM,WAAA;AAA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ory';\nimport { createTool } from '@mastra/core/tools';\nimport { convertSchemaToZod } from '@mastra/schema-compat';\nimport type { Schema } from 'ai';\nimport { z, ZodObject } from 'zod';\nimport type { ZodType } from 'zod';\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 return createTool({\n id: 'update-working-memory',\n description: `Update the working memory with new information. Any data not included will be overwritten.${schema ? ' Always pass data as string to the memory field. Never pass an object.' : ''}`,\n inputSchema,\n execute: async params => {\n const { context, threadId, memory, resourceId } = params;\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 const workingMemory = typeof context.memory === 'string' ? context.memory : JSON.stringify(context.memory);\n\n // Use the new 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 params => {\n const { context, threadId, memory, resourceId } = params;\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 = context.newMemory || '';\n if (!context.updateReason) context.updateReason = `append-new-memory`;\n\n if (\n context.searchString &&\n config.workingMemory?.scope === `resource` &&\n context.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 context.searchString = undefined;\n }\n\n if (context.updateReason === `append-new-memory` && context.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 context.searchString = undefined;\n }\n\n if (context.updateReason !== `append-new-memory` && !context.searchString) {\n return {\n success: false,\n reason: `updateReason was ${context.updateReason} but no searchString was provided. Unable to replace undefined with \"${context.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: context.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 { MastraMessageV2, UIMessageWithMetadata } from '@mastra/core/agent';\nimport { MastraMemory } from '@mastra/core/memory';\nimport type {\n MastraMessageV1,\n MemoryConfig,\n SharedMemoryConfig,\n StorageThreadType,\n WorkingMemoryTemplate,\n} from '@mastra/core/memory';\nimport type { StorageGetMessagesArg, ThreadSortOptions, PaginationInfo } 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 { CoreMessage, 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 { updateWorkingMemoryTool, __experimental_updateWorkingMemoryToolVNext } from './tools/working-memory';\n\n// Type for flexible message deletion input\nexport type MessageDeleteInput = string[] | { id: string }[];\n\n// Average characters per token based on OpenAI's tokenization\nconst CHARS_PER_TOKEN = 4;\n\nconst DEFAULT_MESSAGE_RANGE = { before: 2, after: 2 } as const;\nconst DEFAULT_TOP_K = 2;\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 = typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope === 'resource';\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 if (\n typeof config.semanticRecall === `object` &&\n config.semanticRecall.scope === `resource` &&\n !this.storage.supports.selectByIncludeResourceScope\n ) {\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 query({\n threadId,\n resourceId,\n selectBy,\n threadConfig,\n }: StorageGetMessagesArg & {\n threadConfig?: MemoryConfig;\n }): Promise<{ messages: CoreMessage[]; uiMessages: UIMessageWithMetadata[]; messagesV2: MastraMessageV2[] }> {\n const config = this.getMergedThreadConfig(threadConfig || {});\n if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);\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 query() with:`, {\n threadId,\n selectBy,\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 = typeof config?.semanticRecall === 'object' && config?.semanticRecall?.scope === `resource`;\n\n if (config?.semanticRecall && selectBy?.vectorSearchString && this.vector) {\n const { embeddings, dimension } = await this.embedMessageContent(selectBy.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 // Use paginated method when pagination is requested\n let rawMessages;\n if (selectBy?.pagination) {\n const paginatedResult = await this.storage.getMessagesPaginated({\n threadId,\n resourceId,\n format: 'v2',\n selectBy: {\n ...selectBy,\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 threadConfig: config,\n });\n rawMessages = paginatedResult.messages;\n } else {\n // Fall back to regular getMessages for backward compatibility\n rawMessages = await this.storage.getMessages({\n threadId,\n resourceId,\n format: 'v2',\n selectBy: {\n ...selectBy,\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 threadConfig: config,\n });\n }\n\n const list = new MessageList({ threadId, resourceId }).add(rawMessages, 'memory');\n return {\n get messages() {\n // returning v1 messages for backwards compat! v1 messages were CoreMessages stored in the db.\n // returning .v1() takes stored messages which may be in v2 or v1 format and converts them to v1 shape, which is a CoreMessage + id + threadId + resourceId, etc\n // Perhaps this should be called coreRecord or something ? - for now keeping v1 since it reflects that this used to be our db storage record shape\n const v1Messages = list.get.all.v1();\n // the conversion from V2/UIMessage -> V1/CoreMessage can sometimes split the messages up into more messages than before\n // so slice off the earlier messages if it'll exceed the lastMessages setting\n if (selectBy?.last && v1Messages.length > selectBy.last) {\n // ex: 23 (v1 messages) minus 20 (selectBy.last messages)\n // means we will start from index 3 and keep all the later newer messages from index 3 til the end of the array\n return v1Messages.slice(v1Messages.length - selectBy.last) as CoreMessage[];\n }\n // TODO: this is absolutely wrong but became apparent that this is what we were doing before adding MessageList. Our public types said CoreMessage but we were returning MessageType which is equivalent to MastraMessageV1\n // In a breaking change we should make this the type it actually is.\n return v1Messages as CoreMessage[];\n },\n get uiMessages() {\n return list.get.all.ui();\n },\n get messagesV2() {\n return list.get.all.v2();\n },\n };\n }\n\n async rememberMessages({\n threadId,\n resourceId,\n vectorMessageSearch,\n config,\n }: {\n threadId: string;\n resourceId?: string;\n vectorMessageSearch?: string;\n config?: MemoryConfig;\n }): Promise<{ messages: MastraMessageV1[]; messagesV2: MastraMessageV2[] }> {\n const threadConfig = this.getMergedThreadConfig(config || {});\n if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, threadConfig);\n\n if (!threadConfig.lastMessages && !threadConfig.semanticRecall) {\n return {\n messages: [],\n messagesV2: [],\n };\n }\n\n const messagesResult = await this.query({\n resourceId,\n threadId,\n selectBy: {\n last: threadConfig.lastMessages,\n vectorSearchString: threadConfig.semanticRecall && vectorMessageSearch ? vectorMessageSearch : undefined,\n },\n threadConfig: config,\n format: 'v2',\n });\n // Using MessageList here just to convert mixed input messages to single type output messages\n const list = new MessageList({ threadId, resourceId }).add(messagesResult.messagesV2, 'memory');\n\n this.logger.debug(`Remembered message history includes ${messagesResult.messages.length} messages.`);\n return { messages: list.get.all.v1(), messagesV2: list.get.all.v2() };\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n return this.storage.getThreadById({ threadId });\n }\n\n async getThreadsByResourceId({\n resourceId,\n orderBy,\n sortDirection,\n }: { resourceId: string } & ThreadSortOptions): Promise<StorageThreadType[]> {\n return this.storage.getThreadsByResourceId({ resourceId, orderBy, sortDirection });\n }\n\n async getThreadsByResourceIdPaginated({\n resourceId,\n page,\n perPage,\n orderBy,\n sortDirection,\n }: {\n resourceId: string;\n page: number;\n perPage: number;\n } & ThreadSortOptions): Promise<\n PaginationInfo & {\n threads: StorageThreadType[];\n }\n > {\n return this.storage.getThreadsByResourceIdPaginated({\n resourceId,\n page,\n perPage,\n orderBy,\n sortDirection,\n });\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 || 'thread';\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 || 'thread';\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 = existingWorkingMemory + `\\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 || 'thread';\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(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format?: 'v1';\n }): Promise<MastraMessageV1[]>;\n async saveMessages(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format: 'v2';\n }): Promise<MastraMessageV2[]>;\n async saveMessages({\n messages,\n memoryConfig,\n format = `v1`,\n }: {\n messages: (MastraMessageV1 | MastraMessageV2)[];\n memoryConfig?: MemoryConfig | undefined;\n format?: 'v1' | 'v2';\n }): Promise<MastraMessageV2[] | MastraMessageV1[]> {\n // Then strip working memory tags from all messages\n const updatedMessages = messages\n .map(m => {\n if (MessageList.isMastraMessageV1(m)) {\n return this.updateMessageToHideWorkingMemory(m);\n }\n // add this to prevent \"error saving undefined in the db\" if a project is on an earlier storage version but new memory/storage\n if (!m.type) m.type = `v2`;\n return this.updateMessageToHideWorkingMemoryV2(m);\n })\n .filter((m): m is MastraMessageV1 | MastraMessageV2 => Boolean(m));\n\n const config = this.getMergedThreadConfig(memoryConfig);\n\n const result = this.storage.saveMessages({\n messages: new MessageList().add(updatedMessages, 'memory').get.all.v2(),\n format: 'v2',\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 (MessageList.isMastraMessageV2(message)) {\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 } else if (MessageList.isMastraMessageV1(message)) {\n if (message.content && typeof message.content === 'string' && message.content.trim() !== '') {\n textForEmbedding = message.content;\n } else if (message.content && Array.isArray(message.content) && message.content.length > 0) {\n // Extract text from all text parts, concatenate\n const joined = message.content\n .filter(part => part.type === 'text')\n .map(part => part.text)\n .join(' ')\n .trim();\n if (joined) textForEmbedding = joined;\n }\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 if (format === `v1`) return new MessageList().add(await result, 'memory').get.all.v1(); // for backwards compat convert to v1 message format\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: MastraMessageV2): MastraMessageV2 | 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 || 'thread';\n let workingMemoryData: string | null = null;\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 // Convert ZodObject to JSON Schema\n convertedSchema = zodToJsonSchema(schema as ZodTypeAny) as JSONSchema7;\n } else {\n // Already a JSON Schema\n convertedSchema = schema as any 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: config });\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 getTools(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<MastraMessageV2> & { id: string }[];\n }): Promise<MastraMessageV2[]> {\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"]}
|
|
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":";;;;;;;;;;;;;;;;;;;AAOO,IAAM,uBAAA,GAA0B,CAAC,YAAA,KAAgC;AACtE,EAAA,MAAM,MAAA,GAAS,cAAc,aAAA,EAAe,MAAA;AAE5C,EAAA,IAAI,WAAA,GAAuBA,MAAE,MAAA,CAAO;AAAA,IAClC,MAAA,EAAQA,KAAA,CACL,MAAA,EAAO,CACP,SAAS,CAAA,oGAAA,CAAsG;AAAA,GACnH,CAAA;AAED,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,WAAA,GAAcA,MAAE,MAAA,CAAO;AAAA,MACrB,MAAA,EACE,kBAAkBC,aAAA,GACd,MAAA,GACCC,gCAAmB,EAAE,UAAA,EAAY,MAAA,EAAkB,CAAA,CAAE,QAAA;AAAA,QACpD,CAAA,mDAAA;AAAA;AACF,KACP,CAAA;AAAA,EACH;AAEA,EAAA,OAAOC,gBAAA,CAAW;AAAA,IAChB,EAAA,EAAI,uBAAA;AAAA,IACJ,WAAA,EAAa,CAAA,0FAAA,EAA6F,MAAA,GAAS,wEAAA,GAA2E,EAAE,CAAA,CAAA;AAAA,IAChM,WAAA;AAAA,IACA,OAAA,EAAS,OAAO,SAAA,EAAW,OAAA,KAAY;AACrC,MAAA,MAAM,QAAA,GAAW,SAAS,KAAA,EAAO,QAAA;AACjC,MAAA,MAAM,UAAA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AAA,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\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 return createTool({\n id: 'update-working-memory',\n description: `Update the working memory with new information. Any data not included will be overwritten.${schema ? ' Always pass data as string to the memory field. Never pass an object.' : ''}`,\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 const workingMemory = typeof inputData.memory === 'string' ? inputData.memory : JSON.stringify(inputData.memory);\n\n // Use the new 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 { updateWorkingMemoryTool, __experimental_updateWorkingMemoryToolVNext } from './tools/working-memory';\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 },\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 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,\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,\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 const rawMessages = 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 // Convert ZodObject to JSON Schema\n convertedSchema = zodToJsonSchema(schema as ZodTypeAny) as JSONSchema7;\n } else {\n // Already a JSON Schema\n convertedSchema = schema as any 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: config });\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"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { MastraDBMessage } from '@mastra/core/agent';
|
|
2
2
|
import { MastraMemory } from '@mastra/core/memory';
|
|
3
|
-
import type { MastraMessageV1, MemoryConfig, SharedMemoryConfig, StorageThreadType, WorkingMemoryTemplate } from '@mastra/core/memory';
|
|
4
|
-
import type {
|
|
3
|
+
import type { MastraMessageV1, MemoryConfig, SharedMemoryConfig, StorageThreadType, WorkingMemoryTemplate, MessageDeleteInput } from '@mastra/core/memory';
|
|
4
|
+
import type { StorageListThreadsByResourceIdOutput, StorageListThreadsByResourceIdInput, StorageListMessagesInput } from '@mastra/core/storage';
|
|
5
5
|
import type { ToolAction } from '@mastra/core/tools';
|
|
6
6
|
import { embedMany } from 'ai';
|
|
7
|
-
import type { CoreMessage } from 'ai';
|
|
8
|
-
export type MessageDeleteInput = string[] | {
|
|
9
|
-
id: string;
|
|
10
|
-
}[];
|
|
11
7
|
/**
|
|
12
8
|
* Concrete implementation of MastraMemory that adds support for thread configuration
|
|
13
9
|
* and message injection.
|
|
@@ -16,35 +12,16 @@ export declare class Memory extends MastraMemory {
|
|
|
16
12
|
constructor(config?: SharedMemoryConfig);
|
|
17
13
|
protected validateThreadIsOwnedByResource(threadId: string, resourceId: string, config: MemoryConfig): Promise<void>;
|
|
18
14
|
protected checkStorageFeatureSupport(config: MemoryConfig): void;
|
|
19
|
-
|
|
15
|
+
recall(args: StorageListMessagesInput & {
|
|
20
16
|
threadConfig?: MemoryConfig;
|
|
17
|
+
vectorSearchString?: string;
|
|
21
18
|
}): Promise<{
|
|
22
|
-
messages:
|
|
23
|
-
uiMessages: UIMessageWithMetadata[];
|
|
24
|
-
messagesV2: MastraMessageV2[];
|
|
25
|
-
}>;
|
|
26
|
-
rememberMessages({ threadId, resourceId, vectorMessageSearch, config, }: {
|
|
27
|
-
threadId: string;
|
|
28
|
-
resourceId?: string;
|
|
29
|
-
vectorMessageSearch?: string;
|
|
30
|
-
config?: MemoryConfig;
|
|
31
|
-
}): Promise<{
|
|
32
|
-
messages: MastraMessageV1[];
|
|
33
|
-
messagesV2: MastraMessageV2[];
|
|
19
|
+
messages: MastraDBMessage[];
|
|
34
20
|
}>;
|
|
35
21
|
getThreadById({ threadId }: {
|
|
36
22
|
threadId: string;
|
|
37
23
|
}): Promise<StorageThreadType | null>;
|
|
38
|
-
|
|
39
|
-
resourceId: string;
|
|
40
|
-
} & ThreadSortOptions): Promise<StorageThreadType[]>;
|
|
41
|
-
getThreadsByResourceIdPaginated({ resourceId, page, perPage, orderBy, sortDirection, }: {
|
|
42
|
-
resourceId: string;
|
|
43
|
-
page: number;
|
|
44
|
-
perPage: number;
|
|
45
|
-
} & ThreadSortOptions): Promise<PaginationInfo & {
|
|
46
|
-
threads: StorageThreadType[];
|
|
47
|
-
}>;
|
|
24
|
+
listThreadsByResourceId(args: StorageListThreadsByResourceIdInput): Promise<StorageListThreadsByResourceIdOutput>;
|
|
48
25
|
private handleWorkingMemoryFromMetadata;
|
|
49
26
|
saveThread({ thread, memoryConfig, }: {
|
|
50
27
|
thread: StorageThreadType;
|
|
@@ -86,18 +63,14 @@ export declare class Memory extends MastraMemory {
|
|
|
86
63
|
embeddings: Awaited<ReturnType<typeof embedMany>>["embeddings"];
|
|
87
64
|
dimension: number | undefined;
|
|
88
65
|
}>;
|
|
89
|
-
saveMessages(
|
|
90
|
-
messages:
|
|
91
|
-
memoryConfig?: MemoryConfig | undefined;
|
|
92
|
-
format?: 'v1';
|
|
93
|
-
}): Promise<MastraMessageV1[]>;
|
|
94
|
-
saveMessages(args: {
|
|
95
|
-
messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];
|
|
66
|
+
saveMessages({ messages, memoryConfig, }: {
|
|
67
|
+
messages: MastraDBMessage[];
|
|
96
68
|
memoryConfig?: MemoryConfig | undefined;
|
|
97
|
-
|
|
98
|
-
|
|
69
|
+
}): Promise<{
|
|
70
|
+
messages: MastraDBMessage[];
|
|
71
|
+
}>;
|
|
99
72
|
protected updateMessageToHideWorkingMemory(message: MastraMessageV1): MastraMessageV1 | null;
|
|
100
|
-
protected updateMessageToHideWorkingMemoryV2(message:
|
|
73
|
+
protected updateMessageToHideWorkingMemoryV2(message: MastraDBMessage): MastraDBMessage | null;
|
|
101
74
|
protected parseWorkingMemory(text: string): string | null;
|
|
102
75
|
getWorkingMemory({ threadId, resourceId, memoryConfig, }: {
|
|
103
76
|
threadId: string;
|
|
@@ -129,17 +102,17 @@ export declare class Memory extends MastraMemory {
|
|
|
129
102
|
data: string | null;
|
|
130
103
|
}): string;
|
|
131
104
|
private isVNextWorkingMemoryConfig;
|
|
132
|
-
|
|
105
|
+
listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any>>;
|
|
133
106
|
/**
|
|
134
107
|
* Updates the metadata of a list of messages
|
|
135
108
|
* @param messages - The list of messages to update
|
|
136
109
|
* @returns The list of updated messages
|
|
137
110
|
*/
|
|
138
111
|
updateMessages({ messages, }: {
|
|
139
|
-
messages: Partial<
|
|
112
|
+
messages: Partial<MastraDBMessage> & {
|
|
140
113
|
id: string;
|
|
141
114
|
}[];
|
|
142
|
-
}): Promise<
|
|
115
|
+
}): Promise<MastraDBMessage[]>;
|
|
143
116
|
/**
|
|
144
117
|
* Deletes one or more messages
|
|
145
118
|
* @param input - Must be an array containing either:
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,
|
|
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,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,eAAe,EACf,YAAY,EACZ,kBAAkB,EAClB,iBAAiB,EACjB,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EACV,oCAAoC,EACpC,mCAAmC,EACnC,wBAAwB,EACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGrD,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAkB/B;;;GAGG;AACH,qBAAa,MAAO,SAAQ,YAAY;gBAC1B,MAAM,GAAE,kBAAuB;cAe3B,+BAA+B,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY;IAqB1G,SAAS,CAAC,0BAA0B,CAAC,MAAM,EAAE,YAAY;IAuBnD,MAAM,CACV,IAAI,EAAE,wBAAwB,GAAG;QAC/B,YAAY,CAAC,EAAE,YAAY,CAAC;QAC5B,kBAAkB,CAAC,EAAE,M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