@mastra/core 0.24.7-alpha.0 → 0.24.7-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/agent/index.cjs +13 -13
  3. package/dist/agent/index.js +2 -2
  4. package/dist/agent/input-processor/index.cjs +6 -6
  5. package/dist/agent/input-processor/index.js +1 -1
  6. package/dist/agent/message-list/index.d.ts.map +1 -1
  7. package/dist/ai-tracing/index.cjs +36 -36
  8. package/dist/ai-tracing/index.js +1 -1
  9. package/dist/{chunk-H6SCQEQZ.js → chunk-2BY7C6Y7.js} +145 -19
  10. package/dist/chunk-2BY7C6Y7.js.map +1 -0
  11. package/dist/{chunk-TMGNLNND.cjs → chunk-2YE6RNCZ.cjs} +4 -4
  12. package/dist/{chunk-TMGNLNND.cjs.map → chunk-2YE6RNCZ.cjs.map} +1 -1
  13. package/dist/{chunk-MQOYPEDP.js → chunk-2YN6HGEH.js} +3 -3
  14. package/dist/{chunk-MQOYPEDP.js.map → chunk-2YN6HGEH.js.map} +1 -1
  15. package/dist/{chunk-PAOBGBU7.cjs → chunk-3IDFSGG3.cjs} +4 -4
  16. package/dist/{chunk-PAOBGBU7.cjs.map → chunk-3IDFSGG3.cjs.map} +1 -1
  17. package/dist/{chunk-42RUESSD.cjs → chunk-4YYPQOP7.cjs} +9 -4
  18. package/dist/{chunk-42RUESSD.cjs.map → chunk-4YYPQOP7.cjs.map} +1 -1
  19. package/dist/{chunk-AQGLVU53.cjs → chunk-5PSD3IKG.cjs} +19 -6
  20. package/dist/chunk-5PSD3IKG.cjs.map +1 -0
  21. package/dist/{chunk-6D2K2CAA.js → chunk-6VB52TJV.js} +3 -3
  22. package/dist/{chunk-6D2K2CAA.js.map → chunk-6VB52TJV.js.map} +1 -1
  23. package/dist/{chunk-JVV5LREI.js → chunk-BKBVQTOH.js} +2 -2
  24. package/dist/chunk-BKBVQTOH.js.map +1 -0
  25. package/dist/{chunk-XFEAV36D.cjs → chunk-CNIM7N4E.cjs} +64 -16
  26. package/dist/chunk-CNIM7N4E.cjs.map +1 -0
  27. package/dist/{chunk-DMBN72QF.cjs → chunk-DISETAP2.cjs} +4 -4
  28. package/dist/{chunk-DMBN72QF.cjs.map → chunk-DISETAP2.cjs.map} +1 -1
  29. package/dist/{chunk-BLUDYAPI.js → chunk-DSUKMFZY.js} +19 -6
  30. package/dist/chunk-DSUKMFZY.js.map +1 -0
  31. package/dist/{chunk-NP7A4CAN.js → chunk-E5NCEJEJ.js} +3 -3
  32. package/dist/{chunk-NP7A4CAN.js.map → chunk-E5NCEJEJ.js.map} +1 -1
  33. package/dist/{chunk-VATR2Z2C.cjs → chunk-FQTJPLCW.cjs} +154 -28
  34. package/dist/chunk-FQTJPLCW.cjs.map +1 -0
  35. package/dist/{chunk-Q6LWNLAJ.js → chunk-GIK7MM2K.js} +8 -3
  36. package/dist/{chunk-Q6LWNLAJ.js.map → chunk-GIK7MM2K.js.map} +1 -1
  37. package/dist/{chunk-GSFQAR6S.cjs → chunk-ICICKWAG.cjs} +6 -6
  38. package/dist/{chunk-GSFQAR6S.cjs.map → chunk-ICICKWAG.cjs.map} +1 -1
  39. package/dist/{chunk-7YGCP2UZ.js → chunk-N6P5GJRO.js} +54 -6
  40. package/dist/chunk-N6P5GJRO.js.map +1 -0
  41. package/dist/{chunk-WIMFJ2BA.js → chunk-PPAIPZ6C.js} +51 -13
  42. package/dist/chunk-PPAIPZ6C.js.map +1 -0
  43. package/dist/{chunk-UWTYVVVZ.js → chunk-RLYWCJQ6.js} +3 -3
  44. package/dist/{chunk-UWTYVVVZ.js.map → chunk-RLYWCJQ6.js.map} +1 -1
  45. package/dist/{chunk-HCCXJ5YJ.js → chunk-RP4YCZP7.js} +3 -3
  46. package/dist/{chunk-HCCXJ5YJ.js.map → chunk-RP4YCZP7.js.map} +1 -1
  47. package/dist/{chunk-CYEQK4PM.cjs → chunk-RQPGIUUA.cjs} +6 -6
  48. package/dist/{chunk-CYEQK4PM.cjs.map → chunk-RQPGIUUA.cjs.map} +1 -1
  49. package/dist/{chunk-46XGIEXM.cjs → chunk-RWPKCFZT.cjs} +4 -4
  50. package/dist/{chunk-46XGIEXM.cjs.map → chunk-RWPKCFZT.cjs.map} +1 -1
  51. package/dist/{chunk-NPNGPMT2.js → chunk-V2IMZSNO.js} +3 -3
  52. package/dist/{chunk-NPNGPMT2.js.map → chunk-V2IMZSNO.js.map} +1 -1
  53. package/dist/{chunk-LGKZOO44.cjs → chunk-X5JTTWMF.cjs} +9 -9
  54. package/dist/{chunk-LGKZOO44.cjs.map → chunk-X5JTTWMF.cjs.map} +1 -1
  55. package/dist/{chunk-BMJ6HNP4.js → chunk-Y2BH2LUD.js} +32 -27
  56. package/dist/chunk-Y2BH2LUD.js.map +1 -0
  57. package/dist/{chunk-IAJHRFO4.cjs → chunk-YPYLWTZI.cjs} +60 -21
  58. package/dist/chunk-YPYLWTZI.cjs.map +1 -0
  59. package/dist/{chunk-HJOAX5IQ.cjs → chunk-YYKN3NDZ.cjs} +72 -64
  60. package/dist/chunk-YYKN3NDZ.cjs.map +1 -0
  61. package/dist/{chunk-MHNE743G.js → chunk-Z6ZIJYKK.js} +4 -4
  62. package/dist/{chunk-MHNE743G.js.map → chunk-Z6ZIJYKK.js.map} +1 -1
  63. package/dist/{chunk-TX4TTPYJ.cjs → chunk-ZZ2DSE2G.cjs} +2 -2
  64. package/dist/chunk-ZZ2DSE2G.cjs.map +1 -0
  65. package/dist/index.cjs +88 -56
  66. package/dist/index.js +11 -11
  67. package/dist/loop/index.cjs +2 -2
  68. package/dist/loop/index.js +1 -1
  69. package/dist/loop/workflows/stream.d.ts +1 -1
  70. package/dist/loop/workflows/stream.d.ts.map +1 -1
  71. package/dist/mastra/index.cjs +2 -2
  72. package/dist/mastra/index.d.ts +3 -1
  73. package/dist/mastra/index.d.ts.map +1 -1
  74. package/dist/mastra/index.js +1 -1
  75. package/dist/memory/index.cjs +4 -4
  76. package/dist/memory/index.js +1 -1
  77. package/dist/processors/index.cjs +11 -11
  78. package/dist/processors/index.js +1 -1
  79. package/dist/relevance/index.cjs +4 -4
  80. package/dist/relevance/index.js +1 -1
  81. package/dist/scores/index.cjs +9 -9
  82. package/dist/scores/index.js +2 -2
  83. package/dist/scores/scoreTraces/index.cjs +8 -8
  84. package/dist/scores/scoreTraces/index.js +3 -3
  85. package/dist/server/index.cjs +25 -36
  86. package/dist/server/index.cjs.map +1 -1
  87. package/dist/server/index.js +24 -35
  88. package/dist/server/index.js.map +1 -1
  89. package/dist/server/simple-auth.d.ts +13 -18
  90. package/dist/server/simple-auth.d.ts.map +1 -1
  91. package/dist/storage/base.d.ts +2 -9
  92. package/dist/storage/base.d.ts.map +1 -1
  93. package/dist/storage/domains/workflows/base.d.ts +2 -9
  94. package/dist/storage/domains/workflows/base.d.ts.map +1 -1
  95. package/dist/storage/domains/workflows/inmemory.d.ts +2 -9
  96. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  97. package/dist/storage/index.cjs +31 -10
  98. package/dist/storage/index.cjs.map +1 -1
  99. package/dist/storage/index.js +25 -4
  100. package/dist/storage/index.js.map +1 -1
  101. package/dist/storage/types.d.ts +10 -1
  102. package/dist/storage/types.d.ts.map +1 -1
  103. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  104. package/dist/stream/index.cjs +11 -11
  105. package/dist/stream/index.js +2 -2
  106. package/dist/telemetry/index.cjs +7 -7
  107. package/dist/telemetry/index.js +1 -1
  108. package/dist/telemetry/telemetry.decorators.d.ts.map +1 -1
  109. package/dist/test-utils/llm-mock.cjs +2 -2
  110. package/dist/test-utils/llm-mock.js +1 -1
  111. package/dist/tts/index.cjs +2 -2
  112. package/dist/tts/index.js +1 -1
  113. package/dist/utils.cjs +37 -17
  114. package/dist/utils.d.ts +32 -0
  115. package/dist/utils.d.ts.map +1 -1
  116. package/dist/utils.js +1 -1
  117. package/dist/voice/index.cjs +6 -6
  118. package/dist/voice/index.js +1 -1
  119. package/dist/workflows/default.d.ts +26 -8
  120. package/dist/workflows/default.d.ts.map +1 -1
  121. package/dist/workflows/evented/execution-engine.d.ts +5 -1
  122. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  123. package/dist/workflows/evented/index.cjs +10 -10
  124. package/dist/workflows/evented/index.js +1 -1
  125. package/dist/workflows/evented/workflow-event-processor/index.d.ts +5 -4
  126. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  127. package/dist/workflows/evented/workflow-event-processor/loop.d.ts +1 -1
  128. package/dist/workflows/evented/workflow-event-processor/loop.d.ts.map +1 -1
  129. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts +2 -2
  130. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts.map +1 -1
  131. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts +2 -2
  132. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts.map +1 -1
  133. package/dist/workflows/evented/workflow.d.ts +2 -1
  134. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  135. package/dist/workflows/execution-engine.d.ts +5 -3
  136. package/dist/workflows/execution-engine.d.ts.map +1 -1
  137. package/dist/workflows/index.cjs +26 -14
  138. package/dist/workflows/index.js +1 -1
  139. package/dist/workflows/legacy/index.cjs +22 -22
  140. package/dist/workflows/legacy/index.js +1 -1
  141. package/dist/workflows/step.d.ts +1 -0
  142. package/dist/workflows/step.d.ts.map +1 -1
  143. package/dist/workflows/types.d.ts +51 -1
  144. package/dist/workflows/types.d.ts.map +1 -1
  145. package/dist/workflows/utils.d.ts +20 -0
  146. package/dist/workflows/utils.d.ts.map +1 -1
  147. package/dist/workflows/workflow.d.ts +98 -12
  148. package/dist/workflows/workflow.d.ts.map +1 -1
  149. package/package.json +5 -5
  150. package/dist/chunk-7YGCP2UZ.js.map +0 -1
  151. package/dist/chunk-AQGLVU53.cjs.map +0 -1
  152. package/dist/chunk-BLUDYAPI.js.map +0 -1
  153. package/dist/chunk-BMJ6HNP4.js.map +0 -1
  154. package/dist/chunk-H6SCQEQZ.js.map +0 -1
  155. package/dist/chunk-HJOAX5IQ.cjs.map +0 -1
  156. package/dist/chunk-IAJHRFO4.cjs.map +0 -1
  157. package/dist/chunk-JVV5LREI.js.map +0 -1
  158. package/dist/chunk-TX4TTPYJ.cjs.map +0 -1
  159. package/dist/chunk-VATR2Z2C.cjs.map +0 -1
  160. package/dist/chunk-WIMFJ2BA.js.map +0 -1
  161. package/dist/chunk-XFEAV36D.cjs.map +0 -1
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkV3VLOOSW_cjs = require('./chunk-V3VLOOSW.cjs');
4
- var chunk42RUESSD_cjs = require('./chunk-42RUESSD.cjs');
4
+ var chunk4YYPQOP7_cjs = require('./chunk-4YYPQOP7.cjs');
5
5
  var chunk22DLIF7L_cjs = require('./chunk-22DLIF7L.cjs');
6
- var chunkIAJHRFO4_cjs = require('./chunk-IAJHRFO4.cjs');
6
+ var chunkYPYLWTZI_cjs = require('./chunk-YPYLWTZI.cjs');
7
7
  var chunk6VOPKVYH_cjs = require('./chunk-6VOPKVYH.cjs');
8
8
 
9
9
  // src/memory/memory.ts
@@ -154,7 +154,7 @@ https://mastra.ai/en/docs/memory/overview`
154
154
  if (config?.workingMemory && "use" in config.workingMemory) {
155
155
  throw new Error("The workingMemory.use option has been removed. Working memory always uses tool-call mode.");
156
156
  }
157
- const mergedConfig = chunkIAJHRFO4_cjs.deepMerge(this.threadConfig, config || {});
157
+ const mergedConfig = chunkYPYLWTZI_cjs.deepMerge(this.threadConfig, config || {});
158
158
  if (config?.workingMemory?.schema) {
159
159
  if (mergedConfig.workingMemory) {
160
160
  mergedConfig.workingMemory.schema = config.workingMemory.schema;
@@ -252,7 +252,7 @@ https://mastra.ai/en/docs/memory/overview`
252
252
  toolCallIds
253
253
  };
254
254
  const savedMessages = await this.saveMessages({ messages: [message], memoryConfig: config });
255
- const list = new chunk42RUESSD_cjs.MessageList({ threadId, resourceId }).add(savedMessages[0], "memory");
255
+ const list = new chunk4YYPQOP7_cjs.MessageList({ threadId, resourceId }).add(savedMessages[0], "memory");
256
256
  return list.get.all.v1()[0];
257
257
  }
