@mastra/core 0.21.0-alpha.2 → 0.21.0

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 (90) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/dist/agent/agent.types.d.ts +0 -1
  3. package/dist/agent/agent.types.d.ts.map +1 -1
  4. package/dist/agent/index.cjs +13 -13
  5. package/dist/agent/index.js +2 -2
  6. package/dist/agent/input-processor/index.cjs +6 -6
  7. package/dist/agent/input-processor/index.js +1 -1
  8. package/dist/ai-tracing/index.cjs +32 -32
  9. package/dist/ai-tracing/index.js +1 -1
  10. package/dist/{chunk-YWLOJRIX.js → chunk-2KES233Q.js} +3 -3
  11. package/dist/{chunk-YWLOJRIX.js.map → chunk-2KES233Q.js.map} +1 -1
  12. package/dist/{chunk-X3ECC3CB.js → chunk-3Q5AADIA.js} +17 -9
  13. package/dist/chunk-3Q5AADIA.js.map +1 -0
  14. package/dist/{chunk-NOY6XIU4.js → chunk-4EXSSE3I.js} +4 -4
  15. package/dist/{chunk-NOY6XIU4.js.map → chunk-4EXSSE3I.js.map} +1 -1
  16. package/dist/{chunk-EBF2GIFE.cjs → chunk-AJQHJNNW.cjs} +24 -16
  17. package/dist/chunk-AJQHJNNW.cjs.map +1 -0
  18. package/dist/{chunk-S4FM66W4.cjs → chunk-AVKWVYFN.cjs} +9 -9
  19. package/dist/{chunk-S4FM66W4.cjs.map → chunk-AVKWVYFN.cjs.map} +1 -1
  20. package/dist/{chunk-SJKHIH44.cjs → chunk-BBNBATLR.cjs} +4 -4
  21. package/dist/{chunk-SJKHIH44.cjs.map → chunk-BBNBATLR.cjs.map} +1 -1
  22. package/dist/{chunk-OVJ2WBFK.js → chunk-DD3PWTXW.js} +11 -6
  23. package/dist/chunk-DD3PWTXW.js.map +1 -0
  24. package/dist/{chunk-X6EDVW3U.cjs → chunk-EABGDF4D.cjs} +6 -6
  25. package/dist/{chunk-X6EDVW3U.cjs.map → chunk-EABGDF4D.cjs.map} +1 -1
  26. package/dist/{chunk-FVVPBIUS.cjs → chunk-FJJV3END.cjs} +6 -6
  27. package/dist/{chunk-FVVPBIUS.cjs.map → chunk-FJJV3END.cjs.map} +1 -1
  28. package/dist/{chunk-F3X3A5KA.cjs → chunk-G4GBV44L.cjs} +4 -4
  29. package/dist/{chunk-F3X3A5KA.cjs.map → chunk-G4GBV44L.cjs.map} +1 -1
  30. package/dist/{chunk-M4ZLVM2E.cjs → chunk-HOPRWFM3.cjs} +12 -12
  31. package/dist/{chunk-M4ZLVM2E.cjs.map → chunk-HOPRWFM3.cjs.map} +1 -1
  32. package/dist/{chunk-JRNJL27F.cjs → chunk-HQKCS7H7.cjs} +4 -4
  33. package/dist/{chunk-JRNJL27F.cjs.map → chunk-HQKCS7H7.cjs.map} +1 -1
  34. package/dist/{chunk-T3MCLRO6.cjs → chunk-JKJW6ASJ.cjs} +11 -6
  35. package/dist/chunk-JKJW6ASJ.cjs.map +1 -0
  36. package/dist/{chunk-OBNF7UO2.js → chunk-MUBNGSAO.js} +3 -3
  37. package/dist/{chunk-OBNF7UO2.js.map → chunk-MUBNGSAO.js.map} +1 -1
  38. package/dist/{chunk-GOCHWSR7.js → chunk-NXBBSTIG.js} +3 -3
  39. package/dist/{chunk-GOCHWSR7.js.map → chunk-NXBBSTIG.js.map} +1 -1
  40. package/dist/{chunk-LN5I7LG3.js → chunk-R37WYGEC.js} +3 -3
  41. package/dist/{chunk-LN5I7LG3.js.map → chunk-R37WYGEC.js.map} +1 -1
  42. package/dist/{chunk-KUFI34FC.js → chunk-T4MYULBA.js} +3 -3
  43. package/dist/{chunk-KUFI34FC.js.map → chunk-T4MYULBA.js.map} +1 -1
  44. package/dist/{chunk-TGWK6V72.js → chunk-U5JW6KRX.js} +3 -3
  45. package/dist/{chunk-TGWK6V72.js.map → chunk-U5JW6KRX.js.map} +1 -1
  46. package/dist/{chunk-K7INT7EE.js → chunk-UMLRW5Y3.js} +6 -6
  47. package/dist/chunk-UMLRW5Y3.js.map +1 -0
  48. package/dist/{chunk-KJZFXTQR.cjs → chunk-VLJO4NT4.cjs} +42 -42
  49. package/dist/chunk-VLJO4NT4.cjs.map +1 -0
  50. package/dist/index.cjs +40 -40
  51. package/dist/index.js +7 -7
  52. package/dist/loop/index.cjs +2 -2
  53. package/dist/loop/index.js +1 -1
  54. package/dist/mastra/hooks.d.ts.map +1 -1
  55. package/dist/mastra/index.cjs +2 -2
  56. package/dist/mastra/index.js +1 -1
  57. package/dist/memory/index.cjs +4 -4
  58. package/dist/memory/index.js +1 -1
  59. package/dist/processors/index.cjs +11 -11
  60. package/dist/processors/index.js +1 -1
  61. package/dist/relevance/index.cjs +4 -4
  62. package/dist/relevance/index.js +1 -1
  63. package/dist/scores/index.cjs +9 -9
  64. package/dist/scores/index.js +2 -2
  65. package/dist/scores/scoreTraces/index.cjs +8 -8
  66. package/dist/scores/scoreTraces/index.js +3 -3
  67. package/dist/storage/index.cjs +3 -3
  68. package/dist/storage/index.js +1 -1
  69. package/dist/stream/aisdk/v5/execute.d.ts +6 -1
  70. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  71. package/dist/stream/index.cjs +10 -10
  72. package/dist/stream/index.js +2 -2
  73. package/dist/test-utils/llm-mock.cjs +2 -2
  74. package/dist/test-utils/llm-mock.js +1 -1
  75. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  76. package/dist/utils.cjs +17 -17
  77. package/dist/utils.js +1 -1
  78. package/dist/workflows/evented/index.cjs +10 -10
  79. package/dist/workflows/evented/index.js +1 -1
  80. package/dist/workflows/index.cjs +12 -12
  81. package/dist/workflows/index.js +1 -1
  82. package/dist/workflows/legacy/index.cjs +22 -22
  83. package/dist/workflows/legacy/index.js +1 -1
  84. package/package.json +3 -3
  85. package/dist/chunk-EBF2GIFE.cjs.map +0 -1
  86. package/dist/chunk-K7INT7EE.js.map +0 -1
  87. package/dist/chunk-KJZFXTQR.cjs.map +0 -1
  88. package/dist/chunk-OVJ2WBFK.js.map +0 -1
  89. package/dist/chunk-T3MCLRO6.cjs.map +0 -1
  90. package/dist/chunk-X3ECC3CB.js.map +0 -1
