@mastra/core 0.16.4-alpha.0 → 0.16.4-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/agent/index.cjs +8 -8
  3. package/dist/agent/index.js +1 -1
  4. package/dist/agent/input-processor/index.cjs +6 -6
  5. package/dist/agent/input-processor/index.js +1 -1
  6. package/dist/{chunk-2S2YFQ3W.cjs → chunk-BIXBJ4DU.cjs} +7 -7
  7. package/dist/{chunk-2S2YFQ3W.cjs.map → chunk-BIXBJ4DU.cjs.map} +1 -1
  8. package/dist/{chunk-XKXZ6I72.js → chunk-CLEXBHVL.js} +4 -4
  9. package/dist/{chunk-XKXZ6I72.js.map → chunk-CLEXBHVL.js.map} +1 -1
  10. package/dist/{chunk-Z3DIAA2J.cjs → chunk-DORWTJUT.cjs} +7 -7
  11. package/dist/{chunk-Z3DIAA2J.cjs.map → chunk-DORWTJUT.cjs.map} +1 -1
  12. package/dist/{chunk-ZJRDXVAR.cjs → chunk-EE5TG5UG.cjs} +6 -6
  13. package/dist/{chunk-ZJRDXVAR.cjs.map → chunk-EE5TG5UG.cjs.map} +1 -1
  14. package/dist/{chunk-ZL6RHYVT.cjs → chunk-ELLP4WJF.cjs} +21 -13
  15. package/dist/chunk-ELLP4WJF.cjs.map +1 -0
  16. package/dist/{chunk-CWK46GAF.js → chunk-ENZVBXRB.js} +9 -2
  17. package/dist/chunk-ENZVBXRB.js.map +1 -0
  18. package/dist/{chunk-OSMP67E2.js → chunk-J52TTT6T.js} +21 -13
  19. package/dist/chunk-J52TTT6T.js.map +1 -0
  20. package/dist/{chunk-MS6HHGRW.js → chunk-KFXKSOXF.js} +3 -3
  21. package/dist/{chunk-MS6HHGRW.js.map → chunk-KFXKSOXF.js.map} +1 -1
  22. package/dist/{chunk-33GDW3SI.cjs → chunk-KICLFGCP.cjs} +9 -2
  23. package/dist/chunk-KICLFGCP.cjs.map +1 -0
  24. package/dist/{chunk-6ACAYXAV.cjs → chunk-L34N5NMP.cjs} +4 -4
  25. package/dist/{chunk-6ACAYXAV.cjs.map → chunk-L34N5NMP.cjs.map} +1 -1
  26. package/dist/{chunk-SWI3TK2R.js → chunk-PRTH6W72.js} +3 -3
  27. package/dist/{chunk-SWI3TK2R.js.map → chunk-PRTH6W72.js.map} +1 -1
  28. package/dist/{chunk-P5BVWWMV.js → chunk-WNN3LIOF.js} +3 -3
  29. package/dist/{chunk-P5BVWWMV.js.map → chunk-WNN3LIOF.js.map} +1 -1
  30. package/dist/index.cjs +22 -22
  31. package/dist/index.js +6 -6
  32. package/dist/loop/index.cjs +2 -2
  33. package/dist/loop/index.js +1 -1
  34. package/dist/mastra/index.cjs +2 -2
  35. package/dist/mastra/index.js +1 -1
  36. package/dist/network/index.cjs +2 -2
  37. package/dist/network/index.js +1 -1
  38. package/dist/network/vNext/index.cjs +27 -27
  39. package/dist/network/vNext/index.js +1 -1
  40. package/dist/processors/index.cjs +8 -8
  41. package/dist/processors/index.js +2 -2
  42. package/dist/relevance/index.cjs +4 -4
  43. package/dist/relevance/index.js +1 -1
  44. package/dist/scores/index.cjs +8 -8
  45. package/dist/scores/index.js +1 -1
  46. package/dist/storage/base.d.ts +2 -1
  47. package/dist/storage/base.d.ts.map +1 -1
  48. package/dist/storage/domains/workflows/base.d.ts +1 -0
  49. package/dist/storage/domains/workflows/base.d.ts.map +1 -1
  50. package/dist/storage/domains/workflows/inmemory.d.ts +2 -1
  51. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  52. package/dist/storage/index.cjs +14 -9
  53. package/dist/storage/index.cjs.map +1 -1
  54. package/dist/storage/index.js +10 -5
  55. package/dist/storage/index.js.map +1 -1
  56. package/dist/storage/mock.d.ts +2 -1
  57. package/dist/storage/mock.d.ts.map +1 -1
  58. package/dist/storage/types.d.ts +1 -0
  59. package/dist/storage/types.d.ts.map +1 -1
  60. package/dist/stream/index.cjs +3 -3
  61. package/dist/stream/index.js +1 -1
  62. package/dist/workflows/default.d.ts +15 -7
  63. package/dist/workflows/default.d.ts.map +1 -1
  64. package/dist/workflows/evented/index.cjs +10 -10
  65. package/dist/workflows/evented/index.js +1 -1
  66. package/dist/workflows/execution-engine.d.ts +1 -0
  67. package/dist/workflows/execution-engine.d.ts.map +1 -1
  68. package/dist/workflows/index.cjs +10 -10
  69. package/dist/workflows/index.js +1 -1
  70. package/dist/workflows/legacy/index.cjs +22 -22
  71. package/dist/workflows/legacy/index.js +1 -1
  72. package/dist/workflows/step.d.ts +1 -0
  73. package/dist/workflows/step.d.ts.map +1 -1
  74. package/dist/workflows/workflow.d.ts +13 -0
  75. package/dist/workflows/workflow.d.ts.map +1 -1
  76. package/package.json +1 -1
  77. package/dist/chunk-33GDW3SI.cjs.map +0 -1
  78. package/dist/chunk-CWK46GAF.js.map +0 -1
  79. package/dist/chunk-OSMP67E2.js.map +0 -1
  80. package/dist/chunk-ZL6RHYVT.cjs.map +0 -1
@@ -183,16 +183,23 @@ var MastraStorage = class extends MastraBase {
183
183
  schema: TABLE_SCHEMAS[TABLE_MESSAGES],
184
184
  ifNotExists: ["resourceId"]
185
185
  });
186
+ await this?.alterTable?.({
187
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
188
+ schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT],
189
+ ifNotExists: ["resourceId"]
190
+ });
186
191
  }