258
258
  /**
@@ -267,5 +267,5 @@ https://mastra.ai/en/docs/memory/overview`
267
267
  exports.MastraMemory = MastraMemory;
268
268
  exports.MemoryProcessor = MemoryProcessor;
269
269
  exports.memoryDefaultOptions = memoryDefaultOptions;
270
- //# sourceMappingURL=chunk-GSFQAR6S.cjs.map
271
- //# sourceMappingURL=chunk-GSFQAR6S.cjs.map
270
+ //# sourceMappingURL=chunk-ICICKWAG.cjs.map
271
+ //# sourceMappingURL=chunk-ICICKWAG.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/memory/memory.ts"],"names":["MastraBase","augmentWithInit","ModelRouterEmbeddingModel","deepMerge","MessageList"],"mappings":";;;;;;;;;AA8BO,IAAe,eAAA,GAAf,cAAuCA,4BAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,OAAA,CAAQ,UAAyB,KAAA,EAAoE;AACnG,IAAA,OAAO,QAAA;AAAA,EACT;AACF;AAEO,IAAM,oBAAA,GAAuB;AAAA,EAClC,YAAA,EAAc,EAAA;AAAA,EACd,cAAA,EAAgB,KAAA;AAAA,EAChB,OAAA,EAAS;AAAA,IACP,aAAA,EAAe;AAAA,GACjB;AAAA,EACA,aAAA,EAAe;AAAA,IACb,OAAA,EAAS,KAAA;AAAA,IACT,QAAA,EAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAad;AAWO,IAAe,YAAA,GAAf,cAAoCA,4BAAA,CAAW;AAAA,EACpD,kBAAA;AAAA,EAEU,QAAA;AAAA,EACV,MAAA;AAAA,EACA,QAAA;AAAA,EACQ,aAAgC,EAAC;AAAA,EAC/B,YAAA,GAA6B,EAAE,GAAG,oBAAA,EAAqB;AAAA,EACjE,OAAA;AAAA,EAEA,Y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A,EAAY,CAAA,CAAE,GAAA,CAAI,aAAA,CAAc,CAAC,CAAA,EAAI,QAAQ,CAAA;AACtF,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,EAAA,GAAK,CAAC,CAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,UAAA,GAAqB;AAC1B,IAAA,OAAO,IAAA,CAAK,OAAA,EAAS,UAAA,EAAW,IAAK,OAAO,UAAA,EAAW;AAAA,EACzD;AAiEF","file":"chunk-GSFQAR6S.cjs","sourcesContent":["import type { EmbeddingModelV2 } from '@ai-sdk/provider-v5';\nimport type { AssistantContent, UserContent, CoreMessage, EmbeddingModel } from 'ai';\nimport { MessageList } from '../agent/message-list';\nimport type { MastraMessageV2, UIMessageWithMetadata } from '../agent/message-list';\nimport { MastraBase } from '../base';\nimport { ModelRouterEmbeddingModel } from '../llm/model/index.js';\nimport type { Mastra } from '../mastra';\nimport type { MastraStorage, PaginationInfo, StorageGetMessagesArg, ThreadSortOptions } from '../storage';\nimport { augmentWithInit } from '../storage/storageWithInit';\nimport type { ToolAction } from '../tools';\nimport { deepMerge } from '../utils';\nimport type { MastraVector } from '../vector';\n\nimport type {\n SharedMemoryConfig,\n StorageThreadType,\n MemoryConfig,\n MastraMessageV1,\n WorkingMemoryTemplate,\n} from './types';\n\nexport type MemoryProcessorOpts = {\n systemMessage?: string;\n memorySystemMessage?: string;\n newMessages?: CoreMessage[];\n};\n/**\n * Interface for message processors that can filter or transform messages\n * before they're sent to the LLM.\n */\nexport abstract class MemoryProcessor extends MastraBase {\n /**\n * Process a list of messages and return a filtered or transformed list.\n * @param messages The messages to process\n * @returns The processed messages\n */\n process(messages: CoreMessage[], _opts: MemoryProcessorOpts): CoreMessage[] | Promise<CoreMessage[]> {\n return messages;\n }\n}\n\nexport const memoryDefaultOptions = {\n lastMessages: 10,\n semanticRecall: false,\n threads: {\n generateTitle: true,\n },\n workingMemory: {\n enabled: false,\n template: `\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} satisfies MemoryConfig;\n\n/**\n * Abstract base class for implementing conversation memory systems.\n *\n * Key features:\n * - Thread-based conversation organization with resource association\n * - Optional vector database integration for semantic similarity search\n * - Working memory templates for structured conversation state\n * - Handles memory processors to manipulate messages before they are sent to the LLM\n */\nexport abstract class MastraMemory extends MastraBase {\n MAX_CONTEXT_TOKENS?: number;\n\n protected _storage?: MastraStorage;\n vector?: MastraVector;\n embedder?: EmbeddingModel<string> | EmbeddingModelV2<string>;\n private processors: MemoryProcessor[] = [];\n protected threadConfig: MemoryConfig = { ...memoryDefaultOptions };\n #mastra?: Mastra;\n\n constructor(config: { name: string } & SharedMemoryConfig) {\n super({ component: 'MEMORY', name: config.name });\n\n if (config.options) this.threadConfig = this.getMergedThreadConfig(config.options);\n if (config.processors) this.processors = config.processors;\n if (config.storage) {\n this._storage = augmentWithInit(config.storage);\n this._hasOwnStorage = true;\n }\n\n if (this.threadConfig.semanticRecall) {\n if (!config.vector) {\n throw new Error(\n `Semantic recall requires a vector store to be configured.\\n\\nhttps://mastra.ai/en/docs/memory/semantic-recall`,\n );\n }\n this.vector = config.vector;\n\n if (!config.embedder) {\n throw new Error(\n `Semantic recall requires an embedder to be configured.\\n\\nhttps://mastra.ai/en/docs/memory/semantic-recall`,\n );\n }\n\n // Convert string embedder to ModelRouterEmbeddingModel\n if (typeof config.embedder === 'string') {\n this.embedder = new ModelRouterEmbeddingModel(config.embedder);\n } else {\n this.embedder = config.embedder;\n }\n }\n }\n\n /**\n * Internal method used by Mastra to register itself with the memory.\n * @param mastra The Mastra instance.\n * @internal\n */\n __registerMastra(mastra: Mastra): void {\n this.#mastra = mastra;\n }\n\n protected _hasOwnStorage = false;\n get hasOwnStorage() {\n return this._hasOwnStorage;\n }\n\n get storage() {\n if (!this._storage) {\n throw new Error(\n `Memory requires a storage provider to function. Add a storage configuration to Memory or to your Mastra instance.\\n\\nhttps://mastra.ai/en/docs/memory/overview`,\n );\n }\n return this._storage;\n }\n\n public setStorage(storage: MastraStorage) {\n this._storage = augmentWithInit(storage);\n }\n\n public setVector(vector: MastraVector) {\n this.vector = vector;\n }\n\n public setEmbedder(embedder: EmbeddingModel<string>) {\n this.embedder = embedder;\n }\n\n /**\n * Get a system message to inject into the conversation.\n * This will be called before each conversation turn.\n * Implementations can override this to inject custom system messages.\n */\n public async getSystemMessage(_input: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n return null;\n }\n\n /**\n * Get tools that should be available to the agent.\n * This will be called when converting tools for the agent.\n * Implementations can override this to provide additional tools.\n */\n public getTools(_config?: MemoryConfig): Record<string, ToolAction<any, any, any>> {\n return {};\n }\n\n protected async createEmbeddingIndex(dimensions?: number, config?: MemoryConfig): Promise<{ indexName: string }> {\n const defaultDimensions = 1536;\n const isDefault = dimensions === defaultDimensions;\n const usedDimensions = dimensions ?? defaultDimensions;\n const separator = this.vector?.indexSeparator ?? '_';\n const indexName = isDefault\n ? `memory${separator}messages`\n : `memory${separator}messages${separator}${usedDimensions}`;\n\n if (typeof this.vector === `undefined`) {\n throw new Error(`Tried to create embedding index but no vector db is attached to this Memory instance.`);\n }\n\n // Get index configuration from memory config\n const semanticConfig = typeof config?.semanticRecall === 'object' ? config.semanticRecall : undefined;\n const indexConfig = semanticConfig?.indexConfig;\n\n // Base parameters that all vector stores support\n const createParams: any = {\n indexName,\n dimension: usedDimensions,\n ...(indexConfig?.metric && { metric: indexConfig.metric }),\n };\n\n // Add PG-specific configuration if provided\n // Only PG vector store will use these parameters\n if (indexConfig && (indexConfig.type || indexConfig.ivf || indexConfig.hnsw)) {\n createParams.indexConfig = {};\n if (indexConfig.type) createParams.indexConfig.type = indexConfig.type;\n if (indexConfig.ivf) createParams.indexConfig.ivf = indexConfig.ivf;\n if (indexConfig.hnsw) createParams.indexConfig.hnsw = indexConfig.hnsw;\n }\n\n await this.vector.createIndex(createParams);\n return { indexName };\n }\n\n public getMergedThreadConfig(config?: MemoryConfig): MemoryConfig {\n if (config?.workingMemory && 'use' in config.workingMemory) {\n throw new Error('The workingMemory.use option has been removed. Working memory always uses tool-call mode.');\n }\n const mergedConfig = deepMerge(this.threadConfig, config || {});\n\n if (config?.workingMemory?.schema) {\n if (mergedConfig.workingMemory) {\n mergedConfig.workingMemory.schema = config.workingMemory.schema;\n }\n }\n\n return mergedConfig;\n }\n\n /**\n * Apply all configured message processors to a list of messages.\n * @param messages The messages to process\n * @returns The processed messages\n */\n protected async applyProcessors(\n messages: CoreMessage[],\n opts: {\n processors?: MemoryProcessor[];\n } & MemoryProcessorOpts,\n ): Promise<CoreMessage[]> {\n const processors = opts.processors || this.processors;\n if (!processors || processors.length === 0) {\n return messages;\n }\n\n let processedMessages = [...messages];\n\n for (const processor of processors) {\n processedMessages = await processor.process(processedMessages, {\n systemMessage: opts.systemMessage,\n newMessages: opts.newMessages,\n memorySystemMessage: opts.memorySystemMessage,\n });\n }\n\n return processedMessages;\n }\n\n processMessages({\n messages,\n processors,\n ...opts\n }: {\n messages: CoreMessage[];\n processors?: MemoryProcessor[];\n } & MemoryProcessorOpts) {\n return this.applyProcessors(messages, { processors: processors || this.processors, ...opts });\n }\n\n abstract 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\n estimateTokens(text: string): number {\n return Math.ceil(text.split(' ').length * 1.3);\n }\n\n /**\n * Retrieves a specific thread by its ID\n * @param threadId - The unique identifier of the thread\n * @returns Promise resolving to the thread or null if not found\n */\n abstract getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null>;\n\n /**\n * Retrieves all threads that belong to the specified resource.\n * @param resourceId - The unique identifier of the resource\n * @param orderBy - Which timestamp field to sort by (`'createdAt'` or `'updatedAt'`);\n * defaults to `'createdAt'`\n * @param sortDirection - Sort order for the results (`'ASC'` or `'DESC'`);\n * defaults to `'DESC'`\n * @returns Promise resolving to an array of matching threads; resolves to an empty array\n * if the resource has no threads\n */\n abstract getThreadsByResourceId({\n resourceId,\n orderBy,\n sortDirection,\n }: { resourceId: string } & ThreadSortOptions): Promise<StorageThreadType[]>;\n\n abstract getThreadsByResourceIdPaginated(\n args: {\n resourceId: string;\n page: number;\n perPage: number;\n } & ThreadSortOptions,\n ): Promise<PaginationInfo & { threads: StorageThreadType[] }>;\n\n /**\n * Saves or updates a thread\n * @param thread - The thread data to save\n * @returns Promise resolving to the saved thread\n */\n abstract saveThread({\n thread,\n memoryConfig,\n }: {\n thread: StorageThreadType;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType>;\n\n /**\n * Saves messages to a thread\n * @param messages - Array of messages to save\n * @returns Promise resolving to the saved messages\n */\n abstract saveMessages(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format?: 'v1';\n }): Promise<MastraMessageV1[]>;\n abstract saveMessages(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format: 'v2';\n }): Promise<MastraMessageV2[]>;\n abstract saveMessages(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format?: 'v1' | 'v2';\n }): Promise<MastraMessageV2[] | MastraMessageV1[]>;\n\n /**\n * Retrieves all messages for a specific thread\n * @param threadId - The unique identifier of the thread\n * @returns Promise resolving to array of messages, uiMessages, and messagesV2\n */\n abstract query({ threadId, resourceId, selectBy }: StorageGetMessagesArg): Promise<{\n messages: CoreMessage[];\n uiMessages: UIMessageWithMetadata[];\n messagesV2: MastraMessageV2[];\n }>;\n\n /**\n * Helper method to create a new thread\n * @param title - Optional title for the thread\n * @param metadata - Optional metadata for the thread\n * @returns Promise resolving to the created thread\n */\n async createThread({\n threadId,\n resourceId,\n title,\n metadata,\n memoryConfig,\n saveThread = true,\n }: {\n resourceId: string;\n threadId?: string;\n title?: string;\n metadata?: Record<string, unknown>;\n memoryConfig?: MemoryConfig;\n saveThread?: boolean;\n }): Promise<StorageThreadType> {\n const thread: StorageThreadType = {\n id: threadId || this.generateId(),\n title: title || `New Thread ${new Date().toISOString()}`,\n resourceId,\n createdAt: new Date(),\n updatedAt: new Date(),\n metadata,\n };\n\n return saveThread ? this.saveThread({ thread, memoryConfig }) : thread;\n }\n\n /**\n * Helper method to delete a thread\n * @param threadId - the id of the thread to delete\n */\n abstract deleteThread(threadId: string): Promise<void>;\n\n /**\n * Helper method to add a single message to a thread\n * @param threadId - The thread to add the message to\n * @param content - The message content\n * @param role - The role of the message sender\n * @param type - The type of the message\n * @param toolNames - Optional array of tool names that were called\n * @param toolCallArgs - Optional array of tool call arguments\n * @param toolCallIds - Optional array of tool call ids\n * @returns Promise resolving to the saved message\n * @deprecated use saveMessages instead\n */\n async addMessage({\n threadId,\n resourceId,\n config,\n content,\n role,\n type,\n toolNames,\n toolCallArgs,\n toolCallIds,\n }: {\n threadId: string;\n resourceId: string;\n config?: MemoryConfig;\n content: UserContent | AssistantContent;\n role: 'user' | 'assistant';\n type: 'text' | 'tool-call' | 'tool-result';\n toolNames?: string[];\n toolCallArgs?: Record<string, unknown>[];\n toolCallIds?: string[];\n }): Promise<MastraMessageV1> {\n const message: MastraMessageV1 = {\n id: this.generateId(),\n content,\n role,\n createdAt: new Date(),\n threadId,\n resourceId,\n type,\n toolNames,\n toolCallArgs,\n toolCallIds,\n };\n\n const savedMessages = await this.saveMessages({ messages: [message], memoryConfig: config });\n const list = new MessageList({ threadId, resourceId }).add(savedMessages[0]!, 'memory');\n return list.get.all.v1()[0]!;\n }\n\n /**\n * Generates a unique identifier\n * @returns A unique string ID\n */\n public generateId(): string {\n return this.#mastra?.generateId() || crypto.randomUUID();\n }\n\n /**\n * Retrieves working memory for a specific thread\n * @param threadId - The unique identifier of the thread\n * @param resourceId - The unique identifier of the resource\n * @param memoryConfig - Optional memory configuration\n * @returns Promise resolving to working memory data or null if not found\n */\n abstract getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null>;\n\n /**\n * Retrieves working memory template for a specific thread\n * @param memoryConfig - Optional memory configuration\n * @returns Promise resolving to working memory template or null if not found\n */\n abstract getWorkingMemoryTemplate({\n memoryConfig,\n }?: {\n memoryConfig?: MemoryConfig;\n }): Promise<WorkingMemoryTemplate | null>;\n\n abstract 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\n /**\n * @warning experimental! can be removed or changed at any time\n */\n abstract __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\n /**\n * Deletes multiple messages by their IDs\n * @param messageIds - Array of message IDs to delete\n * @returns Promise that resolves when all messages are deleted\n */\n abstract deleteMessages(messageIds: string[]): Promise<void>;\n}\n"]}
1
+ {"version":3,"sources":["../src/memory/memory.ts"],"names":["MastraBase","augmentWithInit","ModelRouterEmbeddingModel","deepMerge","MessageList"],"mappings":";;;;;;;;;AA8BO,IAAe,eAAA,GAAf,cAAuCA,4BAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,OAAA,CAAQ,UAAyB,KAAA,EAAoE;AACnG,IAAA,OAAO,QAAA;AAAA,EACT;AACF;AAEO,IAAM,oBAAA,GAAuB;AAAA,EAClC,YAAA,EAA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,GACF,EAU6B;AAC3B,IAAA,MAAM,OAAA,GAA2B;AAAA,MAC/B,EAAA,EAAI,KAAK,UAAA,EAAW;AAAA,MACpB,OAAA;AAAA,MACA,IAAA;AAAA,MACA,SAAA,sBAAe,IAAA,EAAK;AAAA,MACpB,QAAA;AAAA,MACA,UAAA;AAAA,MACA,IAAA;AAAA,MACA,SAAA;AAAA,MACA,YAAA;AAAA,MACA;AAAA,KACF;AAEA,IAAA,MAAM,aAAA,GAAgB,MAAM,IAAA,CAAK,YAAA,CAAa,EAAE,QAAA,EAAU,CAAC,OAAO,CAAA,EAAG,YAAA,EAAc,MAAA,EAAQ,CAAA;AAC3F,IAAA,MAAM,IAAA,GAAO,IAAIC,6BAAA,CAAY,EAAE,QAAA,EAAU,UAAA,EAAY,CAAA,CAAE,GAAA,CAAI,aAAA,CAAc,CAAC,CAAA,EAAI,QAAQ,CAAA;AACtF,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,EAAA,GAAK,CAAC,CAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,UAAA,GAAqB;AAC1B,IAAA,OAAO,IAAA,CAAK,OAAA,EAAS,UAAA,EAAW,IAAK,OAAO,UAAA,EAAW;AAAA,EACzD;AAiEF","file":"chunk-ICICKWAG.cjs","sourcesContent":["import type { EmbeddingModelV2 } from '@ai-sdk/provider-v5';\nimport type { AssistantContent, UserContent, CoreMessage, EmbeddingModel } from 'ai';\nimport { MessageList } from '../agent/message-list';\nimport type { MastraMessageV2, UIMessageWithMetadata } from '../agent/message-list';\nimport { MastraBase } from '../base';\nimport { ModelRouterEmbeddingModel } from '../llm/model/index.js';\nimport type { Mastra } from '../mastra';\nimport type { MastraStorage, PaginationInfo, StorageGetMessagesArg, ThreadSortOptions } from '../storage';\nimport { augmentWithInit } from '../storage/storageWithInit';\nimport type { ToolAction } from '../tools';\nimport { deepMerge } from '../utils';\nimport type { MastraVector } from '../vector';\n\nimport type {\n SharedMemoryConfig,\n StorageThreadType,\n MemoryConfig,\n MastraMessageV1,\n WorkingMemoryTemplate,\n} from './types';\n\nexport type MemoryProcessorOpts = {\n systemMessage?: string;\n memorySystemMessage?: string;\n newMessages?: CoreMessage[];\n};\n/**\n * Interface for message processors that can filter or transform messages\n * before they're sent to the LLM.\n */\nexport abstract class MemoryProcessor extends MastraBase {\n /**\n * Process a list of messages and return a filtered or transformed list.\n * @param messages The messages to process\n * @returns The processed messages\n */\n process(messages: CoreMessage[], _opts: MemoryProcessorOpts): CoreMessage[] | Promise<CoreMessage[]> {\n return messages;\n }\n}\n\nexport const memoryDefaultOptions = {\n lastMessages: 10,\n semanticRecall: false,\n threads: {\n generateTitle: true,\n },\n workingMemory: {\n enabled: false,\n template: `\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} satisfies MemoryConfig;\n\n/**\n * Abstract base class for implementing conversation memory systems.\n *\n * Key features:\n * - Thread-based conversation organization with resource association\n * - Optional vector database integration for semantic similarity search\n * - Working memory templates for structured conversation state\n * - Handles memory processors to manipulate messages before they are sent to the LLM\n */\nexport abstract class MastraMemory extends MastraBase {\n MAX_CONTEXT_TOKENS?: number;\n\n protected _storage?: MastraStorage;\n vector?: MastraVector;\n embedder?: EmbeddingModel<string> | EmbeddingModelV2<string>;\n private processors: MemoryProcessor[] = [];\n protected threadConfig: MemoryConfig = { ...memoryDefaultOptions };\n #mastra?: Mastra;\n\n constructor(config: { name: string } & SharedMemoryConfig) {\n super({ component: 'MEMORY', name: config.name });\n\n if (config.options) this.threadConfig = this.getMergedThreadConfig(config.options);\n if (config.processors) this.processors = config.processors;\n if (config.storage) {\n this._storage = augmentWithInit(config.storage);\n this._hasOwnStorage = true;\n }\n\n if (this.threadConfig.semanticRecall) {\n if (!config.vector) {\n throw new Error(\n `Semantic recall requires a vector store to be configured.\\n\\nhttps://mastra.ai/en/docs/memory/semantic-recall`,\n );\n }\n this.vector = config.vector;\n\n if (!config.embedder) {\n throw new Error(\n `Semantic recall requires an embedder to be configured.\\n\\nhttps://mastra.ai/en/docs/memory/semantic-recall`,\n );\n }\n\n // Convert string embedder to ModelRouterEmbeddingModel\n if (typeof config.embedder === 'string') {\n this.embedder = new ModelRouterEmbeddingModel(config.embedder);\n } else {\n this.embedder = config.embedder;\n }\n }\n }\n\n /**\n * Internal method used by Mastra to register itself with the memory.\n * @param mastra The Mastra instance.\n * @internal\n */\n __registerMastra(mastra: Mastra): void {\n this.#mastra = mastra;\n }\n\n protected _hasOwnStorage = false;\n get hasOwnStorage() {\n return this._hasOwnStorage;\n }\n\n get storage() {\n if (!this._storage) {\n throw new Error(\n `Memory requires a storage provider to function. Add a storage configuration to Memory or to your Mastra instance.\\n\\nhttps://mastra.ai/en/docs/memory/overview`,\n );\n }\n return this._storage;\n }\n\n public setStorage(storage: MastraStorage) {\n this._storage = augmentWithInit(storage);\n }\n\n public setVector(vector: MastraVector) {\n this.vector = vector;\n }\n\n public setEmbedder(embedder: EmbeddingModel<string>) {\n this.embedder = embedder;\n }\n\n /**\n * Get a system message to inject into the conversation.\n * This will be called before each conversation turn.\n * Implementations can override this to inject custom system messages.\n */\n public async getSystemMessage(_input: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null> {\n return null;\n }\n\n /**\n * Get tools that should be available to the agent.\n * This will be called when converting tools for the agent.\n * Implementations can override this to provide additional tools.\n */\n public getTools(_config?: MemoryConfig): Record<string, ToolAction<any, any, any>> {\n return {};\n }\n\n protected async createEmbeddingIndex(dimensions?: number, config?: MemoryConfig): Promise<{ indexName: string }> {\n const defaultDimensions = 1536;\n const isDefault = dimensions === defaultDimensions;\n const usedDimensions = dimensions ?? defaultDimensions;\n const separator = this.vector?.indexSeparator ?? '_';\n const indexName = isDefault\n ? `memory${separator}messages`\n : `memory${separator}messages${separator}${usedDimensions}`;\n\n if (typeof this.vector === `undefined`) {\n throw new Error(`Tried to create embedding index but no vector db is attached to this Memory instance.`);\n }\n\n // Get index configuration from memory config\n const semanticConfig = typeof config?.semanticRecall === 'object' ? config.semanticRecall : undefined;\n const indexConfig = semanticConfig?.indexConfig;\n\n // Base parameters that all vector stores support\n const createParams: any = {\n indexName,\n dimension: usedDimensions,\n ...(indexConfig?.metric && { metric: indexConfig.metric }),\n };\n\n // Add PG-specific configuration if provided\n // Only PG vector store will use these parameters\n if (indexConfig && (indexConfig.type || indexConfig.ivf || indexConfig.hnsw)) {\n createParams.indexConfig = {};\n if (indexConfig.type) createParams.indexConfig.type = indexConfig.type;\n if (indexConfig.ivf) createParams.indexConfig.ivf = indexConfig.ivf;\n if (indexConfig.hnsw) createParams.indexConfig.hnsw = indexConfig.hnsw;\n }\n\n await this.vector.createIndex(createParams);\n return { indexName };\n }\n\n public getMergedThreadConfig(config?: MemoryConfig): MemoryConfig {\n if (config?.workingMemory && 'use' in config.workingMemory) {\n throw new Error('The workingMemory.use option has been removed. Working memory always uses tool-call mode.');\n }\n const mergedConfig = deepMerge(this.threadConfig, config || {});\n\n if (config?.workingMemory?.schema) {\n if (mergedConfig.workingMemory) {\n mergedConfig.workingMemory.schema = config.workingMemory.schema;\n }\n }\n\n return mergedConfig;\n }\n\n /**\n * Apply all configured message processors to a list of messages.\n * @param messages The messages to process\n * @returns The processed messages\n */\n protected async applyProcessors(\n messages: CoreMessage[],\n opts: {\n processors?: MemoryProcessor[];\n } & MemoryProcessorOpts,\n ): Promise<CoreMessage[]> {\n const processors = opts.processors || this.processors;\n if (!processors || processors.length === 0) {\n return messages;\n }\n\n let processedMessages = [...messages];\n\n for (const processor of processors) {\n processedMessages = await processor.process(processedMessages, {\n systemMessage: opts.systemMessage,\n newMessages: opts.newMessages,\n memorySystemMessage: opts.memorySystemMessage,\n });\n }\n\n return processedMessages;\n }\n\n processMessages({\n messages,\n processors,\n ...opts\n }: {\n messages: CoreMessage[];\n processors?: MemoryProcessor[];\n } & MemoryProcessorOpts) {\n return this.applyProcessors(messages, { processors: processors || this.processors, ...opts });\n }\n\n abstract 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\n estimateTokens(text: string): number {\n return Math.ceil(text.split(' ').length * 1.3);\n }\n\n /**\n * Retrieves a specific thread by its ID\n * @param threadId - The unique identifier of the thread\n * @returns Promise resolving to the thread or null if not found\n */\n abstract getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null>;\n\n /**\n * Retrieves all threads that belong to the specified resource.\n * @param resourceId - The unique identifier of the resource\n * @param orderBy - Which timestamp field to sort by (`'createdAt'` or `'updatedAt'`);\n * defaults to `'createdAt'`\n * @param sortDirection - Sort order for the results (`'ASC'` or `'DESC'`);\n * defaults to `'DESC'`\n * @returns Promise resolving to an array of matching threads; resolves to an empty array\n * if the resource has no threads\n */\n abstract getThreadsByResourceId({\n resourceId,\n orderBy,\n sortDirection,\n }: { resourceId: string } & ThreadSortOptions): Promise<StorageThreadType[]>;\n\n abstract getThreadsByResourceIdPaginated(\n args: {\n resourceId: string;\n page: number;\n perPage: number;\n } & ThreadSortOptions,\n ): Promise<PaginationInfo & { threads: StorageThreadType[] }>;\n\n /**\n * Saves or updates a thread\n * @param thread - The thread data to save\n * @returns Promise resolving to the saved thread\n */\n abstract saveThread({\n thread,\n memoryConfig,\n }: {\n thread: StorageThreadType;\n memoryConfig?: MemoryConfig;\n }): Promise<StorageThreadType>;\n\n /**\n * Saves messages to a thread\n * @param messages - Array of messages to save\n * @returns Promise resolving to the saved messages\n */\n abstract saveMessages(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format?: 'v1';\n }): Promise<MastraMessageV1[]>;\n abstract saveMessages(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format: 'v2';\n }): Promise<MastraMessageV2[]>;\n abstract saveMessages(args: {\n messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];\n memoryConfig?: MemoryConfig | undefined;\n format?: 'v1' | 'v2';\n }): Promise<MastraMessageV2[] | MastraMessageV1[]>;\n\n /**\n * Retrieves all messages for a specific thread\n * @param threadId - The unique identifier of the thread\n * @returns Promise resolving to array of messages, uiMessages, and messagesV2\n */\n abstract query({ threadId, resourceId, selectBy }: StorageGetMessagesArg): Promise<{\n messages: CoreMessage[];\n uiMessages: UIMessageWithMetadata[];\n messagesV2: MastraMessageV2[];\n }>;\n\n /**\n * Helper method to create a new thread\n * @param title - Optional title for the thread\n * @param metadata - Optional metadata for the thread\n * @returns Promise resolving to the created thread\n */\n async createThread({\n threadId,\n resourceId,\n title,\n metadata,\n memoryConfig,\n saveThread = true,\n }: {\n resourceId: string;\n threadId?: string;\n title?: string;\n metadata?: Record<string, unknown>;\n memoryConfig?: MemoryConfig;\n saveThread?: boolean;\n }): Promise<StorageThreadType> {\n const thread: StorageThreadType = {\n id: threadId || this.generateId(),\n title: title || `New Thread ${new Date().toISOString()}`,\n resourceId,\n createdAt: new Date(),\n updatedAt: new Date(),\n metadata,\n };\n\n return saveThread ? this.saveThread({ thread, memoryConfig }) : thread;\n }\n\n /**\n * Helper method to delete a thread\n * @param threadId - the id of the thread to delete\n */\n abstract deleteThread(threadId: string): Promise<void>;\n\n /**\n * Helper method to add a single message to a thread\n * @param threadId - The thread to add the message to\n * @param content - The message content\n * @param role - The role of the message sender\n * @param type - The type of the message\n * @param toolNames - Optional array of tool names that were called\n * @param toolCallArgs - Optional array of tool call arguments\n * @param toolCallIds - Optional array of tool call ids\n * @returns Promise resolving to the saved message\n * @deprecated use saveMessages instead\n */\n async addMessage({\n threadId,\n resourceId,\n config,\n content,\n role,\n type,\n toolNames,\n toolCallArgs,\n toolCallIds,\n }: {\n threadId: string;\n resourceId: string;\n config?: MemoryConfig;\n content: UserContent | AssistantContent;\n role: 'user' | 'assistant';\n type: 'text' | 'tool-call' | 'tool-result';\n toolNames?: string[];\n toolCallArgs?: Record<string, unknown>[];\n toolCallIds?: string[];\n }): Promise<MastraMessageV1> {\n const message: MastraMessageV1 = {\n id: this.generateId(),\n content,\n role,\n createdAt: new Date(),\n threadId,\n resourceId,\n type,\n toolNames,\n toolCallArgs,\n toolCallIds,\n };\n\n const savedMessages = await this.saveMessages({ messages: [message], memoryConfig: config });\n const list = new MessageList({ threadId, resourceId }).add(savedMessages[0]!, 'memory');\n return list.get.all.v1()[0]!;\n }\n\n /**\n * Generates a unique identifier\n * @returns A unique string ID\n */\n public generateId(): string {\n return this.#mastra?.generateId() || crypto.randomUUID();\n }\n\n /**\n * Retrieves working memory for a specific thread\n * @param threadId - The unique identifier of the thread\n * @param resourceId - The unique identifier of the resource\n * @param memoryConfig - Optional memory configuration\n * @returns Promise resolving to working memory data or null if not found\n */\n abstract getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n }): Promise<string | null>;\n\n /**\n * Retrieves working memory template for a specific thread\n * @param memoryConfig - Optional memory configuration\n * @returns Promise resolving to working memory template or null if not found\n */\n abstract getWorkingMemoryTemplate({\n memoryConfig,\n }?: {\n memoryConfig?: MemoryConfig;\n }): Promise<WorkingMemoryTemplate | null>;\n\n abstract 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\n /**\n * @warning experimental! can be removed or changed at any time\n */\n abstract __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\n /**\n * Deletes multiple messages by their IDs\n * @param messageIds - Array of message IDs to delete\n * @returns Promise that resolves when all messages are deleted\n */\n abstract deleteMessages(messageIds: string[]): Promise<void>;\n}\n"]}
@@ -1,11 +1,11 @@
1
- import { WorkflowEventProcessor } from './chunk-H6SCQEQZ.js';
2
- import { saveScorePayloadSchema } from './chunk-UWTYVVVZ.js';
1
+ import { WorkflowEventProcessor } from './chunk-2BY7C6Y7.js';
2
+ import { saveScorePayloadSchema } from './chunk-RLYWCJQ6.js';
3
3
  import { augmentWithInit } from './chunk-436FFEF6.js';
4
4
  import { PubSub } from './chunk-BVUMKER5.js';
5
- import { InstrumentClass, Telemetry } from './chunk-BLUDYAPI.js';
5
+ import { InstrumentClass, Telemetry } from './chunk-DSUKMFZY.js';
6
6
  import { InMemoryServerCache } from './chunk-3NTOFNIU.js';
7
7
  import { registerHook } from './chunk-TTELJD4F.js';
8
- import { setupAITracing, getAllAITracing, shutdownAITracingRegistry } from './chunk-WIMFJ2BA.js';
8
+ import { setupAITracing, getAllAITracing, shutdownAITracingRegistry } from './chunk-PPAIPZ6C.js';
9
9
  import { noopLogger } from './chunk-PFXXH2RP.js';
10
10
  import { MastraError } from './chunk-PZUZNPFM.js';
11
11
  import { ConsoleLogger, LogLevel } from './chunk-UXG7PYML.js';
@@ -500,6 +500,9 @@ do:
500
500
  tts: this.#tts,
501
501
  vectors: this.#vectors
502
502
  });