@@ -1,11 +1,11 @@
1
- import { WorkflowEventProcessor } from './chunk-LN5I7LG3.js';
2
- import { saveScorePayloadSchema } from './chunk-TGWK6V72.js';
1
+ import { WorkflowEventProcessor } from './chunk-R37WYGEC.js';
2
+ import { saveScorePayloadSchema } from './chunk-U5JW6KRX.js';
3
3
  import { augmentWithInit } from './chunk-436FFEF6.js';
4
4
  import { PubSub } from './chunk-BVUMKER5.js';
5
5
  import { InstrumentClass, Telemetry } from './chunk-2DVGQK2L.js';
6
6
  import { InMemoryServerCache } from './chunk-EQV2PPN2.js';
7
7
  import { registerHook } from './chunk-TTELJD4F.js';
8
- import { setupAITracing, getAllAITracing, shutdownAITracingRegistry } from './chunk-OVJ2WBFK.js';
8
+ import { setupAITracing, getAllAITracing, shutdownAITracingRegistry } from './chunk-DD3PWTXW.js';
9
9
  import { noopLogger } from './chunk-PFXXH2RP.js';
10
10
  import { MastraError } from './chunk-T3JFFQH2.js';
11
11
  import { ConsoleLogger, LogLevel } from './chunk-BN2M4UK5.js';