187
192
  async persistWorkflowSnapshot({
188
193
  workflowName,
189
194
  runId,
195
+ resourceId,
190
196
  snapshot
191
197
  }) {
192
198
  await this.init();
193
199
  const data = {
194
200
  workflow_name: workflowName,
195
201
  run_id: runId,
202
+ resourceId,
196
203
  snapshot,
197
204
  createdAt: /* @__PURE__ */ new Date(),
198
205
  updatedAt: /* @__PURE__ */ new Date()
@@ -336,5 +343,5 @@ var MastraStorage = class extends MastraBase {
336
343
  };
337
344
 
338
345
  export { MastraStorage, ensureDate, resolveMessageLimit, serializeDate };
339
- //# sourceMappingURL=chunk-CWK46GAF.js.map
340
- //# sourceMappingURL=chunk-CWK46GAF.js.map
346
+ //# sourceMappingURL=chunk-ENZVBXRB.js.map
347
+ //# sourceMappingURL=chunk-ENZVBXRB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/base.ts"],"names":[],"mappings":";;;;;AA0DO,SAAS,WAAW,IAAA,EAAmD;AAC5E,EAAA,IAAI,CAAC,MAAM,OAAO,MAAA;AAClB,EAAA,OAAO,IAAA,YAAgB,IAAA,GAAO,IAAA,GAAO,IAAI,KAAK,IAAI,CAAA;AACpD;AAEO,SAAS,cAAc,IAAA,EAAqD;AACjF,EAAA,IAAI,CAAC,MAAM,OAAO,MAAA;AAClB,EAAA,MAAM,OAAA,GAAU,WAAW,IAAI,CAAA;AAC/B,EAAA,OAAO,SAAS,WAAA,EAAY;AAC9B;AAEO,SAAS,mBAAA,CAAoB;AAAA,EAClC,IAAA;AAAA,EACA;AACF,CAAA,EAGW;AAET,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,SAAiB,IAAA,CAAK,GAAA,CAAI,GAAG,IAAI,CAAA;AACrD,EAAA,IAAI,IAAA,KAAS,OAAO,OAAO,CAAA;AAC3B,EAAA,OAAO,YAAA;AACT;AACO,IAAe,aAAA,GAAf,cAAqC,UAAA,CAAW;AAAA;AAAA,EAErD,OAAgB,uBAAA,GAA0B,uBAAA;AAAA;AAAA,EAE1C,OAAgB,WAAA,GAAc,WAAA;AAAA;AAAA,EAE9B,OAAgB,cAAA,GAAiB,cAAA;AAAA;AAAA,EAEjC,OAAgB,aAAA,GAAgB,aAAA;AAAA;AAAA,EAEhC,OAAgB,YAAA,GAAe,YAAA;AAAA,EAErB,cAAA,GAA0C,IAAA;AAAA,EAC1C,eAAA,GAAkB,IAAA;AAAA,EAE5B,MAAA;AAAA,EAEA,WAAA,CAAY,EAAE,IAAA,EAAK,EAAqB;AACtC,IAAA,KAAA,CAAM;AAAA,MACJ,SAAA,EAAW,SAAA;AAAA,MACX;A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AAAA,KACpF,CAAA;AAAA,EACH;AACF","file":"chunk-ENZVBXRB.js","sourcesContent":["import type { MastraMessageContentV2, MastraMessageV2 } from '../agent';\nimport type { TracingStrategy } from '../ai-tracing';\nimport { MastraBase } from '../base';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport type { MastraMessageV1, StorageThreadType } from '../memory/types';\nimport type { ScoreRowData, ScoringSource, ValidatedSaveScorePayload } from '../scores';\nimport type { Trace } from '../telemetry';\nimport type { StepResult, WorkflowRunState } from '../workflows/types';\n\nimport {\n TABLE_WORKFLOW_SNAPSHOT,\n TABLE_EVALS,\n TABLE_MESSAGES,\n TABLE_THREADS,\n TABLE_TRACES,\n TABLE_RESOURCES,\n TABLE_SCORERS,\n TABLE_SCHEMAS,\n TABLE_AI_SPANS,\n} from './constants';\nimport type { TABLE_NAMES } from './constants';\nimport type {\n ScoresStorage,\n StoreOperations,\n WorkflowsStorage,\n TracesStorage,\n MemoryStorage,\n LegacyEvalsStorage,\n ObservabilityStorage,\n} from './domains';\nimport type {\n EvalRow,\n PaginationInfo,\n StorageColumn,\n StorageGetMessagesArg,\n StorageResourceType,\n StoragePagination,\n ThreadSortOptions,\n WorkflowRun,\n WorkflowRuns,\n StorageGetTracesArg,\n PaginationArgs,\n StorageGetTracesPaginatedArg,\n AISpanRecord,\n AITraceRecord,\n AITracesPaginatedArg,\n} from './types';\n\nexport type StorageDomains = {\n legacyEvals: LegacyEvalsStorage;\n operations: StoreOperations;\n workflows: WorkflowsStorage;\n scores: ScoresStorage;\n traces: TracesStorage;\n memory: MemoryStorage;\n observability?: ObservabilityStorage;\n};\n\nexport function ensureDate(date: Date | string | undefined): Date | undefined {\n if (!date) return undefined;\n return date instanceof Date ? date : new Date(date);\n}\n\nexport function serializeDate(date: Date | string | undefined): string | undefined {\n if (!date) return undefined;\n const dateObj = ensureDate(date);\n return dateObj?.toISOString();\n}\n\nexport function resolveMessageLimit({\n last,\n defaultLimit,\n}: {\n last: number | false | undefined;\n defaultLimit: number;\n}): number {\n // TODO: Figure out consistent default limit for all stores as some stores use 40 and some use no limit (Number.MAX_SAFE_INTEGER)\n if (typeof last === 'number') return Math.max(0, last);\n if (last === false) return 0;\n return defaultLimit;\n}\nexport abstract class MastraStorage extends MastraBase {\n /** @deprecated import from { TABLE_WORKFLOW_SNAPSHOT } '@mastra/core/storage' instead */\n static readonly TABLE_WORKFLOW_SNAPSHOT = TABLE_WORKFLOW_SNAPSHOT;\n /** @deprecated import from { TABLE_EVALS } '@mastra/core/storage' instead */\n static readonly TABLE_EVALS = TABLE_EVALS;\n /** @deprecated import from { TABLE_MESSAGES } '@mastra/core/storage' instead */\n static readonly TABLE_MESSAGES = TABLE_MESSAGES;\n /** @deprecated import from { TABLE_THREADS } '@mastra/core/storage' instead */\n static readonly TABLE_THREADS = TABLE_THREADS;\n /** @deprecated import { TABLE_TRACES } from '@mastra/core/storage' instead */\n static readonly TABLE_TRACES = TABLE_TRACES;\n\n protected hasInitialized: null | Promise<boolean> = null;\n protected shouldCacheInit = true;\n\n stores?: StorageDomains;\n\n constructor({ name }: { name: string }) {\n super({\n component: 'STORAGE',\n name,\n });\n }\n\n public get supports(): {\n selectByIncludeResourceScope: boolean;\n resourceWorkingMemory: boolean;\n hasColumn: boolean;\n createTable: boolean;\n deleteMessages: boolean;\n aiTracing?: boolean;\n } {\n return {\n selectByIncludeResourceScope: false,\n resourceWorkingMemory: false,\n hasColumn: false,\n createTable: false,\n deleteMessages: false,\n aiTracing: false,\n };\n }\n\n protected ensureDate(date: Date | string | undefined): Date | undefined {\n return ensureDate(date);\n }\n\n protected serializeDate(date: Date | string | undefined): string | undefined {\n return serializeDate(date);\n }\n\n /**\n * Resolves limit for how many messages to fetch\n *\n * @param last The number of messages to fetch\n * @param defaultLimit The default limit to use if last is not provided\n * @returns The resolved limit\n */\n protected resolveMessageLimit({\n last,\n defaultLimit,\n }: {\n last: number | false | undefined;\n defaultLimit: number;\n }): number {\n return resolveMessageLimit({ last, defaultLimit });\n }\n\n protected getSqlType(type: StorageColumn['type']): string {\n switch (type) {\n case 'text':\n return 'TEXT';\n case 'timestamp':\n return 'TIMESTAMP';\n case 'float':\n return 'FLOAT';\n case 'integer':\n return 'INTEGER';\n case 'bigint':\n return 'BIGINT';\n case 'jsonb':\n return 'JSONB';\n default:\n return 'TEXT';\n }\n }\n\n protected getDefaultValue(type: StorageColumn['type']): string {\n switch (type) {\n case 'text':\n case 'uuid':\n return \"DEFAULT ''\";\n case 'timestamp':\n return \"DEFAULT '1970-01-01 00:00:00'\";\n case 'integer':\n case 'float':\n case 'bigint':\n return 'DEFAULT 0';\n case 'jsonb':\n return \"DEFAULT '{}'\";\n default:\n return \"DEFAULT ''\";\n }\n }\n\n abstract createTable({ tableName }: { tableName: TABLE_NAMES; schema: Record<string, StorageColumn> }): Promise<void>;\n\n abstract clearTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void>;\n\n abstract dropTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void>;\n\n abstract alterTable(args: {\n tableName: TABLE_NAMES;\n schema: Record<string, StorageColumn>;\n ifNotExists: string[];\n }): Promise<void>;\n\n abstract insert({ tableName, record }: { tableName: TABLE_NAMES; record: Record<string, any> }): Promise<void>;\n\n abstract batchInsert({\n tableName,\n records,\n }: {\n tableName: TABLE_NAMES;\n records: Record<string, any>[];\n }): Promise<void>;\n\n batchTraceInsert({ records }: { records: Record<string, any>[] }): Promise<void> {\n if (this.stores?.traces) {\n return this.stores.traces.batchTraceInsert({ records });\n }\n return this.batchInsert({ tableName: TABLE_TRACES, records });\n }\n\n abstract load<R>({ tableName, keys }: { tableName: TABLE_NAMES; keys: Record<string, any> }): Promise<R | null>;\n\n abstract getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null>;\n\n abstract getThreadsByResourceId({\n resourceId,\n orderBy,\n sortDirection,\n }: { resourceId: string } & ThreadSortOptions): Promise<StorageThreadType[]>;\n\n abstract saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType>;\n\n abstract updateThread({\n id,\n title,\n metadata,\n }: {\n id: string;\n title: string;\n metadata: Record<string, unknown>;\n }): Promise<StorageThreadType>;\n\n abstract deleteThread({ threadId }: { threadId: string }): Promise<void>;\n\n async getResourceById(_: { resourceId: string }): Promise<StorageResourceType | null> {\n throw new Error(\n `Resource working memory is not supported by this storage adapter (${this.constructor.name}). ` +\n `Supported storage adapters: LibSQL (@mastra/libsql), PostgreSQL (@mastra/pg), Upstash (@mastra/upstash). ` +\n `To use per-resource working memory, switch to one of these supported storage adapters.`,\n );\n }\n\n async saveResource(_: { resource: StorageResourceType }): Promise<StorageResourceType> {\n throw new Error(\n `Resource working memory is not supported by this storage adapter (${this.constructor.name}). ` +\n `Supported storage adapters: LibSQL (@mastra/libsql), PostgreSQL (@mastra/pg), Upstash (@mastra/upstash). ` +\n `To use per-resource working memory, switch to one of these supported storage adapters.`,\n );\n }\n\n async updateResource(_: {\n resourceId: string;\n workingMemory?: string;\n metadata?: Record<string, unknown>;\n }): Promise<StorageResourceType> {\n throw new Error(\n `Resource working memory is not supported by this storage adapter (${this.constructor.name}). ` +\n `Supported storage adapters: LibSQL (@mastra/libsql), PostgreSQL (@mastra/pg), Upstash (@mastra/upstash). ` +\n `To use per-resource working memory, switch to one of these supported storage adapters.`,\n );\n }\n\n abstract getMessages(args: StorageGetMessagesArg & { format?: 'v1' }): Promise<MastraMessageV1[]>;\n abstract getMessages(args: StorageGetMessagesArg & { format: 'v2' }): Promise<MastraMessageV2[]>;\n abstract getMessages({\n threadId,\n resourceId,\n selectBy,\n format,\n }: StorageGetMessagesArg & { format?: 'v1' | 'v2' }): Promise<MastraMessageV1[] | MastraMessageV2[]>;\n abstract getMessagesById({ messageIds }: { messageIds: string[]; format: 'v1' }): Promise<MastraMessageV1[]>;\n abstract getMessagesById({ messageIds }: { messageIds: string[]; format?: 'v2' }): Promise<MastraMessageV2[]>;\n abstract getMessagesById({\n messageIds,\n }: {\n messageIds: string[];\n format?: 'v1' | 'v2';\n }): Promise<MastraMessageV1[] | MastraMessageV2[]>;\n\n abstract saveMessages(args: { messages: MastraMessageV1[]; format?: undefined | 'v1' }): Promise<MastraMessageV1[]>;\n abstract saveMessages(args: { messages: MastraMessageV2[]; format: 'v2' }): Promise<MastraMessageV2[]>;\n abstract saveMessages(\n args: { messages: MastraMessageV1[]; format?: undefined | 'v1' } | { messages: MastraMessageV2[]; format: 'v2' },\n ): Promise<MastraMessageV2[] | MastraMessageV1[]>;\n\n abstract updateMessages(args: {\n messages: Partial<Omit<MastraMessageV2, 'createdAt'>> &\n {\n id: string;\n content?: { metadata?: MastraMessageContentV2['metadata']; content?: MastraMessageContentV2['content'] };\n }[];\n }): Promise<MastraMessageV2[]>;\n\n async deleteMessages(_messageIds: string[]): Promise<void> {\n throw new Error(\n `Message deletion is not supported by this storage adapter (${this.constructor.name}). ` +\n `The deleteMessages method needs to be implemented in the storage adapter.`,\n );\n }\n\n abstract getTraces(args: StorageGetTracesArg): Promise<Trace[]>;\n\n abstract getTracesPaginated(args: StorageGetTracesPaginatedArg): Promise<PaginationInfo & { traces: Trace[] }>;\n\n async init(): Promise<void> {\n // to prevent race conditions, await any current init\n if (this.shouldCacheInit && (await this.hasInitialized)) {\n return;\n }\n\n const tableCreationTasks = [\n this.createTable({\n tableName: TABLE_WORKFLOW_SNAPSHOT,\n schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT],\n }),\n\n this.createTable({\n tableName: TABLE_EVALS,\n schema: TABLE_SCHEMAS[TABLE_EVALS],\n }),\n\n this.createTable({\n tableName: TABLE_THREADS,\n schema: TABLE_SCHEMAS[TABLE_THREADS],\n }),\n\n this.createTable({\n tableName: TABLE_MESSAGES,\n schema: TABLE_SCHEMAS[TABLE_MESSAGES],\n }),\n\n this.createTable({\n tableName: TABLE_TRACES,\n schema: TABLE_SCHEMAS[TABLE_TRACES],\n }),\n\n this.createTable({\n tableName: TABLE_SCORERS,\n schema: TABLE_SCHEMAS[TABLE_SCORERS],\n }),\n ];\n\n // Only create resources table for storage adapters that support it\n if (this.supports.resourceWorkingMemory) {\n tableCreationTasks.push(\n this.createTable({\n tableName: TABLE_RESOURCES,\n schema: TABLE_SCHEMAS[TABLE_RESOURCES],\n }),\n );\n }\n\n if (this.supports.aiTracing) {\n tableCreationTasks.push(\n this.createTable({\n tableName: TABLE_AI_SPANS,\n schema: TABLE_SCHEMAS[TABLE_AI_SPANS],\n }),\n );\n }\n\n this.hasInitialized = Promise.all(tableCreationTasks).then(() => true);\n\n await this.hasInitialized;\n\n await this?.alterTable?.({\n tableName: TABLE_MESSAGES,\n schema: TABLE_SCHEMAS[TABLE_MESSAGES],\n ifNotExists: ['resourceId'],\n });\n await this?.alterTable?.({\n tableName: TABLE_WORKFLOW_SNAPSHOT,\n schema: TABLE_SCHEMAS[TABLE_WORKFLOW_SNAPSHOT],\n ifNotExists: ['resourceId'],\n });\n }\n\n async persistWorkflowSnapshot({\n workflowName,\n runId,\n resourceId,\n snapshot,\n }: {\n workflowName: string;\n runId: string;\n resourceId?: string;\n snapshot: WorkflowRunState;\n }): Promise<void> {\n await this.init();\n\n const data = {\n workflow_name: workflowName,\n run_id: runId,\n resourceId,\n snapshot,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n this.logger.debug('Persisting workflow snapshot', { workflowName, runId, data });\n await this.insert({\n tableName: TABLE_WORKFLOW_SNAPSHOT,\n record: data,\n });\n }\n\n abstract updateWorkflowResults({\n workflowName,\n runId,\n stepId,\n result,\n }: {\n workflowName: string;\n runId: string;\n stepId: string;\n result: StepResult<any, any, any, any>;\n runtimeContext: Record<string, any>;\n }): Promise<Record<string, StepResult<any, any, any, any>>>;\n\n abstract updateWorkflowState({\n workflowName,\n runId,\n opts,\n }: {\n workflowName: string;\n runId: string;\n opts: {\n status: string;\n result?: StepResult<any, any, any, any>;\n error?: string;\n suspendedPaths?: Record<string, number[]>;\n waitingPaths?: Record<string, number[]>;\n };\n }): Promise<WorkflowRunState | undefined>;\n\n async loadWorkflowSnapshot({\n workflowName,\n runId,\n }: {\n workflowName: string;\n runId: string;\n }): Promise<WorkflowRunState | null> {\n if (!this.hasInitialized) {\n await this.init();\n }\n this.logger.debug('Loading workflow snapshot', { workflowName, runId });\n const d = await this.load<{ snapshot: WorkflowRunState }>({\n tableName: TABLE_WORKFLOW_SNAPSHOT,\n keys: { workflow_name: workflowName, run_id: runId },\n });\n\n return d ? d.snapshot : null;\n }\n\n /**\n * SCORERS\n */\n\n abstract getScoreById({ id }: { id: string }): Promise<ScoreRowData | null>;\n\n abstract saveScore(score: ValidatedSaveScorePayload): Promise<{ score: ScoreRowData }>;\n\n abstract getScoresByScorerId({\n scorerId,\n pagination,\n entityId,\n entityType,\n source,\n }: {\n scorerId: string;\n pagination: StoragePagination;\n entityId?: string;\n entityType?: string;\n source?: ScoringSource;\n }): Promise<{ pagination: PaginationInfo; scores: ScoreRowData[] }>;\n\n abstract getScoresByRunId({\n runId,\n pagination,\n }: {\n runId: string;\n pagination: StoragePagination;\n }): Promise<{ pagination: PaginationInfo; scores: ScoreRowData[] }>;\n\n abstract getScoresByEntityId({\n entityId,\n entityType,\n pagination,\n }: {\n pagination: StoragePagination;\n entityId: string;\n entityType: string;\n }): Promise<{ pagination: PaginationInfo; scores: ScoreRowData[] }>;\n\n abstract getEvals(\n options: {\n agentName?: string;\n type?: 'test' | 'live';\n } & PaginationArgs,\n ): Promise<PaginationInfo & { evals: EvalRow[] }>;\n\n abstract getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;\n\n abstract getWorkflowRuns(args?: {\n workflowName?: string;\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n offset?: number;\n resourceId?: string;\n }): Promise<WorkflowRuns>;\n\n abstract getWorkflowRunById(args: { runId: string; workflowName?: string }): Promise<WorkflowRun | null>;\n\n abstract getThreadsByResourceIdPaginated(\n args: {\n resourceId: string;\n page: number;\n perPage: number;\n } & ThreadSortOptions,\n ): Promise<PaginationInfo & { threads: StorageThreadType[] }>;\n\n abstract getMessagesPaginated(\n args: StorageGetMessagesArg & { format?: 'v1' | 'v2' },\n ): Promise<PaginationInfo & { messages: MastraMessageV1[] | MastraMessageV2[] }>;\n\n /**\n * OBSERVABILITY\n */\n\n /**\n * Provides hints for AI tracing strategy selection by the DefaultExporter.\n * Storage adapters can override this to specify their preferred and supported strategies.\n */\n public get aiTracingStrategy(): {\n preferred: TracingStrategy;\n supported: TracingStrategy[];\n } {\n if (this.stores?.observability) {\n return this.stores.observability.aiTracingStrategy;\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_TRACING_STRATEGY_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n\n /**\n * Creates a single AI span record in the storage provider.\n */\n async createAISpan(span: AISpanRecord): Promise<void> {\n if (this.stores?.observability) {\n return this.stores.observability.createAISpan(span);\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_CREATE_AI_SPAN_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n\n /**\n * Updates a single AI span with partial data. Primarily used for realtime trace creation.\n */\n async updateAISpan(params: {\n spanId: string;\n traceId: string;\n updates: Partial<Omit<AISpanRecord, 'spanId' | 'traceId'>>;\n }): Promise<void> {\n if (this.stores?.observability) {\n return this.stores.observability.updateAISpan(params);\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_UPDATE_AI_SPAN_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n\n /**\n * Retrieves a single AI trace with all its associated spans.\n */\n async getAITrace(traceId: string): Promise<AITraceRecord | null> {\n if (this.stores?.observability) {\n return this.stores.observability.getAITrace(traceId);\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_GET_AI_TRACE_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n\n /**\n * Retrieves a paginated list of AI traces with optional filtering.\n */\n async getAITracesPaginated(\n args: AITracesPaginatedArg,\n ): Promise<{ pagination: PaginationInfo; spans: AISpanRecord[] }> {\n if (this.stores?.observability) {\n return this.stores.observability.getAITracesPaginated(args);\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_GET_AI_TRACES_PAGINATED_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n\n /**\n * Creates multiple AI spans in a single batch.\n */\n async batchCreateAISpans(args: { records: AISpanRecord[] }): Promise<void> {\n if (this.stores?.observability) {\n return this.stores.observability.batchCreateAISpans(args);\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_BATCH_CREATE_AI_SPANS_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n\n /**\n * Updates multiple AI spans in a single batch.\n */\n async batchUpdateAISpans(args: {\n records: {\n traceId: string;\n spanId: string;\n updates: Partial<Omit<AISpanRecord, 'spanId' | 'traceId'>>;\n }[];\n }): Promise<void> {\n if (this.stores?.observability) {\n return this.stores.observability.batchUpdateAISpans(args);\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_BATCH_UPDATE_AI_SPANS_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n\n /**\n * Deletes multiple AI traces and all their associated spans in a single batch operation.\n */\n async batchDeleteAITraces(args: { traceIds: string[] }): Promise<void> {\n if (this.stores?.observability) {\n return this.stores.observability.batchDeleteAITraces(args);\n }\n throw new MastraError({\n id: 'MASTRA_STORAGE_BATCH_DELETE_AI_TRACES_NOT_SUPPORTED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.SYSTEM,\n text: `AI tracing is not supported by this storage adapter (${this.constructor.name})`,\n });\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { DefaultVoice } from './chunk-QQIBOVFQ.js';
2
2
  import { STREAM_FORMAT_SYMBOL, EMITTER_SYMBOL } from './chunk-NLNKQD2T.js';
3
- import { MastraLLMV1 } from './chunk-O5GOFG6A.js';
4
3
  import { InstrumentClass, Telemetry } from './chunk-TLJPVRO5.js';
4
+ import { MastraLLMV1 } from './chunk-O5GOFG6A.js';
5
5
  import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-ZDMAOD35.js';
6
6
  import { executeHook } from './chunk-TTELJD4F.js';
7
7
  import { zodToJsonSchema } from './chunk-PJKCPRYF.js';
@@ -197,16 +197,16 @@ var DefaultExecutionEngine=class extends ExecutionEngine{/**
197
197
  * @param graph The execution graph to execute
198
198
  * @param input The input data for the workflow
199
199
  * @returns A promise that resolves to the workflow output
200
- */async execute(params){const{workflowId,runId,graph,input,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;for(let i=startIdx;i<steps.length;i++){const entry=steps[i];try{lastOutput=await this.executeEntry({workflowId,runId,entry,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,executionContext:{workflowId,runId,executionPath:[i],suspendedPaths:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format},tracingContext:{currentSpan:workflowAISpan,isInternal:workflowAISpan?.isInternal},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{if(entry.type==="step"||entry.type==="waitForEvent"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="parallel"||entry.type==="conditional"){const parallelResult=this.getStepOutput(stepResults,entry)?.output;acc={...acc,...parallelResult};}else if(entry.type==="loop"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="foreach"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="sleep"||entry.type==="sleepUntil"){acc[entry.id]=stepResults[entry.id]?.output;}return acc;},{});}else if(step.type==="loop"){return stepResults[step.step.id]?.output;}else if(step.type==="foreach"){return stepResults[step.step.id]?.output;}}async executeSleep({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{duration,fn}=entry;const sleepSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleep: ${duration?`${duration}ms`:"dynamic"}`,attributes:{durationMs:duration,sleepType:fn?"dynamic":"fixed"},isInternal:tracingContext?.isInternal});if(fn){const stepCallId=randomUUID();duration=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,runCount:-1,tracingContext:{currentSpan:sleepSpan,isInternal:sleepSpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step=>{if(!step?.id){return null;}const result=stepResults[step.id];if(result?.status==="success"){return result.output;}return null;},// TODO: this function shouldn't have suspend probably?
200
+ */async execute(params){const{workflowId,runId,resourceId,graph,input,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId,resourceId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;for(let i=startIdx;i<steps.length;i++){const entry=steps[i];try{lastOutput=await this.executeEntry({workflowId,runId,resourceId,entry,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,executionContext:{workflowId,runId,executionPath:[i],suspendedPaths:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format},tracingContext:{currentSpan:workflowAISpan,isInternal:workflowAISpan?.isInternal},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{if(entry.type==="step"||entry.type==="waitForEvent"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="parallel"||entry.type==="conditional"){const parallelResult=this.getStepOutput(stepResults,entry)?.output;acc={...acc,...parallelResult};}else if(entry.type==="loop"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="foreach"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="sleep"||entry.type==="sleepUntil"){acc[entry.id]=stepResults[entry.id]?.output;}return acc;},{});}else if(step.type==="loop"){return stepResults[step.step.id]?.output;}else if(step.type==="foreach"){return stepResults[step.step.id]?.output;}}async executeSleep({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{duration,fn}=entry;const sleepSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleep: ${duration?`${duration}ms`:"dynamic"}`,attributes:{durationMs:duration,sleepType:fn?"dynamic":"fixed"},isInternal:tracingContext?.isInternal});if(fn){const stepCallId=randomUUID();duration=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,runCount:-1,tracingContext:{currentSpan:sleepSpan,isInternal:sleepSpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step=>{if(!step?.id){return null;}const result=stepResults[step.id];if(result?.status==="success"){return result.output;}return null;},// TODO: this function shouldn't have suspend probably?
201
201
  suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:stepCallId,name:"sleep",runId},writableStream)});sleepSpan?.update({attributes:{durationMs:duration}});}try{await new Promise(resolve=>setTimeout(resolve,!duration||duration<0?0:duration));sleepSpan?.end();}catch(e){sleepSpan?.error({error:e});}}async executeSleepUntil({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{date,fn}=entry;const sleepUntilSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleepUntil: ${date?date.toISOString():"dynamic"}`,attributes:{untilDate:date,durationMs:date?Math.max(0,date.getTime()-Date.now()):void 0,sleepType:fn?"dynamic":"fixed"},isInternal:tracingContext?.isInternal});if(fn){const stepCallId=randomUUID();date=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,runCount:-1,tracingContext:{currentSpan:sleepUntilSpan,isInternal:sleepUntilSpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step=>{if(!step?.id){return null;}const result=stepResults[step.id];if(result?.status==="success"){return result.output;}return null;},// TODO: this function shouldn't have suspend probably?
202
- suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:stepCallId,name:"sleepUntil",runId},writableStream)});const time2=!date?0:date.getTime()-Date.now();sleepUntilSpan?.update({attributes:{durationMs:Math.max(0,time2)}});}const time=!date?0:date?.getTime()-Date.now();try{await new Promise(resolve=>setTimeout(resolve,time<0?0:time));sleepUntilSpan?.end();}catch(e){sleepUntilSpan?.error({error:e});}}async executeWaitForEvent({event,emitter,timeout,tracingContext}){const waitSpan=tracingContext?.currentSpan?.createChildSpan({type:"workflow_wait_event"/* WORKFLOW_WAIT_EVENT */,name:`wait: ${event}`,attributes:{eventName:event,timeoutMs:timeout},isInternal:tracingContext?.isInternal});const startTime=Date.now();return new Promise((resolve,reject)=>{const cb=eventData=>{waitSpan?.end({output:eventData,attributes:{eventReceived:true,waitDurationMs:Date.now()-startTime}});resolve(eventData);};if(timeout){setTimeout(()=>{emitter.off(`user-event-${event}`,cb);const error=new Error("Timeout waiting for event");waitSpan?.error({error,attributes:{eventReceived:false,waitDurationMs:Date.now()-startTime}});reject(error);},timeout);}emitter.once(`user-event-${event}`,cb);});}async executeStep({workflowId,runId,step,stepResults,executionContext,resume,prevOutput,emitter,abortController,runtimeContext,skipEmits=false,writableStream,disableScorers,serializedStepGraph,tracingContext}){const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepCallId=randomUUID();const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{}),status:"running"};const stepAISpan=tracingContext.currentSpan?.createChildSpan({name:`workflow step: '${step.id}'`,type:"workflow_step"/* WORKFLOW_STEP */,input:prevOutput,attributes:{stepId:step.id},isInternal:tracingContext?.isInternal});if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,stepCallId,...stepInfo}});}await this.persistStepUpdate({workflowId,runId,serializedStepGraph,stepResults:{...stepResults,[step.id]:stepInfo},executionContext,workflowStatus:"running",runtimeContext});const _runStep=(step2,spanName,attributes)=>{return async data=>{const telemetry=this.mastra?.getTelemetry();const span=executionContext.executionSpan;if(!telemetry||!span){return step2.execute(data);}return context.with(trace.setSpan(context.active(),span),async()=>{return telemetry.traceMethod(step2.execute.bind(step2),{spanName,attributes})(data);});};};const runStep=_runStep(step,`workflow.${workflowId}.step.${step.id}`,{componentName:workflowId,runId});let execResults;const retries=step.retries??executionContext.retryConfig.attempts??0;const delay2=executionContext.retryConfig.delay??0;for(let i=0;i<retries+1;i++){if(i>0&&delay2){await new Promise(resolve=>setTimeout(resolve,delay2));}try{let suspended;let bailed;const result=await runStep({runId,workflowId,mastra:this.mastra?wrapMastra(this.mastra,{currentSpan:stepAISpan}):void 0,runtimeContext,inputData:prevOutput,runCount:this.getOrGenerateRunCount(step.id),resumeData:resume?.steps[0]===step.id?resume?.resumePayload:void 0,tracingContext:{currentSpan:stepAISpan,isInternal:stepAISpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step2=>{if(!step2?.id){return null;}const result2=stepResults[step2.id];if(result2?.status==="success"){return result2.output;}return null;},suspend:async suspendPayload=>{executionContext.suspendedPaths[step.id]=executionContext.executionPath;suspended={payload:suspendPayload};},bail:result2=>{bailed={payload:result2};},abort:()=>{abortController?.abort();},// Only pass resume data if this step was actually suspended before
202
+ suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:stepCallId,name:"sleepUntil",runId},writableStream)});const time2=!date?0:date.getTime()-Date.now();sleepUntilSpan?.update({attributes:{durationMs:Math.max(0,time2)}});}const time=!date?0:date?.getTime()-Date.now();try{await new Promise(resolve=>setTimeout(resolve,time<0?0:time));sleepUntilSpan?.end();}catch(e){sleepUntilSpan?.error({error:e});}}async executeWaitForEvent({event,emitter,timeout,tracingContext}){const waitSpan=tracingContext?.currentSpan?.createChildSpan({type:"workflow_wait_event"/* WORKFLOW_WAIT_EVENT */,name:`wait: ${event}`,attributes:{eventName:event,timeoutMs:timeout},isInternal:tracingContext?.isInternal});const startTime=Date.now();return new Promise((resolve,reject)=>{const cb=eventData=>{waitSpan?.end({output:eventData,attributes:{eventReceived:true,waitDurationMs:Date.now()-startTime}});resolve(eventData);};if(timeout){setTimeout(()=>{emitter.off(`user-event-${event}`,cb);const error=new Error("Timeout waiting for event");waitSpan?.error({error,attributes:{eventReceived:false,waitDurationMs:Date.now()-startTime}});reject(error);},timeout);}emitter.once(`user-event-${event}`,cb);});}async executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,emitter,abortController,runtimeContext,skipEmits=false,writableStream,disableScorers,serializedStepGraph,tracingContext}){const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepCallId=randomUUID();const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{}),status:"running"};const stepAISpan=tracingContext.currentSpan?.createChildSpan({name:`workflow step: '${step.id}'`,type:"workflow_step"/* WORKFLOW_STEP */,input:prevOutput,attributes:{stepId:step.id},isInternal:tracingContext?.isInternal});if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,stepCallId,...stepInfo}});}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults:{...stepResults,[step.id]:stepInfo},executionContext,workflowStatus:"running",runtimeContext});const _runStep=(step2,spanName,attributes)=>{return async data=>{const telemetry=this.mastra?.getTelemetry();const span=executionContext.executionSpan;if(!telemetry||!span){return step2.execute(data);}return context.with(trace.setSpan(context.active(),span),async()=>{return telemetry.traceMethod(step2.execute.bind(step2),{spanName,attributes})(data);});};};const runStep=_runStep(step,`workflow.${workflowId}.step.${step.id}`,{componentName:workflowId,runId,resourceId:resourceId??""});let execResults;const retries=step.retries??executionContext.retryConfig.attempts??0;const delay2=executionContext.retryConfig.delay??0;for(let i=0;i<retries+1;i++){if(i>0&&delay2){await new Promise(resolve=>setTimeout(resolve,delay2));}try{let suspended;let bailed;const result=await runStep({runId,resourceId,workflowId,mastra:this.mastra?wrapMastra(this.mastra,{currentSpan:stepAISpan}):void 0,runtimeContext,inputData:prevOutput,runCount:this.getOrGenerateRunCount(step.id),resumeData:resume?.steps[0]===step.id?resume?.resumePayload:void 0,tracingContext:{currentSpan:stepAISpan,isInternal:stepAISpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step2=>{if(!step2?.id){return null;}const result2=stepResults[step2.id];if(result2?.status==="success"){return result2.output;}return null;},suspend:async suspendPayload=>{executionContext.suspendedPaths[step.id]=executionContext.executionPath;suspended={payload:suspendPayload};},bail:result2=>{bailed={payload:result2};},abort:()=>{abortController?.abort();},// Only pass resume data if this step was actually suspended before
203
203
  // This prevents pending nested workflows from trying to resume instead of start
204
204
  resume:stepResults[step.id]?.status==="suspended"?{steps:resume?.steps?.slice(1)||[],resumePayload:resume?.resumePayload,// @ts-ignore
205
205
  runId:stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId}:void 0,[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:stepCallId,name:step.id,runId},writableStream),// Disable scorers must be explicitly set to false they are on by default
206
- scorers:disableScorers===false?void 0:step.scorers});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:prevOutput,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:tracingContext.currentSpan,isInternal:true}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:id,scorerObject,runId,input:[input],output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},isInternal:tracingContext?.isInternal});let execResults;const results=await Promise.all(entry.steps.map((step,i)=>this.executeEntry({workflowId,runId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,i],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan},tracingContext:{currentSpan:parallelSpan,isInternal:parallelSpan?.isInternal},emitter,abortController,runtimeContext,writableStream,disableScorers})));const hasFailed=results.find(result=>result.result.status==="failed");const hasSuspended=results.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[entry.steps[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){parallelSpan?.error({error:new Error(execResults.error)});}else {parallelSpan?.end({output:execResults.output||execResults});}return execResults;}async executeConditional({workflowId,runId,entry,prevOutput,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const conditionalSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_conditional"/* WORKFLOW_CONDITIONAL */,name:`conditional: '${entry.conditions.length} conditions'`,input:prevOutput,attributes:{conditionCount:entry.conditions.length},isInternal:tracingContext?.isInternal});let execResults;const truthyIndexes=(await Promise.all(entry.conditions.map(async(cond,index)=>{const evalSpan=conditionalSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition '${index}'`,input:prevOutput,attributes:{conditionIndex:index},isInternal:tracingContext?.isInternal});try{const result=await cond({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,runCount:-1,tracingContext:{currentSpan:evalSpan,isInternal:evalSpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step=>{if(!step?.id){return null;}const result2=stepResults[step.id];if(result2?.status==="success"){return result2.output;}return null;},// TODO: this function shouldn't have suspend probably?
207
- suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:randomUUID(),name:"conditional",runId},writableStream)});evalSpan?.end({output:result,attributes:{result:!!result}});return result?index:null;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_CONDITION_EVALUATION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error evaluating condition: ");evalSpan?.error({error,attributes:{result:false}});return null;}}))).filter(index=>index!==null);const stepsToRun=entry.steps.filter((_,index)=>truthyIndexes.includes(index));conditionalSpan?.update({attributes:{truthyIndexes,selectedSteps:stepsToRun.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)}});const stepsToExecute=stepsToRun.filter(step=>{if(resume&&step.type==="step"){const existingResult=stepResults[step.step.id];return !existingResult||existingResult.status==="suspended"||existingResult.status==="failed";}return true;});const results=await Promise.all(stepsToExecute.map((step,_index)=>this.executeEntry({workflowId,runId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,stepsToRun.indexOf(step)],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan},tracingContext:{currentSpan:conditionalSpan,isInternal:conditionalSpan?.isInternal},emitter,abortController,runtimeContext,writableStream,disableScorers})));const mergedStepResults={...stepResults};results.forEach(result=>{if("stepResults"in result&&result.stepResults){Object.assign(mergedStepResults,result.stepResults);}});const allResults=stepsToRun.map(step=>{if(step.type==="step"){const stepResult=mergedStepResults[step.step.id];if(stepResult){return {result:stepResult};}}return {result:{status:"success",output:{}}};}).filter(Boolean);const hasFailed=allResults.find(result=>result.result.status==="failed");const hasSuspended=allResults.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:allResults.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[stepsToRun[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){conditionalSpan?.error({error:new Error(execResults.error)});}else {conditionalSpan?.end({output:execResults.output||execResults});}return execResults;}async executeLoop({workflowId,runId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,condition}=entry;const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: '${entry.loopType}'`,input:prevOutput,attributes:{loopType:entry.loopType},isInternal:tracingContext?.isInternal});let isTrue=true;let iteration=0;const prevPayload=stepResults[step.id]?.payload;let result={status:"success",output:prevPayload??prevOutput};let currentResume=resume;do{result=await this.executeStep({workflowId,runId,step,stepResults,executionContext,resume:currentResume,prevOutput:result.output,tracingContext:{currentSpan:loopSpan,isInternal:loopSpan?.isInternal},emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});if(currentResume&&result.status!=="suspended"){currentResume=void 0;}if(result.status!=="success"){loopSpan?.end({attributes:{totalIterations:iteration}});return result;}const evalSpan=loopSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition: '${entry.loopType}'`,input:selectFields(result.output,["stepResult","output.text","output.object","messages"]),attributes:{conditionIndex:iteration},isInternal:tracingContext?.isInternal});isTrue=await condition({workflowId,runId,mastra:this.mastra,runtimeContext,inputData:result.output,runCount:-1,tracingContext:{currentSpan:evalSpan,isInternal:evalSpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step2=>{if(!step2?.id){return null;}const result2=stepResults[step2.id];return result2?.status==="success"?result2.output:null;},suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:randomUUID(),name:"loop",runId},writableStream)});evalSpan?.end({output:isTrue});iteration++;}while(entry.loopType==="dowhile"?isTrue:!isTrue);loopSpan?.end({output:result.output,attributes:{totalIterations:iteration}});return result;}async executeForeach({workflowId,runId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,opts}=entry;const results=[];const concurrency=opts.concurrency;const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: 'foreach'`,input:prevOutput,attributes:{loopType:"foreach",concurrency},isInternal:tracingContext?.isInternal});await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,status:"running",...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{status:"running",...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,...stepInfo,status:"running"}});for(let i=0;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map(item=>{return this.executeStep({workflowId,runId,step,stepResults,executionContext,resume,prevOutput:item,tracingContext:{currentSpan:loopSpan,isInternal:loopSpan?.isInternal},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const result of itemsResults){if(result.status!=="success"){const{status,error,suspendPayload,suspendedAt,endedAt,output}=result;const execResults={status,error,suspendPayload,suspendedAt,endedAt,output};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});}return result;}results.push(result?.output);}}await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,status:"success",output:results,endedAt:Date.now()},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,status:"success",output:results,endedAt:Date.now()}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,status:"success",output:results,endedAt:Date.now()}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});loopSpan?.end({output:results});return {...stepInfo,status:"success",output:results,//@ts-ignore
208
- endedAt:Date.now()};}async persistStepUpdate({workflowId,runId,stepResults,serializedStepGraph,executionContext,workflowStatus,result,error,runtimeContext}){const runtimeContextObj={};runtimeContext.forEach((value,key)=>{runtimeContextObj[key]=value;});await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:workflowId,runId,snapshot:{runId,status:workflowStatus,value:{},context:stepResults,activePaths:[],serializedStepGraph,suspendedPaths:executionContext.suspendedPaths,waitingPaths:{},result,error,runtimeContext:runtimeContextObj,// @ts-ignore
209
- timestamp:Date.now()}});}async executeEntry({workflowId,runId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const prevOutput=this.getStepOutput(stepResults,prevStep);let execResults;if(entry.type==="step"){const{step}=entry;execResults=await this.executeStep({workflowId,runId,step,stepResults,executionContext,resume,prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(resume?.resumePath?.length&&entry.type==="parallel"){const idx=resume.resumePath.shift();const resumedStepResult=await this.executeEntry({workflowId,runId,entry:entry.steps[idx],prevStep,serializedStepGraph,stepResults,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,idx],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan},tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});if(resumedStepResult.stepResults){Object.assign(stepResults,resumedStepResult.stepResults);}const allParallelStepsComplete=entry.steps.every(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="success";}return true;});if(allParallelStepsComplete){execResults={status:"success",output:entry.steps.reduce((acc,parallelStep)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="success"){acc[parallelStep.step.id]=stepResult.output;}}return acc;},{})};}else {const stillSuspended=entry.steps.find(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="suspended";}return false;});execResults={status:"suspended",payload:stillSuspended&&stillSuspended.type==="step"?stepResults[stillSuspended.step.id]?.suspendPayload:{}};}const updatedExecutionContext={...executionContext,...resumedStepResult.executionContext,suspendedPaths:{...executionContext.suspendedPaths,...resumedStepResult.executionContext?.suspendedPaths}};if(execResults.status==="suspended"){entry.steps.forEach((parallelStep,stepIndex)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="suspended"){updatedExecutionContext.suspendedPaths[parallelStep.step.id]=[...executionContext.executionPath,stepIndex];}}});}return {result:execResults,stepResults:resumedStepResult.stepResults,executionContext:updatedExecutionContext};}else if(entry.type==="parallel"){execResults=await this.executeParallel({workflowId,runId,entry,prevStep,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="conditional"){execResults=await this.executeConditional({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="loop"){execResults=await this.executeLoop({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="foreach"){execResults=await this.executeForeach({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="sleep"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleep({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="sleepUntil"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleepUntil({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="waitForEvent"){const startedAt=Date.now();let eventData;await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.step.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.step.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.step.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});try{eventData=await this.executeWaitForEvent({event:entry.event,emitter,timeout:entry.timeout,tracingContext});const{step}=entry;execResults=await this.executeStep({workflowId,runId,step,stepResults,executionContext,resume:{resumePayload:eventData,steps:[entry.step.id]},prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}catch(error){execResults={status:"failed",error};}const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...execResults,...stepInfo};}if(entry.type==="step"||entry.type==="waitForEvent"||entry.type==="loop"||entry.type==="foreach"){stepResults[entry.step.id]=execResults;}if(abortController?.signal?.aborted){execResults={...execResults,status:"canceled"};}await this.persistStepUpdate({workflowId,runId,serializedStepGraph,stepResults,executionContext,workflowStatus:execResults.status==="success"?"running":execResults.status,runtimeContext});if(execResults.status==="canceled"){await emitter.emit("watch-v2",{type:"workflow-canceled",payload:{}});}return {result:execResults,stepResults,executionContext};}};// src/workflows/workflow.ts
206
+ scorers:disableScorers===false?void 0:step.scorers});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:prevOutput,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:tracingContext.currentSpan,isInternal:true}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:id,scorerObject,runId,input:[input],output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},isInternal:tracingContext?.isInternal});let execResults;const results=await Promise.all(entry.steps.map((step,i)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,i],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan},tracingContext:{currentSpan:parallelSpan,isInternal:parallelSpan?.isInternal},emitter,abortController,runtimeContext,writableStream,disableScorers})));const hasFailed=results.find(result=>result.result.status==="failed");const hasSuspended=results.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[entry.steps[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){parallelSpan?.error({error:new Error(execResults.error)});}else {parallelSpan?.end({output:execResults.output||execResults});}return execResults;}async executeConditional({workflowId,runId,resourceId,entry,prevOutput,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const conditionalSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_conditional"/* WORKFLOW_CONDITIONAL */,name:`conditional: '${entry.conditions.length} conditions'`,input:prevOutput,attributes:{conditionCount:entry.conditions.length},isInternal:tracingContext?.isInternal});let execResults;const truthyIndexes=(await Promise.all(entry.conditions.map(async(cond,index)=>{const evalSpan=conditionalSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition '${index}'`,input:prevOutput,attributes:{conditionIndex:index},isInternal:tracingContext?.isInternal});try{const result=await cond({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,runCount:-1,tracingContext:{currentSpan:evalSpan,isInternal:evalSpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step=>{if(!step?.id){return null;}const result2=stepResults[step.id];if(result2?.status==="success"){return result2.output;}return null;},// TODO: this function shouldn't have suspend probably?
207
+ suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:randomUUID(),name:"conditional",runId},writableStream)});evalSpan?.end({output:result,attributes:{result:!!result}});return result?index:null;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_CONDITION_EVALUATION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error evaluating condition: ");evalSpan?.error({error,attributes:{result:false}});return null;}}))).filter(index=>index!==null);const stepsToRun=entry.steps.filter((_,index)=>truthyIndexes.includes(index));conditionalSpan?.update({attributes:{truthyIndexes,selectedSteps:stepsToRun.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)}});const stepsToExecute=stepsToRun.filter(step=>{if(resume&&step.type==="step"){const existingResult=stepResults[step.step.id];return !existingResult||existingResult.status==="suspended"||existingResult.status==="failed";}return true;});const results=await Promise.all(stepsToExecute.map((step,_index)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,stepsToRun.indexOf(step)],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan},tracingContext:{currentSpan:conditionalSpan,isInternal:conditionalSpan?.isInternal},emitter,abortController,runtimeContext,writableStream,disableScorers})));const mergedStepResults={...stepResults};results.forEach(result=>{if("stepResults"in result&&result.stepResults){Object.assign(mergedStepResults,result.stepResults);}});const allResults=stepsToRun.map(step=>{if(step.type==="step"){const stepResult=mergedStepResults[step.step.id];if(stepResult){return {result:stepResult};}}return {result:{status:"success",output:{}}};}).filter(Boolean);const hasFailed=allResults.find(result=>result.result.status==="failed");const hasSuspended=allResults.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:allResults.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[stepsToRun[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){conditionalSpan?.error({error:new Error(execResults.error)});}else {conditionalSpan?.end({output:execResults.output||execResults});}return execResults;}async executeLoop({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,condition}=entry;const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: '${entry.loopType}'`,input:prevOutput,attributes:{loopType:entry.loopType},isInternal:tracingContext?.isInternal});let isTrue=true;let iteration=0;const prevPayload=stepResults[step.id]?.payload;let result={status:"success",output:prevPayload??prevOutput};let currentResume=resume;do{result=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:currentResume,prevOutput:result.output,tracingContext:{currentSpan:loopSpan,isInternal:loopSpan?.isInternal},emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});if(currentResume&&result.status!=="suspended"){currentResume=void 0;}if(result.status!=="success"){loopSpan?.end({attributes:{totalIterations:iteration}});return result;}const evalSpan=loopSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition: '${entry.loopType}'`,input:selectFields(result.output,["stepResult","output.text","output.object","messages"]),attributes:{conditionIndex:iteration},isInternal:tracingContext?.isInternal});isTrue=await condition({workflowId,runId,mastra:this.mastra,runtimeContext,inputData:result.output,runCount:-1,tracingContext:{currentSpan:evalSpan,isInternal:evalSpan?.isInternal},getInitData:()=>stepResults?.input,getStepResult:step2=>{if(!step2?.id){return null;}const result2=stepResults[step2.id];return result2?.status==="success"?result2.output:null;},suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:randomUUID(),name:"loop",runId},writableStream)});evalSpan?.end({output:isTrue});iteration++;}while(entry.loopType==="dowhile"?isTrue:!isTrue);loopSpan?.end({output:result.output,attributes:{totalIterations:iteration}});return result;}async executeForeach({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,opts}=entry;const results=[];const concurrency=opts.concurrency;const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: 'foreach'`,input:prevOutput,attributes:{loopType:"foreach",concurrency},isInternal:tracingContext?.isInternal});await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,status:"running",...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{status:"running",...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,...stepInfo,status:"running"}});for(let i=0;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map(item=>{return this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput:item,tracingContext:{currentSpan:loopSpan,isInternal:loopSpan?.isInternal},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const result of itemsResults){if(result.status!=="success"){const{status,error,suspendPayload,suspendedAt,endedAt,output}=result;const execResults={status,error,suspendPayload,suspendedAt,endedAt,output};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});}return result;}results.push(result?.output);}}await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,status:"success",output:results,endedAt:Date.now()},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,status:"success",output:results,endedAt:Date.now()}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,status:"success",output:results,endedAt:Date.now()}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});loopSpan?.end({output:results});return {...stepInfo,status:"success",output:results,//@ts-ignore
208
+ endedAt:Date.now()};}async persistStepUpdate({workflowId,runId,resourceId,stepResults,serializedStepGraph,executionContext,workflowStatus,result,error,runtimeContext}){const runtimeContextObj={};runtimeContext.forEach((value,key)=>{runtimeContextObj[key]=value;});await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:workflowId,runId,resourceId,snapshot:{runId,status:workflowStatus,value:{},context:stepResults,activePaths:[],serializedStepGraph,suspendedPaths:executionContext.suspendedPaths,waitingPaths:{},result,error,runtimeContext:runtimeContextObj,// @ts-ignore
209
+ timestamp:Date.now()}});}async executeEntry({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const prevOutput=this.getStepOutput(stepResults,prevStep);let execResults;if(entry.type==="step"){const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(resume?.resumePath?.length&&entry.type==="parallel"){const idx=resume.resumePath.shift();const resumedStepResult=await this.executeEntry({workflowId,runId,resourceId,entry:entry.steps[idx],prevStep,serializedStepGraph,stepResults,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,idx],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan},tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});if(resumedStepResult.stepResults){Object.assign(stepResults,resumedStepResult.stepResults);}const allParallelStepsComplete=entry.steps.every(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="success";}return true;});if(allParallelStepsComplete){execResults={status:"success",output:entry.steps.reduce((acc,parallelStep)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="success"){acc[parallelStep.step.id]=stepResult.output;}}return acc;},{})};}else {const stillSuspended=entry.steps.find(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="suspended";}return false;});execResults={status:"suspended",payload:stillSuspended&&stillSuspended.type==="step"?stepResults[stillSuspended.step.id]?.suspendPayload:{}};}const updatedExecutionContext={...executionContext,...resumedStepResult.executionContext,suspendedPaths:{...executionContext.suspendedPaths,...resumedStepResult.executionContext?.suspendedPaths}};if(execResults.status==="suspended"){entry.steps.forEach((parallelStep,stepIndex)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="suspended"){updatedExecutionContext.suspendedPaths[parallelStep.step.id]=[...executionContext.executionPath,stepIndex];}}});}return {result:execResults,stepResults:resumedStepResult.stepResults,executionContext:updatedExecutionContext};}else if(entry.type==="parallel"){execResults=await this.executeParallel({workflowId,runId,entry,prevStep,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="conditional"){execResults=await this.executeConditional({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="loop"){execResults=await this.executeLoop({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="foreach"){execResults=await this.executeForeach({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="sleep"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleep({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="sleepUntil"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleepUntil({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="waitForEvent"){const startedAt=Date.now();let eventData;await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.step.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.step.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.step.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});try{eventData=await this.executeWaitForEvent({event:entry.event,emitter,timeout:entry.timeout,tracingContext});const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:{resumePayload:eventData,steps:[entry.step.id]},prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}catch(error){execResults={status:"failed",error};}const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...execResults,...stepInfo};}if(entry.type==="step"||entry.type==="waitForEvent"||entry.type==="loop"||entry.type==="foreach"){stepResults[entry.step.id]=execResults;}if(abortController?.signal?.aborted){execResults={...execResults,status:"canceled"};}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:execResults.status==="success"?"running":execResults.status,runtimeContext});if(execResults.status==="canceled"){await emitter.emit("watch-v2",{type:"workflow-canceled",payload:{}});}return {result:execResults,stepResults,executionContext};}};// src/workflows/workflow.ts
210
210
  function mapVariable(config){return config;}function createStep(params){if(params instanceof Agent){return {id:params.name,// @ts-ignore
211
211
  inputSchema:z.object({prompt:z.string()// resourceId: z.string().optional(),
212
212
  // threadId: z.string().optional(),
@@ -243,12 +243,18 @@ condition,loopType:"dountil",serializedCondition:{id:`${step.id}-condition`,fn:c
243
243
  */commit(){this.executionGraph=this.buildExecutionGraph();return this;}get stepGraph(){return this.stepFlow;}get serializedStepGraph(){return this.serializedStepFlow;}/**
244
244
  * Creates a new workflow run instance
245
245
  * @param options Optional configuration for the run
246
+ * @param options.runId Optional custom run ID, defaults to a random UUID
247
+ * @param options.resourceId Optional resource ID to associate with this run
248
+ * @param options.disableScorers Optional flag to disable scorers for this run
246
249
  * @returns A Run instance that can be used to execute the workflow
247
- */createRun(options){if(this.stepFlow.length===0){throw new Error("Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc.");}if(!this.executionGraph.steps){throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");}const runIdToUse=options?.runId||this.#mastra?.generateId()||randomUUID();const run=this.#runs.get(runIdToUse)??new Run({workflowId:this.id,runId:runIdToUse,executionEngine:this.executionEngine,executionGraph:this.executionGraph,mastra:this.#mastra,retryConfig:this.retryConfig,serializedStepGraph:this.serializedStepGraph,disableScorers:options?.disableScorers,cleanup:()=>this.#runs.delete(runIdToUse)});this.#runs.set(runIdToUse,run);this.mastra?.getLogger().warn("createRun() will be removed on September 16th, 2025. Use createRunAsync() instead.");return run;}/**
250
+ */createRun(options){if(this.stepFlow.length===0){throw new Error("Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc.");}if(!this.executionGraph.steps){throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");}const runIdToUse=options?.runId||this.#mastra?.generateId()||randomUUID();const run=this.#runs.get(runIdToUse)??new Run({workflowId:this.id,runId:runIdToUse,resourceId:options?.resourceId,executionEngine:this.executionEngine,executionGraph:this.executionGraph,mastra:this.#mastra,retryConfig:this.retryConfig,serializedStepGraph:this.serializedStepGraph,disableScorers:options?.disableScorers,cleanup:()=>this.#runs.delete(runIdToUse)});this.#runs.set(runIdToUse,run);this.mastra?.getLogger().warn("createRun() will be removed on September 16th, 2025. Use createRunAsync() instead.");return run;}/**
248
251
  * Creates a new workflow run instance and stores a snapshot of the workflow in the storage
249
252
  * @param options Optional configuration for the run
253
+ * @param options.runId Optional custom run ID, defaults to a random UUID
254
+ * @param options.resourceId Optional resource ID to associate with this run
255
+ * @param options.disableScorers Optional flag to disable scorers for this run
250
256
  * @returns A Run instance that can be used to execute the workflow
251
- */async createRunAsync(options){if(this.stepFlow.length===0){throw new Error("Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc.");}if(!this.executionGraph.steps){throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");}const runIdToUse=options?.runId||this.#mastra?.generateId()||randomUUID();const run=this.#runs.get(runIdToUse)??new Run({workflowId:this.id,runId:runIdToUse,executionEngine:this.executionEngine,executionGraph:this.executionGraph,mastra:this.#mastra,retryConfig:this.retryConfig,serializedStepGraph:this.serializedStepGraph,disableScorers:options?.disableScorers,cleanup:()=>this.#runs.delete(runIdToUse)});this.#runs.set(runIdToUse,run);const workflowSnapshotInStorage=await this.getWorkflowRunExecutionResult(runIdToUse,false);if(!workflowSnapshotInStorage){await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:this.id,runId:runIdToUse,snapshot:{runId:runIdToUse,status:"pending",value:{},context:{},activePaths:[],serializedStepGraph:this.serializedStepGraph,suspendedPaths:{},waitingPaths:{},result:void 0,error:void 0,// @ts-ignore
257
+ */async createRunAsync(options){if(this.stepFlow.length===0){throw new Error("Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc.");}if(!this.executionGraph.steps){throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");}const runIdToUse=options?.runId||this.#mastra?.generateId()||randomUUID();const run=this.#runs.get(runIdToUse)??new Run({workflowId:this.id,runId:runIdToUse,resourceId:options?.resourceId,executionEngine:this.executionEngine,executionGraph:this.executionGraph,mastra:this.#mastra,retryConfig:this.retryConfig,serializedStepGraph:this.serializedStepGraph,disableScorers:options?.disableScorers,cleanup:()=>this.#runs.delete(runIdToUse)});this.#runs.set(runIdToUse,run);const workflowSnapshotInStorage=await this.getWorkflowRunExecutionResult(runIdToUse,false);if(!workflowSnapshotInStorage){await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:this.id,runId:runIdToUse,resourceId:options?.resourceId,snapshot:{runId:runIdToUse,status:"pending",value:{},context:{},activePaths:[],serializedStepGraph:this.serializedStepGraph,suspendedPaths:{},waitingPaths:{},result:void 0,error:void 0,// @ts-ignore
252
258
  timestamp:Date.now()}});}return run;}async getScorers({runtimeContext=new RuntimeContext()}={}){const steps=this.steps;if(!steps||Object.keys(steps).length===0){return {};}const scorers={};for(const step of Object.values(steps)){if(step.scorers){let scorersToUse=step.scorers;if(typeof scorersToUse==="function"){scorersToUse=await scorersToUse({runtimeContext});}for(const[id,scorer]of Object.entries(scorersToUse)){scorers[id]=scorer;}}}return scorers;}// This method should only be called internally for nested workflow execution, as well as from mastra server handlers
253
259
  // To run a workflow use `.createRunAsync` and then `.start` or `.resume`
254
260
  async execute({runId,inputData,resumeData,suspend,resume,[EMITTER_SYMBOL]:emitter,mastra,runtimeContext,abort,abortSignal,runCount,tracingContext,writer}){this.__registerMastra(mastra);const isResume=!!(resume?.steps&&resume.steps.length>0);const run=isResume?await this.createRunAsync({runId:resume.runId}):await this.createRunAsync({runId});const nestedAbortCb=()=>{abort();};run.abortController.signal.addEventListener("abort",nestedAbortCb);abortSignal.addEventListener("abort",async()=>{run.abortController.signal.removeEventListener("abort",nestedAbortCb);await run.cancel();});const unwatchV2=run.watch(event=>{emitter.emit("nested-watch-v2",{event,workflowId:this.id});},"watch-v2");const unwatch=run.watch(event=>{emitter.emit("nested-watch",{event,workflowId:this.id,runId:run.runId,isResume:!!resume?.steps?.length});},"watch");if(runCount&&runCount>0&&resume?.steps?.length&&runtimeContext){runtimeContext.set("__mastraWorflowInputData",inputData);}const res=isResume?await run.resume({resumeData,step:resume.steps,runtimeContext,tracingContext}):await run.start({inputData,runtimeContext,tracingContext,writableStream:writer});unwatch();unwatchV2();const suspendedSteps=Object.entries(res.steps).filter(([_stepName,stepResult])=>{const stepRes=stepResult;return stepRes?.status==="suspended";});if(suspendedSteps?.length){for(const[stepName,stepResult]of suspendedSteps){const suspendPath=[stepName,...(stepResult?.suspendPayload?.__workflow_meta?.path??[])];await suspend({...stepResult?.suspendPayload,__workflow_meta:{runId:run.runId,path:suspendPath}});}}if(res.status==="failed"){throw res.error;}return res.status==="success"?res.result:void 0;}async getWorkflowRuns(args){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs. Mastra storage is not initialized");return {runs:[],total:0};}return storage.getWorkflowRuns({workflowName:this.id,...(args??{})});}async getWorkflowRunById(runId){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs from storage. Mastra storage is not initialized");return this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});return run??(this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null);}async getWorkflowRunSteps({runId,workflowId}){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run steps. Mastra storage is not initialized");return {};}const run=await storage.getWorkflowRunById({runId,workflowName:workflowId});let snapshot=run?.snapshot;if(!snapshot){return {};}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return {};}}const{serializedStepGraph,context}=snapshot;const{input,...steps}=context;let finalSteps={};for(const step of Object.keys(steps)){const stepGraph=serializedStepGraph.find(stepGraph2=>stepGraph2?.step?.id===step);finalSteps[step]=steps[step];if(stepGraph&&stepGraph?.step?.component==="WORKFLOW"){const nestedSteps=await this.getWorkflowRunSteps({runId,workflowId:step});if(nestedSteps){const updatedNestedSteps=Object.entries(nestedSteps).reduce((acc,[key,value])=>{acc[`${step}.${key}`]=value;return acc;},{});finalSteps={...finalSteps,...updatedNestedSteps};}}}return finalSteps;}async getWorkflowRunExecutionResult(runId,withNestedWorkflows=true){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run execution result. Mastra storage is not initialized");return null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});let snapshot=run?.snapshot;if(!snapshot){return null;}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return null;}}const fullSteps=withNestedWorkflows?await this.getWorkflowRunSteps({runId,workflowId:this.id}):snapshot.context;return {status:snapshot.status,result:snapshot.result,error:snapshot.error,payload:snapshot.context?.input,steps:fullSteps};}};var Run=class{#abortController;emitter;/**
@@ -256,6 +262,8 @@ async execute({runId,inputData,resumeData,suspend,resume,[EMITTER_SYMBOL]:emitte
256
262
  */workflowId;/**
257
263
  * Unique identifier for this run
258
264
  */runId;/**
265
+ * Unique identifier for the resource this run is associated with
266
+ */resourceId;/**
259
267
  * Whether to disable scorers for this run
260
268
  */disableScorers;/**
261
269
  * Internal state of the workflow run
@@ -267,9 +275,9 @@ async execute({runId,inputData,resumeData,suspend,resume,[EMITTER_SYMBOL]:emitte
267
275
  * The serialized step graph for this run
268
276
  */serializedStepGraph;/**
269
277
  * The storage for this run
270
- */#mastra;get mastra(){return this.#mastra;}closeStreamAction;executionResults;cleanup;retryConfig;constructor(params){this.workflowId=params.workflowId;this.runId=params.runId;this.serializedStepGraph=params.serializedStepGraph;this.executionEngine=params.executionEngine;this.executionGraph=params.executionGraph;this.#mastra=params.mastra;this.emitter=new EventEmitter();this.retryConfig=params.retryConfig;this.cleanup=params.cleanup;this.disableScorers=params.disableScorers;}get abortController(){if(!this.#abortController){this.#abortController=new AbortController();}return this.#abortController;}/**
278
+ */#mastra;get mastra(){return this.#mastra;}closeStreamAction;executionResults;cleanup;retryConfig;constructor(params){this.workflowId=params.workflowId;this.runId=params.runId;this.resourceId=params.resourceId;this.serializedStepGraph=params.serializedStepGraph;this.executionEngine=params.executionEngine;this.executionGraph=params.executionGraph;this.#mastra=params.mastra;this.emitter=new EventEmitter();this.retryConfig=params.retryConfig;this.cleanup=params.cleanup;this.disableScorers=params.disableScorers;}get abortController(){if(!this.#abortController){this.#abortController=new AbortController();}return this.#abortController;}/**
271
279
  * Cancels the workflow execution
272
- */async cancel(){this.abortController?.abort();}async sendEvent(event,data){this.emitter.emit(`user-event-${event}`,data);}async _start({inputData,runtimeContext,writableStream,tracingContext,tracingOptions,format}){const workflowAISpan=getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:inputData,attributes:{workflowId:this.workflowId},tracingContext,tracingOptions,runtimeContext});const traceId=getValidTraceId(workflowAISpan);const result=await this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,disableScorers:this.disableScorers,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:inputData,emitter:{emit:async(event,data)=>{this.emitter.emit(event,data);},on:(event,callback)=>{this.emitter.on(event,callback);},off:(event,callback)=>{this.emitter.off(event,callback);},once:(event,callback)=>{this.emitter.once(event,callback);}},retryConfig:this.retryConfig,runtimeContext:runtimeContext??new RuntimeContext(),abortController:this.abortController,writableStream,workflowAISpan,format});if(result.status!=="suspended"){this.cleanup?.();}result.traceId=traceId;return result;}/**
280
+ */async cancel(){this.abortController?.abort();}async sendEvent(event,data){this.emitter.emit(`user-event-${event}`,data);}async _start({inputData,runtimeContext,writableStream,tracingContext,tracingOptions,format}){const workflowAISpan=getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:inputData,attributes:{workflowId:this.workflowId},tracingContext,tracingOptions,runtimeContext});const traceId=getValidTraceId(workflowAISpan);const result=await this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,resourceId:this.resourceId,disableScorers:this.disableScorers,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:inputData,emitter:{emit:async(event,data)=>{this.emitter.emit(event,data);},on:(event,callback)=>{this.emitter.on(event,callback);},off:(event,callback)=>{this.emitter.off(event,callback);},once:(event,callback)=>{this.emitter.once(event,callback);}},retryConfig:this.retryConfig,runtimeContext:runtimeContext??new RuntimeContext(),abortController:this.abortController,writableStream,workflowAISpan,format});if(result.status!=="suspended"){this.cleanup?.();}result.traceId=traceId;return result;}/**
273
281
  * Starts the workflow execution with the provided input
274
282
  * @param input The input data for the workflow
275
283
  * @returns A promise that resolves to the workflow output
@@ -736,5 +744,5 @@ Target: ${this.targetLanguages.join("/")}${translate}`;}};// src/agent/input-pro
736
744
  var LanguageDetectorInputProcessor=class{name="language-detector";processor;constructor(options){this.processor=new LanguageDetector(options);}async process(args){return this.processor.processInput(args);}};
737
745
 
738
746
  export { AISDKV5OutputStream, Agent, DefaultExecutionEngine, ExecutionEngine, LanguageDetector, LanguageDetectorInputProcessor, LegacyStep, LegacyWorkflow, MastraModelOutput, ModerationInputProcessor, ModerationProcessor, PIIDetector, PIIDetectorInputProcessor, PromptInjectionDetector, PromptInjectionDetectorInputProcessor, RESOURCE_TYPES, Run, StructuredOutputProcessor, TripWire, UnicodeNormalizer, UnicodeNormalizerInputProcessor, WhenConditionReturnValue, Workflow, agentToStep, cloneStep, cloneWorkflow, createStep, createWorkflow, getActivePathsAndStatus, getResultActivePaths, getStepResult, getSuspendedPaths, isAgent, isConditionalKey, isErrorEvent, isFinalState, isLimboState, isTransitionEvent, isVariableReference, isWorkflow, loop, mapVariable, mergeChildValue, recursivelyCheckForFinalState, resolveVariables, updateStepInHierarchy, workflowToStep };
739
- //# sourceMappingURL=chunk-OSMP67E2.js.map
740
- //# sourceMappingURL=chunk-OSMP67E2.js.map
747
+ //# sourceMappingURL=chunk-J52TTT6T.js.map
748
+ //# sourceMappingURL=chunk-J52TTT6T.js.map