503
+ if (!workflow.committed) {
504
+ workflow.commit();
505
+ }
503
506
  this.#workflows[key] = workflow;
504
507
  });
505
508
  }
@@ -950,6 +953,51 @@ do:
950
953
  }
951
954
  return workflow;
952
955
  }
956
+ async listActiveWorkflowRuns() {
957
+ const storage = this.#storage;
958
+ if (!storage) {
959
+ this.#logger.debug("Cannot get active workflow runs. Mastra storage is not initialized");
960
+ return {
961
+ runs: [],
962
+ total: 0
963
+ };
964
+ }
965
+ const defaultEngineWorkflows = Object.values(this.#workflows).filter(workflow => workflow.engineType === "default");
966
+ const allRuns = [];
967
+ let allTotal = 0;
968
+ for (const workflow of defaultEngineWorkflows) {
969
+ const runningRuns = await workflow.getWorkflowRuns({
970
+ status: "running"
971
+ });
972
+ const waitingRuns = await workflow.getWorkflowRuns({
973
+ status: "waiting"
974
+ });
975
+ allRuns.push(...runningRuns.runs, ...waitingRuns.runs);
976
+ allTotal += runningRuns.total + waitingRuns.total;
977
+ }
978
+ return {
979
+ runs: allRuns,
980
+ total: allTotal
981
+ };
982
+ }
983
+ async restartAllActiveWorkflowRuns() {
984
+ const activeRuns = await this.listActiveWorkflowRuns();
985
+ if (activeRuns.runs.length > 0) {
986
+ this.#logger.debug(`Restarting ${activeRuns.runs.length} active workflow run${activeRuns.runs.length > 1 ? "s" : ""}`);
987
+ }
988
+ for (const runSnapshot of activeRuns.runs) {
989
+ const workflow = this.getWorkflowById(runSnapshot.workflowName);
990
+ try {
991
+ const run = await workflow.createRunAsync({
992
+ runId: runSnapshot.runId
993
+ });
994
+ await run.restart();
995
+ this.#logger.debug(`Restarted ${runSnapshot.workflowName} workflow run ${runSnapshot.runId}`);
996
+ } catch (error) {
997
+ this.#logger.error(`Failed to restart ${runSnapshot.workflowName} workflow run ${runSnapshot.runId}: ${error}`);
998
+ }
999
+ }
1000
+ }
953
1001
  /**
954
1002
  * Returns all registered legacy workflows as a record keyed by their IDs.
955
1003
  *
@@ -1696,5 +1744,5 @@ Mastra = /*@__PURE__*/(_ => {
1696
1744
  })();
1697
1745
 
1698
1746
  export { Mastra };
1699
- //# sourceMappingURL=chunk-7YGCP2UZ.js.map
1700
- //# sourceMappingURL=chunk-7YGCP2UZ.js.map
1747
+ //# sourceMappingURL=chunk-N6P5GJRO.js.map
1748
+ //# sourceMappingURL=chunk-N6P5GJRO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mastra/index.ts","../src/events/event-emitter.ts","../src/mastra/hooks.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;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IAAA,CAAA,YAAA;AAAA,EAAA;AAAA;AAAA,MAAA,gBAAA,CAAA,CAAA,IAAA;AAAA,EAAA,KAAA,GAAA,gBAAA,CAAA,IAAA,CAAA;AAAA,EA2BA,MAAM,GAAA,iBAA0B,CAAA,KAAA,EAAA,CAAA,EAAA,QAAA,EAAA,kBAAA,EAAA,MAAA,CAAA;AAE9B,EAAA,iBAAM,CAAA,KAAA,EAAA,CAAA,EAAA,MAA0B,CAAA;AAChC,EAAA,OAAA,MAAW;AAEX,CAAA,EAAK","file":"chunk-N6P5GJRO.js","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../agent';\nimport { getAllAITracing, setupAITracing, shutdownAITracingRegistry } from '../ai-tracing';\nimport type { ObservabilityRegistryConfig } from '../ai-tracing';\nimport type { BundlerConfig } from '../bundler/types';\nimport { InMemoryServerCache } from '../cache';\nimport type { MastraServerCache } from '../cache';\nimport type { MastraDeployer } from '../deployer';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../error';\nimport { EventEmitterPubSub } from '../events/event-emitter';\nimport type { PubSub } from '../events/pubsub';\nimport type { Event } from '../events/types';\nimport { AvailableHooks, registerHook } from '../hooks';\nimport type { MastraModelGateway } from '../llm/model/gateways';\nimport { LogLevel, noopLogger, ConsoleLogger } from '../logger';\nimport type { IMastraLogger } from '../logger';\nimport type { MCPServerBase } from '../mcp';\nimport type { MastraMemory } from '../memory/memory';\nimport type { MastraScorer } from '../scores';\nimport type { Middleware, ServerConfig } from '../server/types';\nimport type { MastraStorage, WorkflowRuns } from '../storage';\nimport { augmentWithInit } from '../storage/storageWithInit';\nimport { InstrumentClass, Telemetry } from '../telemetry';\nimport type { OtelConfig } from '../telemetry';\nimport type { MastraTTS } from '../tts';\nimport type { MastraIdGenerator } from '../types';\nimport type { MastraVector } from '../vector';\nimport type { Workflow } from '../workflows';\nimport { WorkflowEventProcessor } from '../workflows/evented/workflow-event-processor';\nimport type { LegacyWorkflow } from '../workflows/legacy';\nimport { createOnScorerHook } from './hooks';\n\n/**\n * Configuration interface for initializing a Mastra instance.\n *\n * The Config interface defines all the optional components that can be registered\n * with a Mastra instance, including agents, workflows, storage, logging, and more.\n *\n * @template TAgents - Record of agent instances keyed by their names\n * @template TLegacyWorkflows - Record of legacy workflow instances\n * @template TWorkflows - Record of workflow instances\n * @template TVectors - Record of vector store instances\n * @template TTTS - Record of text-to-speech instances\n * @template TLogger - Logger implementation type\n * @template TVNextNetworks - Record of agent network instances\n * @template TMCPServers - Record of MCP server instances\n * @template TScorers - Record of scorer instances\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * name: 'weather-agent',\n * instructions: 'You help with weather information',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new LibSQLStore({ url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport interface Config<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TLegacyWorkflows extends Record<string, LegacyWorkflow> = Record<string, LegacyWorkflow>,\n TWorkflows extends Record<string, Workflow<any, any, any, any, any, any>> = Record<\n string,\n Workflow<any, any, any, any, any, any>\n >,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase> = Record<string, MCPServerBase>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n> {\n /**\n * Agents are autonomous systems that can make decisions and take actions.\n */\n agents?: TAgents;\n\n /**\n * Storage provider for persisting data, conversation history, and workflow state.\n * Required for agent memory and workflow persistence.\n */\n storage?: MastraStorage;\n\n /**\n * Vector stores for semantic search and retrieval-augmented generation (RAG).\n * Used for storing and querying embeddings.\n */\n vectors?: TVectors;\n\n /**\n * Logger implementation for application logging and debugging.\n * Set to `false` to disable logging entirely.\n * @default `INFO` level in development, `WARN` in production.\n */\n logger?: TLogger | false;\n\n /**\n * Legacy workflow definitions for backward compatibility.\n * @deprecated Use `workflows` instead.\n */\n legacy_workflows?: TLegacyWorkflows;\n\n /**\n * Workflows provide type-safe, composable task execution with built-in error handling.\n */\n workflows?: TWorkflows;\n\n /**\n * Text-to-speech providers for voice synthesis capabilities.\n */\n tts?: TTTS;\n\n /**\n * OpenTelemetry configuration for distributed tracing and observability.\n *\n * @deprecated Use {@link observability} instead.\n */\n telemetry?: OtelConfig;\n\n /**\n * AI-specific observability configuration for tracking model interactions.\n */\n observability?: ObservabilityRegistryConfig;\n\n /**\n * Custom ID generator function for creating unique identifiers.\n * @default `crypto.randomUUID()`\n */\n idGenerator?: MastraIdGenerator;\n\n /**\n * Deployment provider for publishing applications to cloud platforms.\n */\n deployer?: MastraDeployer;\n\n /**\n * Server configuration for HTTP endpoints and middleware.\n */\n server?: ServerConfig;\n\n /**\n * MCP servers provide tools and resources that agents can use.\n */\n mcpServers?: TMCPServers;\n\n /**\n * Bundler configuration for packaging and deployment.\n */\n bundler?: BundlerConfig;\n\n /**\n * Pub/sub system for event-driven communication between components.\n * @default EventEmitterPubSub\n */\n pubsub?: PubSub;\n\n /**\n * Scorers help assess the quality of agent responses and workflow outputs.\n */\n scorers?: TScorers;\n\n /**\n * Server middleware functions to be applied to API routes\n * Each middleware can specify a path pattern (defaults to '/api/*')\n * @deprecated use server.middleware instead\n */\n serverMiddleware?: Array<{\n handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;\n path?: string;\n }>;\n\n // @deprecated add memory to your Agent directly instead\n memory?: never;\n\n /**\n * Custom model router gateways for accessing LLM providers.\n * Gateways handle provider-specific authentication, URL construction, and model resolution.\n */\n gateways?: Record<string, MastraModelGateway>;\n\n /**\n * Event handlers for custom application events.\n * Maps event topics to handler functions for event-driven architectures.\n */\n events?: {\n [topic: string]: (\n event: Event,\n cb?: () => Promise<void>,\n ) => Promise<void> | ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n };\n}\n\n@InstrumentClass({\n prefix: 'mastra',\n excludeMethods: ['getLogger', 'getTelemetry'],\n})\n/**\n * The central orchestrator for Mastra applications, managing agents, workflows, storage, logging, telemetry, and more.\n *\n * The `Mastra` class serves as the main entry point and registry for all components in a Mastra application.\n * It coordinates the interaction between agents, workflows, storage systems, and other services.\n\n * @template TAgents - Record of agent instances keyed by their names\n * @template TLegacyWorkflows - Record of legacy workflow instances for backward compatibility\n * @template TWorkflows - Record of modern workflow instances\n * @template TVectors - Record of vector store instances for semantic search and RAG\n * @template TTTS - Record of text-to-speech provider instances\n * @template TLogger - Logger implementation type for application logging\n * @template TVNextNetworks - Record of next-generation agent network instances\n * @template TMCPServers - Record of Model Context Protocol server instances\n * @template TScorers - Record of evaluation scorer instances for measuring AI performance\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * name: 'weather-agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5',\n * tools: [getWeatherTool]\n * })\n * },\n * workflows: { dataWorkflow },\n * storage: new LibSQLStore({ url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport class Mastra<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TLegacyWorkflows extends Record<string, LegacyWorkflow> = Record<string, LegacyWorkflow>,\n TWorkflows extends Record<string, Workflow<any, any, any, any, any, any>> = Record<\n string,\n Workflow<any, any, any, any, any, any>\n >,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase> = Record<string, MCPServerBase>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n> {\n #vectors?: TVectors;\n #agents: TAgents;\n #logger: TLogger;\n #legacy_workflows: TLegacyWorkflows;\n #workflows: TWorkflows;\n #tts?: TTTS;\n #deployer?: MastraDeployer;\n #serverMiddleware: Array<{\n handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;\n path: string;\n }> = [];\n\n /**\n * @deprecated Use {@link getAITracing()} instead.\n */\n #telemetry?: Telemetry;\n #storage?: MastraStorage;\n #memory?: MastraMemory;\n #scorers?: TScorers;\n #server?: ServerConfig;\n #mcpServers?: TMCPServers;\n #bundler?: BundlerConfig;\n #idGenerator?: MastraIdGenerator;\n #pubsub: PubSub;\n #gateways?: Record<string, MastraModelGateway>;\n #events: {\n [topic: string]: ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n } = {};\n #internalMastraWorkflows: Record<string, Workflow> = {};\n // This is only used internally for server handlers that require temporary persistence\n #serverCache: MastraServerCache;\n\n /**\n * @deprecated use {@link getAITracing()} instead\n */\n get telemetry() {\n return this.#telemetry;\n }\n\n /**\n * @deprecated use getStorage() instead\n */\n get storage() {\n return this.#storage;\n }\n\n /**\n * @deprecated use getMemory() instead\n */\n get memory() {\n return this.#memory;\n }\n\n get pubsub() {\n return this.#pubsub;\n }\n\n /**\n * Gets the currently configured ID generator function.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * idGenerator: () => `custom-${Date.now()}`\n * });\n * const generator = mastra.getIdGenerator();\n * console.log(generator?.()); // \"custom-1234567890\"\n * ```\n */\n public getIdGenerator() {\n return this.#idGenerator;\n }\n\n /**\n * Generates a unique identifier using the configured generator or defaults to `crypto.randomUUID()`.\n *\n * This method is used internally by Mastra for creating unique IDs for various entities\n * like workflow runs, agent conversations, and other resources that need unique identification.\n *\n * @throws {MastraError} When the custom ID generator returns an empty string\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const id = mastra.generateId();\n * console.log(id); // \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\n public generateId(): string {\n if (this.#idGenerator) {\n const id = this.#idGenerator();\n if (!id) {\n const error = new MastraError({\n id: 'MASTRA_ID_GENERATOR_RETURNED_EMPTY_STRING',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'ID generator returned an empty string, which is not allowed',\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return id;\n }\n return randomUUID();\n }\n\n /**\n * Sets a custom ID generator function for creating unique identifiers.\n *\n * The ID generator function will be used by `generateId()` instead of the default\n * `crypto.randomUUID()`. This is useful for creating application-specific ID formats\n * or integrating with existing ID generation systems.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * mastra.setIdGenerator(() => `custom-${Date.now()}`);\n * const id = mastra.generateId();\n * console.log(id); // \"custom-1234567890\"\n * ```\n */\n public setIdGenerator(idGenerator: MastraIdGenerator) {\n this.#idGenerator = idGenerator;\n }\n\n /**\n * Creates a new Mastra instance with the provided configuration.\n *\n * The constructor initializes all the components specified in the config, sets up\n * internal systems like logging and telemetry, and registers components with each other.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * name: 'assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\n constructor(config?: Config<TAgents, TLegacyWorkflows, TWorkflows, TVectors, TTTS, TLogger, TMCPServers, TScorers>) {\n // Store server middleware with default path\n if (config?.serverMiddleware) {\n this.#serverMiddleware = config.serverMiddleware.map(m => ({\n handler: m.handler,\n path: m.path || '/api/*',\n }));\n }\n\n /*\n Server Cache\n */\n\n // This is only used internally for server handlers that require temporary persistence\n this.#serverCache = new InMemoryServerCache();\n\n /*\n Events\n */\n if (config?.pubsub) {\n this.#pubsub = config.pubsub;\n } else {\n this.#pubsub = new EventEmitterPubSub();\n }\n\n this.#events = {};\n for (const topic in config?.events ?? {}) {\n if (!Array.isArray(config?.events?.[topic])) {\n this.#events[topic] = [config?.events?.[topic] as any];\n } else {\n this.#events[topic] = config?.events?.[topic] ?? [];\n }\n }\n\n const workflowEventProcessor = new WorkflowEventProcessor({ mastra: this });\n const workflowEventCb = async (event: Event, cb?: () => Promise<void>): Promise<void> => {\n try {\n await workflowEventProcessor.process(event, cb);\n } catch (e) {\n console.error('Error processing event', e);\n }\n };\n if (this.#events.workflows) {\n this.#events.workflows.push(workflowEventCb);\n } else {\n this.#events.workflows = [workflowEventCb];\n }\n\n /*\n Logger\n */\n\n let logger: TLogger;\n if (config?.logger === false) {\n logger = noopLogger as unknown as TLogger;\n } else {\n if (config?.logger) {\n logger = config.logger;\n } else {\n const levelOnEnv =\n process.env.NODE_ENV === 'production' && process.env.MASTRA_DEV !== 'true' ? LogLevel.WARN : LogLevel.INFO;\n logger = new ConsoleLogger({ name: 'Mastra', level: levelOnEnv }) as unknown as TLogger;\n }\n }\n this.#logger = logger;\n\n this.#idGenerator = config?.idGenerator;\n\n let storage = config?.storage;\n\n if (storage) {\n storage = augmentWithInit(storage);\n }\n\n /*\n Telemetry\n */\n\n this.#telemetry = Telemetry.init(config?.telemetry);\n\n // Warn if telemetry is enabled but the instrumentation global is not set\n if (\n config?.telemetry?.enabled !== false &&\n typeof globalThis !== 'undefined' &&\n (globalThis as any).___MASTRA_TELEMETRY___ !== true\n ) {\n this.#logger?.warn(\n `Mastra telemetry is enabled, but the required instrumentation file was not loaded. ` +\n `If you are using Mastra outside of the mastra server environment, see: https://mastra.ai/en/docs/observability/tracing#tracing-outside-mastra-server-environment`,\n `If you are using a custom instrumentation file or want to disable this warning, set the globalThis.___MASTRA_TELEMETRY___ variable to true in your instrumentation file.`,\n );\n }\n\n if (config?.telemetry?.enabled !== false) {\n this.#logger?.warn(\n `Mastra telemetry is deprecated and will be removed on the Nov 4th release. Instead use AI Tracing. ` +\n `More info can be found here: https://github.com/mastra-ai/mastra/issues/8577 and here: https://mastra.ai/en/docs/observability/ai-tracing/overview`,\n );\n }\n\n /*\n AI Tracing\n */\n\n if (config?.observability) {\n setupAITracing(config.observability);\n }\n\n /*\n Storage\n */\n if (this.#telemetry && storage) {\n this.#storage = this.#telemetry.traceClass(storage, {\n excludeMethods: ['__setTelemetry', '__getTelemetry', 'batchTraceInsert', 'getTraces', 'getEvalsByAgentName'],\n });\n this.#storage.__setTelemetry(this.#telemetry);\n } else {\n this.#storage = storage;\n }\n\n // Initialize gateways\n this.#gateways = config?.gateways;\n if (config?.gateways) {\n this.#syncGatewayRegistry();\n }\n\n /*\n Vectors\n */\n if (config?.vectors) {\n let vectors: Record<string, MastraVector> = {};\n Object.entries(config.vectors).forEach(([key, vector]) => {\n if (this.#telemetry) {\n vectors[key] = this.#telemetry.traceClass(vector, {\n excludeMethods: ['__setTelemetry', '__getTelemetry'],\n });\n vectors[key].__setTelemetry(this.#telemetry);\n } else {\n vectors[key] = vector;\n }\n });\n\n this.#vectors = vectors as TVectors;\n }\n\n if (config?.mcpServers) {\n this.#mcpServers = config.mcpServers;\n\n // Set logger/telemetry/Mastra instance/id for MCP servers\n Object.entries(this.#mcpServers).forEach(([key, server]) => {\n server.setId(key);\n if (this.#telemetry) {\n server.__setTelemetry(this.#telemetry);\n }\n\n server.__registerMastra(this);\n server.__setLogger(this.getLogger());\n });\n }\n\n if (config && `memory` in config) {\n const error = new MastraError({\n id: 'MASTRA_CONSTRUCTOR_INVALID_MEMORY_CONFIG',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `\n Memory should be added to Agents, not to Mastra.\n\nInstead of:\n new Mastra({ memory: new Memory() })\n\ndo:\n new Agent({ memory: new Memory() })\n`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (config?.tts) {\n this.#tts = config.tts;\n Object.entries(this.#tts).forEach(([key, ttsCl]) => {\n if (this.#tts?.[key]) {\n if (this.#telemetry) {\n // @ts-ignore\n this.#tts[key] = this.#telemetry.traceClass(ttsCl, {\n excludeMethods: ['__setTelemetry', '__getTelemetry'],\n });\n this.#tts[key].__setTelemetry(this.#telemetry);\n }\n }\n });\n }\n\n /*\n Agents\n */\n const agents: Record<string, Agent> = {};\n if (config?.agents) {\n Object.entries(config.agents).forEach(([key, agent]) => {\n if (agents[key]) {\n const error = new MastraError({\n id: 'MASTRA_AGENT_REGISTRATION_DUPLICATE_ID',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with name ID:${key} already exists`,\n details: {\n agentId: key,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n agent.__registerMastra(this);\n\n agent.__registerPrimitives({\n logger: this.getLogger(),\n telemetry: this.#telemetry,\n storage: this.storage,\n memory: this.memory,\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n\n agents[key] = agent;\n });\n }\n\n this.#agents = agents as TAgents;\n\n /**\n * Scorers\n */\n\n const scorers = {} as Record<string, MastraScorer<any, any, any, any>>;\n if (config?.scorers) {\n Object.entries(config.scorers).forEach(([key, scorer]) => {\n scorers[key] = scorer;\n });\n }\n this.#scorers = scorers as TScorers;\n\n /*\n Legacy Workflows\n */\n this.#legacy_workflows = {} as TLegacyWorkflows;\n\n if (config?.legacy_workflows) {\n Object.entries(config.legacy_workflows).forEach(([key, workflow]) => {\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n telemetry: this.#telemetry,\n storage: this.storage,\n memory: this.memory,\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n // @ts-ignore\n this.#legacy_workflows[key] = workflow;\n\n const workflowSteps = Object.values(workflow.steps).filter(step => !!step.workflowId && !!step.workflow);\n if (workflowSteps.length > 0) {\n workflowSteps.forEach(step => {\n // @ts-ignore\n this.#legacy_workflows[step.workflowId] = step.workflow;\n });\n }\n });\n }\n\n this.#workflows = {} as TWorkflows;\n if (config?.workflows) {\n Object.entries(config.workflows).forEach(([key, workflow]) => {\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n telemetry: this.#telemetry,\n storage: this.storage,\n memory: this.memory,\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n if (!workflow.committed) {\n workflow.commit();\n }\n // @ts-ignore\n this.#workflows[key] = workflow;\n });\n }\n\n if (config?.server) {\n this.#server = config.server;\n }\n\n registerHook(AvailableHooks.ON_SCORER_RUN, createOnScorerHook(this));\n\n /*\n Register Mastra instance with AI tracing exporters and initialize them\n */\n if (config?.observability) {\n this.registerAITracingExporters();\n this.initAITracingExporters();\n }\n\n this.setLogger({ logger });\n }\n\n /**\n * Register this Mastra instance with AI tracing exporters that need it\n */\n private registerAITracingExporters(): void {\n const allTracingInstances = getAllAITracing();\n allTracingInstances.forEach(tracing => {\n const exporters = tracing.getExporters();\n exporters.forEach(exporter => {\n // Check if exporter has __registerMastra method\n if ('__registerMastra' in exporter && typeof (exporter as any).__registerMastra === 'function') {\n (exporter as any).__registerMastra(this);\n }\n });\n });\n }\n\n /**\n * Initialize all AI tracing exporters after registration is complete\n */\n private initAITracingExporters(): void {\n const allTracingInstances = getAllAITracing();\n\n allTracingInstances.forEach(tracing => {\n const config = tracing.getConfig();\n const exporters = tracing.getExporters();\n exporters.forEach(exporter => {\n // Initialize exporter if it has an init method\n if ('init' in exporter && typeof exporter.init === 'function') {\n try {\n exporter.init(config);\n } catch (error) {\n this.#logger?.warn('Failed to initialize AI tracing exporter', {\n exporterName: exporter.name,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n });\n });\n }\n\n /**\n * Retrieves a registered agent by its name.\n *\n * @template TAgentName - The specific agent name type from the registered agents\n * @throws {MastraError} When the agent with the specified name is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * name: 'weather-agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n * const agent = mastra.getAgent('weatherAgent');\n * const response = await agent.generate('What is the weather?');\n * ```\n */\n public getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName] {\n const agent = this.#agents?.[name];\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with name ${String(name)} not found`,\n details: {\n status: 404,\n agentName: String(name),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#agents[name];\n }\n\n /**\n * Retrieves a registered agent by its unique ID.\n *\n * This method searches for an agent using its internal ID property. If no agent\n * is found with the given ID, it also attempts to find an agent using the ID as\n * a name (for backward compatibility).\n *\n * @throws {MastraError} When no agent is found with the specified ID\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * name: 'assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * const assistant = mastra.getAgent('assistant');\n * const sameAgent = mastra.getAgentById(assistant.id);\n * ```\n */\n public getAgentById(id: string): Agent {\n let agent = Object.values(this.#agents).find(a => a.id === id);\n\n if (!agent) {\n try {\n agent = this.getAgent(id as any);\n } catch {\n // do nothing\n }\n }\n\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_AGENT_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with id ${String(id)} not found`,\n details: {\n status: 404,\n agentId: String(id),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return agent;\n }\n\n /**\n * Returns all registered agents as a record keyed by their names.\n *\n * This method provides access to the complete registry of agents, allowing you to\n * iterate over them, check what agents are available, or perform bulk operations.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({ name: 'weather', model: openai('gpt-4o') }),\n * supportAgent: new Agent({ name: 'support', model: openai('gpt-4o') })\n * }\n * });\n *\n * const allAgents = mastra.getAgents();\n * console.log(Object.keys(allAgents)); // ['weatherAgent', 'supportAgent']\n * ```\n */\n public getAgents() {\n return this.#agents;\n }\n\n /**\n * Retrieves a registered vector store by its name.\n *\n * @template TVectorName - The specific vector store name type from the registered vectors\n * @throws {MastraError} When the vector store with the specified name is not found\n *\n * @example Using a vector store for semantic search\n * ```typescript\n * import { PineconeVector } from '@mastra/pinecone';\n * import { OpenAIEmbedder } from '@mastra/embedders';\n *\n * const mastra = new Mastra({\n * vectors: {\n * knowledge: new PineconeVector({\n * apiKey: process.env.PINECONE_API_KEY,\n * indexName: 'knowledge-base',\n * embedder: new OpenAIEmbedder({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'text-embedding-3-small'\n * })\n * }),\n * products: new PineconeVector({\n * apiKey: process.env.PINECONE_API_KEY,\n * indexName: 'product-catalog'\n * })\n * }\n * });\n *\n * // Get a vector store and perform semantic search\n * const knowledgeBase = mastra.getVector('knowledge');\n * const results = await knowledgeBase.query({\n * query: 'How to reset password?',\n * topK: 5\n * });\n *\n * console.log('Relevant documents:', results);\n * ```\n */\n public getVector<TVectorName extends keyof TVectors>(name: TVectorName): TVectors[TVectorName] {\n const vector = this.#vectors?.[name];\n if (!vector) {\n const error = new MastraError({\n id: 'MASTRA_GET_VECTOR_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Vector with name ${String(name)} not found`,\n details: {\n status: 404,\n vectorName: String(name),\n vectors: Object.keys(this.#vectors ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return vector;\n }\n\n /**\n * Returns all registered vector stores as a record keyed by their names.\n *\n * @example Listing all vector stores\n * ```typescript\n * const mastra = new Mastra({\n * vectors: {\n * documents: new PineconeVector({ indexName: 'docs' }),\n * images: new PineconeVector({ indexName: 'images' }),\n * products: new ChromaVector({ collectionName: 'products' })\n * }\n * });\n *\n * const allVectors = mastra.getVectors();\n * console.log(Object.keys(allVectors)); // ['documents', 'images', 'products']\n *\n * // Check vector store types and configurations\n * for (const [name, vectorStore] of Object.entries(allVectors)) {\n * console.log(`Vector store ${name}:`, vectorStore.constructor.name);\n * }\n * ```\n */\n public getVectors() {\n return this.#vectors;\n }\n\n /**\n * Gets the currently configured deployment provider.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * deployer: new VercelDeployer({\n * token: process.env.VERCEL_TOKEN,\n * projectId: process.env.VERCEL_PROJECT_ID\n * })\n * });\n *\n * const deployer = mastra.getDeployer();\n * if (deployer) {\n * await deployer.deploy({\n * name: 'my-mastra-app',\n * environment: 'production'\n * });\n * }\n * ```\n */\n public getDeployer() {\n return this.#deployer;\n }\n\n /**\n * Retrieves a registered legacy workflow by its ID.\n *\n * Legacy workflows are the previous generation of workflow system in Mastra,\n * maintained for backward compatibility. For new implementations, use the\n * modern workflow system accessed via `getWorkflow()`.\n *\n * @template TWorkflowId - The specific workflow ID type from the registered legacy workflows\n * @throws {MastraError} When the legacy workflow with the specified ID is not found\n * @deprecated Use `getWorkflow()` for new implementations\n *\n * @example Getting a legacy workflow\n * ```typescript\n * const mastra = new Mastra({\n * legacy_workflows: {\n * oldDataFlow: legacyWorkflowInstance\n * }\n * });\n *\n * const workflow = mastra.legacy_getWorkflow('oldDataFlow');\n * const result = await workflow.execute({ input: 'data' });\n * ```\n */\n public legacy_getWorkflow<TWorkflowId extends keyof TLegacyWorkflows>(\n id: TWorkflowId,\n { serialized }: { serialized?: boolean } = {},\n ): TLegacyWorkflows[TWorkflowId] {\n const workflow = this.#legacy_workflows?.[id];\n if (!workflow) {\n const error = new MastraError({\n id: 'MASTRA_GET_LEGACY_WORKFLOW_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Workflow with ID ${String(id)} not found`,\n details: {\n status: 404,\n workflowId: String(id),\n workflows: Object.keys(this.#legacy_workflows ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (serialized) {\n return { name: workflow.name } as TLegacyWorkflows[TWorkflowId];\n }\n\n return workflow;\n }\n\n /**\n * Retrieves a registered workflow by its ID.\n *\n * @template TWorkflowId - The specific workflow ID type from the registered workflows\n * @throws {MastraError} When the workflow with the specified ID is not found\n *\n * @example Getting and executing a workflow\n * ```typescript\n * import { createWorkflow, createStep } from '@mastra/core/workflows';\n * import { z } from 'zod';\n *\n * const processDataWorkflow = createWorkflow({\n * name: 'process-data',\n * triggerSchema: z.object({ input: z.string() })\n * })\n * .then(validateStep)\n * .then(transformStep)\n * .then(saveStep)\n * .commit();\n *\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: processDataWorkflow\n * }\n * });\n * ```\n */\n public getWorkflow<TWorkflowId extends keyof TWorkflows>(\n id: TWorkflowId,\n { serialized }: { serialized?: boolean } = {},\n ): TWorkflows[TWorkflowId] {\n const workflow = this.#workflows?.[id];\n if (!workflow) {\n const error = new MastraError({\n id: 'MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Workflow with ID ${String(id)} not found`,\n details: {\n status: 404,\n workflowId: String(id),\n workflows: Object.keys(this.#workflows ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (serialized) {\n return { name: workflow.name } as TWorkflows[TWorkflowId];\n }\n\n return workflow;\n }\n\n __registerInternalWorkflow(workflow: Workflow) {\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.storage,\n });\n this.#internalMastraWorkflows[workflow.id] = workflow;\n }\n\n __hasInternalWorkflow(id: string): boolean {\n return Object.values(this.#internalMastraWorkflows).some(workflow => workflow.id === id);\n }\n\n __getInternalWorkflow(id: string): Workflow {\n const workflow = Object.values(this.#internalMastraWorkflows).find(a => a.id === id);\n if (!workflow) {\n throw new MastraError({\n id: 'MASTRA_GET_INTERNAL_WORKFLOW_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: `Workflow with id ${String(id)} not found`,\n details: {\n status: 404,\n workflowId: String(id),\n },\n });\n }\n\n return workflow;\n }\n\n /**\n * Retrieves a registered workflow by its unique ID.\n *\n * This method searches for a workflow using its internal ID property. If no workflow\n * is found with the given ID, it also attempts to find a workflow using the ID as\n * a name (for backward compatibility).\n *\n * @throws {MastraError} When no workflow is found with the specified ID\n *\n * @example Finding a workflow by ID\n * ```typescript\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: createWorkflow({\n * name: 'process-data',\n * triggerSchema: z.object({ input: z.string() })\n * }).commit()\n * }\n * });\n *\n * // Get the workflow's ID\n * const workflow = mastra.getWorkflow('dataProcessor');\n * const workflowId = workflow.id;\n *\n * // Later, retrieve the workflow by ID\n * const sameWorkflow = mastra.getWorkflowById(workflowId);\n * console.log(sameWorkflow.name); // \"process-data\"\n * ```\n */\n public getWorkflowById(id: string): Workflow {\n let workflow = Object.values(this.#workflows).find(a => a.id === id);\n\n if (!workflow) {\n try {\n workflow = this.getWorkflow(id as any);\n } catch {\n // do nothing\n }\n }\n\n if (!workflow) {\n const error = new MastraError({\n id: 'MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Workflow with id ${String(id)} not found`,\n details: {\n status: 404,\n workflowId: String(id),\n workflows: Object.keys(this.#workflows ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return workflow;\n }\n\n public async listActiveWorkflowRuns(): Promise<WorkflowRuns> {\n const storage = this.#storage;\n if (!storage) {\n this.#logger.debug('Cannot get active workflow runs. Mastra storage is not initialized');\n return { runs: [], total: 0 };\n }\n\n // Get all workflows with default engine type\n const defaultEngineWorkflows = Object.values(this.#workflows).filter(workflow => workflow.engineType === 'default');\n\n // Collect all active runs for workflows with default engine type\n const allRuns: WorkflowRuns['runs'] = [];\n let allTotal = 0;\n\n for (const workflow of defaultEngineWorkflows) {\n const runningRuns = await workflow.getWorkflowRuns({ status: 'running' });\n const waitingRuns = await workflow.getWorkflowRuns({ status: 'waiting' });\n\n allRuns.push(...runningRuns.runs, ...waitingRuns.runs);\n allTotal += runningRuns.total + waitingRuns.total;\n }\n\n return {\n runs: allRuns,\n total: allTotal,\n };\n }\n\n public async restartAllActiveWorkflowRuns(): Promise<void> {\n const activeRuns = await this.listActiveWorkflowRuns();\n if (activeRuns.runs.length > 0) {\n this.#logger.debug(\n `Restarting ${activeRuns.runs.length} active workflow run${activeRuns.runs.length > 1 ? 's' : ''}`,\n );\n }\n for (const runSnapshot of activeRuns.runs) {\n const workflow = this.getWorkflowById(runSnapshot.workflowName);\n try {\n const run = await workflow.createRunAsync({ runId: runSnapshot.runId });\n await run.restart();\n this.#logger.debug(`Restarted ${runSnapshot.workflowName} workflow run ${runSnapshot.runId}`);\n } catch (error) {\n this.#logger.error(`Failed to restart ${runSnapshot.workflowName} workflow run ${runSnapshot.runId}: ${error}`);\n }\n }\n }\n\n /**\n * Returns all registered legacy workflows as a record keyed by their IDs.\n *\n * Legacy workflows are the previous generation of workflow system in Mastra,\n * maintained for backward compatibility. For new implementations, use `getWorkflows()`.\n *\n * @deprecated Use `getWorkflows()` for new implementations\n *\n * @example Listing all legacy workflows\n * ```typescript\n * const mastra = new Mastra({\n * legacy_workflows: {\n * oldFlow1: legacyWorkflow1,\n * oldFlow2: legacyWorkflow2\n * }\n * });\n *\n * const allLegacyWorkflows = mastra.legacy_getWorkflows();\n * console.log(Object.keys(allLegacyWorkflows)); // ['oldFlow1', 'oldFlow2']\n *\n * // Execute all legacy workflows\n * for (const [id, workflow] of Object.entries(allLegacyWorkflows)) {\n * console.log(`Legacy workflow ${id}:`, workflow.name);\n * }\n * ```\n */\n public legacy_getWorkflows(props: { serialized?: boolean } = {}): Record<string, LegacyWorkflow> {\n if (props.serialized) {\n return Object.entries(this.#legacy_workflows).reduce((acc, [k, v]) => {\n return {\n ...acc,\n [k]: { name: v.name },\n };\n }, {});\n }\n return this.#legacy_workflows;\n }\n\n /**\n * Returns all registered scorers as a record keyed by their IDs.\n *\n * @example Listing all scorers\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer, RelevanceScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer(),\n * accuracy: new AccuracyScorer(),\n * relevance: new RelevanceScorer()\n * }\n * });\n *\n * const allScorers = mastra.getScorers();\n * console.log(Object.keys(allScorers)); // ['helpfulness', 'accuracy', 'relevance']\n *\n * // Check scorer configurations\n * for (const [id, scorer] of Object.entries(allScorers)) {\n * console.log(`Scorer ${id}:`, scorer.name, scorer.description);\n * }\n * ```\n */\n public getScorers() {\n return this.#scorers;\n }\n\n /**\n * Retrieves a registered scorer by its key.\n *\n * @template TScorerKey - The specific scorer key type from the registered scorers\n * @throws {MastraError} When the scorer with the specified key is not found\n *\n * @example Getting and using a scorer\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer({\n * model: openai('gpt-4o'),\n * criteria: 'Rate how helpful this response is'\n * }),\n * accuracy: new AccuracyScorer({\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Get a specific scorer\n * const helpfulnessScorer = mastra.getScorer('helpfulness');\n * const score = await helpfulnessScorer.score({\n * input: 'How do I reset my password?',\n * output: 'You can reset your password by clicking the forgot password link.',\n * expected: 'Detailed password reset instructions'\n * });\n *\n * console.log('Helpfulness score:', score);\n * ```\n */\n public getScorer<TScorerKey extends keyof TScorers>(key: TScorerKey): TScorers[TScorerKey] {\n const scorer = this.#scorers?.[key];\n if (!scorer) {\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with ${String(key)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return scorer;\n }\n\n /**\n * Retrieves a registered scorer by its name.\n *\n * This method searches through all registered scorers to find one with the specified name.\n * Unlike `getScorer()` which uses the registration key, this method uses the scorer's\n * internal name property.\n *\n * @throws {MastraError} When no scorer is found with the specified name\n *\n * @example Finding a scorer by name\n * ```typescript\n * import { HelpfulnessScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * myHelpfulnessScorer: new HelpfulnessScorer({\n * name: 'helpfulness-evaluator',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Find scorer by its internal name, not the registration key\n * const scorer = mastra.getScorerByName('helpfulness-evaluator');\n * const score = await scorer.score({\n * input: 'question',\n * output: 'answer'\n * });\n * ```\n */\n public getScorerByName(name: string): MastraScorer<any, any, any, any> {\n for (const [_key, value] of Object.entries(this.#scorers ?? {})) {\n if (value.name === name) {\n return value;\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with name ${String(name)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Returns all registered workflows as a record keyed by their IDs.\n *\n * @example Listing all workflows\n * ```typescript\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: createWorkflow({...}).commit(),\n * emailSender: createWorkflow({...}).commit(),\n * reportGenerator: createWorkflow({...}).commit()\n * }\n * });\n *\n * const allWorkflows = mastra.getWorkflows();\n * console.log(Object.keys(allWorkflows)); // ['dataProcessor', 'emailSender', 'reportGenerator']\n *\n * // Execute all workflows with sample data\n * for (const [id, workflow] of Object.entries(allWorkflows)) {\n * console.log(`Workflow ${id}:`, workflow.name);\n * // const result = await workflow.execute(sampleData);\n * }\n * ```\n */\n public getWorkflows(props: { serialized?: boolean } = {}): Record<string, Workflow> {\n if (props.serialized) {\n return Object.entries(this.#workflows).reduce((acc, [k, v]) => {\n return {\n ...acc,\n [k]: { name: v.name },\n };\n }, {});\n }\n return this.#workflows;\n }\n\n /**\n * Sets the storage provider for the Mastra instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n *\n * // Set PostgreSQL storage\n * mastra.setStorage(new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }));\n *\n * // Now agents can use memory with the storage\n * const agent = new Agent({\n * name: 'assistant',\n * memory: new Memory({ storage: mastra.getStorage() })\n * });\n * ```\n */\n public setStorage(storage: MastraStorage) {\n this.#storage = augmentWithInit(storage);\n }\n\n public setLogger({ logger }: { logger: TLogger }) {\n this.#logger = logger;\n\n if (this.#agents) {\n Object.keys(this.#agents).forEach(key => {\n this.#agents?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#memory) {\n this.#memory.__setLogger(this.#logger);\n }\n\n if (this.#deployer) {\n this.#deployer.__setLogger(this.#logger);\n }\n\n if (this.#tts) {\n Object.keys(this.#tts).forEach(key => {\n this.#tts?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#storage) {\n this.#storage.__setLogger(this.#logger);\n }\n\n if (this.#vectors) {\n Object.keys(this.#vectors).forEach(key => {\n this.#vectors?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#mcpServers) {\n Object.keys(this.#mcpServers).forEach(key => {\n this.#mcpServers?.[key]?.__setLogger(this.#logger);\n });\n }\n\n // Set logger for AI tracing instances\n const allTracingInstances = getAllAITracing();\n allTracingInstances.forEach(instance => {\n instance.__setLogger(this.#logger);\n });\n }\n\n public setTelemetry(telemetry: OtelConfig) {\n this.#telemetry = Telemetry.init(telemetry);\n\n if (this.#agents) {\n Object.keys(this.#agents).forEach(key => {\n if (this.#telemetry) {\n this.#agents?.[key]?.__setTelemetry(this.#telemetry);\n }\n });\n }\n\n if (this.#memory) {\n this.#memory = this.#telemetry.traceClass(this.#memory, {\n excludeMethods: ['__setTelemetry', '__getTelemetry'],\n });\n this.#memory.__setTelemetry(this.#telemetry);\n }\n\n if (this.#deployer) {\n this.#deployer = this.#telemetry.traceClass(this.#deployer, {\n excludeMethods: ['__setTelemetry', '__getTelemetry'],\n });\n this.#deployer.__setTelemetry(this.#telemetry);\n }\n\n if (this.#tts) {\n let tts = {} as Record<string, MastraTTS>;\n Object.entries(this.#tts).forEach(([key, ttsCl]) => {\n if (this.#telemetry) {\n tts[key] = this.#telemetry.traceClass(ttsCl, {\n excludeMethods: ['__setTelemetry', '__getTelemetry'],\n });\n tts[key].__setTelemetry(this.#telemetry);\n }\n });\n this.#tts = tts as TTTS;\n }\n\n if (this.#storage) {\n this.#storage = this.#telemetry.traceClass(this.#storage, {\n excludeMethods: ['__setTelemetry', '__getTelemetry'],\n });\n this.#storage.__setTelemetry(this.#telemetry);\n }\n\n if (this.#vectors) {\n let vectors = {} as Record<string, MastraVector>;\n Object.entries(this.#vectors).forEach(([key, vector]) => {\n if (this.#telemetry) {\n vectors[key] = this.#telemetry.traceClass(vector, {\n excludeMethods: ['__setTelemetry', '__getTelemetry'],\n });\n vectors[key].__setTelemetry(this.#telemetry);\n }\n });\n this.#vectors = vectors as TVectors;\n }\n }\n\n /**\n * Gets all registered text-to-speech (TTS) providers.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tts: {\n * openai: new OpenAITTS({\n * apiKey: process.env.OPENAI_API_KEY,\n * voice: 'alloy'\n * })\n * }\n * });\n *\n * const ttsProviders = mastra.getTTS();\n * const openaiTTS = ttsProviders?.openai;\n * if (openaiTTS) {\n * const audioBuffer = await openaiTTS.synthesize('Hello, world!');\n * }\n * ```\n */\n public getTTS() {\n return this.#tts;\n }\n\n /**\n * Gets the currently configured logger instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * logger: new PinoLogger({\n * name: 'MyApp',\n * level: 'info'\n * })\n * });\n *\n * const logger = mastra.getLogger();\n * logger.info('Application started');\n * logger.error('An error occurred', { error: 'details' });\n * ```\n */\n public getLogger() {\n return this.#logger;\n }\n\n /**\n * Gets the currently configured telemetry instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * telemetry: {\n * enabled: true,\n * serviceName: 'my-mastra-app'\n * }\n * });\n *\n * const telemetry = mastra.getTelemetry();\n * if (telemetry) {\n * const span = telemetry.startSpan('custom-operation');\n * span.setAttributes({ operation: 'data-processing' });\n * span.end();\n * }\n * ```\n *\n * @deprecated use {@link getAITracing()} instead\n */\n public getTelemetry() {\n return this.#telemetry;\n }\n\n /**\n * Gets the currently configured memory instance.\n *\n * @deprecated Memory should be configured directly on agents instead of on the Mastra instance.\n * Use `new Agent({ memory: new Memory() })` instead.\n *\n * @example Legacy memory usage (deprecated)\n * ```typescript\n * // This approach is deprecated\n * const mastra = new Mastra({\n * // memory: new Memory() // This is no longer supported\n * });\n *\n * // Use this instead:\n * const agent = new Agent({\n * name: 'assistant',\n * memory: new Memory({\n * storage: new LibSQLStore({ url: ':memory:' })\n * })\n * });\n * ```\n */\n public getMemory() {\n return this.#memory;\n }\n\n /**\n * Gets the currently configured storage provider.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * storage: new LibSQLStore({ url: 'file:./data.db' })\n * });\n *\n * // Use the storage in agent memory\n * const agent = new Agent({\n * name: 'assistant',\n * memory: new Memory({\n * storage: mastra.getStorage()\n * })\n * });\n * ```\n */\n public getStorage() {\n return this.#storage;\n }\n\n public getServerMiddleware() {\n return this.#serverMiddleware;\n }\n\n public getServerCache() {\n return this.#serverCache;\n }\n\n public setServerMiddleware(serverMiddleware: Middleware | Middleware[]) {\n if (typeof serverMiddleware === 'function') {\n this.#serverMiddleware = [\n {\n handler: serverMiddleware,\n path: '/api/*',\n },\n ];\n return;\n }\n\n if (!Array.isArray(serverMiddleware)) {\n const error = new MastraError({\n id: 'MASTRA_SET_SERVER_MIDDLEWARE_INVALID_TYPE',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Invalid middleware: expected a function or array, received ${typeof serverMiddleware}`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n this.#serverMiddleware = serverMiddleware.map(m => {\n if (typeof m === 'function') {\n return {\n handler: m,\n path: '/api/*',\n };\n }\n return {\n handler: m.handler,\n path: m.path || '/api/*',\n };\n });\n }\n\n public getServer() {\n return this.#server;\n }\n\n public getBundlerConfig() {\n return this.#bundler;\n }\n\n public async getLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n transportId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_BY_RUN_ID_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger?.getLogsByRunId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_BY_RUN_ID_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not configured or does not support getLogsByRunId operation',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return await this.#logger.getLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n });\n }\n\n public async getLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not set',\n details: {\n transportId,\n },\n });\n throw error;\n }\n\n return await this.#logger.getLogs(transportId, params);\n }\n\n /**\n * Gets all registered Model Context Protocol (MCP) server instances.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const mcpServers = mastra.getMCPServers();\n * if (mcpServers) {\n * const fsServer = mcpServers.filesystem;\n * const tools = await fsServer.getTools();\n * }\n * ```\n */\n public getMCPServers(): Record<string, MCPServerBase> | undefined {\n return this.#mcpServers;\n }\n\n /**\n * Retrieves a specific Model Context Protocol (MCP) server instance by its logical ID.\n *\n * This method searches for an MCP server using its logical ID. If a version is specified,\n * it returns the exact version match. If no version is provided, it returns the server\n * with the most recent release date.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * id: 'fs-server',\n * version: '1.0.0',\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const fsServer = mastra.getMCPServer('fs-server');\n * if (fsServer) {\n * const tools = await fsServer.getTools();\n * }\n * ```\n */\n public getMCPServer(serverId: string, version?: string): MCPServerBase | undefined {\n if (!this.#mcpServers) {\n return undefined;\n }\n\n const allRegisteredServers = Object.values(this.#mcpServers || {});\n\n const matchingLogicalIdServers = allRegisteredServers.filter(server => server.id === serverId);\n\n if (matchingLogicalIdServers.length === 0) {\n this.#logger?.debug(`No MCP servers found with logical ID: ${serverId}`);\n return undefined;\n }\n\n if (version) {\n const specificVersionServer = matchingLogicalIdServers.find(server => server.version === version);\n if (!specificVersionServer) {\n this.#logger?.debug(`MCP server with logical ID '${serverId}' found, but not version '${version}'.`);\n }\n return specificVersionServer;\n } else {\n // No version specified, find the one with the most recent releaseDate\n if (matchingLogicalIdServers.length === 1) {\n return matchingLogicalIdServers[0];\n }\n\n matchingLogicalIdServers.sort((a, b) => {\n // Ensure releaseDate exists and is a string before creating a Date object\n const dateAVal = a.releaseDate && typeof a.releaseDate === 'string' ? new Date(a.releaseDate).getTime() : NaN;\n const dateBVal = b.releaseDate && typeof b.releaseDate === 'string' ? new Date(b.releaseDate).getTime() : NaN;\n\n if (isNaN(dateAVal) && isNaN(dateBVal)) return 0;\n if (isNaN(dateAVal)) return 1; // Treat invalid/missing dates as older\n if (isNaN(dateBVal)) return -1; // Treat invalid/missing dates as older\n\n return dateBVal - dateAVal; // Sorts in descending order of time (latest first)\n });\n\n // After sorting, the first element should be the latest if its date is valid\n if (matchingLogicalIdServers.length > 0) {\n const latestServer = matchingLogicalIdServers[0];\n if (\n latestServer &&\n latestServer.releaseDate &&\n typeof latestServer.releaseDate === 'string' &&\n !isNaN(new Date(latestServer.releaseDate).getTime())\n ) {\n return latestServer;\n }\n }\n this.#logger?.warn(\n `Could not determine the latest server for logical ID '${serverId}' due to invalid or missing release dates, or no servers left after filtering.`,\n );\n return undefined;\n }\n }\n\n public async addTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.subscribe(topic, listener);\n }\n\n public async removeTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.unsubscribe(topic, listener);\n }\n\n public async startEventEngine() {\n for (const topic in this.#events) {\n if (!this.#events[topic]) {\n continue;\n }\n\n const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];\n for (const listener of listeners) {\n await this.#pubsub.subscribe(topic, listener);\n }\n }\n }\n\n public async stopEventEngine() {\n for (const topic in this.#events) {\n if (!this.#events[topic]) {\n continue;\n }\n\n const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];\n for (const listener of listeners) {\n await this.#pubsub.unsubscribe(topic, listener);\n }\n }\n\n await this.#pubsub.flush();\n }\n\n /**\n * Returns all registered gateways as a record keyed by their names.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * gateways: {\n * netlify: new NetlifyGateway(),\n * custom: new CustomGateway()\n * }\n * });\n *\n * const allGateways = mastra.listGateways();\n * console.log(Object.keys(allGateways)); // ['netlify', 'custom']\n * ```\n */\n public listGateways(): Record<string, MastraModelGateway> | undefined {\n return this.#gateways;\n }\n\n /**\n * Sync custom gateways with the GatewayRegistry for type generation\n * @private\n */\n #syncGatewayRegistry(): void {\n try {\n // Only sync in dev mode (when MASTRA_DEV is set)\n if (process.env.MASTRA_DEV !== 'true' && process.env.MASTRA_DEV !== '1') {\n return;\n }\n\n // Trigger sync immediately (non-blocking, but logs progress)\n import('../llm/model/provider-registry.js')\n .then(async ({ GatewayRegistry }) => {\n const registry = GatewayRegistry.getInstance();\n const customGateways = Object.values(this.#gateways || {});\n registry.registerCustomGateways(customGateways);\n\n // Log that we're syncing\n const logger = this.getLogger();\n logger.info('🔄 Syncing custom gateway types...');\n\n // Trigger a sync to regenerate types\n await registry.syncGateways(true);\n\n logger.info('✅ Custom gateway types synced! Restart your TypeScript server to see autocomplete.');\n })\n .catch(err => {\n const logger = this.getLogger();\n logger.debug('Gateway registry sync skipped:', err);\n });\n } catch (err) {\n // Silent fail - this is a dev-only feature\n const logger = this.getLogger();\n logger.debug('Gateway registry sync failed:', err);\n }\n }\n\n /**\n * Gracefully shuts down the Mastra instance and cleans up all resources.\n *\n * This method performs a clean shutdown of all Mastra components, including:\n * - AI tracing registry and all tracing instances\n * - Event engine and pub/sub system\n * - All registered components and their resources\n *\n * It's important to call this method when your application is shutting down\n * to ensure proper cleanup and prevent resource leaks.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: { myAgent },\n * workflows: { myWorkflow }\n * });\n *\n * // Graceful shutdown on SIGINT\n * process.on('SIGINT', async () => {\n * await mastra.shutdown();\n * process.exit(0);\n * });\n * ```\n */\n async shutdown(): Promise<void> {\n // Shutdown AI tracing registry and all instances\n await shutdownAITracingRegistry();\n await this.stopEventEngine();\n\n this.#logger?.info('Mastra shutdown completed');\n }\n\n // This method is only used internally for server hnadlers that require temporary persistence\n public get serverCache() {\n return this.#serverCache;\n }\n}\n","import EventEmitter from 'events';\nimport { PubSub } from './pubsub';\nimport type { Event } from './types';\n\nexport class EventEmitterPubSub extends PubSub {\n private emitter: EventEmitter;\n\n constructor() {\n super();\n this.emitter = new EventEmitter();\n }\n\n async publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>): Promise<void> {\n const id = crypto.randomUUID();\n const createdAt = new Date();\n this.emitter.emit(topic, {\n ...event,\n id,\n createdAt,\n });\n }\n\n async subscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n this.emitter.on(topic, cb);\n }\n\n async unsubscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n this.emitter.off(topic, cb);\n }\n\n async flush(): Promise<void> {\n // no-op\n }\n}\n","import pMap from 'p-map';\nimport type { Mastra } from '..';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport { saveScorePayloadSchema } from '../scores';\nimport type { ScoringHookInput } from '../scores/types';\nimport type { MastraStorage } from '../storage';\n\nexport function createOnScorerHook(mastra: Mastra) {\n return async (hookData: ScoringHookInput) => {\n const storage = mastra.getStorage();\n\n if (!storage) {\n mastra.getLogger()?.warn('Storage not found, skipping score validation and saving');\n return;\n }\n\n const entityId = hookData.entity.id;\n const entityType = hookData.entityType;\n const scorer = hookData.scorer;\n try {\n const scorerToUse = await findScorer(mastra, entityId, entityType, scorer.name);\n\n if (!scorerToUse) {\n throw new MastraError({\n id: 'MASTRA_SCORER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with ID ${hookData.scorer.id} not found`,\n });\n }\n\n let input = hookData.input;\n let output = hookData.output;\n\n const { structuredOutput, ...rest } = hookData;\n\n const runResult = await scorerToUse.scorer.run({\n ...rest,\n input,\n output,\n });\n\n let spanId;\n let traceId;\n const currentSpan = hookData.tracingContext?.currentSpan;\n if (currentSpan && currentSpan.isValid) {\n spanId = currentSpan.id;\n traceId = currentSpan.traceId;\n }\n\n const payload = {\n ...rest,\n ...runResult,\n entityId,\n scorerId: hookData.scorer.name,\n spanId,\n traceId,\n metadata: {\n structuredOutput: !!structuredOutput,\n },\n };\n await validateAndSaveScore(storage, payload);\n\n if (currentSpan && spanId && traceId) {\n await pMap(\n currentSpan.aiTracing.getExporters(),\n async exporter => {\n if (exporter.addScoreToTrace) {\n await exporter.addScoreToTrace({\n traceId: traceId,\n spanId: spanId,\n score: runResult.score,\n reason: runResult.reason,\n scorerName: scorerToUse.scorer.name,\n metadata: {\n ...(currentSpan.metadata ?? {}),\n },\n });\n }\n },\n { concurrency: 3 },\n );\n }\n } catch (error) {\n const mastraError = new MastraError(\n {\n id: 'MASTRA_SCORER_FAILED_TO_RUN_HOOK',\n domain: ErrorDomain.SCORER,\n category: ErrorCategory.USER,\n details: {\n scorerId: scorer.id,\n entityId,\n entityType,\n },\n },\n error,\n );\n\n mastra.getLogger()?.trackException(mastraError);\n mastra.getLogger()?.error(mastraError.toString());\n }\n };\n}\n\nexport async function validateAndSaveScore(storage: MastraStorage, payload: unknown) {\n const payloadToSave = saveScorePayloadSchema.parse(payload);\n await storage?.saveScore(payloadToSave);\n}\n\nasync function findScorer(mastra: Mastra, entityId: string, entityType: string, scorerName: string) {\n let scorerToUse;\n if (entityType === 'AGENT') {\n const scorers = await mastra.getAgentById(entityId).getScorers();\n for (const [_, scorer] of Object.entries(scorers)) {\n if (scorer.scorer.name === scorerName) {\n scorerToUse = scorer;\n break;\n }\n }\n } else if (entityType === 'WORKFLOW') {\n const scorers = await mastra.getWorkflowById(entityId).getScorers();\n for (const [_, scorer] of Object.entries(scorers)) {\n if (scorer.scorer.name === scorerName) {\n scorerToUse = scorer;\n break;\n }\n }\n }\n\n // Fallback to mastra-registered scorer\n if (!scorerToUse) {\n const mastraRegisteredScorer = mastra.getScorerByName(scorerName);\n scorerToUse = mastraRegisteredScorer ? { scorer: mastraRegisteredScorer } : undefined;\n }\n\n return scorerToUse;\n}\n"]}
@@ -5,7 +5,7 @@ import { isVercelTool, validateToolInput } from './chunk-WM4RO23J.js';
5
5
  import { MastraBase } from './chunk-VQASQG5D.js';
6
6
  import { ConsoleLogger, LogLevel, RegisteredLogger } from './chunk-UXG7PYML.js';
7
7
  import { createHash } from 'crypto';
8
- import jsonSchemaToZod from 'json-schema-to-zod';
8
+ import { jsonSchemaToZod } from '@mastra/schema-compat/json-to-zod';
9
9
  import { z } from 'zod';
10
10
  import { convertZodSchemaToAISDKSchema, OpenAIReasoningSchemaCompatLayer, OpenAISchemaCompatLayer, GoogleSchemaCompatLayer, AnthropicSchemaCompatLayer, DeepSeekSchemaCompatLayer, MetaSchemaCompatLayer, applyCompatLayer } from '@mastra/schema-compat';
11
11
  import { TransformStream } from 'stream/web';
@@ -996,6 +996,44 @@ async function fetchWithRetry(url, options = {}, maxRetries = 3) {
996
996
  }
997
997
  throw lastError || new Error("Request failed after multiple retry attempts");
998
998
  }