@@ -68,23 +68,31 @@ function createOnScorerHook(mastra) {
68
68
  input,
69
69
  output
70
70
  });
71
+ let spanId;
72
+ let traceId;
73
+ const currentSpan = hookData.tracingContext?.currentSpan;
74
+ if (currentSpan && currentSpan.isValid) {
75
+ spanId = currentSpan.id;
76
+ traceId = currentSpan.traceId;
77
+ }
71
78
  const payload = {
72
79
  ...rest,
73
80
  ...runResult,
74
81
  entityId,
75
82
  scorerId: hookData.scorer.name,
83
+ spanId,
84
+ traceId,
76
85
  metadata: {
77
86
  structuredOutput: !!structuredOutput
78
87
  }
79
88
  };
80
89
  await validateAndSaveScore(storage, payload);
81
- const currentSpan = hookData.tracingContext?.currentSpan;
82
- if (currentSpan && currentSpan.isValid) {
90
+ if (currentSpan && spanId && traceId) {
83
91
  await pMap(currentSpan.aiTracing.getExporters(), async exporter => {
84
92
  if (exporter.addScoreToTrace) {
85
93
  await exporter.addScoreToTrace({
86
- traceId: currentSpan.traceId,
87
- spanId: currentSpan.id,
94
+ traceId,
95
+ spanId,
88
96
  score: runResult.score,
89
97
  reason: runResult.reason,
90
98
  scorerName: scorerToUse.scorer.name,
@@ -1636,5 +1644,5 @@ Mastra = /*@__PURE__*/(_ => {
1636
1644
  })();
1637
1645
 
1638
1646
  export { Mastra };
1639
- //# sourceMappingURL=chunk-X3ECC3CB.js.map
1640
- //# sourceMappingURL=chunk-X3ECC3CB.js.map
1647
+ //# sourceMappingURL=chunk-3Q5AADIA.js.map
1648
+ //# sourceMappingURL=chunk-3Q5AADIA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mastra/index.ts","../src/events/event-emitter.ts","../src/mastra/hooks.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB,CAAA,MAAA,EAAA;;;ACA3B,IAAA,IAAO,CAAA,OAAA,EAAA;AAIA,MAAM,MAAA,CAAA,SAAA,EAAA,gEAAkC,CAAA;AAAA,MACrC;AAAA,IAER;AACE,IAAA,MAAM,QAAA,GAAA,QAAA,CAAA,MAAA,CAAA,EAAA;AACN,IAAA,MAAK,aAAc,QAAA,CAAA,UAAa;AAAA,IAClC,MAAA,MAAA,GAAA,QAAA,CAAA,MAAA;AAAA,IAEA,IAAM;AACJ,MAAA,MAAM,WAAY,GAAA,MAAA,UAAW,CAAA,MAAA,EAAA,QAAA,EAAA,UAAA,EAAA,MAAA,CAAA,IAAA,CAAA;AAC7B,MAAA,IAAM,CAAA,WAAY;AAClB,QAAA,MAAK,eAAoB,CAAA;AAAA,UACpB,EAAA,EAAA,yBAAA;AAAA,UACH,MAAA,EAAA,QAAA;AAAA,UACA,QAAA,EAAA,MAAA;AAAA,UACD,IAAA,EAAA,CAAA,eAAA,EAAA,QAAA,CAAA,MAAA,CAAA,EAAA,CAAA,UAAA;AAAA,SACH,C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MAAA,CAAA;AAAA,EAAA,OAAA,MAAA;AAAA,CAAA,EAAA","file":"chunk-3Q5AADIA.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 { 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 } 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> = Record<string, MastraVector>,\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 * 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> = Record<string, MastraVector>,\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 #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 /*\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 // @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 /**\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 * 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"]}
@@ -1,6 +1,6 @@
1
1
  import { augmentWithInit } from './chunk-436FFEF6.js';
2
- import { MessageList } from './chunk-YWLOJRIX.js';
3
- import { deepMerge } from './chunk-OVJ2WBFK.js';
2
+ import { MessageList } from './chunk-2KES233Q.js';
3
+ import { deepMerge } from './chunk-DD3PWTXW.js';
4
4
  import { MastraBase } from './chunk-BMVFEBPE.js';
5
5
 
6
6
  // src/memory/memory.ts
@@ -258,5 +258,5 @@ https://mastra.ai/en/docs/memory/overview`
258
258
  };
259
259
 
260
260
  export { MastraMemory, MemoryProcessor, memoryDefaultOptions };
261
- //# sourceMappingURL=chunk-NOY6XIU4.js.map
262
- //# sourceMappingURL=chunk-NOY6XIU4.js.map
261
+ //# sourceMappingURL=chunk-4EXSSE3I.js.map
262
+ //# sourceMappingURL=chunk-4EXSSE3I.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/memory/memory.ts"],"names":[],"mappings":";;;;;;AA6BO,IAAe,eAAA,GAAf,cAAuC,UAAA,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,cAAoC,UAAA,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,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AAA;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-NOY6XIU4.js","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 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 this.embedder = config.embedder;\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 and uiMessages\n */\n abstract query({\n threadId,\n resourceId,\n selectBy,\n }: StorageGetMessagesArg): Promise<{ messages: CoreMessage[]; uiMessages: UIMessageWithMetadata[] }>;\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":[],"mappings":";;;;;;AA6BO,IAAe,eAAA,GAAf,cAAuC,UAAA,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,cAAoC,UAAA,CAAW;AAAA,EACpD,kBAAA;AAAA,EAEU,QAAA;AAAA,EACV,MAAA;AAAA,EACA,QAAA;AAAA,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AA,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-4EXSSE3I.js","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 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 this.embedder = config.embedder;\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 and uiMessages\n */\n abstract query({\n threadId,\n resourceId,\n selectBy,\n }: StorageGetMessagesArg): Promise<{ messages: CoreMessage[]; uiMessages: UIMessageWithMetadata[] }>;\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,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var chunkM4ZLVM2E_cjs = require('./chunk-M4ZLVM2E.cjs');
4
- var chunkJRNJL27F_cjs = require('./chunk-JRNJL27F.cjs');
3
+ var chunkHOPRWFM3_cjs = require('./chunk-HOPRWFM3.cjs');
4
+ var chunkHQKCS7H7_cjs = require('./chunk-HQKCS7H7.cjs');
5
5
  var chunkV3VLOOSW_cjs = require('./chunk-V3VLOOSW.cjs');
6
6
  var chunk4D4KB75Y_cjs = require('./chunk-4D4KB75Y.cjs');
7
7
  var chunk2JUDZXVI_cjs = require('./chunk-2JUDZXVI.cjs');
8
8
  var chunkUU5L5GDY_cjs = require('./chunk-UU5L5GDY.cjs');
9
9
  var chunkTSNDVBUU_cjs = require('./chunk-TSNDVBUU.cjs');
10
- var chunkT3MCLRO6_cjs = require('./chunk-T3MCLRO6.cjs');
10
+ var chunkJKJW6ASJ_cjs = require('./chunk-JKJW6ASJ.cjs');
11
11
  var chunk6TEQIYXV_cjs = require('./chunk-6TEQIYXV.cjs');
12
12
  var chunkWM4VQWOZ_cjs = require('./chunk-WM4VQWOZ.cjs');
13
13
  var chunkWVCEJBDR_cjs = require('./chunk-WVCEJBDR.cjs');
@@ -75,23 +75,31 @@ function createOnScorerHook(mastra) {
75
75
  input,
76
76
  output
77
77
  });
78
+ let spanId;
79
+ let traceId;
80
+ const currentSpan = hookData.tracingContext?.currentSpan;
81
+ if (currentSpan && currentSpan.isValid) {
82
+ spanId = currentSpan.id;
83
+ traceId = currentSpan.traceId;
84
+ }
78
85
  const payload = {
79
86
  ...rest,
80
87
  ...runResult,
81
88
  entityId,
82
89
  scorerId: hookData.scorer.name,
90
+ spanId,
91
+ traceId,
83
92
  metadata: {
84
93
  structuredOutput: !!structuredOutput
85
94
  }
86
95
  };
87
96
  await validateAndSaveScore(storage, payload);
88
- const currentSpan = hookData.tracingContext?.currentSpan;
89
- if (currentSpan && currentSpan.isValid) {
97
+ if (currentSpan && spanId && traceId) {
90
98
  await pMap__default.default(currentSpan.aiTracing.getExporters(), async exporter => {
91
99
  if (exporter.addScoreToTrace) {
92
100
  await exporter.addScoreToTrace({
93
- traceId: currentSpan.traceId,
94
- spanId: currentSpan.id,
101
+ traceId,
102
+ spanId,
95
103
  score: runResult.score,
96
104
  reason: runResult.reason,
97
105
  scorerName: scorerToUse.scorer.name,
@@ -121,7 +129,7 @@ function createOnScorerHook(mastra) {
121
129
  };
122
130
  }
123
131
  async function validateAndSaveScore(storage, payload) {
124
- const payloadToSave = chunkJRNJL27F_cjs.saveScorePayloadSchema.parse(payload);
132
+ const payloadToSave = chunkHQKCS7H7_cjs.saveScorePayloadSchema.parse(payload);
125
133
  await storage?.saveScore(payloadToSave);
126
134
  }
127
135
  async function findScorer(mastra, entityId, entityType, scorerName) {
@@ -313,7 +321,7 @@ exports.Mastra = class Mastra {
313
321
  this.#events[topic] = config?.events?.[topic] ?? [];
314
322
  }
315
323
  }
316
- const workflowEventProcessor = new chunkM4ZLVM2E_cjs.WorkflowEventProcessor({
324
+ const workflowEventProcessor = new chunkHOPRWFM3_cjs.WorkflowEventProcessor({
317
325
  mastra: this
318
326
  });
319
327
  const workflowEventCb = async (event, cb) => {
@@ -356,7 +364,7 @@ exports.Mastra = class Mastra {
356
364
  this.#logger?.warn(`Mastra telemetry is deprecated and will be removed on the Nov 4th release. Instead use AI Tracing. 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`);
357
365
  }
358
366
  if (config?.observability) {
359
- chunkT3MCLRO6_cjs.setupAITracing(config.observability);
367
+ chunkJKJW6ASJ_cjs.setupAITracing(config.observability);
360
368
  }
361
369
  if (this.#telemetry && storage) {
362
370
  this.#storage = this.#telemetry.traceClass(storage, {
@@ -513,7 +521,7 @@ do:
513
521
  * Register this Mastra instance with AI tracing exporters that need it
514
522
  */
515
523
  registerAITracingExporters() {
516
- const allTracingInstances = chunkT3MCLRO6_cjs.getAllAITracing();
524
+ const allTracingInstances = chunkJKJW6ASJ_cjs.getAllAITracing();
517
525
  allTracingInstances.forEach(tracing => {
518
526
  const exporters = tracing.getExporters();
519
527
  exporters.forEach(exporter => {
@@ -527,7 +535,7 @@ do:
527
535
  * Initialize all AI tracing exporters after registration is complete
528
536
  */
529
537
  initAITracingExporters() {
530
- const allTracingInstances = chunkT3MCLRO6_cjs.getAllAITracing();
538
+ const allTracingInstances = chunkJKJW6ASJ_cjs.getAllAITracing();
531
539
  allTracingInstances.forEach(tracing => {
532
540
  const config = tracing.getConfig();
533
541
  const exporters = tracing.getExporters();
@@ -1193,7 +1201,7 @@ do:
1193
1201
  this.#mcpServers?.[key]?.__setLogger(this.#logger);
1194
1202
  });
1195
1203
  }
1196
- const allTracingInstances = chunkT3MCLRO6_cjs.getAllAITracing();
1204
+ const allTracingInstances = chunkJKJW6ASJ_cjs.getAllAITracing();
1197
1205
  allTracingInstances.forEach(instance => {
1198
1206
  instance.__setLogger(this.#logger);
1199
1207
  });
@@ -1626,7 +1634,7 @@ do:
1626
1634
  * ```
1627
1635
  */
1628
1636
  async shutdown() {
1629
- await chunkT3MCLRO6_cjs.shutdownAITracingRegistry();
1637
+ await chunkJKJW6ASJ_cjs.shutdownAITracingRegistry();
1630
1638
  await this.stopEventEngine();
1631
1639
  this.#logger?.info("Mastra shutdown completed");
1632
1640
  }
@@ -1641,5 +1649,5 @@ exports.Mastra = /*@__PURE__*/(_ => {
1641
1649
  chunkEBVYYC2Q_cjs.__runInitializers(_init, 1, exports.Mastra);
1642
1650
  return exports.Mastra;
1643
1651
  })();
1644
- //# sourceMappingURL=chunk-EBF2GIFE.cjs.map
1645
- //# sourceMappingURL=chunk-EBF2GIFE.cjs.map
1652
+ //# sourceMappingURL=chunk-AJQHJNNW.cjs.map
1653
+ //# sourceMappingURL=chunk-AJQHJNNW.cjs.map