999
+ function omitKeys(obj, keysToOmit) {
1000
+ return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key)));
1001
+ }
1002
+ function selectFields(obj, fields) {
1003
+ if (!obj || typeof obj !== "object") {
1004
+ return obj;
1005
+ }
1006
+ const result = {};
1007
+ for (const field of fields) {
1008
+ const value = getNestedValue(obj, field);
1009
+ if (value !== void 0) {
1010
+ setNestedValue(result, field, value);
1011
+ }
1012
+ }
1013
+ return result;
1014
+ }
1015
+ function getNestedValue(obj, path) {
1016
+ return path.split(".").reduce((current, key) => {
1017
+ return current && typeof current === "object" ? current[key] : void 0;
1018
+ }, obj);
1019
+ }
1020
+ function setNestedValue(obj, path, value) {
1021
+ const keys = path.split(".");
1022
+ const lastKey = keys.pop();
1023
+ if (!lastKey) {
1024
+ return;
1025
+ }
1026
+ const target = keys.reduce((current, key) => {
1027
+ if (!current[key] || typeof current[key] !== "object") {
1028
+ current[key] = {};
1029
+ }
1030
+ return current[key];
1031
+ }, obj);
1032
+ target[lastKey] = value;
1033
+ }
1034
+ var removeUndefinedValues = (obj) => {
1035
+ return Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== void 0));
1036
+ };
999
1037
 
1000
1038
  // src/ai-tracing/exporters/cloud.ts
1001
1039
  var CloudExporter = class extends BaseExporter {
@@ -2044,28 +2082,28 @@ function setupAITracing(config) {
2044
2082
  }
2045
2083
 
2046
2084
  // src/ai-tracing/utils.ts
2047
- function omitKeys(obj, keysToOmit) {
2085
+ function omitKeys2(obj, keysToOmit) {
2048
2086
  return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key)));
2049
2087
  }
2050
- function selectFields(obj, fields) {
2088
+ function selectFields2(obj, fields) {
2051
2089
  if (!obj || typeof obj !== "object") {
2052
2090
  return obj;
2053
2091
  }
2054
2092
  const result = {};
2055
2093
  for (const field of fields) {
2056
- const value = getNestedValue(obj, field);
2094
+ const value = getNestedValue2(obj, field);
2057
2095
  if (value !== void 0) {
2058
- setNestedValue(result, field, value);
2096
+ setNestedValue2(result, field, value);
2059
2097
  }
2060
2098
  }
2061
2099
  return result;
2062
2100
  }
2063
- function getNestedValue(obj, path) {
2101
+ function getNestedValue2(obj, path) {
2064
2102
  return path.split(".").reduce((current, key) => {
2065
2103
  return current && typeof current === "object" ? current[key] : void 0;
2066
2104
  }, obj);
2067
2105
  }
2068
- function setNestedValue(obj, path, value) {
2106
+ function setNestedValue2(obj, path, value) {
2069
2107
  const keys = path.split(".");
2070
2108
  const lastKey = keys.pop();
2071
2109
  if (!lastKey) {
@@ -2315,12 +2353,12 @@ var BaseAITracing = class extends MastraBase {
2315
2353
  if (value !== void 0) {
2316
2354
  if (parts.length > 1) {
2317
2355
  const nestedPath = parts.slice(1).join(".");
2318
- const nestedValue = getNestedValue(value, nestedPath);
2356
+ const nestedValue = getNestedValue2(value, nestedPath);
2319
2357
  if (nestedValue !== void 0) {
2320
- setNestedValue(result, key, nestedValue);
2358
+ setNestedValue2(result, key, nestedValue);
2321
2359
  }
2322
2360
  } else {
2323
- setNestedValue(result, key, value);
2361
+ setNestedValue2(result, key, value);
2324
2362
  }
2325
2363
  }
2326
2364
  }
@@ -2875,6 +2913,6 @@ var ModelSpanTracker = class {
2875
2913
  }
2876
2914
  };
2877
2915
 
2878
- export { AISpanType, AITracingEventType, BaseAISpan, BaseAITracing, BaseExporter, CloudExporter, ConsoleExporter, DefaultAISpan, DefaultAITracing, DefaultExporter, InternalSpans, ModelSpanTracker, NoOpAISpan, SamplingStrategyType, SensitiveDataFilter, checkEvalStorageFields, clearAITracingRegistry, createMastraProxy, deepClean, deepMerge, delay, ensureToolProperties, fetchWithRetry, generateEmptyFromSchema, getAITracing, getAllAITracing, getDefaultAITracing, getNestedValue, getOrCreateSpan, getSelectedAITracing, getValidTraceId, hasAITracing, isCoreMessage, isMastra, isUiMessage, isZodType, makeCoreTool, makeCoreToolV5, maskStreamTags, omitKeys, parseFieldKey, parseSqlIdentifier, registerAITracing, resolveSerializedZodOutput, selectFields, setNestedValue, setSelector, setupAITracing, shutdownAITracingRegistry, unregisterAITracing, wrapMastra };
2879
- //# sourceMappingURL=chunk-WIMFJ2BA.js.map
2880
- //# sourceMappingURL=chunk-WIMFJ2BA.js.map
2916
+ export { AISpanType, AITracingEventType, BaseAISpan, BaseAITracing, BaseExporter, CloudExporter, ConsoleExporter, DefaultAISpan, DefaultAITracing, DefaultExporter, InternalSpans, ModelSpanTracker, NoOpAISpan, SamplingStrategyType, SensitiveDataFilter, checkEvalStorageFields, clearAITracingRegistry, createMastraProxy, deepClean, deepMerge, delay, ensureToolProperties, fetchWithRetry, generateEmptyFromSchema, getAITracing, getAllAITracing, getDefaultAITracing, getNestedValue2 as getNestedValue, getNestedValue as getNestedValue2, getOrCreateSpan, getSelectedAITracing, getValidTraceId, hasAITracing, isCoreMessage, isMastra, isUiMessage, isZodType, makeCoreTool, makeCoreToolV5, maskStreamTags, omitKeys2 as omitKeys, omitKeys as omitKeys2, parseFieldKey, parseSqlIdentifier, registerAITracing, removeUndefinedValues, resolveSerializedZodOutput, selectFields2 as selectFields, selectFields as selectFields2, setNestedValue2 as setNestedValue, setNestedValue as setNestedValue2, setSelector, setupAITracing, shutdownAITracingRegistry, unregisterAITracing, wrapMastra };
2917
+ //# sourceMappingURL=chunk-PPAIPZ6C.js.map
2918
+ //# sourceMappingURL=chunk-PPAIPZ6C.js.map