{"version":3,"file":"workflow-event-processor-CkjVcesJ.cjs","names":["z","MastraError","ErrorDomain","ErrorCategory","removeUndefinedValues","getErrorFromUnknown","result","PUBSUB_SYMBOL","STREAM_FORMAT_SYMBOL","resolveObservabilityContext","TripWire","resolveObservabilityContext","TripWire","MastraBase","RegisteredLogger","EntityType","executeWithContext","ToolStream","PUBSUB_SYMBOL","STREAM_FORMAT_SYMBOL","createObservabilityContext","getErrorFromUnknown","MastraError","ErrorDomain","ErrorCategory","MastraNonRetryableError","TripWire","RequestContext","RequestContext","RequestContext","getErrorFromUnknown","MastraError","ErrorDomain","ErrorCategory","EventEmitter","RequestContext","#dispatch","#setDeliveryAttempts","#tryResolveWorkflow"],"sources":["../src/workflows/stream-utils.ts","../src/workflows/step.ts","../src/workflows/step-entry.ts","../src/workflows/utils.ts","../src/workflows/entry-executors/run-agent-entry.ts","../src/workflows/entry-executors/run-tool-entry.ts","../src/workflows/mapping-template.ts","../src/workflows/entry-executors/run-mapping-entry.ts","../src/workflows/evented/workflow-event-processor/utils.ts","../src/workflows/evented/helpers.ts","../src/events/processor.ts","../src/workflows/evented/step-executor.ts","../src/workflows/evented/types.ts","../src/workflows/evented/workflow-event-processor/loop.ts","../src/workflows/evented/workflow-event-processor/parallel.ts","../src/workflows/evented/workflow-event-processor/sleep.ts","../src/workflows/evented/workflow-event-processor/index.ts"],"sourcesContent":["export type StreamChunkWriter = {\n  write: (chunk: unknown) => Promise<void>;\n};\n\nexport async function forwardAgentStreamChunk({\n  writer,\n  chunk,\n}: {\n  writer?: StreamChunkWriter;\n  chunk: unknown;\n}): Promise<void> {\n  if (!writer) {\n    return;\n  }\n\n  await writer.write(chunk);\n}\n","import type { ActorSignal } from '../auth/ee';\nimport type { MastraScorers } from '../evals';\nimport type { PubSub } from '../events';\nimport type { Mastra } from '../mastra';\nimport type { ObservabilityContext } from '../observability';\nimport type { RequestContext } from '../request-context';\nimport type { InferStandardSchemaOutput, StandardSchemaWithJSON } from '../schema';\nimport type { ToolStream } from '../tools/stream';\nimport type { DynamicArgument } from '../types';\nimport type { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from './constants';\nimport type { OutputWriter, StepResult, StepMetadata } from './types';\nimport type { Workflow } from './workflow';\n\nexport type SuspendOptions = {\n  resumeLabel?: string | string[];\n} & Record<string, any>;\n\n// Create a unique symbol that only exists at the type level\ndeclare const SuspendBrand: unique symbol;\n\n// Create a branded type that can ONLY be produced by suspend()\nexport type InnerOutput = void & { readonly [SuspendBrand]: never };\n\nexport type ExecuteFunctionParams<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResume,\n  TSuspend,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = Partial<ObservabilityContext> & {\n  runId: string;\n  resourceId?: string;\n  workflowId: string;\n  mastra: Mastra;\n  requestContext: RequestContext<TRequestContext>;\n  actor?: ActorSignal;\n  inputData: TStepInput;\n  state: TState;\n  setState(state: TState): Promise<void>;\n  resumeData?: TResume;\n  suspendData?: TSuspend;\n  retryCount: number;\n  getInitData<T>(): T extends Workflow<any, any, any, any, any, any, any, any>\n    ? InferStandardSchemaOutput<T['inputSchema']>\n    : T;\n  getStepResult<TOutput>(step: string): TOutput;\n  getStepResult<TStep extends Step<string, any, any, any, any, any, EngineType>>(\n    step: TStep,\n  ): InferStandardSchemaOutput<TStep['outputSchema']>;\n  suspend: unknown extends TSuspend\n    ? (suspendPayload?: TSuspend, suspendOptions?: SuspendOptions) => InnerOutput | Promise<InnerOutput>\n    : (suspendPayload: TSuspend, suspendOptions?: SuspendOptions) => InnerOutput | Promise<InnerOutput>;\n  bail(result: TStepOutput): InnerOutput;\n  bail<T>(\n    result: T extends Workflow<any, any, any, any, any, infer TWorkflowOutput, any, any> ? TWorkflowOutput : T,\n  ): InnerOutput;\n  abort(): void;\n  resume?: {\n    steps: string[];\n    resumePayload: TResume;\n  };\n  restart?: boolean;\n  [PUBSUB_SYMBOL]: PubSub;\n  [STREAM_FORMAT_SYMBOL]: 'legacy' | 'vnext' | undefined;\n  engine: EngineType;\n  abortSignal: AbortSignal;\n  writer: ToolStream;\n  outputWriter?: OutputWriter;\n  validateSchemas?: boolean;\n};\n\nexport type ConditionFunctionParams<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = Omit<\n  ExecuteFunctionParams<TState, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema, EngineType, TRequestContext>,\n  'setState' | 'suspend'\n>;\n\nexport type ExecuteFunction<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = (\n  params: ExecuteFunctionParams<\n    TState,\n    TStepInput,\n    TStepOutput,\n    TResumeSchema,\n    TSuspendSchema,\n    EngineType,\n    TRequestContext\n  >,\n) => Promise<TStepOutput | InnerOutput>;\n\nexport type ConditionFunction<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = (\n  params: ConditionFunctionParams<\n    TState,\n    TStepInput,\n    TStepOutput,\n    TResumeSchema,\n    TSuspendSchema,\n    EngineType,\n    TRequestContext\n  >,\n) => Promise<boolean>;\n\nexport type LoopConditionFunction<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = (\n  params: ConditionFunctionParams<\n    TState,\n    TStepInput,\n    TStepOutput,\n    TResumeSchema,\n    TSuspendSchema,\n    EngineType,\n    TRequestContext\n  > & {\n    iterationCount: number;\n  },\n) => Promise<boolean>;\n\n// Define a Step interface\nexport interface Step<\n  TStepId extends string = string,\n  TState = unknown,\n  TInput = unknown,\n  TOutput = unknown,\n  TResume = unknown,\n  TSuspend = unknown,\n  TEngineType = any,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> {\n  id: TStepId;\n  description?: string;\n  inputSchema: StandardSchemaWithJSON<TInput>;\n  outputSchema: StandardSchemaWithJSON<TOutput>;\n  resumeSchema?: StandardSchemaWithJSON<TResume>;\n  suspendSchema?: StandardSchemaWithJSON<TSuspend>;\n  stateSchema?: StandardSchemaWithJSON<TState>;\n  /**\n   * Optional schema for validating request context values.\n   * When provided, the request context will be validated against this schema before step execution.\n   */\n  requestContextSchema?: StandardSchemaWithJSON<TRequestContext>;\n  execute: ExecuteFunction<TState, TInput, TOutput, TResume, TSuspend, TEngineType, TRequestContext>;\n  scorers?: DynamicArgument<MastraScorers>;\n  retries?: number;\n  component?: string;\n  metadata?: StepMetadata;\n}\n\nexport const getStepResult = (stepResults: Record<string, StepResult<any, any, any, any>>, step: any) => {\n  let result;\n\n  if (typeof step === 'string') {\n    result = stepResults[step];\n  } else {\n    if (!step?.id) {\n      return null;\n    }\n\n    result = stepResults[step.id];\n  }\n\n  return result?.status === 'success' ? result.output : null;\n};\n","import { z } from 'zod';\nimport type { Mastra } from '../mastra';\nimport { toStandardSchema } from '../schema';\nimport type { Step } from './step';\nimport type { SingleStepEntry } from './types';\nimport type { Workflow } from './workflow';\n\n/**\n * Accessors for the {@link SingleStepEntry} union.\n *\n * This module is the single place allowed to pattern-match the union's shape.\n * Everything else (both engines, handlers, utils) should go through these\n * helpers so that adding a new variant means changing exactly one file.\n *\n * Union *shape* questions (id, retries, schemas, …) live here; how each\n * declarative kind is *interpreted* at run time lives in `./entry-executors`.\n */\n\n/**\n * The id of a single step-like entry. Plain `step` entries key off the wrapped\n * step's id; declarative variants (agent / tool / mapping) carry their own `id`.\n */\nexport function getEntryId(entry: SingleStepEntry): string {\n  return entry.type === 'step' ? entry.step.id : entry.id;\n}\n\n/**\n * The effective retry count for an entry, falling back to the provided\n * workflow-level default when the entry doesn't declare its own.\n *\n * - `step` — the step's own `retries`\n * - `agent` / `tool` — the declarative `options.retries`\n * - `mapping` — never declares retries; always the fallback\n */\nexport function getEntryRetries(entry: SingleStepEntry, fallback?: number): number | undefined {\n  switch (entry.type) {\n    case 'step':\n      return entry.step.retries ?? fallback;\n    case 'agent':\n    case 'tool':\n      return entry.options?.retries ?? fallback;\n    case 'mapping':\n      return fallback;\n  }\n}\n\n/**\n * The `component` discriminator of the entry, if any. Only plain `step`\n * entries can carry one (notably `'WORKFLOW'` for nested workflows);\n * declarative variants have none.\n */\nexport function getEntryComponent(entry: SingleStepEntry): string | undefined {\n  return entry.type === 'step' ? (entry.step as { component?: string }).component : undefined;\n}\n\n/**\n * Probes an entry for a nested workflow. Only the `type: 'step'` variant can\n * wrap a live `Workflow` (identified by its `component === 'WORKFLOW'`\n * discriminator from MastraBase); declarative variants never nest one.\n */\nexport function getEntryWorkflow(entry: SingleStepEntry): Workflow | null {\n  if (entry.type !== 'step') {\n    return null;\n  }\n  const step = entry.step as unknown as { component?: string };\n  if (step && typeof step === 'object' && step.component === 'WORKFLOW') {\n    return entry.step as unknown as Workflow;\n  }\n  return null;\n}\n\n/**\n * The human-readable description of the entry, if any. Declarative variants\n * don't carry a live description (agent descriptions live on the agent itself).\n */\nexport function getEntryDescription(entry: SingleStepEntry): string | undefined {\n  return entry.type === 'step' ? entry.step.description : undefined;\n}\n\n/**\n * The validation schemas of an entry, used by the engines to validate step\n * input / suspend / resume data without materializing a live Step.\n *\n * - `step` — the step's own schemas\n * - `agent` — the fixed `{ prompt: string }` input contract (mirrors `createStepFromAgent`)\n * - `tool` — the resolved tool's schemas\n * - `mapping` — none (mappings accept and return anything)\n *\n * Never throws: when a tool can't be resolved the schemas are simply empty and\n * the run path surfaces the actionable not-found error.\n */\nexport function getEntrySchemas(\n  entry: SingleStepEntry,\n  mastra?: Mastra,\n): Partial<Pick<Step<string, any, any>, 'inputSchema' | 'resumeSchema' | 'suspendSchema'>> {\n  switch (entry.type) {\n    case 'step':\n      return {\n        inputSchema: entry.step.inputSchema,\n        resumeSchema: entry.step.resumeSchema,\n        suspendSchema: entry.step.suspendSchema,\n      };\n    case 'agent':\n      return { inputSchema: toStandardSchema(z.object({ prompt: z.string() })) };\n    case 'tool': {\n      let tool: { inputSchema?: any; resumeSchema?: any; suspendSchema?: any } | undefined;\n      try {\n        tool = entry.tool ?? mastra?.getTool(entry.toolId);\n      } catch {\n        tool = undefined;\n      }\n      return tool\n        ? { inputSchema: tool.inputSchema, resumeSchema: tool.resumeSchema, suspendSchema: tool.suspendSchema }\n        : {};\n    }\n    case 'mapping':\n      return {};\n  }\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { ErrorCategory, ErrorDomain, getErrorFromUnknown, MastraError } from '../error';\nimport type { IMastraLogger } from '../logger';\nimport type { RequestContext } from '../request-context';\nimport type { StandardSchemaWithJSON } from '../schema';\nimport { removeUndefinedValues } from '../utils';\nimport type { ExecutionGraph } from './execution-engine';\nimport type { Step } from './step';\nimport { getEntryId } from './step-entry';\nimport type {\n  ForeachConcurrencyContext,\n  ForeachOptions,\n  RestartExecutionParams,\n  SingleStepEntry,\n  StepFlowEntry,\n  StepResult,\n  TimeTravelContext,\n  TimeTravelExecutionParams,\n  WorkflowRunState,\n} from './types';\n\n/**\n * Validates data against a StandardSchema and returns the result.\n * Works with both sync and async schemas.\n */\nasync function validateWithStandardSchema<T>(\n  schema: StandardSchemaWithJSON<T>,\n  data: unknown,\n): Promise<{ success: true; data: T } | { success: false; issues: { path?: (string | number)[]; message: string }[] }> {\n  const result = schema['~standard'].validate(data);\n  const resolvedResult = result instanceof Promise ? await result : result;\n\n  if ('issues' in resolvedResult && resolvedResult.issues) {\n    return {\n      success: false,\n      issues: resolvedResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n        path: issue.path?.map((p: PropertyKey | StandardSchemaV1.PathSegment) =>\n          typeof p === 'object' && 'key' in p ? p.key : p,\n        ) as (string | number)[] | undefined,\n        message: issue.message,\n      })),\n    };\n  }\n\n  return { success: true, data: resolvedResult.value as T };\n}\n\nexport async function validateStepInput({\n  prevOutput,\n  step,\n  validateInputs,\n}: {\n  prevOutput: any;\n  step: Partial<Pick<Step<string, any, any>, 'inputSchema'>>;\n  validateInputs: boolean;\n}) {\n  let inputData = prevOutput;\n\n  let validationError: Error | undefined;\n\n  const inputSchema = step.inputSchema;\n  if (validateInputs && inputSchema) {\n    const validatedInput = await validateWithStandardSchema(inputSchema, prevOutput);\n\n    if (!validatedInput.success) {\n      const errorMessages = validatedInput.issues.map(e => `- ${e.path?.join('.')}: ${e.message}`).join('\\n');\n      validationError = new MastraError(\n        {\n          id: 'WORKFLOW_STEP_INPUT_VALIDATION_FAILED',\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.USER,\n          text: 'Step input validation failed: \\n' + errorMessages,\n        },\n        { issues: validatedInput.issues },\n      );\n    } else {\n      const isEmptyObject =\n        validatedInput.data !== null &&\n        typeof validatedInput.data === 'object' &&\n        !Array.isArray(validatedInput.data) &&\n        Object.keys(validatedInput.data as Record<string, unknown>).length === 0;\n      inputData = isEmptyObject ? prevOutput : validatedInput.data;\n    }\n  }\n\n  return { inputData, validationError };\n}\n\nexport async function validateStepResumeData({\n  resumeData,\n  step,\n}: {\n  resumeData?: any;\n  step: Partial<Pick<Step<string, any, any>, 'resumeSchema'>>;\n}) {\n  if (!resumeData) {\n    return { resumeData: undefined, validationError: undefined };\n  }\n\n  let validationError: Error | undefined;\n\n  const resumeSchema = step.resumeSchema;\n\n  if (resumeSchema) {\n    const validatedResumeData = await validateWithStandardSchema(resumeSchema, resumeData);\n    if (!validatedResumeData.success) {\n      const errorMessages = validatedResumeData.issues.map(e => `- ${e.path?.join('.')}: ${e.message}`).join('\\n');\n      validationError = new MastraError({\n        id: 'WORKFLOW_STEP_RESUME_DATA_VALIDATION_FAILED',\n        domain: ErrorDomain.MASTRA_WORKFLOW,\n        category: ErrorCategory.USER,\n        text: 'Step resume data validation failed: \\n' + errorMessages,\n      });\n    } else {\n      resumeData = validatedResumeData.data;\n    }\n  }\n  return { resumeData, validationError };\n}\n\nexport async function validateStepSuspendData({\n  suspendData,\n  step,\n  validateInputs,\n}: {\n  suspendData?: any;\n  step: Partial<Pick<Step<string, any, any>, 'suspendSchema'>>;\n  validateInputs: boolean;\n}) {\n  if (!suspendData) {\n    return { suspendData: undefined, validationError: undefined };\n  }\n\n  let validationError: Error | undefined;\n\n  const suspendSchema = step.suspendSchema;\n\n  if (suspendSchema && validateInputs) {\n    const validatedSuspendData = await validateWithStandardSchema(suspendSchema, suspendData);\n    if (!validatedSuspendData.success) {\n      const errorMessages = validatedSuspendData.issues.map(e => `- ${e.path?.join('.')}: ${e.message}`).join('\\n');\n      validationError = new MastraError({\n        id: 'WORKFLOW_STEP_SUSPEND_DATA_VALIDATION_FAILED',\n        domain: ErrorDomain.MASTRA_WORKFLOW,\n        category: ErrorCategory.USER,\n        text: 'Step suspend data validation failed: \\n' + errorMessages,\n      });\n    } else {\n      suspendData = validatedSuspendData.data;\n    }\n  }\n  return { suspendData, validationError };\n}\n\nexport async function validateStepStateData({\n  stateData,\n  step,\n  validateInputs,\n}: {\n  stateData?: any;\n  step: Step<string, any, any>;\n  validateInputs: boolean;\n}) {\n  if (!stateData) {\n    return { stateData: undefined, validationError: undefined };\n  }\n\n  let validationError: Error | undefined;\n\n  const stateSchema = step.stateSchema;\n\n  if (stateSchema && validateInputs) {\n    const validatedStateData = await validateWithStandardSchema(stateSchema, stateData);\n    if (!validatedStateData.success) {\n      const errorMessages = validatedStateData.issues.map(e => `- ${e.path?.join('.')}: ${e.message}`).join('\\n');\n      validationError = new Error('Step state data validation failed: \\n' + errorMessages);\n    } else {\n      stateData = validatedStateData.data;\n    }\n  }\n  return { stateData, validationError };\n}\n\nexport async function validateStepRequestContext({\n  requestContext,\n  step,\n  validateInputs,\n}: {\n  requestContext?: RequestContext;\n  step: Step<string, any, any>;\n  validateInputs: boolean;\n}) {\n  let validationError: Error | undefined;\n\n  const requestContextSchema = step.requestContextSchema;\n\n  if (requestContextSchema && validateInputs) {\n    // Get all values from requestContext\n    const contextValues = requestContext?.all ?? {};\n    const validatedRequestContext = await validateWithStandardSchema(requestContextSchema, contextValues);\n    if (!validatedRequestContext.success) {\n      const errorMessages = validatedRequestContext.issues.map(e => `- ${e.path?.join('.')}: ${e.message}`).join('\\n');\n      validationError = new MastraError({\n        id: 'WORKFLOW_STEP_REQUEST_CONTEXT_VALIDATION_FAILED',\n        domain: ErrorDomain.MASTRA_WORKFLOW,\n        category: ErrorCategory.USER,\n        text: `Step request context validation failed for step '${step.id}': \\n` + errorMessages,\n      });\n    }\n  }\n  return { validationError };\n}\n\nexport function getResumeLabelsByStepId(\n  resumeLabels: Record<string, { stepId: string; foreachIndex?: number }>,\n  stepId: string,\n) {\n  return Object.entries(resumeLabels)\n    .filter(([_, value]) => value.stepId === stepId)\n    .reduce(\n      (acc, [key, value]) => {\n        acc[key] = value;\n        return acc;\n      },\n      {} as Record<string, { stepId: string; foreachIndex?: number }>,\n    );\n}\n\nexport const runCountDeprecationMessage =\n  \"Warning: 'runCount' is deprecated and will be removed on November 4th, 2025. Please use 'retryCount' instead.\";\n\n/**\n * Track which deprecation warnings have been shown globally to avoid spam\n */\nconst shownWarnings = new Set<string>();\n\n/**\n * Creates a Proxy that wraps execute function parameters to show deprecation warnings\n * when accessing deprecated properties.\n *\n * Currently handles:\n * - `runCount`: Deprecated in favor of `retryCount`, will be removed on November 4th, 2025\n */\nexport function createDeprecationProxy<T extends Record<string, any>>(\n  params: T,\n  {\n    paramName,\n    deprecationMessage,\n    logger,\n  }: {\n    paramName: string;\n    deprecationMessage: string;\n    logger: IMastraLogger;\n  },\n): T {\n  return new Proxy(params, {\n    get(target, prop, receiver) {\n      if (prop === paramName && !shownWarnings.has(paramName)) {\n        shownWarnings.add(paramName);\n        if (logger) {\n          logger.warn('\\x1b[33m%s\\x1b[0m', deprecationMessage);\n        } else {\n          console.warn('\\x1b[33m%s\\x1b[0m', deprecationMessage);\n        }\n      }\n      return Reflect.get(target, prop, receiver);\n    },\n  });\n}\n\nconst SINGLE_STEP_TYPES = ['step', 'agent', 'tool', 'mapping'] as const;\n\n/**\n * Whether an entry is a \"single step-like\" entry: a plain user step or one of the\n * declarative variants (agent / tool / mapping) that resolve to exactly one step.\n */\nexport function isSingleStepEntry(entry: StepFlowEntry): entry is SingleStepEntry {\n  return (SINGLE_STEP_TYPES as readonly string[]).includes(entry.type);\n}\n\n/**\n * The id of a single step-like entry. Plain `step` entries key off the wrapped\n * step's id; declarative variants (agent / tool / mapping) carry their own `id`.\n *\n * Public alias of {@link getEntryId} from `./step-entry`.\n */\nexport const getSingleStepEntryId = getEntryId;\n\nexport const getStepIds = (entry: StepFlowEntry): string[] => {\n  if (isSingleStepEntry(entry)) {\n    return [getSingleStepEntryId(entry)];\n  }\n  if (entry.type === 'foreach' || entry.type === 'loop') {\n    return [getSingleStepEntryId(entry.step)];\n  }\n  if (entry.type === 'parallel' || entry.type === 'conditional') {\n    return entry.steps.map(s => getSingleStepEntryId(s));\n  }\n  if (entry.type === 'sleep' || entry.type === 'sleepUntil') {\n    return [entry.id];\n  }\n  return [];\n};\n\nexport const createTimeTravelExecutionParams = (params: {\n  steps: string[];\n  inputData?: any;\n  resumeData?: any;\n  context?: TimeTravelContext<any, any, any, any>;\n  nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n  snapshot: WorkflowRunState;\n  initialState?: any;\n  graph: ExecutionGraph;\n  perStep?: boolean;\n}) => {\n  const { steps, inputData, resumeData, context, nestedStepsContext, snapshot, initialState, graph, perStep } = params;\n  const firstStepId = steps[0]!;\n\n  let executionPath: number[] = [];\n  const stepResults: Record<string, StepResult<any, any, any, any>> = {};\n  const snapshotContext = snapshot.context as Record<string, any>;\n\n  for (const [index, entry] of graph.steps.entries()) {\n    const currentExecPathLength = executionPath.length;\n    //if there is resumeData, steps down the graph until the suspended step will have stepResult info to use\n    if (currentExecPathLength > 0 && !resumeData) {\n      break;\n    }\n    const stepIds = getStepIds(entry);\n    const isTargetEntry = stepIds.includes(firstStepId);\n    if (isTargetEntry) {\n      const innerExecutionPath = stepIds?.length > 1 ? [stepIds?.findIndex(s => s === firstStepId)] : [];\n      //parallel and loop steps will have more than one step id,\n      // and if the step is one of those, we need the index for the execution path\n      executionPath = [index, ...innerExecutionPath];\n    }\n\n    const prevStep = graph.steps[index - 1]!;\n    let stepPayload = undefined;\n    if (prevStep) {\n      const prevStepIds = getStepIds(prevStep);\n      if (prevStepIds.length > 0) {\n        if (prevStepIds.length === 1) {\n          stepPayload = (stepResults?.[prevStepIds[0]!] as any)?.output ?? {};\n        } else {\n          stepPayload = prevStepIds.reduce(\n            (acc, stepId) => {\n              acc[stepId] = (stepResults?.[stepId] as any)?.output ?? {};\n              return acc;\n            },\n            {} as Record<string, any>,\n          );\n        }\n      }\n    }\n\n    //the stepResult input is basically the payload of the first step\n    if (index === 0 && stepIds.includes(firstStepId)) {\n      stepResults.input = (context?.[firstStepId]?.payload ?? inputData ?? snapshotContext?.input) as any;\n    } else if (index === 0) {\n      stepResults.input =\n        stepIds?.reduce((acc, stepId) => {\n          if (acc) return acc;\n          return context?.[stepId]?.payload ?? snapshotContext?.[stepId]?.payload;\n        }, null) ??\n        snapshotContext?.input ??\n        {};\n    }\n\n    let stepOutput = undefined;\n    const nextStep = graph.steps[index + 1]!;\n    if (nextStep) {\n      const nextStepIds = getStepIds(nextStep);\n      if (\n        nextStepIds.length > 0 &&\n        inputData &&\n        nextStepIds.includes(firstStepId) &&\n        steps.length === 1 //steps being greater than 1 means it's travelling to step in a nested workflow\n        //if it's a nested wokrflow step, the step being resumed in the nested workflow might not be the first step in it,\n        // making the inputData the output here wrong\n      ) {\n        stepOutput = inputData;\n      }\n    }\n\n    stepIds.forEach(stepId => {\n      let result;\n      const stepContext = context?.[stepId] ?? snapshotContext[stepId];\n      // Siblings of the time-travel target inside a conditional were not selected by the\n      // branch's condition, so they should be reported as skipped rather than as a fake\n      // success (otherwise their empty output leaks into the conditional's aggregated result).\n      const isUnselectedConditionalSibling = isTargetEntry && entry.type === 'conditional' && !steps?.includes(stepId);\n      const defaultStepStatus = steps?.includes(stepId)\n        ? 'running'\n        : isUnselectedConditionalSibling\n          ? 'skipped'\n          : 'success';\n      const status = ['failed', 'canceled'].includes(stepContext?.status)\n        ? defaultStepStatus\n        : (stepContext?.status ?? defaultStepStatus);\n      const isCompleteStatus = ['success', 'failed', 'canceled'].includes(status);\n      result = {\n        status,\n        payload: context?.[stepId]?.payload ?? stepPayload ?? snapshotContext[stepId]?.payload ?? {},\n        output: isCompleteStatus\n          ? (context?.[stepId]?.output ?? stepOutput ?? snapshotContext[stepId]?.output ?? {})\n          : undefined,\n        resumePayload: stepContext?.resumePayload,\n        suspendPayload: stepContext?.suspendPayload,\n        suspendOutput: stepContext?.suspendOutput,\n        startedAt: stepContext?.startedAt ?? Date.now(),\n        endedAt: isCompleteStatus ? (stepContext?.endedAt ?? Date.now()) : undefined,\n        suspendedAt: stepContext?.suspendedAt,\n        resumedAt: stepContext?.resumedAt,\n      };\n      const execPathLengthToUse = perStep ? executionPath.length : currentExecPathLength;\n      if (\n        execPathLengthToUse > 0 &&\n        !steps?.includes(stepId) &&\n        !context?.[stepId] &&\n        (!snapshotContext[stepId] || (snapshotContext[stepId] && snapshotContext[stepId].status !== 'suspended'))\n      ) {\n        // if the step is after the timeTravelled step in the graph\n        // and it doesn't exist in the snapshot,\n        // OR it exists in snapshot and is not suspended,\n        // we don't need to set stepResult for it\n        // if perStep is true, and the step is a parallel step,\n        // we want to construct result for only the timetraveled step and any step context is passed for\n        result = undefined;\n      }\n      if (result) {\n        const formattedResult = removeUndefinedValues(result);\n        stepResults[stepId] = formattedResult as any;\n      }\n    });\n  }\n\n  if (!executionPath.length) {\n    throw new Error(\n      `Time travel target step not found in execution graph: '${steps?.join('.')}'. Verify the step id/path.`,\n    );\n  }\n\n  const timeTravelData: TimeTravelExecutionParams = {\n    inputData,\n    executionPath,\n    steps,\n    stepResults,\n    nestedStepResults: nestedStepsContext as any,\n    state: initialState ?? snapshot.value ?? {},\n    resumeData,\n    stepExecutionPath: snapshot?.stepExecutionPath,\n  };\n\n  return timeTravelData;\n};\n\nexport const createRestartExecutionParams = ({\n  snapshot,\n  graph,\n}: {\n  snapshot: WorkflowRunState;\n  graph: ExecutionGraph;\n}) => {\n  let nestedWorkflowPending = false;\n\n  if (snapshot.status !== 'running' && snapshot.status !== 'waiting') {\n    const hasPendingInput =\n      snapshot.status === 'pending' &&\n      snapshot.context &&\n      Object.prototype.hasOwnProperty.call(snapshot.context, 'input');\n    if (hasPendingInput) {\n      //possible the server died just before the nested workflow execution started.\n      //only nested workflows have input data in context when it's still pending\n      nestedWorkflowPending = true;\n    } else {\n      throw new Error('This workflow run was not active');\n    }\n  }\n\n  let nestedWorkflowActiveStepsPath: Record<string, number[]> = {};\n\n  const firstEntry = graph.steps[0]!;\n\n  if (isSingleStepEntry(firstEntry)) {\n    nestedWorkflowActiveStepsPath = {\n      [getSingleStepEntryId(firstEntry)]: [0],\n    };\n  } else if (firstEntry.type === 'foreach' || firstEntry.type === 'loop') {\n    nestedWorkflowActiveStepsPath = {\n      [getSingleStepEntryId(firstEntry.step)]: [0],\n    };\n  } else if (firstEntry.type === 'sleep' || firstEntry.type === 'sleepUntil') {\n    nestedWorkflowActiveStepsPath = {\n      [firstEntry.id]: [0],\n    };\n  } else if (firstEntry.type === 'conditional' || firstEntry.type === 'parallel') {\n    nestedWorkflowActiveStepsPath = firstEntry.steps.reduce(\n      (acc, step) => {\n        acc[getSingleStepEntryId(step)] = [0];\n        return acc;\n      },\n      {} as Record<string, number[]>,\n    );\n  }\n  const restartData: RestartExecutionParams = {\n    activePaths: nestedWorkflowPending ? [0] : snapshot.activePaths,\n    activeStepsPath: nestedWorkflowPending ? nestedWorkflowActiveStepsPath : snapshot.activeStepsPath,\n    stepResults: snapshot.context,\n    state: snapshot.value,\n    stepExecutionPath: snapshot?.stepExecutionPath,\n  };\n\n  return restartData;\n};\n\n/**\n * Re-hydrates serialized errors in step results back into proper Error instances.\n * This is useful when errors have been serialized through an event system (e.g., evented engine, Inngest)\n * and need to be converted back to Error instances with their custom properties preserved.\n *\n * @param steps - The workflow step results (context) that may contain serialized errors\n * @returns The same steps object with errors hydrated as Error instances\n */\nexport function hydrateSerializedStepErrors(steps: WorkflowRunState['context']) {\n  if (steps) {\n    for (const step of Object.values(steps)) {\n      if (step.status === 'failed' && 'error' in step && step.error) {\n        step.error = getErrorFromUnknown(step.error, { serializeStack: false });\n      }\n    }\n  }\n  return steps;\n}\n\n/**\n * Cleans a single step result object by removing internal properties.\n * This is a helper for cleanStepResult that handles one level of cleaning.\n */\nfunction cleanSingleResult(result: Record<string, unknown>): Record<string, unknown> {\n  const { __state: _state, metadata, ...rest } = result;\n\n  // Strip nestedRunId from metadata but keep other user-defined fields\n  if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {\n    const { nestedRunId: _nestedRunId, ...userMetadata } = metadata as Record<string, unknown>;\n    if (Object.keys(userMetadata).length > 0) {\n      return { ...rest, metadata: userMetadata };\n    }\n  }\n\n  return rest;\n}\n\n/**\n * Cleans step result data by removing internal properties at known structural levels.\n *\n * Removes:\n * - `__state` properties (internal workflow state for state propagation)\n * - `nestedRunId` from `metadata` objects (internal tracking for nested workflow retrieval)\n *\n * ## Why targeted cleaning instead of recursive?\n *\n * Internal properties only appear at specific, known locations:\n *\n * 1. **`__state`** - Added by step-executor.ts to every step result. For forEach,\n *    suspended iterations store the full result (including __state) while completed\n *    iterations only store the output value. See workflow-event-processor/index.ts:1227-1230.\n *\n * 2. **`metadata.nestedRunId`** - Added when nested workflows complete, stored at the\n *    step result level. For forEach with nested workflows, each iteration result can\n *    have this. See workflow-event-processor/index.ts:1449-1453.\n *\n * By only cleaning at the step result level and forEach iteration level, we avoid\n * accidentally stripping user data that happens to use `__state` as a property name\n * in their actual output values.\n *\n * @param stepResult - A step result object, or an array of iteration results (forEach)\n * @returns The cleaned step result with internal properties removed\n */\nexport function cleanStepResult(stepResult: unknown): unknown {\n  if (stepResult === null || stepResult === undefined) {\n    return stepResult;\n  }\n\n  if (typeof stepResult !== 'object') {\n    return stepResult;\n  }\n\n  // Handle arrays (forEach iteration results) - clean each element at the result level only\n  if (Array.isArray(stepResult)) {\n    return stepResult.map(item => {\n      if (item && typeof item === 'object' && !Array.isArray(item)) {\n        return cleanSingleResult(item as Record<string, unknown>);\n      }\n      return item;\n    });\n  }\n\n  const result = stepResult as Record<string, unknown>;\n  const cleaned = cleanSingleResult(result);\n\n  // If output is an array (forEach results), clean each iteration result\n  // Iteration results can have __state (for suspended) or metadata.nestedRunId (for nested workflows)\n  if (Array.isArray(cleaned.output)) {\n    cleaned.output = cleaned.output.map((item: unknown) => {\n      if (item && typeof item === 'object' && !Array.isArray(item)) {\n        return cleanSingleResult(item as Record<string, unknown>);\n      }\n      return item;\n    });\n  }\n\n  return cleaned;\n}\n\n/**\n * Resolves the effective concurrency for a foreach entry at execution time.\n *\n * Supports both a static number and a {@link ForeachConcurrencyResolver}\n * function that derives concurrency from the run's input. Invalid or\n * non-positive values fall back to 1 (sequential).\n */\nexport function resolveForeachConcurrency(\n  opts: ForeachOptions | undefined,\n  context: ForeachConcurrencyContext,\n): number {\n  const configured = opts?.concurrency ?? 1;\n  const resolved = typeof configured === 'function' ? configured(context) : configured;\n  if (typeof resolved !== 'number' || !Number.isFinite(resolved) || resolved < 1) {\n    return 1;\n  }\n  return Math.floor(resolved);\n}\n\nconst RESUME_SNAPSHOT_POLL_INTERVAL_MS = 25;\nconst RESUME_SNAPSHOT_POLL_TIMEOUT_MS = 2000;\n\nexport async function waitForSuspendedSnapshot(\n  workflowsStore:\n    | { loadWorkflowSnapshot: (args: { workflowName: string; runId: string }) => Promise<WorkflowRunState | null> }\n    | undefined,\n  workflowName: string,\n  runId: string,\n): Promise<WorkflowRunState | null> {\n  if (!workflowsStore) return null;\n\n  const deadline = Date.now() + RESUME_SNAPSHOT_POLL_TIMEOUT_MS;\n  let snapshot = (await workflowsStore.loadWorkflowSnapshot({ workflowName, runId })) ?? null;\n  while ((!snapshot || snapshot.status !== 'suspended') && Date.now() < deadline) {\n    await new Promise(resolve => setTimeout(resolve, RESUME_SNAPSHOT_POLL_INTERVAL_MS));\n    snapshot = (await workflowsStore.loadWorkflowSnapshot({ workflowName, runId })) ?? null;\n  }\n  return snapshot;\n}\n","import type { ReadableStream } from 'node:stream/web';\nimport { TripWire } from '../../agent/trip-wire';\nimport type { PubSub } from '../../events';\nimport type { Mastra } from '../../mastra';\nimport { resolveObservabilityContext } from '../../observability';\nimport type { ChunkType } from '../../stream/types';\nimport { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '../constants';\nimport { forwardAgentStreamChunk } from '../stream-utils';\nimport type { AgentStepEntry } from '../types';\nimport type { EntryExecuteContext } from './types';\n\n/**\n * Runs a declarative `agent` entry: resolves the agent (inline handle, else the\n * Mastra registry), streams the prompt through it, forwards stream chunks, and\n * returns either the structured output or `{ text }`.\n *\n * `ctx` is the step execute context (the same object a plain step's `execute`\n * receives). `mastra` defaults to `ctx.mastra` when omitted.\n */\nexport async function runAgentEntry(\n  entry: AgentStepEntry,\n  ctx: EntryExecuteContext,\n  mastra?: Mastra,\n): Promise<unknown> {\n  const registry = mastra ?? (ctx?.mastra as Mastra | undefined);\n  const agent = entry.agent ?? registry?.getAgentById(entry.agentId);\n  if (!agent) {\n    throw new Error(\n      `Agent '${entry.agentId}' not found for workflow step '${entry.id}'. Register the agent on the Mastra instance or pass the agent instance directly.`,\n    );\n  }\n\n  // `retries` / `scorers` / `metadata` are step-level concerns handled by the\n  // engine (see getEntryRetries); everything else is passed to the agent run.\n  const { retries: _retries, scorers: _scorers, metadata: _metadata, ...agentOptions } = (entry.options ?? {}) as any;\n\n  const {\n    inputData,\n    runId,\n    [PUBSUB_SYMBOL]: pubsub,\n    [STREAM_FORMAT_SYMBOL]: streamFormat,\n    requestContext,\n    abortSignal,\n    abort,\n    writer,\n    ...rest\n  } = ctx;\n  const observabilityContext = resolveObservabilityContext(rest);\n  let streamPromise = {} as {\n    promise: Promise<string>;\n    resolve: (value: string) => void;\n    reject: (reason?: any) => void;\n  };\n\n  streamPromise.promise = new Promise((resolve, reject) => {\n    streamPromise.resolve = resolve;\n    streamPromise.reject = reject;\n  });\n  // The promise is awaited later (and sometimes not at all when structured\n  // output short-circuits); attach a no-op handler so an early rejection\n  // can't surface as an unhandled rejection before the await.\n  streamPromise.promise.catch(() => {});\n\n  // Track structured output result\n  let structuredResult: any = null;\n\n  const toolData = {\n    name: agent.name,\n    args: inputData,\n  };\n\n  let stream: ReadableStream<any>;\n\n  const handleFinish = (result: any) => {\n    const resultWithObject = result as typeof result & { object?: unknown };\n    if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {\n      structuredResult = resultWithObject.object;\n    }\n    streamPromise.resolve(result.text);\n    void agentOptions?.onFinish?.(result);\n  };\n\n  if (\n    (await agent.getModel({ requestContext })).specificationVersion === 'v1' &&\n    typeof agent.streamLegacy === 'function'\n  ) {\n    const { fullStream } = await agent.streamLegacy((inputData as { prompt: string }).prompt, {\n      ...agentOptions,\n      requestContext,\n      ...observabilityContext,\n      onFinish: handleFinish,\n      abortSignal,\n    });\n    stream = fullStream as any;\n  } else {\n    const modelOutput = await agent.stream((inputData as { prompt: string }).prompt, {\n      ...agentOptions,\n      requestContext,\n      ...observabilityContext,\n      onFinish: handleFinish,\n      abortSignal,\n    });\n\n    // handleFinish (the agent's onFinish) is the sole source of truth for the\n    // final text — the success side of .text is intentionally a no-op.\n    // `modelOutput.text` can resolve with '' if a downstream output-processor\n    // throws inside the base output's try/catch (see output.ts:970-973,978-981)\n    // and it fires BEFORE handleFinish, so racing here would poison\n    // streamPromise. Only the rejection channel below is wired up so genuine\n    // stream errors still propagate.\n    void modelOutput.text.then(\n      () => {},\n      (err: unknown) => streamPromise.reject(err),\n    );\n    stream = modelOutput.fullStream as ReadableStream<ChunkType>;\n  }\n\n  const tripwireChunk =\n    streamFormat === 'legacy'\n      ? await bridgeLegacyWatchEvents({ stream, pubsub, runId, toolData })\n      : await consumeStreamForTripwire(stream, writer);\n\n  // If a tripwire was detected, throw TripWire to abort the workflow step\n  if (tripwireChunk) {\n    throw new TripWire(\n      tripwireChunk.payload?.reason || 'Agent tripwire triggered',\n      {\n        retry: tripwireChunk.payload?.retry,\n        metadata: tripwireChunk.payload?.metadata,\n      },\n      tripwireChunk.payload?.processorId,\n    );\n  }\n\n  if (abortSignal.aborted) {\n    return abort();\n  }\n\n  // Return structured output if available, otherwise default text\n  if (structuredResult !== null) {\n    return structuredResult;\n  }\n  return {\n    text: await streamPromise.promise,\n  };\n}\n\n/**\n * Legacy-format watch-event bridge: instead of forwarding chunks to the step\n * writer, mirrors the agent stream onto the run's pubsub watch channel as\n * `tool-call-streaming-*` / `tool-call-delta` events (the shape v1 watchers\n * expect). Returns the tripwire chunk if one was seen, else `null`.\n */\nasync function bridgeLegacyWatchEvents({\n  stream,\n  pubsub,\n  runId,\n  toolData,\n}: {\n  stream: ReadableStream<any>;\n  pubsub: PubSub;\n  runId: string;\n  toolData: { name: string; args: unknown };\n}): Promise<any> {\n  let tripwireChunk: any = null;\n  await pubsub.publish(`workflow.events.v2.${runId}`, {\n    type: 'watch',\n    runId,\n    data: { type: 'tool-call-streaming-start', ...(toolData ?? {}) },\n  });\n  try {\n    for await (const chunk of stream) {\n      if (chunk.type === 'tripwire') {\n        tripwireChunk = chunk;\n        break;\n      }\n      if (chunk.type === 'text-delta') {\n        await pubsub.publish(`workflow.events.v2.${runId}`, {\n          type: 'watch',\n          runId,\n          data: { type: 'tool-call-delta', ...(toolData ?? {}), argsTextDelta: chunk.textDelta },\n        });\n      }\n    }\n  } finally {\n    // Watchers pair streaming-start with streaming-finish; publish it even\n    // when iteration throws or breaks early so they never hang open. Swallow\n    // publish failures here so they can't mask the original error.\n    await pubsub\n      .publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: { type: 'tool-call-streaming-finish', ...(toolData ?? {}) },\n      })\n      .catch(() => {});\n  }\n  return tripwireChunk;\n}\n\n/**\n * Forwards every chunk to the step writer, stopping early when a tripwire\n * chunk appears. Returns the tripwire chunk if one was seen, else `null`.\n */\nasync function consumeStreamForTripwire(\n  stream: ReadableStream<any>,\n  writer: EntryExecuteContext['writer'],\n): Promise<any> {\n  for await (const chunk of stream) {\n    await forwardAgentStreamChunk({ writer, chunk });\n    if (chunk.type === 'tripwire') {\n      return chunk;\n    }\n  }\n  return null;\n}\n","import type { Mastra } from '../../mastra';\nimport { resolveObservabilityContext } from '../../observability';\nimport type { ToolStepEntry } from '../types';\nimport type { EntryExecuteContext } from './types';\n\n/**\n * Runs a declarative `tool` entry: resolves the tool (inline handle, else the\n * Mastra registry) and executes it with the step context mapped into the tool\n * execution context.\n */\nexport async function runToolEntry(entry: ToolStepEntry, ctx: EntryExecuteContext, mastra?: Mastra): Promise<unknown> {\n  const registry = mastra ?? (ctx?.mastra as Mastra | undefined);\n  const tool = entry.tool ?? registry?.getTool(entry.toolId);\n  if (!tool) {\n    throw new Error(\n      `Tool '${entry.toolId}' not found for workflow step '${entry.id}'. Pass the tool instance directly.`,\n    );\n  }\n\n  const {\n    inputData,\n    mastra: ctxMastra,\n    requestContext,\n    suspend,\n    resumeData,\n    runId,\n    workflowId,\n    state,\n    setState,\n    abortSignal,\n    ...rest\n  } = ctx;\n  const observabilityContext = resolveObservabilityContext(rest);\n  const toolContext = {\n    mastra: ctxMastra,\n    requestContext,\n    ...observabilityContext,\n    abortSignal,\n    resumeData,\n    workflow: {\n      runId,\n      suspend,\n      resumeData,\n      workflowId,\n      state,\n      setState,\n    },\n  };\n\n  return tool.execute(inputData, toolContext);\n}\n","/**\n * The `${scope.path}` mapping-template DSL used by `.map()` template sources.\n *\n * Definition-time syntax checks live in {@link validateTemplate}; run-time\n * resolution (path lookup + value coercion) lives in {@link resolveTemplate}.\n * This module has no knowledge of the step-entry union — it is a pure\n * string-DSL interpreter over a step's execute context.\n */\n\n/** Walks a dotted path on an object. `''` or `'.'` returns the root unchanged. */\nexport function traverseMappingPath(root: unknown, path: string, errorLabel: string): unknown {\n  if (path === '' || path === '.') return root;\n  const parts = path.split('.');\n  let value: any = root;\n  for (const part of parts) {\n    if (typeof value === 'object' && value !== null) {\n      value = value[part];\n    } else {\n      throw new Error(`Invalid path ${path} in ${errorLabel}`);\n    }\n  }\n  return value;\n}\n\nconst TEMPLATE_PLACEHOLDER = /\\$\\{([^}]*)\\}/g;\n\nconst TEMPLATE_NAMESPACES = ['inputData', 'initData', 'state', 'requestContext', 'stepResults'] as const;\ntype TemplateScope = (typeof TEMPLATE_NAMESPACES)[number];\n\n/** Common error-message prefix so every template diagnostic points at the exact placeholder. */\nfunction describeBadPlaceholder(template: string, idx: number, rawExpr: string): string {\n  return `Template placeholder #${idx} (\\${${rawExpr}}) in '${template}'`;\n}\n\n/** Split a placeholder body `scope.path.with.dots` into its leading scope and the dotted remainder. */\nfunction parseTemplatePlaceholder(rawExpr: string): { scope: string; rest: string } {\n  const dot = rawExpr.indexOf('.');\n  return {\n    scope: dot === -1 ? rawExpr : rawExpr.slice(0, dot),\n    rest: dot === -1 ? '' : rawExpr.slice(dot + 1),\n  };\n}\n\n/**\n * Validates a `{ template }` source's syntax at workflow-definition time.\n * Throws if any placeholder is empty, whitespace-padded, references an unknown\n * namespace, or is a malformed `stepResults.<stepId>` / `stepResults.<stepId>.<path>` shape.\n *\n * Run-time concerns (does the step actually exist, does the path resolve, is\n * the value a primitive) stay in {@link resolveTemplate}.\n */\nexport function validateTemplate(template: string): void {\n  let idx = 0;\n  for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) {\n    idx++;\n    const rawExpr = match[1] ?? '';\n    if (rawExpr.length === 0 || rawExpr !== rawExpr.trim()) {\n      throw new Error(\n        `${describeBadPlaceholder(template, idx, rawExpr)} has empty or whitespace-padded contents. ` +\n          `Use \\${<scope>.<path>} with no surrounding whitespace.`,\n      );\n    }\n    const { scope, rest } = parseTemplatePlaceholder(rawExpr);\n    if (scope === 'stepResults') {\n      const innerDot = rest.indexOf('.');\n      const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);\n      if (!stepId) {\n        throw new Error(\n          `${describeBadPlaceholder(template, idx, rawExpr)} must be of the form \\${stepResults.<stepId>} or \\${stepResults.<stepId>.<path>}.`,\n        );\n      }\n      continue;\n    }\n    if (scope === 'requestContext') {\n      if (!rest) {\n        throw new Error(\n          `${describeBadPlaceholder(template, idx, rawExpr)} requires a request-context key — use \\${requestContext.<key>}.`,\n        );\n      }\n      continue;\n    }\n    if ((TEMPLATE_NAMESPACES as readonly string[]).includes(scope)) continue;\n    throw new Error(\n      `${describeBadPlaceholder(template, idx, rawExpr)} references unknown namespace \"${scope}\". ` +\n        `Use one of: ${TEMPLATE_NAMESPACES.join(', ')}.`,\n    );\n  }\n}\n\n/**\n * Collects the step ids referenced by `${stepResults.<stepId>}` /\n * `${stepResults.<stepId>.<path>}` placeholders in a template. Assumes the\n * template already passed {@link validateTemplate}; malformed placeholders are\n * skipped. Used by validation to scope-check template references against the\n * preceding workflow-local steps.\n */\nexport function collectTemplateStepIds(template: string): string[] {\n  const ids: string[] = [];\n  for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) {\n    const { scope, rest } = parseTemplatePlaceholder(match[1] ?? '');\n    if (scope !== 'stepResults') continue;\n    const innerDot = rest.indexOf('.');\n    const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);\n    if (stepId) ids.push(stepId);\n  }\n  return ids;\n}\n\n/**\n * Coerces a resolved placeholder value to a string. Primitives are stringified\n * the normal way; objects and arrays are JSON-encoded so downstream agents can\n * consume complex step outputs (e.g. `foreach(agent)` returns `{ text }[]`)\n * directly in a template. `null`/`undefined` render as empty. If JSON encoding\n * fails (circular references, BigInt, etc.), throws with a hint pointing at\n * the offending placeholder.\n */\nfunction stringifyTemplateValue(v: unknown, template: string, idx: number, rawExpr: string): string {\n  if (v === null || v === undefined) return '';\n  if (typeof v === 'object') {\n    try {\n      return JSON.stringify(v);\n    } catch (err) {\n      throw new Error(\n        `${describeBadPlaceholder(template, idx, rawExpr)} resolved to a value that could not be JSON-stringified ` +\n          `(${(err as Error).message}). Drill into a primitive path (e.g. \\${${rawExpr}.someField}) or reshape the value in a preceding step.`,\n      );\n    }\n  }\n  return String(v);\n}\n\n/**\n * Resolves `${<scope>.<path>}` placeholders against the implicit namespaces\n * available in a step's execute context. See the `.map()` overload signature\n * for the full list of accepted scopes (`inputData`, `initData`, `state`,\n * `requestContext`, `stepResults.<stepId>`).\n */\nexport function resolveTemplate(template: string, ctx: any): string {\n  let idx = 0;\n  return template.replace(TEMPLATE_PLACEHOLDER, (_match, rawExpr: string) => {\n    idx++;\n    return resolveTemplatePlaceholder(rawExpr, template, idx, ctx);\n  });\n}\n\nfunction resolveTemplatePlaceholder(rawExpr: string, template: string, idx: number, ctx: any): string {\n  // validateTemplate(template) is called at definition time so we know the\n  // raw expr is well-formed (non-empty, no surrounding whitespace, known\n  // scope). Runtime only cares about path-resolution + value coercion.\n  const { scope, rest } = parseTemplatePlaceholder(rawExpr);\n  const label = describeBadPlaceholder(template, idx, rawExpr);\n  switch (scope as TemplateScope) {\n    case 'inputData':\n      return stringifyTemplateValue(traverseMappingPath(ctx.inputData, rest, label), template, idx, rawExpr);\n    case 'initData':\n      return stringifyTemplateValue(traverseMappingPath(ctx.getInitData(), rest, label), template, idx, rawExpr);\n    case 'state':\n      return stringifyTemplateValue(traverseMappingPath(ctx.state, rest, label), template, idx, rawExpr);\n    case 'requestContext':\n      return stringifyTemplateValue(ctx.requestContext.get(rest), template, idx, rawExpr);\n    case 'stepResults': {\n      const innerDot = rest.indexOf('.');\n      const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);\n      const subPath = innerDot === -1 ? '' : rest.slice(innerDot + 1);\n      const stepResult = ctx.getStepResult(stepId);\n      // Nullish (not just null) so a step that \"succeeded\" with `undefined`\n      // output is reported as missing too — consistent with how predicates\n      // treat nullish step results. Nullish *path values inside* a present\n      // result still render as '' via stringifyTemplateValue.\n      if (stepResult == null) {\n        throw new Error(\n          `${label} references stepResults.${stepId} but step \"${stepId}\" has no successful output ` +\n            `(not run yet, not registered, failed, or produced no output).`,\n        );\n      }\n      return stringifyTemplateValue(traverseMappingPath(stepResult, subPath, label), template, idx, rawExpr);\n    }\n    default:\n      // validateTemplate guarantees this branch is unreachable for well-formed\n      // workflows; this is a safety net for templates that bypassed validation\n      // (e.g. constructed programmatically and pushed into stepFlow).\n      throw new Error(\n        `${label} references unknown namespace \"${scope}\". Use one of: ${TEMPLATE_NAMESPACES.join(', ')}.`,\n      );\n  }\n}\n","import { resolveTemplate, traverseMappingPath } from '../mapping-template';\nimport type { MappingStepEntry } from '../types';\nimport type { EntryExecuteContext } from './types';\n\n/**\n * Runs a declarative `mapping` entry. Function configs are invoked directly;\n * object configs are interpreted key-by-key (`value` / `fn` / `template` /\n * `requestContextPath` / `step`+`path` / `initData`+`path`).\n */\nexport async function runMappingEntry(entry: MappingStepEntry, ctx: EntryExecuteContext): Promise<unknown> {\n  const { mapConfig } = entry;\n  if (typeof mapConfig === 'function') {\n    return mapConfig(ctx);\n  }\n\n  const { getStepResult, getInitData, requestContext } = ctx;\n\n  const result: Record<string, any> = {};\n  for (const [key, mapping] of Object.entries(mapConfig)) {\n    const m: any = mapping;\n\n    if (m.value !== undefined) {\n      result[key] = m.value;\n      continue;\n    }\n\n    if (m.fn !== undefined) {\n      result[key] = await m.fn(ctx);\n      continue;\n    }\n\n    if (typeof m.template === 'string') {\n      result[key] = resolveTemplate(m.template, ctx);\n      continue;\n    }\n\n    if (m.requestContextPath) {\n      result[key] = requestContext.get(m.requestContextPath);\n      continue;\n    }\n\n    const stepResult = m.initData\n      ? getInitData()\n      : getStepResult(\n          Array.isArray(m.step)\n            ? m.step.find((s: any) => {\n                const stepRes = getStepResult(s);\n                if (typeof stepRes === 'object' && stepRes !== null) {\n                  return Object.keys(stepRes).length > 0;\n                }\n                return stepRes;\n              })\n            : m.step,\n        );\n\n    result[key] = traverseMappingPath(stepResult, m.path, describeMappingSource(m));\n  }\n  return result;\n}\n\n/** Human-readable source label for path-traversal errors. */\nfunction describeMappingSource(m: any): string {\n  if (m.initData) return 'initData';\n  const stepLabel = (s: any): string => (typeof s === 'string' ? s : (s?.id ?? 'unknown'));\n  if (Array.isArray(m.step)) return `step ${m.step.map(stepLabel).join('|')}`;\n  return `step ${stepLabel(m.step)}`;\n}\n","import type { StepFlowEntry, Workflow } from '../..';\nimport type { Mastra } from '../../../mastra';\nimport { getEntryId, getEntryWorkflow } from '../../step-entry';\nimport type { SingleStepEntry } from '../../types';\nimport { isSingleStepEntry } from '../../utils';\nimport type { ParentWorkflow } from '.';\n\nexport function getNestedWorkflow(\n  mastra: Mastra,\n  { workflowId, executionPath, parentWorkflow, runId }: ParentWorkflow,\n): Workflow | null {\n  let workflow: Workflow | null = null;\n\n  if (parentWorkflow) {\n    const nestedWorkflow = getNestedWorkflow(mastra, parentWorkflow);\n    if (!nestedWorkflow) {\n      return null;\n    }\n\n    workflow = nestedWorkflow;\n  }\n\n  // Internal workflows (registered via `Mastra.__registerInternalWorkflow`)\n  // aren't visible to `Mastra.getWorkflow` — it only sees the public registry.\n  // Prefer the internal registry first so nested-workflow resolution works\n  // for callers like the bg-tasks `__background-task` workflow. When `runId`\n  // is set we hand it to the registry so concurrent invocations sharing the\n  // same workflow id (e.g. parent + sub-agent each owning their own\n  // `agentic-loop` instance with distinct closures) resolve to the right\n  // closure-bound instance instead of whichever one happened to register last.\n  workflow =\n    workflow ??\n    (mastra.__hasInternalWorkflow(workflowId, runId)\n      ? mastra.__getInternalWorkflow(workflowId, runId)\n      : mastra.getWorkflow(workflowId));\n  const stepGraph = workflow.stepGraph;\n  let parentStep = stepGraph[executionPath[0]!];\n  if (parentStep?.type === 'parallel' || parentStep?.type === 'conditional') {\n    parentStep = parentStep.steps[executionPath[1]!];\n  }\n\n  // `loop` / `foreach` carry their body as a SingleStepEntry.\n  if (parentStep?.type === 'loop' || parentStep?.type === 'foreach') {\n    return getEntryWorkflow(parentStep.step);\n  }\n\n  if (parentStep && isSingleStepEntry(parentStep)) {\n    return getEntryWorkflow(parentStep);\n  }\n\n  return null;\n}\n\n/**\n * Resolves the single-step entry addressed by an execution path, or null when\n * the path doesn't land on a single-step-like entry. For `loop` / `foreach`\n * the body entry is returned.\n */\nexport function getStepEntry(workflow: Workflow, executionPath: number[]): SingleStepEntry | null {\n  const stepGraph = workflow.stepGraph;\n  let parentStep = stepGraph[executionPath[0]!];\n  if (parentStep?.type === 'parallel' || parentStep?.type === 'conditional') {\n    parentStep = parentStep.steps[executionPath[1]!];\n  }\n\n  if (parentStep?.type === 'loop' || parentStep?.type === 'foreach') {\n    return parentStep.step;\n  }\n\n  if (parentStep && isSingleStepEntry(parentStep)) {\n    return parentStep;\n  }\n\n  return null;\n}\n\n/**\n * Resolves the id of the entry addressed by an execution path, or null when the\n * path doesn't land on a single-step-like entry. For `loop` / `foreach` the id\n * of the body entry is returned.\n */\nexport function getStepId(workflow: Workflow, executionPath: number[]): string | null {\n  const entry = getStepEntry(workflow, executionPath);\n  return entry ? getEntryId(entry) : null;\n}\n\nexport function isExecutableStep(step: StepFlowEntry<any>) {\n  return isSingleStepEntry(step) || step.type === 'loop' || step.type === 'foreach';\n}\n","/**\n * Helper functions for evented workflow execution.\n */\n\nimport { TripWire } from '../../agent/trip-wire';\n\n/**\n * Interface for tripwire chunks in the stream.\n * These chunks are emitted when a processor triggers a tripwire.\n */\nexport interface TripwireChunk {\n  type: 'tripwire';\n  payload: {\n    reason: string;\n    retry?: boolean;\n    metadata?: unknown;\n    processorId?: string;\n  };\n}\n\n/**\n * Type guard to check if a chunk is a tripwire chunk.\n * @param chunk - The chunk to check\n * @returns True if the chunk is a TripwireChunk\n */\nexport function isTripwireChunk(chunk: unknown): chunk is TripwireChunk {\n  return (\n    chunk !== null && typeof chunk === 'object' && 'type' in chunk && chunk.type === 'tripwire' && 'payload' in chunk\n  );\n}\n\n/**\n * Creates a TripWire error from a tripwire chunk.\n * @param chunk - The tripwire chunk from the stream\n * @returns A TripWire error instance\n */\nexport function createTripWireFromChunk(chunk: TripwireChunk): TripWire {\n  const { payload } = chunk;\n  return new TripWire(\n    payload.reason || 'Agent tripwire triggered',\n    {\n      retry: payload.retry,\n      metadata: payload.metadata,\n    },\n    payload.processorId,\n  );\n}\n\n/**\n * Extracts text delta from a stream chunk, handling V1 vs V2 differences.\n *\n * V1 (AI SDK v4): Uses `chunk.textDelta` for raw text\n * V2 (AI SDK v5): Uses `chunk.payload.text` for normalized text\n *\n * @param chunk - The stream chunk\n * @param isV2Model - Whether this is a V2 model (uses normalized payload)\n * @returns The text delta string, or undefined if not a text-delta chunk\n */\nexport function getTextDeltaFromChunk(\n  chunk: { type: string; textDelta?: string; payload?: { text?: string } },\n  isV2Model: boolean,\n): string | undefined {\n  if (chunk.type !== 'text-delta') {\n    return undefined;\n  }\n  return isV2Model ? chunk.payload?.text : chunk.textDelta;\n}\n\n/**\n * Parameters for resolving the current workflow state.\n */\nexport interface ResolveStateParams {\n  /** State from a step result (highest priority). Uses `any` to accommodate various StepResult types. */\n  stepResult?: unknown;\n  /** State from all step results */\n  stepResults?: { __state?: Record<string, unknown> };\n  /** State passed directly */\n  state?: Record<string, unknown>;\n}\n\n/**\n * Resolves the current workflow state from multiple potential sources.\n * Priority order: stepResult.__state > stepResults.__state > state > empty object\n *\n * @param params - The state sources to check\n * @returns The resolved state object\n */\nexport function resolveCurrentState(params: ResolveStateParams): Record<string, unknown> {\n  const { stepResult, stepResults, state } = params;\n  return (stepResult as any)?.__state ?? stepResults?.__state ?? state ?? {};\n}\n","import type { Mastra } from '../mastra';\nimport type { Event } from './types';\n\nexport abstract class EventProcessor {\n  protected mastra: Mastra;\n\n  __registerMastra(mastra: Mastra) {\n    this.mastra = mastra;\n  }\n\n  constructor({ mastra }: { mastra: Mastra }) {\n    this.mastra = mastra;\n  }\n\n  protected abstract process(event: Event): Promise<void>;\n}\n","import { randomUUID } from 'node:crypto';\nimport { TripWire } from '../../agent/trip-wire';\nimport { MastraBase } from '../../base';\nimport type { RequestContext } from '../../di';\nimport { MastraError, MastraNonRetryableError, ErrorDomain, ErrorCategory } from '../../error';\nimport { getErrorFromUnknown } from '../../error/utils.js';\nimport { RegisteredLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { TracingContext, TracingPolicy } from '../../observability';\nimport { EntityType, SpanType, createObservabilityContext } from '../../observability';\nimport { executeWithContext } from '../../observability/utils';\nimport { ToolStream } from '../../tools/stream';\nimport { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '../constants';\nimport { runAgentEntry, runMappingEntry, runToolEntry } from '../entry-executors';\nimport { getStepResult } from '../step';\nimport type { InnerOutput, LoopConditionFunction, SuspendOptions } from '../step';\nimport { getEntryComponent, getEntryId, getEntrySchemas } from '../step-entry';\nimport type { SingleStepEntry, StepFlowEntry, StepResult } from '../types';\nimport {\n  validateStepInput,\n  createDeprecationProxy,\n  runCountDeprecationMessage,\n  validateStepSuspendData,\n} from '../utils';\n\nexport class StepExecutor extends MastraBase {\n  protected mastra?: Mastra;\n  constructor({ mastra }: { mastra?: Mastra }) {\n    super({ name: 'StepExecutor', component: RegisteredLogger.WORKFLOW });\n    this.mastra = mastra;\n  }\n\n  __registerMastra(mastra: Mastra) {\n    this.mastra = mastra;\n    const logger = mastra?.getLogger();\n    if (logger) {\n      this.__setLogger(logger);\n    }\n  }\n\n  /**\n   * Creates an output writer function that publishes chunks to the workflow event stream.\n   * @param runId - The workflow run ID\n   * @returns An async function that writes chunks to the pubsub\n   */\n  private createOutputWriter(runId: string): (chunk: unknown) => Promise<void> {\n    return async (chunk: unknown) => {\n      try {\n        if (this.mastra?.pubsub) {\n          await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n            type: 'watch',\n            runId,\n            data: chunk,\n          });\n        }\n      } catch (err) {\n        // Non-critical: streaming events are observational\n        // Errors here should not fail step execution\n        this.logger.debug('Failed to publish workflow watch event', { runId, error: err });\n      }\n    };\n  }\n\n  async execute(params: {\n    workflowId: string;\n    entry: SingleStepEntry;\n    runId: string;\n    input?: any;\n    resumeData?: any;\n    stepResults: Record<string, StepResult<any, any, any, any>>;\n    state: Record<string, any>;\n    requestContext: RequestContext;\n    retryCount?: number;\n    foreachIdx?: number;\n    validateInputs?: boolean;\n    abortController?: AbortController;\n    perStep?: boolean;\n    format?: 'legacy' | 'vnext';\n    /** Tracing context for span nesting */\n    tracingContext?: TracingContext;\n    /** Workflow tracing policy, used to mark the step's span internal/external. */\n    tracingPolicy?: TracingPolicy;\n  }): Promise<StepResult<any, any, any, any>> {\n    const { entry, stepResults, runId, requestContext, retryCount = 0, perStep } = params;\n    const stepId = getEntryId(entry);\n    const schemas = getEntrySchemas(entry, this.mastra);\n\n    // Use provided abortController or create a new one for backwards compatibility\n    const abortController = params.abortController ?? new AbortController();\n\n    let suspended: { payload: any } | undefined;\n    let bailed: { payload: any } | undefined;\n    const startedAt = Date.now();\n    const { inputData, validationError } = await validateStepInput({\n      prevOutput: typeof params.foreachIdx === 'number' ? params.input?.[params.foreachIdx] : params.input,\n      step: schemas,\n      validateInputs: params.validateInputs ?? true,\n    });\n\n    let stepInfo: {\n      startedAt: number;\n      payload: any;\n      resumePayload?: any;\n      resumedAt?: number;\n      [key: string]: any;\n    } = {\n      ...stepResults[stepId],\n      startedAt,\n      payload: (typeof params.foreachIdx === 'number' ? params.input : inputData) ?? {},\n    };\n\n    if (params.resumeData) {\n      stepInfo.resumePayload = params.resumeData;\n      stepInfo.resumedAt = Date.now();\n      // Strip __workflow_meta from suspendPayload when step is resumed\n      // This metadata is only needed during suspend, not in the final completed result\n      if (stepInfo.suspendPayload && '__workflow_meta' in stepInfo.suspendPayload) {\n        const { __workflow_meta, ...userSuspendPayload } = stepInfo.suspendPayload;\n        stepInfo.suspendPayload = userSuspendPayload;\n      }\n    }\n\n    // Extract suspend data if this step was previously suspended\n    let suspendDataToUse =\n      params.stepResults[stepId]?.status === 'suspended' ? params.stepResults[stepId]?.suspendPayload : undefined;\n\n    // A suspended foreach step's step-level suspendPayload only carries the FIRST suspended\n    // iteration's payload. When resuming a specific iteration, use that iteration's own payload\n    // from `__workflow_meta.foreachOutput` so parallel suspensions don't read a sibling's data\n    // (e.g. another tool call's suspended run id).\n    if (suspendDataToUse && typeof params.foreachIdx === 'number') {\n      const iterationResult = suspendDataToUse.__workflow_meta?.foreachOutput?.[params.foreachIdx];\n      if (iterationResult?.status === 'suspended' && iterationResult.suspendPayload) {\n        suspendDataToUse = iterationResult.suspendPayload;\n      }\n    }\n\n    // Filter out internal workflow metadata before exposing to step code\n    if (suspendDataToUse && '__workflow_meta' in suspendDataToUse) {\n      const { __workflow_meta, ...userSuspendData } = suspendDataToUse;\n      suspendDataToUse = userSuspendData;\n    }\n\n    // Track state updates - don't mutate params.state in place\n    // This matches the default engine's behavior where setState captures\n    // the update and applies it AFTER the step completes\n    let stateUpdate: Record<string, any> | undefined;\n\n    // The evented engine, unlike the default engine, has no per-step span.\n    // Emit the WORKFLOW_STEP span here so the step's child spans nest under it\n    // and traces match the default engine.\n    const workflowStepSpan = params.tracingContext?.currentSpan?.createChildSpan({\n      type: SpanType.WORKFLOW_STEP,\n      name: `workflow step: '${stepId}'`,\n      entityType: EntityType.WORKFLOW_STEP,\n      entityId: stepId,\n      input: inputData,\n      tracingPolicy: params.tracingPolicy,\n      requestContext,\n    });\n    const stepTracingContext: TracingContext = workflowStepSpan\n      ? { currentSpan: workflowStepSpan }\n      : (params.tracingContext ?? {});\n\n    try {\n      if (validationError) {\n        throw validationError;\n      }\n\n      const callId = randomUUID();\n      const outputWriter = this.createOutputWriter(runId);\n\n      const stepOutput = await executeWithContext({\n        span: stepTracingContext.currentSpan,\n        fn: () => {\n          const executionContext = createDeprecationProxy(\n            {\n              workflowId: params.workflowId,\n              runId,\n              mastra: this.mastra!,\n              requestContext,\n              inputData,\n              state: params.state,\n              setState: async (newState: Record<string, any>) => {\n                // Capture state update - don't mutate params.state in place\n                // This matches default engine behavior where state changes\n                // are applied AFTER the step completes, not during execution\n                stateUpdate = { ...(stateUpdate ?? params.state), ...newState };\n              },\n              retryCount,\n              resumeData: params.resumeData,\n              suspendData: suspendDataToUse,\n              getInitData: () => stepResults?.input as any,\n              getStepResult: getStepResult.bind(this, stepResults),\n              suspend: async (suspendPayload: unknown, suspendOptions?: SuspendOptions): Promise<InnerOutput> => {\n                const { suspendData, validationError } = await validateStepSuspendData({\n                  suspendData: suspendPayload,\n                  step: schemas,\n                  validateInputs: params.validateInputs ?? true,\n                });\n                if (validationError) {\n                  throw validationError;\n                }\n                // Build resume labels if provided\n                const resumeLabels: Record<string, { stepId: string; foreachIndex?: number }> = {};\n                if (suspendOptions?.resumeLabel) {\n                  const labels = Array.isArray(suspendOptions.resumeLabel)\n                    ? suspendOptions.resumeLabel\n                    : [suspendOptions.resumeLabel];\n                  for (const label of labels) {\n                    resumeLabels[label] = {\n                      stepId,\n                      foreachIndex: params.foreachIdx,\n                    };\n                  }\n                }\n                suspended = {\n                  payload: {\n                    ...suspendData,\n                    __workflow_meta: {\n                      runId,\n                      path: [stepId],\n                      foreachIndex: params.foreachIdx,\n                      resumeLabels: Object.keys(resumeLabels).length > 0 ? resumeLabels : undefined,\n                    },\n                  },\n                };\n              },\n              bail: (result: any): InnerOutput => {\n                bailed = { payload: result };\n              },\n              writer: new ToolStream(\n                {\n                  prefix: 'workflow-step',\n                  callId,\n                  name: stepId,\n                  runId,\n                },\n                outputWriter,\n              ),\n              abort: () => {\n                abortController?.abort();\n              },\n              [PUBSUB_SYMBOL]: this.mastra!.pubsub,\n              [STREAM_FORMAT_SYMBOL]: params.format,\n              engine: {},\n              abortSignal: abortController?.signal,\n              ...createObservabilityContext(stepTracingContext),\n            },\n            {\n              paramName: 'runCount',\n              deprecationMessage: runCountDeprecationMessage,\n              logger: this.logger,\n            },\n          );\n          switch (entry.type) {\n            case 'step':\n              return entry.step.execute(executionContext);\n            case 'agent':\n              return runAgentEntry(entry, executionContext, this.mastra);\n            case 'tool':\n              return runToolEntry(entry, executionContext, this.mastra);\n            case 'mapping':\n              return runMappingEntry(entry, executionContext);\n          }\n        },\n      });\n\n      const isNestedWorkflowStep = getEntryComponent(entry) === 'WORKFLOW';\n\n      const nestedWflowStepPaused = isNestedWorkflowStep && perStep;\n\n      const endedAt = Date.now();\n\n      // Use stateUpdate if setState was called, otherwise use original state\n      const finalState = stateUpdate ?? params.state;\n\n      let finalResult: StepResult<any, any, any, any> & { __state?: Record<string, any> };\n      if (suspended) {\n        finalResult = {\n          ...stepInfo,\n          status: 'suspended',\n          suspendedAt: endedAt,\n          ...(stepOutput ? { suspendOutput: stepOutput } : {}),\n          __state: finalState,\n        };\n\n        if (suspended.payload) {\n          finalResult.suspendPayload = suspended.payload;\n        }\n      } else if (bailed) {\n        finalResult = {\n          ...stepInfo,\n          // @ts-expect-error - bailed status not in type\n          status: 'bailed',\n          endedAt,\n          output: bailed.payload,\n          __state: finalState,\n        };\n      } else if (nestedWflowStepPaused) {\n        finalResult = {\n          ...stepInfo,\n          status: 'paused',\n          __state: finalState,\n        };\n      } else {\n        finalResult = {\n          ...stepInfo,\n          status: 'success',\n          endedAt,\n          output: stepOutput,\n          __state: finalState,\n        };\n      }\n\n      if (finalResult.status === 'success') {\n        workflowStepSpan?.end({ output: stepOutput, attributes: { status: 'success' } });\n      } else {\n        workflowStepSpan?.end({ attributes: { status: finalResult.status } });\n      }\n\n      return finalResult;\n    } catch (error: any) {\n      const endedAt = Date.now();\n\n      const errorInstance = getErrorFromUnknown(error, {\n        serializeStack: false,\n        fallbackMessage: 'Unknown step execution error',\n      });\n\n      workflowStepSpan?.error({ error: errorInstance });\n\n      // Log the error for observability (matching default engine behavior)\n      const mastraError = new MastraError(\n        {\n          id: 'WORKFLOW_STEP_INVOKE_FAILED',\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.USER,\n          details: { workflowId: params.workflowId, runId: params.runId, stepId },\n        },\n        errorInstance,\n      );\n      this.logger?.trackException(mastraError);\n      this.logger?.error(`Error executing step ${stepId}: ` + errorInstance?.stack);\n\n      return {\n        ...stepInfo,\n        status: 'failed',\n        endedAt,\n        error: errorInstance,\n        ...(error instanceof MastraNonRetryableError && { nonRetryable: true as const }),\n        // Preserve TripWire data as plain object for proper serialization\n        // Important: Check `error` not `errorInstance` because getErrorFromUnknown\n        // converts the error and loses the prototype chain\n        tripwire:\n          error instanceof TripWire\n            ? {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n                processorId: error.processorId,\n              }\n            : undefined,\n      };\n    }\n  }\n\n  async evaluateConditions(params: {\n    workflowId: string;\n    step: Extract<StepFlowEntry, { type: 'conditional' }>;\n    runId: string;\n    input?: any;\n    resumeData?: any;\n    stepResults: Record<string, StepResult<any, any, any, any>>;\n    state: Record<string, any>;\n    requestContext: RequestContext;\n    retryCount?: number;\n    abortController?: AbortController;\n  }): Promise<number[]> {\n    const { step, stepResults, runId, requestContext, retryCount = 0 } = params;\n\n    const abortController = params.abortController ?? new AbortController();\n\n    const results = await Promise.all(\n      step.conditions.map(condition => {\n        try {\n          return this.evaluateCondition({\n            workflowId: params.workflowId,\n            condition,\n            runId,\n            requestContext,\n            inputData: params.input,\n            state: params.state,\n            retryCount,\n            resumeData: params.resumeData,\n            abortController,\n            stepResults,\n            iterationCount: 0,\n          });\n        } catch (e) {\n          this.mastra?.getLogger()?.error('error evaluating condition', e);\n          return false;\n        }\n      }),\n    );\n\n    const idxs = results.reduce((acc, result, idx) => {\n      if (result) {\n        acc.push(idx);\n      }\n\n      return acc;\n    }, [] as number[]);\n\n    return idxs;\n  }\n\n  async evaluateCondition({\n    workflowId,\n    condition,\n    runId,\n    inputData,\n    resumeData,\n    stepResults,\n    state,\n    requestContext,\n    abortController,\n    retryCount = 0,\n    iterationCount,\n  }: {\n    workflowId: string;\n    condition: LoopConditionFunction<any, any, any, any, any, any>;\n    runId: string;\n    inputData?: any;\n    resumeData?: any;\n    stepResults: Record<string, StepResult<any, any, any, any>>;\n    state: Record<string, any>;\n    requestContext: RequestContext;\n    abortController: AbortController;\n    retryCount?: number;\n    iterationCount: number;\n  }): Promise<boolean> {\n    const callId = randomUUID();\n    const outputWriter = this.createOutputWriter(runId);\n\n    return condition(\n      createDeprecationProxy(\n        {\n          workflowId,\n          runId,\n          mastra: this.mastra!,\n          requestContext,\n          inputData,\n          state,\n          retryCount,\n          resumeData: resumeData,\n          getInitData: () => stepResults?.input as any,\n          getStepResult: getStepResult.bind(this, stepResults),\n          bail: (_result: any) => {\n            throw new Error('Not implemented');\n          },\n          writer: new ToolStream(\n            {\n              prefix: 'workflow-step',\n              callId,\n              name: 'condition',\n              runId,\n            },\n            outputWriter,\n          ),\n          abort: () => {\n            abortController?.abort();\n          },\n          [PUBSUB_SYMBOL]: this.mastra!.pubsub,\n          [STREAM_FORMAT_SYMBOL]: undefined, // TODO\n          engine: {},\n          abortSignal: abortController?.signal,\n          // TODO\n          ...createObservabilityContext(),\n          iterationCount,\n        },\n        {\n          paramName: 'runCount',\n          deprecationMessage: runCountDeprecationMessage,\n          logger: this.logger,\n        },\n      ),\n    );\n  }\n\n  async resolveSleep(params: {\n    workflowId: string;\n    step: Extract<StepFlowEntry, { type: 'sleep' }>;\n    runId: string;\n    input?: any;\n    resumeData?: any;\n    stepResults: Record<string, StepResult<any, any, any, any>>;\n    state?: Record<string, any>;\n    requestContext: RequestContext;\n    retryCount?: number;\n    abortController?: AbortController;\n  }): Promise<number> {\n    const { step, stepResults, runId, requestContext, retryCount = 0 } = params;\n    const currentState = params.state ?? stepResults?.__state ?? {};\n\n    const abortController = params.abortController ?? new AbortController();\n\n    if (step.duration) {\n      return step.duration;\n    }\n\n    if (!step.fn) {\n      return 0;\n    }\n\n    try {\n      const callId = randomUUID();\n      const outputWriter = this.createOutputWriter(runId);\n\n      return await step.fn(\n        createDeprecationProxy(\n          {\n            workflowId: params.workflowId,\n            runId,\n            mastra: this.mastra!,\n            requestContext,\n            inputData: params.input,\n            state: currentState,\n            setState: async (newState: Record<string, any>) => {\n              Object.assign(currentState, newState);\n            },\n            retryCount,\n            resumeData: params.resumeData,\n            getInitData: () => stepResults?.input as any,\n            getStepResult: getStepResult.bind(this, stepResults),\n            suspend: async (_suspendPayload: any): Promise<any> => {\n              throw new Error('Not implemented');\n            },\n            bail: (_result: any) => {\n              throw new Error('Not implemented');\n            },\n            abort: () => {\n              abortController?.abort();\n            },\n            writer: new ToolStream(\n              {\n                prefix: 'workflow-step',\n                callId,\n                name: step.id,\n                runId,\n              },\n              outputWriter,\n            ),\n            [PUBSUB_SYMBOL]: this.mastra!.pubsub,\n            [STREAM_FORMAT_SYMBOL]: undefined, // TODO\n            engine: {},\n            abortSignal: abortController?.signal,\n            // TODO\n            ...createObservabilityContext(),\n          },\n          {\n            paramName: 'runCount',\n            deprecationMessage: runCountDeprecationMessage,\n            logger: this.logger,\n          },\n        ),\n      );\n    } catch (e) {\n      this.mastra?.getLogger()?.error('error evaluating condition', e);\n      return 0;\n    }\n  }\n\n  async resolveSleepUntil(params: {\n    workflowId: string;\n    step: Extract<StepFlowEntry, { type: 'sleepUntil' }>;\n    runId: string;\n    input?: any;\n    resumeData?: any;\n    stepResults: Record<string, StepResult<any, any, any, any>>;\n    state?: Record<string, any>;\n    requestContext: RequestContext;\n    retryCount?: number;\n    abortController?: AbortController;\n  }): Promise<number> {\n    const { step, stepResults, runId, requestContext, retryCount = 0 } = params;\n    const currentState = params.state ?? stepResults?.__state ?? {};\n\n    const abortController = params.abortController ?? new AbortController();\n\n    if (step.date) {\n      return step.date.getTime() - Date.now();\n    }\n\n    if (!step.fn) {\n      return 0;\n    }\n\n    try {\n      const callId = randomUUID();\n      const outputWriter = this.createOutputWriter(runId);\n\n      const result = await step.fn(\n        createDeprecationProxy(\n          {\n            workflowId: params.workflowId,\n            runId,\n            mastra: this.mastra!,\n            requestContext,\n            inputData: params.input,\n            state: currentState,\n            setState: async (newState: Record<string, any>) => {\n              Object.assign(currentState, newState);\n            },\n            retryCount,\n            resumeData: params.resumeData,\n            getInitData: () => stepResults?.input as any,\n            getStepResult: getStepResult.bind(this, stepResults),\n            suspend: async (_suspendPayload: any): Promise<any> => {\n              throw new Error('Not implemented');\n            },\n            bail: (_result: any) => {\n              throw new Error('Not implemented');\n            },\n            abort: () => {\n              abortController?.abort();\n            },\n            writer: new ToolStream(\n              {\n                prefix: 'workflow-step',\n                callId,\n                name: step.id,\n                runId,\n              },\n              outputWriter,\n            ),\n            [PUBSUB_SYMBOL]: this.mastra!.pubsub,\n            [STREAM_FORMAT_SYMBOL]: undefined, // TODO\n            engine: {},\n            abortSignal: abortController?.signal,\n            // TODO\n            ...createObservabilityContext(),\n          },\n          {\n            paramName: 'runCount',\n            deprecationMessage: runCountDeprecationMessage,\n            logger: this.logger,\n          },\n        ),\n      );\n\n      return result.getTime() - Date.now();\n    } catch (e) {\n      this.mastra?.getLogger()?.error('error evaluating condition', e);\n      return 0;\n    }\n  }\n}\n","/**\n * Types and utilities for evented workflow execution.\n */\n\n/**\n * String key used to mark pending forEach iterations.\n * Using a string key (not Symbol) ensures the marker survives JSON serialization\n * which is critical for distributed execution where state is persisted to storage\n * and loaded by different engine instances.\n */\nexport const PENDING_MARKER_KEY = '__mastra_pending__' as const;\n\n/**\n * Type for the pending marker object used in forEach iteration tracking.\n */\nexport type PendingMarker = { [PENDING_MARKER_KEY]: true };\n\n/**\n * Creates a new pending marker object.\n * Used to mark forEach iterations that are about to be resumed.\n */\nexport function createPendingMarker(): PendingMarker {\n  return { [PENDING_MARKER_KEY]: true };\n}\n\n/**\n * Type guard to check if a value is a pending marker.\n * Works correctly after JSON serialization/deserialization.\n * @param val - The value to check\n * @returns True if the value is a PendingMarker\n */\nexport function isPendingMarker(val: unknown): val is PendingMarker {\n  return (\n    val !== null &&\n    typeof val === 'object' &&\n    Object.prototype.hasOwnProperty.call(val, PENDING_MARKER_KEY) &&\n    (val as Record<string, unknown>)[PENDING_MARKER_KEY] === true &&\n    Object.keys(val).length === 1\n  );\n}\n","import type { StepFlowEntry, StepResult } from '../..';\nimport { RequestContext } from '../../../di';\nimport type { PubSub } from '../../../events';\nimport type { Mastra } from '../../../mastra';\nimport { getEntryId, getEntryWorkflow } from '../../step-entry';\nimport { resolveForeachConcurrency } from '../../utils';\nimport { resolveCurrentState } from '../helpers';\nimport type { StepExecutor } from '../step-executor';\nimport { createPendingMarker } from '../types';\nimport type { ProcessorArgs } from '.';\n\nexport async function processWorkflowLoop(\n  {\n    workflowId,\n    prevResult,\n    runId,\n    executionPath,\n    stepResults,\n    activeStepsPath,\n    resumeSteps,\n    resumeData,\n    parentWorkflow,\n    requestContext,\n    retryCount = 0,\n    perStep,\n    state,\n    outputOptions,\n  }: ProcessorArgs,\n  {\n    pubsub,\n    stepExecutor,\n    step,\n    stepResult,\n  }: {\n    pubsub: PubSub;\n    stepExecutor: StepExecutor;\n    step: Extract<StepFlowEntry, { type: 'loop' }>;\n    stepResult: StepResult<any, any, any, any>;\n  },\n) {\n  // Get current state from stepResult, stepResults or passed state\n  const currentState = resolveCurrentState({ stepResult, stepResults, state });\n\n  // Create a proper RequestContext from the plain object passed in ProcessorArgs\n  const reqContext = new RequestContext(Object.entries(requestContext ?? {}) as any);\n\n  // Get iteration count from step results metadata (same pattern as control-flow.ts)\n  const prevIterationCount = stepResults[getEntryId(step.step)]?.metadata?.iterationCount ?? 0;\n  const iterationCount = prevIterationCount + 1;\n\n  const loopCondition = await stepExecutor.evaluateCondition({\n    workflowId,\n    condition: step.condition,\n    runId,\n    stepResults,\n    state: currentState,\n    requestContext: reqContext,\n    inputData: prevResult?.status === 'success' ? prevResult.output : undefined,\n    resumeData,\n    abortController: new AbortController(),\n    retryCount,\n    iterationCount,\n  });\n\n  // When the loop body runs again, it's a fresh iteration — not a resume — so drop any\n  // resume metadata. Otherwise the body would keep receiving the same resumeData on every\n  // iteration (and e.g. never re-suspend).\n  const loopAgainData = {\n    parentWorkflow,\n    workflowId,\n    runId,\n    executionPath,\n    resumeSteps: [] as string[],\n    // Carry the iteration count forward on the loop body's stepResults entry. The\n    // loop-again path does not merge the body result back into stepResults[bodyStepId]\n    // (only prevResult carries it), and the evented step executor never writes\n    // iterationCount, so without this the next processWorkflowLoop re-reads 0 and the\n    // condition is always evaluated with iterationCount === 1 (an infinite loop when\n    // termination depends on the count). Mirrors the default engine, which stamps\n    // metadata.iterationCount onto the step result. See handlers/step.ts.\n    stepResults: {\n      ...stepResults,\n      [getEntryId(step.step)]: {\n        ...stepResults[getEntryId(step.step)],\n        metadata: { ...stepResults[getEntryId(step.step)]?.metadata, iterationCount },\n      },\n    },\n    prevResult: stepResult,\n    resumeData: undefined,\n    activeStepsPath,\n    requestContext,\n    retryCount,\n    perStep,\n    state: currentState,\n    outputOptions,\n  };\n  const loopEndData = {\n    parentWorkflow,\n    workflowId,\n    runId,\n    executionPath,\n    resumeSteps,\n    stepResults,\n    prevResult: stepResult,\n    resumeData,\n    activeStepsPath,\n    requestContext,\n    perStep,\n    state: currentState,\n    outputOptions,\n  };\n\n  if (step.loopType === 'dountil') {\n    if (loopCondition) {\n      await pubsub.publish('workflows', { type: 'workflow.step.end', runId, data: loopEndData });\n    } else {\n      await pubsub.publish('workflows', { type: 'workflow.step.run', runId, data: loopAgainData });\n    }\n  } else {\n    if (loopCondition) {\n      await pubsub.publish('workflows', { type: 'workflow.step.run', runId, data: loopAgainData });\n    } else {\n      await pubsub.publish('workflows', { type: 'workflow.step.end', runId, data: loopEndData });\n    }\n  }\n}\n\nexport async function processWorkflowForEach(\n  {\n    workflowId,\n    prevResult,\n    runId,\n    executionPath,\n    stepResults,\n    activeStepsPath,\n    resumeSteps,\n    timeTravel,\n    restart,\n    resumeData,\n    parentWorkflow,\n    requestContext,\n    perStep,\n    state,\n    outputOptions,\n    forEachIndex,\n  }: ProcessorArgs,\n  {\n    pubsub,\n    mastra,\n    step,\n  }: {\n    pubsub: PubSub;\n    mastra: Mastra;\n    step: Extract<StepFlowEntry, { type: 'foreach' }>;\n  },\n) {\n  // Get current state from stepResults or passed state\n  const currentState = resolveCurrentState({ stepResults, state });\n  const currentResult: Extract<StepResult<any, any, any, any>, { status: 'success' }> = stepResults[\n    getEntryId(step.step)\n  ] as any;\n\n  const idx = currentResult?.output?.length ?? 0;\n  const targetLen = (prevResult as any)?.output?.length ?? 0;\n\n  // Handle resume with forEachIndex: kick off the targeted iteration resume\n  if (forEachIndex !== undefined && resumeSteps?.length > 0 && idx > 0) {\n    // Validate forEachIndex is within bounds to fail loudly instead of silently no-op\n    const outputArray = currentResult?.output;\n    const outputLength = Array.isArray(outputArray) ? outputArray.length : 0;\n    if (!Array.isArray(outputArray) || forEachIndex < 0 || forEachIndex >= outputLength) {\n      const error = new Error(\n        `Invalid forEachIndex ${forEachIndex} for forEach resume: ` +\n          `expected index in range [0, ${outputLength - 1}] but output array has length ${outputLength}`,\n      );\n      await pubsub.publish('workflows', {\n        type: 'workflow.fail',\n        runId,\n        data: {\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          stepResults,\n          prevResult: { status: 'failed', error },\n          activeStepsPath,\n          requestContext,\n          state: currentState,\n          outputOptions,\n        },\n      });\n      return;\n    }\n\n    // Check if the target iteration is suspended\n    const iterationResult = currentResult?.output?.[forEachIndex];\n    if (iterationResult?.status === 'suspended' || iterationResult === null) {\n      // Only pass resumeData to the targeted iteration\n      const isNestedWorkflow = getEntryWorkflow(step.step) !== null;\n      const targetArray = (prevResult as any)?.output;\n      const iterationPrevResult =\n        isNestedWorkflow && prevResult.status === 'success' && Array.isArray(targetArray)\n          ? { status: 'success' as const, output: targetArray[forEachIndex] }\n          : prevResult;\n\n      await pubsub.publish('workflows', {\n        type: 'workflow.step.run',\n        runId,\n        data: {\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath: [executionPath[0]!, forEachIndex],\n          resumeSteps,\n          timeTravel,\n          restart,\n          stepResults,\n          prevResult: iterationPrevResult,\n          resumeData,\n          activeStepsPath,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n        },\n      });\n      return;\n    }\n\n    // If forEachIndex was provided but the iteration is already complete,\n    // check if there are still pending (null or suspended) iterations.\n    // If so, re-suspend the workflow to wait for those to be resumed.\n    const pendingIterations = currentResult.output.filter((r: any) => r === null || r?.status === 'suspended');\n    if (pendingIterations.length > 0) {\n      // Collect resumeLabels from all suspended iterations and capture the first\n      // suspended iteration's full suspendPayload so non-__workflow_meta keys\n      // (e.g. __streamState stashed by the agent loop) survive aggregation.\n      const collectedResumeLabels: Record<string, { stepId: string; foreachIndex?: number }> = {};\n      let firstSuspendedIterationPayload: Record<string, unknown> | undefined;\n      for (let i = 0; i < currentResult.output.length; i++) {\n        const iterResult = currentResult.output[i];\n        if (iterResult?.status === 'suspended') {\n          if (iterResult.suspendPayload?.__workflow_meta?.resumeLabels) {\n            Object.assign(collectedResumeLabels, iterResult.suspendPayload.__workflow_meta.resumeLabels);\n          }\n          if (firstSuspendedIterationPayload === undefined) {\n            firstSuspendedIterationPayload = iterResult.suspendPayload;\n          }\n        }\n      }\n\n      // Build the suspend metadata with all collected resumeLabels\n      const suspendMeta: {\n        foreachIndex?: number;\n        resumeLabels?: Record<string, { stepId: string; foreachIndex?: number }>;\n      } = {\n        foreachIndex: forEachIndex,\n      };\n      if (Object.keys(collectedResumeLabels).length > 0) {\n        suspendMeta.resumeLabels = collectedResumeLabels;\n      }\n\n      const aggregatedSuspendPayload = {\n        ...firstSuspendedIterationPayload,\n        __workflow_meta: suspendMeta,\n      };\n\n      // Re-suspend the workflow - there are still pending iterations\n      // Use workflow.step.end with suspended status to update storage\n      await pubsub.publish('workflows', {\n        type: 'workflow.step.end',\n        runId,\n        data: {\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          stepResults: {\n            ...stepResults,\n            [getEntryId(step.step)]: {\n              ...currentResult,\n              status: 'suspended',\n              suspendedAt: Date.now(),\n              suspendPayload: aggregatedSuspendPayload,\n            },\n          },\n          prevResult: {\n            status: 'suspended',\n            output: currentResult.output,\n            suspendPayload: aggregatedSuspendPayload,\n            payload: currentResult.payload,\n            startedAt: currentResult.startedAt,\n            suspendedAt: Date.now(),\n          },\n          activeStepsPath,\n          requestContext,\n          state: currentState,\n          outputOptions,\n        },\n      });\n      return;\n    }\n\n    // forEachIndex was provided but the target iteration is already complete,\n    // and there are no pending iterations. The workflow step.end handler will\n    // advance the workflow. This is expected behavior for completed forEach loops.\n    return;\n  }\n\n  // Handle bulk resume: when resumeData is provided but no forEachIndex,\n  // resume suspended iterations up to the concurrency limit\n  if (resumeData !== undefined && forEachIndex === undefined && currentResult?.output?.length > 0) {\n    const suspendedIndices: number[] = [];\n    for (let i = 0; i < currentResult.output.length; i++) {\n      const iterResult = currentResult.output[i];\n      if (iterResult && typeof iterResult === 'object' && iterResult.status === 'suspended') {\n        suspendedIndices.push(i);\n      }\n    }\n\n    if (suspendedIndices.length > 0) {\n      // Limit resumption to concurrency value (like initial execution)\n      const concurrency = resolveForeachConcurrency(step.opts, {\n        inputData: (prevResult as any)?.output,\n        getInitData: () => (stepResults as any)?.input,\n      });\n      const indicesToResume = suspendedIndices.slice(0, concurrency);\n\n      // Reset suspended iterations to \"pending\" state before re-running them.\n      //\n      // Why PendingMarker instead of null?\n      // The storage merge logic treats null as \"keep existing value\" to prevent\n      // completed results from being overwritten by concurrent iterations that\n      // haven't finished yet. But when resuming, we need to force-reset the\n      // suspended result to null so the iteration can run fresh.\n      //\n      // PendingMarker ({ __mastra_pending__: true }) tells the storage layer\n      // \"force this to null, don't preserve the existing suspended result.\"\n      // See inmemory.ts updateWorkflowResults for the merge logic.\n      const workflowsStore = await mastra.getStorage()?.getStore('workflows');\n      const updatedOutput = [...currentResult.output];\n      for (const suspIdx of indicesToResume) {\n        updatedOutput[suspIdx] = createPendingMarker() as any;\n      }\n\n      await workflowsStore?.updateWorkflowResults({\n        workflowName: workflowId,\n        runId,\n        stepId: getEntryId(step.step),\n        result: {\n          ...currentResult,\n          output: updatedOutput,\n        } as any,\n        requestContext,\n      });\n\n      // Check if inner step is a nested workflow\n      const isNestedWorkflow = getEntryWorkflow(step.step) !== null;\n\n      // Resume iterations up to concurrency limit\n      // Wrap in try-catch to prevent partial state issues if some publishes fail\n      for (const suspIdx of indicesToResume) {\n        const targetArray = (prevResult as any)?.output;\n        const iterationPrevResult =\n          isNestedWorkflow && prevResult.status === 'success' && Array.isArray(targetArray)\n            ? { status: 'success' as const, output: targetArray[suspIdx] }\n            : prevResult;\n\n        try {\n          await pubsub.publish('workflows', {\n            type: 'workflow.step.run',\n            runId,\n            data: {\n              parentWorkflow,\n              workflowId,\n              runId,\n              executionPath: [executionPath[0]!, suspIdx],\n              resumeSteps,\n              timeTravel,\n              restart,\n              stepResults,\n              prevResult: iterationPrevResult,\n              resumeData,\n              activeStepsPath,\n              requestContext,\n              perStep,\n              state: currentState,\n              outputOptions,\n            },\n          });\n        } catch {\n          // Log error but continue - the iteration will be picked up on next resume\n          // State was already updated, so no data loss\n        }\n      }\n      return;\n    }\n  }\n\n  const workflowsStore = await mastra.getStorage()?.getStore('workflows');\n\n  if (\n    (idx >= targetLen && currentResult?.output?.filter((r: any) => r !== null)?.length >= targetLen) ||\n    (prevResult as any)?.output?.length === 0\n  ) {\n    // Foreach completed all iterations or the previous result is an empty array - advance to next step\n    // If the previous result is an empty array, we need to create a new result with an empty array output, save to stroage and stepResults\n    let result = currentResult;\n    if ((prevResult as any)?.output?.length === 0) {\n      result = {\n        status: 'success',\n        output: [],\n        startedAt: Date.now(),\n        endedAt: Date.now(),\n        payload: (prevResult as any)?.output,\n      };\n      await workflowsStore?.updateWorkflowResults({\n        workflowName: workflowId,\n        runId,\n        stepId: getEntryId(step.step),\n        result,\n        requestContext,\n      });\n      stepResults[getEntryId(step.step)] = result as StepResult<any, any, any, any>;\n    }\n\n    await pubsub.publish('workflows', {\n      type: 'workflow.step.run',\n      runId,\n      data: {\n        parentWorkflow,\n        workflowId,\n        runId,\n        executionPath: executionPath.slice(0, -1).concat([executionPath[executionPath.length - 1]! + 1]),\n        resumeSteps,\n        stepResults,\n        timeTravel,\n        restart,\n        prevResult: result,\n        resumeData: undefined, // No resumeData when advancing past foreach\n        activeStepsPath,\n        requestContext,\n        perStep,\n        state: currentState,\n        outputOptions,\n      },\n    });\n\n    return;\n  } else if (idx >= targetLen) {\n    // wait for the 'null' values to be filled from the concurrent run\n    return;\n  }\n\n  if (executionPath.length === 1 && idx === 0) {\n    // on first iteratation we need to kick off up to the set concurrency\n    const resolvedConcurrency = resolveForeachConcurrency(step.opts, {\n      inputData: (prevResult as any)?.output,\n      getInitData: () => (stepResults as any)?.input,\n    });\n    const concurrency = Math.min(resolvedConcurrency, targetLen);\n    const dummyResult = Array.from({ length: concurrency }, () => null);\n\n    await workflowsStore?.updateWorkflowResults({\n      workflowName: workflowId,\n      runId,\n      stepId: getEntryId(step.step),\n      result: {\n        status: 'success',\n        output: dummyResult as any,\n        startedAt: Date.now(),\n        payload: (prevResult as any)?.output,\n      } as any,\n      requestContext,\n    });\n\n    // Check if inner step is a nested workflow - only then extract individual items\n    // Regular steps use foreachIdx in step executor for item extraction\n    const isNestedWorkflow = getEntryWorkflow(step.step) !== null;\n\n    for (let i = 0; i < concurrency; i++) {\n      // For nested workflows, extract individual item since they receive prevResult directly\n      // For regular steps, step executor handles extraction via foreachIdx\n      const targetArray = (prevResult as any)?.output;\n      const iterationPrevResult =\n        isNestedWorkflow && prevResult.status === 'success' && Array.isArray(targetArray)\n          ? { status: 'success' as const, output: targetArray[i] }\n          : prevResult;\n      await pubsub.publish('workflows', {\n        type: 'workflow.step.run',\n        runId,\n        data: {\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath: [executionPath[0]!, i],\n          resumeSteps,\n          stepResults,\n          timeTravel,\n          restart,\n          prevResult: iterationPrevResult,\n          resumeData,\n          activeStepsPath,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n        },\n      });\n    }\n\n    return;\n  }\n\n  (currentResult as any).output.push(null);\n  await workflowsStore?.updateWorkflowResults({\n    workflowName: workflowId,\n    runId,\n    stepId: getEntryId(step.step),\n    result: {\n      status: 'success',\n      output: (currentResult as any).output,\n      startedAt: Date.now(),\n      payload: (prevResult as any)?.output,\n    } as any,\n    requestContext,\n  });\n\n  // For nested workflows, extract individual item since they receive prevResult directly\n  // For regular steps, step executor handles extraction via foreachIdx\n  const isNestedWorkflow = getEntryWorkflow(step.step) !== null;\n  const targetArray = (prevResult as any)?.output;\n  const iterationPrevResult =\n    isNestedWorkflow && prevResult.status === 'success' && Array.isArray(targetArray)\n      ? { status: 'success' as const, output: targetArray[idx] }\n      : prevResult;\n\n  await pubsub.publish('workflows', {\n    type: 'workflow.step.run',\n    runId,\n    data: {\n      parentWorkflow,\n      workflowId,\n      runId,\n      executionPath: [executionPath[0]!, idx],\n      resumeSteps,\n      timeTravel,\n      restart,\n      stepResults,\n      prevResult: iterationPrevResult,\n      resumeData,\n      activeStepsPath,\n      requestContext,\n      perStep,\n      state: currentState,\n      outputOptions,\n    },\n  });\n}\n","import type { SingleStepEntry, StepFlowEntry } from '../..';\nimport { RequestContext } from '../../../di';\nimport type { PubSub } from '../../../events';\nimport { getSingleStepEntryId } from '../../utils';\nimport { resolveCurrentState } from '../helpers';\nimport type { StepExecutor } from '../step-executor';\nimport type { ProcessorArgs } from '.';\n\nexport async function processWorkflowParallel(\n  {\n    workflowId,\n    runId,\n    executionPath,\n    stepResults,\n    activeStepsPath,\n    resumeSteps,\n    timeTravel,\n    restart,\n    prevResult,\n    resumeData,\n    parentWorkflow,\n    requestContext,\n    perStep,\n    state,\n    outputOptions,\n  }: ProcessorArgs,\n  {\n    pubsub,\n    step,\n  }: {\n    pubsub: PubSub;\n    step: Extract<StepFlowEntry, { type: 'parallel' }>;\n  },\n) {\n  const pathsToRun: Record<string, boolean> = {};\n  // Get current state from stepResults or passed state\n  const currentState = resolveCurrentState({ stepResults, state });\n  for (let i = 0; i < step.steps.length; i++) {\n    const nestedStep = step.steps[i];\n    if (nestedStep) {\n      const nestedStepId = getSingleStepEntryId(nestedStep);\n      //if restart, only run the step if it's in the active steps path\n      if (restart) {\n        pathsToRun[nestedStepId] = !!restart.activeStepsPath[nestedStepId];\n      } else {\n        pathsToRun[nestedStepId] = true;\n      }\n      if (perStep) {\n        break;\n      }\n    }\n  }\n\n  await Promise.all(\n    // Iterate the full steps array and guard inside so `idx` stays the branch's\n    // real index. Filtering first and using the post-filter index would route a\n    // restart to the wrong branch when the active branches are not a zero-based\n    // contiguous prefix (mirrors `processWorkflowConditional` below).\n    step.steps?.map(async (child, idx) => {\n      if (!pathsToRun[getSingleStepEntryId(child)]) {\n        return;\n      }\n      return pubsub.publish('workflows', {\n        type: 'workflow.step.run',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath: restart ? executionPath.slice(0, -1).concat([idx]) : executionPath.concat([idx]),\n          resumeSteps,\n          stepResults,\n          prevResult,\n          resumeData,\n          timeTravel,\n          restart: restart ? { ...restart, isParallelOrConditionalRestarted: true } : undefined,\n          parentWorkflow,\n          activeStepsPath,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n        },\n      });\n    }),\n  );\n}\n\nexport async function processWorkflowConditional(\n  {\n    workflowId,\n    runId,\n    executionPath,\n    stepResults,\n    activeStepsPath,\n    resumeSteps,\n    timeTravel,\n    restart,\n    prevResult,\n    resumeData,\n    parentWorkflow,\n    requestContext,\n    perStep,\n    state,\n    outputOptions,\n  }: ProcessorArgs,\n  {\n    pubsub,\n    stepExecutor,\n    step,\n  }: {\n    pubsub: PubSub;\n    stepExecutor: StepExecutor;\n    step: Extract<StepFlowEntry, { type: 'conditional' }>;\n  },\n) {\n  // Get current state from stepResults or passed state\n  const currentState = resolveCurrentState({ stepResults, state });\n\n  // Create a proper RequestContext from the plain object passed in ProcessorArgs\n  const reqContext = new RequestContext(Object.entries(requestContext ?? {}) as any);\n\n  const idxs = await stepExecutor.evaluateConditions({\n    workflowId,\n    step,\n    runId,\n    stepResults,\n    state: currentState,\n    requestContext: reqContext,\n    input: prevResult?.status === 'success' ? prevResult.output : undefined,\n    resumeData,\n  });\n\n  const truthyIdxs: Record<number, boolean> = {};\n  for (let i = 0; i < idxs.length; i++) {\n    truthyIdxs[idxs[i]!] = true;\n  }\n\n  let onlyStepToRun: SingleStepEntry | undefined;\n\n  if (perStep) {\n    const stepsToRun = step.steps.filter((_, idx) => truthyIdxs[idx]);\n    onlyStepToRun = stepsToRun[0];\n  }\n\n  if (onlyStepToRun) {\n    const onlyStepToRunId = getSingleStepEntryId(onlyStepToRun);\n    const stepIndex = step.steps.findIndex(child => getSingleStepEntryId(child) === onlyStepToRunId);\n    activeStepsPath[onlyStepToRunId] = executionPath.concat([stepIndex]);\n    await pubsub.publish('workflows', {\n      type: 'workflow.step.run',\n      runId,\n      data: {\n        workflowId,\n        runId,\n        executionPath: executionPath.concat([stepIndex]),\n        resumeSteps,\n        stepResults,\n        timeTravel,\n        restart,\n        prevResult,\n        resumeData,\n        parentWorkflow,\n        activeStepsPath,\n        requestContext,\n        perStep,\n        state: currentState,\n        outputOptions,\n      },\n    });\n  } else {\n    await Promise.all(\n      step.steps.map(async (child, idx) => {\n        if (truthyIdxs[idx]) {\n          if (child) {\n            activeStepsPath[getSingleStepEntryId(child)] = executionPath.concat([idx]);\n          }\n          return pubsub.publish('workflows', {\n            type: 'workflow.step.run',\n            runId,\n            data: {\n              workflowId,\n              runId,\n              executionPath: executionPath.concat([idx]),\n              resumeSteps,\n              stepResults,\n              timeTravel,\n              restart: restart ? { ...restart, isParallelOrConditionalRestarted: true } : undefined,\n              prevResult,\n              resumeData,\n              parentWorkflow,\n              activeStepsPath,\n              requestContext,\n              perStep,\n              state: currentState,\n              outputOptions,\n            },\n          });\n        } else {\n          return pubsub.publish('workflows', {\n            type: 'workflow.step.end',\n            runId,\n            data: {\n              workflowId,\n              runId,\n              executionPath: executionPath.concat([idx]),\n              resumeSteps,\n              stepResults,\n              prevResult: { status: 'skipped' },\n              resumeData,\n              parentWorkflow,\n              activeStepsPath,\n              requestContext,\n              perStep,\n              state: currentState,\n              outputOptions,\n            },\n          });\n        }\n      }),\n    );\n  }\n}\n","import type { StepFlowEntry, WorkflowRunState } from '../..';\nimport { RequestContext } from '../../../di';\nimport type { PubSub } from '../../../events';\nimport type { StepExecutor } from '../step-executor';\nimport { getStepId } from './utils';\nimport type { ProcessorArgs } from '.';\n\nexport async function processWorkflowWaitForEvent(\n  workflowData: ProcessorArgs,\n  {\n    pubsub,\n    eventName,\n    currentState,\n  }: {\n    pubsub: PubSub;\n    eventName: string;\n    currentState: WorkflowRunState;\n  },\n) {\n  const executionPath = currentState?.waitingPaths[eventName];\n  if (!executionPath) {\n    return;\n  }\n\n  const currentStepId = getStepId(workflowData.workflow, executionPath);\n  const prevResult = {\n    status: 'success',\n    output: currentState?.context[currentStepId ?? 'input']?.payload,\n  };\n\n  await pubsub.publish('workflows', {\n    type: 'workflow.step.run',\n    runId: workflowData.runId,\n    data: {\n      workflowId: workflowData.workflowId,\n      runId: workflowData.runId,\n      executionPath,\n      resumeSteps: [],\n      resumeData: workflowData.resumeData,\n      parentWorkflow: workflowData.parentWorkflow,\n      stepResults: currentState?.context,\n      prevResult,\n      activeStepsPath: {},\n      requestContext: currentState?.requestContext,\n      perStep: workflowData.perStep,\n    },\n  });\n}\n\nexport async function processWorkflowSleep(\n  {\n    workflowId,\n    runId,\n    executionPath,\n    stepResults,\n    activeStepsPath,\n    resumeSteps,\n    timeTravel,\n    restart,\n    prevResult,\n    resumeData,\n    parentWorkflow,\n    requestContext,\n    perStep,\n  }: ProcessorArgs,\n  {\n    pubsub,\n    stepExecutor,\n    step,\n  }: {\n    pubsub: PubSub;\n    stepExecutor: StepExecutor;\n    step: Extract<StepFlowEntry, { type: 'sleep' }>;\n  },\n) {\n  const startedAt = Date.now();\n  await pubsub.publish(`workflow.events.v2.${runId}`, {\n    type: 'watch',\n    runId,\n    data: {\n      type: 'workflow-step-waiting',\n      payload: {\n        id: step.id,\n        status: 'waiting',\n        payload: prevResult.status === 'success' ? prevResult.output : undefined,\n        startedAt,\n      },\n    },\n  });\n\n  // Create a proper RequestContext from the plain object passed in ProcessorArgs\n  const reqContext = new RequestContext(Object.entries(requestContext ?? {}) as any);\n\n  const duration = await stepExecutor.resolveSleep({\n    workflowId,\n    step,\n    runId,\n    stepResults,\n    requestContext: reqContext,\n    input: prevResult?.status === 'success' ? prevResult.output : undefined,\n    resumeData,\n  });\n\n  setTimeout(\n    async () => {\n      await pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-step-result',\n          payload: {\n            id: step.id,\n            status: 'success',\n            payload: prevResult.status === 'success' ? prevResult.output : undefined,\n            output: prevResult.status === 'success' ? prevResult.output : undefined,\n            startedAt,\n            endedAt: Date.now(),\n          },\n        },\n      });\n\n      await pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-step-finish',\n          payload: {\n            id: step.id,\n            metadata: {},\n          },\n        },\n      });\n\n      await pubsub.publish('workflows', {\n        type: 'workflow.step.run',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath: executionPath.slice(0, -1).concat([executionPath[executionPath.length - 1]! + 1]),\n          resumeSteps,\n          timeTravel,\n          restart,\n          stepResults,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          activeStepsPath,\n          requestContext,\n          perStep,\n        },\n      });\n    },\n    duration < 0 ? 0 : duration,\n  );\n}\n\nexport async function processWorkflowSleepUntil(\n  {\n    workflowId,\n    runId,\n    executionPath,\n    stepResults,\n    activeStepsPath,\n    resumeSteps,\n    timeTravel,\n    restart,\n    prevResult,\n    resumeData,\n    parentWorkflow,\n    requestContext,\n    perStep,\n  }: ProcessorArgs,\n  {\n    pubsub,\n    stepExecutor,\n    step,\n  }: {\n    pubsub: PubSub;\n    stepExecutor: StepExecutor;\n    step: Extract<StepFlowEntry, { type: 'sleepUntil' }>;\n  },\n) {\n  const startedAt = Date.now();\n\n  // Create a proper RequestContext from the plain object passed in ProcessorArgs\n  const reqContext = new RequestContext(Object.entries(requestContext ?? {}) as any);\n\n  const duration = await stepExecutor.resolveSleepUntil({\n    workflowId,\n    step,\n    runId,\n    stepResults,\n    requestContext: reqContext,\n    input: prevResult?.status === 'success' ? prevResult.output : undefined,\n    resumeData,\n  });\n\n  await pubsub.publish(`workflow.events.v2.${runId}`, {\n    type: 'watch',\n    runId,\n    data: {\n      type: 'workflow-step-waiting',\n      payload: {\n        id: step.id,\n        status: 'waiting',\n        payload: prevResult.status === 'success' ? prevResult.output : undefined,\n        startedAt,\n      },\n    },\n  });\n\n  setTimeout(\n    async () => {\n      await pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-step-result',\n          payload: {\n            id: step.id,\n            status: 'success',\n            payload: prevResult.status === 'success' ? prevResult.output : undefined,\n            output: prevResult.status === 'success' ? prevResult.output : undefined,\n            startedAt,\n            endedAt: Date.now(),\n          },\n        },\n      });\n\n      await pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-step-finish',\n          payload: {\n            id: step.id,\n            metadata: {},\n          },\n        },\n      });\n\n      await pubsub.publish('workflows', {\n        type: 'workflow.step.run',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath: executionPath.slice(0, -1).concat([executionPath[executionPath.length - 1]! + 1]),\n          resumeSteps,\n          timeTravel,\n          restart,\n          stepResults,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          activeStepsPath,\n          requestContext,\n          perStep,\n        },\n      });\n    },\n    duration < 0 ? 0 : duration,\n  );\n}\n","import { randomUUID } from 'node:crypto';\nimport EventEmitter from 'node:events';\nimport { ErrorCategory, ErrorDomain, MastraError, getErrorFromUnknown } from '../../../error';\nimport { EventProcessor } from '../../../events/processor';\nimport type { Event } from '../../../events/types';\nimport type { Mastra } from '../../../mastra';\nimport type { TracingContext } from '../../../observability';\nimport { RequestContext } from '../../../request-context/';\nimport type { StepExecutionStrategy } from '../../../worker/types';\nimport { getEntryId, getEntryRetries, getEntrySchemas, getEntryWorkflow } from '../../../workflows/step-entry';\nimport type {\n  RestartExecutionParams,\n  SingleStepEntry,\n  StepFlowEntry,\n  StepResult,\n  StepSuccess,\n  TimeTravelExecutionParams,\n  WorkflowRunState,\n} from '../../../workflows/types';\nimport type { Workflow } from '../../../workflows/workflow';\nimport {\n  createRestartExecutionParams,\n  createTimeTravelExecutionParams,\n  getSingleStepEntryId,\n  getStepIds,\n  isSingleStepEntry,\n  validateStepResumeData,\n} from '../../utils';\nimport { resolveCurrentState } from '../helpers';\nimport { StepExecutor } from '../step-executor';\nimport { processWorkflowForEach, processWorkflowLoop } from './loop';\nimport { processWorkflowConditional, processWorkflowParallel } from './parallel';\nimport { processWorkflowSleep, processWorkflowSleepUntil, processWorkflowWaitForEvent } from './sleep';\nimport { getNestedWorkflow, getStepId, isExecutableStep } from './utils';\n\nexport type ProcessorArgs = {\n  activeStepsPath: Record<string, number[]>;\n  workflow: Workflow;\n  workflowId: string;\n  runId: string;\n  executionPath: number[];\n  stepResults: Record<string, StepResult<any, any, any, any>>;\n  resumeSteps: string[];\n  prevResult: StepResult<any, any, any, any>;\n  requestContext: Record<string, any>;\n  timeTravel?: TimeTravelExecutionParams;\n  restart?: RestartExecutionParams;\n  resumeData?: any;\n  parentWorkflow?: ParentWorkflow;\n  parentContext?: {\n    workflowId: string;\n    input: any;\n  };\n  retryCount?: number;\n  perStep?: boolean;\n  format?: 'legacy' | 'vnext';\n  state?: Record<string, any>;\n  outputOptions?: {\n    includeState?: boolean;\n    includeResumeLabels?: boolean;\n  };\n  forEachIndex?: number;\n  nestedRunId?: string; // runId of nested workflow when reporting back to parent\n};\n\nexport type ParentWorkflow = {\n  workflowId: string;\n  runId: string;\n  executionPath: number[];\n  resume: boolean;\n  stepResults: Record<string, StepResult<any, any, any, any>>;\n  parentWorkflow?: ParentWorkflow;\n  timeTravel?: TimeTravelExecutionParams;\n  restart?: RestartExecutionParams;\n  stepId: string;\n  stepGraph: StepFlowEntry[];\n  activeStepsPath: Record<string, number[]>;\n  resumeSteps: string[];\n  resumeData: any;\n  input: any;\n  parentContext?: {\n    workflowId: string;\n    input: any;\n  };\n};\n\n/**\n * A foreach step stores its per-iteration state in a shape that layers on top\n * of {@link StepResult}: the `payload` is the input array and `output` is the\n * (partial) array of iteration results, with any per-iteration `suspendPayload`\n * shape flowing through. This helper narrows the union so call sites that\n * specifically consume foreach state don't need `as any`, while keeping the\n * per-iteration item shape untyped (it varies by inner step).\n */\ntype ForeachIterationResult = null | {\n  status?: string;\n  output?: unknown;\n  suspendPayload?: any;\n  [key: string]: unknown;\n};\ntype ForeachStepResult = {\n  output?: ForeachIterationResult[];\n  payload?: unknown[];\n  status?: string;\n  startedAt?: number;\n  [key: string]: unknown;\n};\n\nfunction readForeachResult(\n  stepResults: Record<string, StepResult<any, any, any, any>>,\n  id: string,\n): ForeachStepResult | undefined {\n  const result = stepResults[id] as (StepResult<any, any, any, any> & ForeachStepResult) | undefined;\n  return result;\n}\n\nexport class WorkflowEventProcessor extends EventProcessor {\n  private stepExecutor: StepExecutor;\n  private stepExecutionStrategy?: StepExecutionStrategy;\n  // Map of runId -> AbortController for active workflow runs\n  private abortControllers: Map<string, AbortController> = new Map();\n  // Map of child runId -> parent runId for tracking nested workflows\n  private parentChildRelationships: Map<string, string> = new Map();\n  private runFormats: Map<string, 'legacy' | 'vnext' | undefined> = new Map();\n  // Map of event.id -> number of times we've returned { retry: true } for it.\n  // Used to cap transport-level redelivery so a poisoned event (e.g. sustained\n  // SQLITE_BUSY) eventually surfaces as a terminal workflow.fail rather than\n  // silently hanging agent.generate().\n  private deliveryAttempts: Map<string, number> = new Map();\n  // Maximum number of times handle() will ask the transport to redeliver the\n  // same event before declaring it terminally failed. The underlying storage\n  // layer already retries lock errors internally (~5 attempts with backoff)\n  // so 3 transport-level redeliveries is enough headroom for transient\n  // failures without keeping a poisoned event in flight for minutes.\n  private static readonly MAX_DELIVERY_ATTEMPTS = 3;\n  // Sentinel value stored in deliveryAttempts to mark an event whose terminal\n  // workflow.fail has already been published. Any subsequent redelivery of\n  // the same logical event short-circuits as terminal and does NOT re-run\n  // errorWorkflow or reset the per-event budget.\n  private static readonly TERMINAL_SENTINEL = Number.POSITIVE_INFINITY;\n  // Upper bound on entries kept in deliveryAttempts so a long-lived processor\n  // can't grow the map without limit. When the map exceeds this size we evict\n  // the oldest entries in insertion order (Map preserves insertion order). The\n  // cap is high enough that a realistic burst of concurrent runs never trims\n  // an entry mid-retry, but low enough to bound memory.\n  private static readonly DELIVERY_ATTEMPTS_MAX_ENTRIES = 1024;\n\n  // How long after a run reaches a terminal state before its\n  // `workflow.events.v2.<runId>` topic is cleared from the pubsub. The\n  // terminal `workflow-finish` watch event is published to that same topic,\n  // so deletion must lag long enough for attached watchers/streams to drain\n  // it. Mirrors DurableAgent's cleanupTimeoutMs default. 0 disables cleanup.\n  private readonly topicCleanupDelayMs: number;\n  private static readonly DEFAULT_TOPIC_CLEANUP_DELAY_MS = 30_000;\n\n  // Pending per-run topic cleanup timers, so a run restarted in this process\n  // (timeTravel/restart reuse the runId) cancels its own pending deletion.\n  private readonly pendingTopicCleanups = new Map<string, ReturnType<typeof setTimeout>>();\n\n  // Statuses under which a run is still (or again) writing to its watch\n  // topic. If the run was restarted via timeTravel/restart after its terminal\n  // end, deletion must be skipped — the new execution reschedules cleanup\n  // when it reaches its own terminal state.\n  private static readonly ACTIVE_RUN_STATUSES: ReadonlySet<string> = new Set([\n    'running',\n    'pending',\n    'waiting',\n    'suspended',\n    'paused',\n  ]);\n\n  constructor({\n    mastra,\n    stepExecutionStrategy,\n    topicCleanupDelayMs,\n  }: {\n    mastra: Mastra;\n    stepExecutionStrategy?: StepExecutionStrategy;\n    topicCleanupDelayMs?: number;\n  }) {\n    super({ mastra });\n    this.stepExecutor = new StepExecutor({ mastra });\n    this.stepExecutionStrategy = stepExecutionStrategy;\n    this.topicCleanupDelayMs = topicCleanupDelayMs ?? WorkflowEventProcessor.DEFAULT_TOPIC_CLEANUP_DELAY_MS;\n  }\n\n  /**\n   * Schedule deletion of a finished run's `workflow.events.v2.<runId>` topic.\n   *\n   * Per-run watch topics are written by every step of a run; on transports\n   * that retain messages (e.g. Redis Streams) they would otherwise live\n   * forever once the run ends. Deletion is delayed so subscribers still\n   * draining the terminal `workflow-finish` event aren't cut off, and\n   * fire-and-forget because topic cleanup must never affect run completion.\n   *\n   * Best-effort by design: if the process exits before the timer fires, the\n   * transport-level idle TTL (e.g. `streamIdleTtlMs`) is the backstop.\n   *\n   * A finished run can be re-executed under the same runId (`timeTravel`,\n   * `restart`), so deletion is double-guarded: a restart processed by this\n   * process cancels the pending timer directly, and when the timer fires we\n   * re-check the run's persisted status — a restart may have been picked up\n   * by a different worker process — and skip deletion while the run is\n   * active again.\n   */\n  private scheduleRunTopicCleanup(workflowId: string, runId: string): void {\n    if (this.topicCleanupDelayMs <= 0) return;\n    this.cancelRunTopicCleanup(runId);\n    const timer = setTimeout(() => {\n      this.pendingTopicCleanups.delete(runId);\n      void this.clearRunTopicUnlessActive(workflowId, runId);\n    }, this.topicCleanupDelayMs);\n    // Don't let a pending cleanup timer keep a short-lived process alive.\n    timer.unref?.();\n    this.pendingTopicCleanups.set(runId, timer);\n  }\n\n  private cancelRunTopicCleanup(runId: string): void {\n    const timer = this.pendingTopicCleanups.get(runId);\n    if (timer !== undefined) {\n      clearTimeout(timer);\n      this.pendingTopicCleanups.delete(runId);\n    }\n  }\n\n  private async clearRunTopicUnlessActive(workflowId: string, runId: string): Promise<void> {\n    try {\n      // Without a storage backend there is no way to observe a cross-process\n      // restart, so we delete unconditionally — the in-process timer\n      // cancellation in processWorkflowStart still covers same-process\n      // restarts. The status check below is also not atomic with the delete:\n      // a restart persisting `running` between the read and the DEL can still\n      // lose its topic. That window is milliseconds (vs. the full cleanup\n      // delay without this guard) and self-heals — persistent transports\n      // recover subscribers on the next publish (e.g. Redis NOGROUP\n      // recreation). Closing it fully would require distributed locking,\n      // which best-effort topic cleanup does not justify.\n      const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n      if (workflowsStore) {\n        const snapshot = await workflowsStore.loadWorkflowSnapshot({ workflowName: workflowId, runId });\n        const status = typeof snapshot === 'string' ? undefined : snapshot?.status;\n        // Run was restarted (possibly by another worker process) after the\n        // terminal end that scheduled this cleanup: it is writing to its\n        // topic again, and its own terminal end will reschedule deletion.\n        if (status && WorkflowEventProcessor.ACTIVE_RUN_STATUSES.has(status)) return;\n      }\n      await this.mastra.pubsub.clearTopic(`workflow.events.v2.${runId}`);\n    } catch (err) {\n      this.mastra.getLogger()?.warn('Failed to clear workflow events topic', { workflowId, runId, error: err });\n    }\n  }\n\n  /**\n   * Get or create an AbortController for a workflow run\n   */\n  private getOrCreateAbortController(runId: string): AbortController {\n    let controller = this.abortControllers.get(runId);\n    if (!controller) {\n      controller = new AbortController();\n      this.abortControllers.set(runId, controller);\n    }\n    return controller;\n  }\n\n  /**\n   * Cancel a workflow run and all its nested child workflows\n   */\n  private cancelRunAndChildren(runId: string): void {\n    // Abort the controller for this run\n    const controller = this.abortControllers.get(runId);\n    if (controller) {\n      controller.abort();\n    }\n\n    // Find and cancel all child workflows\n    for (const [childRunId, parentRunId] of this.parentChildRelationships.entries()) {\n      if (parentRunId === runId) {\n        this.cancelRunAndChildren(childRunId);\n      }\n    }\n  }\n\n  /**\n   * Clean up abort controller and relationships when a workflow completes.\n   * Also cleans up any orphaned child entries that reference this run as parent.\n   */\n  private cleanupRun(runId: string): void {\n    this.abortControllers.delete(runId);\n    this.parentChildRelationships.delete(runId);\n    this.runFormats.delete(runId);\n\n    // Clean up any orphaned child entries pointing to this run as their parent\n    for (const [childRunId, parentRunId] of this.parentChildRelationships.entries()) {\n      if (parentRunId === runId) {\n        this.parentChildRelationships.delete(childRunId);\n      }\n    }\n  }\n\n  /**\n   * Resolves the tracing context for a run, walking up the parent chain so a\n   * nested workflow run (e.g. `agentic-execution` inside `agentic-loop`)\n   * inherits its parent's parent span. `EventedRun.start` records the context\n   * on Mastra keyed by runId; nested runs are only registered against their\n   * parent.\n   */\n  private resolveRunTracingContext(runId: string): TracingContext | undefined {\n    const seen = new Set<string>();\n    let current: string | undefined = runId;\n    while (current && !seen.has(current)) {\n      seen.add(current);\n      const ctx = this.mastra.__getRunTracingContext(current);\n      if (ctx) return ctx;\n      current = this.parentChildRelationships.get(current);\n    }\n    return undefined;\n  }\n\n  /**\n   * Snapshot of the run's current span as the {traceId, spanId, parentSpanId} shape that\n   * `UpdateWorkflowStateOptions.tracingContext` expects, so a suspend's persisted snapshot\n   * can stitch the resumed AGENT_RUN/WORKFLOW_RUN span back to the original trace. Mirrors\n   * `default.ts`'s `persistTracingContext`; the evented engine holds the live span on\n   * Mastra (since it can't ride pubsub events), so we resolve it via runId here.\n   */\n  private resolveSuspendTracingContext(\n    runId: string,\n  ): { traceId?: string; spanId?: string; parentSpanId?: string } | undefined {\n    const span = this.resolveRunTracingContext(runId)?.currentSpan as\n      | { id?: string; traceId?: string; getParentSpanId?: () => string | undefined }\n      | undefined;\n    if (!span) return undefined;\n    return { traceId: span.traceId, spanId: span.id, parentSpanId: span.getParentSpanId?.() };\n  }\n\n  /**\n   * Applies the workflow's `pruneSnapshot` option to an already-persisted snapshot.\n   *\n   * The evented engine persists suspensions via merge operations\n   * (`updateWorkflowResults` + `updateWorkflowState`) rather than writing a full\n   * snapshot object, so the prune hook can't intercept the write itself. Instead,\n   * after the merge completes, we load the merged snapshot, prune it, and\n   * re-persist the full row. No-op when the workflow has no `pruneSnapshot` option.\n   */\n  private async pruneAndRepersistSnapshot({\n    workflow,\n    workflowId,\n    runId,\n  }: {\n    workflow: Workflow | undefined;\n    workflowId: string;\n    runId: string;\n  }): Promise<void> {\n    const pruneSnapshot = workflow?.options?.pruneSnapshot;\n    if (!pruneSnapshot) return;\n    try {\n      const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n      if (!workflowsStore) return;\n      const run = await workflowsStore.getWorkflowRunById({ runId, workflowName: workflowId });\n      const snapshot = run?.snapshot;\n      if (!snapshot || typeof snapshot === 'string') return;\n      const pruned = pruneSnapshot({ snapshot, workflowStatus: snapshot.status });\n      await workflowsStore.persistWorkflowSnapshot({\n        workflowName: workflowId,\n        runId,\n        resourceId: run?.resourceId,\n        snapshot: pruned,\n      });\n    } catch (error) {\n      // Pruning is a size optimization — never fail the suspension over it.\n      this.mastra.getLogger()?.warn?.(`Failed to prune workflow snapshot for run ${runId}: ${error}`);\n    }\n  }\n\n  __registerMastra(mastra: Mastra) {\n    super.__registerMastra(mastra);\n    this.stepExecutor.__registerMastra(mastra);\n  }\n\n  /**\n   * Resolves a workflow by id without throwing. Searches first by the\n   * workflow's `.id` (the value that ends up on event payloads) and then\n   * falls back to the registration key in `Mastra.workflows`. Returns\n   * `undefined` if neither lookup succeeds — callers decide how to handle\n   * the missing case (e.g. terminal failure vs. cleanup pass-through) so\n   * we don't throw inside `#dispatch` and trigger infinite event retries.\n   */\n  #tryResolveWorkflow(workflowId: string): Workflow | undefined {\n    try {\n      return this.mastra.getWorkflowById(workflowId) as Workflow;\n    } catch {\n      return undefined;\n    }\n  }\n\n  private async errorWorkflow(\n    {\n      parentWorkflow,\n      workflowId,\n      runId,\n      resumeSteps,\n      stepResults,\n      resumeData,\n      requestContext,\n    }: Omit<ProcessorArgs, 'workflow'>,\n    e: Error,\n  ) {\n    await this.mastra.pubsub.publish('workflows', {\n      type: 'workflow.fail',\n      runId,\n      data: {\n        workflowId,\n        runId,\n        executionPath: [],\n        resumeSteps,\n        stepResults,\n        prevResult: { status: 'failed', error: getErrorFromUnknown(e).toJSON() },\n        requestContext,\n        resumeData,\n        activeStepsPath: {},\n        parentWorkflow: parentWorkflow,\n      },\n    });\n  }\n\n  protected async processWorkflowCancel({ workflowId, runId, prevResult, ...args }: ProcessorArgs) {\n    // Cancel this workflow and all nested child workflows\n    this.cancelRunAndChildren(runId);\n\n    const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n    const currentState = await workflowsStore?.loadWorkflowSnapshot({\n      workflowName: workflowId,\n      runId,\n    });\n\n    if (!currentState) {\n      this.mastra.getLogger()?.warn('Canceling workflow without loaded state', { workflowId, runId });\n    }\n\n    //call end workflow with status of canceled to indicate the workflow was canceled\n    await this.endWorkflow(\n      {\n        workflowId,\n        runId,\n        prevResult,\n        ...args,\n      },\n      'canceled',\n    );\n  }\n\n  protected async processWorkflowStart({\n    workflow,\n    parentWorkflow,\n    workflowId,\n    runId,\n    resumeSteps,\n    prevResult,\n    resumeData,\n    timeTravel,\n    restart,\n    executionPath,\n    stepResults,\n    requestContext,\n    perStep,\n    format,\n    state,\n    outputOptions,\n    forEachIndex,\n  }: ProcessorArgs & { initialState?: Record<string, any> }) {\n    // Use initialState from event data if provided, otherwise use state from ProcessorArgs\n    const initialState = (arguments[0] as any).initialState ?? state ?? {};\n    const resolvedFormat = format ?? this.runFormats.get(runId);\n    this.runFormats.set(runId, resolvedFormat);\n    // The run is starting (or restarting via timeTravel/restart under the\n    // same runId): any topic cleanup pending from a previous terminal end\n    // must not fire while the run is writing to its topic again.\n    this.cancelRunTopicCleanup(runId);\n    // Create abort controller for this workflow run\n    this.getOrCreateAbortController(runId);\n\n    // Track parent-child relationship if this is a nested workflow\n    if (parentWorkflow?.runId) {\n      this.parentChildRelationships.set(runId, parentWorkflow.runId);\n    }\n    // Preserve resourceId from existing snapshot if present\n    const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n    const existingRun = await workflowsStore?.getWorkflowRunById({ runId, workflowName: workflow.id });\n    const resourceId = existingRun?.resourceId;\n\n    // Check shouldPersistSnapshot option - default to true if not specified\n    // This is particularly important for resume: if shouldPersist returns false for 'running',\n    // we shouldn't overwrite the existing 'suspended' status with 'running'\n    const shouldPersist =\n      workflow?.options?.shouldPersistSnapshot?.({\n        stepResults: stepResults ?? {},\n        workflowStatus: 'running',\n      }) ?? true;\n\n    if (shouldPersist) {\n      const runningSnapshot: WorkflowRunState = {\n        activePaths: [],\n        suspendedPaths: {},\n        resumeLabels: {},\n        waitingPaths: {},\n        activeStepsPath: {},\n        serializedStepGraph: workflow.serializedStepGraph,\n        timestamp: Date.now(),\n        runId,\n        context: {\n          ...(stepResults ?? {\n            input: prevResult?.status === 'success' ? prevResult.output : undefined,\n          }),\n          __state: initialState,\n        } as WorkflowRunState['context'],\n        status: 'running',\n        value: initialState,\n      };\n      await workflowsStore?.persistWorkflowSnapshot({\n        workflowName: workflow.id,\n        runId,\n        resourceId,\n        snapshot: workflow?.options?.pruneSnapshot\n          ? workflow.options.pruneSnapshot({ snapshot: runningSnapshot, workflowStatus: 'running' })\n          : runningSnapshot,\n      });\n\n      if (parentWorkflow) {\n        const parentSnap = await workflowsStore?.loadWorkflowSnapshot({\n          workflowName: parentWorkflow.workflowId,\n          runId: parentWorkflow.runId,\n        });\n        const existing = parentSnap?.context?.[workflowId] as any;\n        await workflowsStore?.updateWorkflowResults({\n          workflowName: parentWorkflow.workflowId,\n          runId: parentWorkflow.runId,\n          stepId: workflowId,\n          result: {\n            startedAt: existing?.startedAt ?? Date.now(),\n            status: 'running',\n            payload: existing?.payload ?? parentWorkflow.input?.output ?? {},\n            ...(existing ?? {}), // preserve anything else (suspendPayload, etc.)\n            metadata: { ...(existing?.metadata ?? {}), nestedRunId: runId },\n          },\n          requestContext,\n        });\n      }\n    }\n\n    const startExecutionPath = executionPath ?? [0];\n    await this.mastra.pubsub.publish('workflows', {\n      type: 'workflow.step.run',\n      runId,\n      data: {\n        parentWorkflow,\n        workflowId,\n        runId,\n        executionPath: startExecutionPath,\n        resumeSteps,\n        stepResults: {\n          ...(stepResults ?? {\n            input: prevResult?.status === 'success' ? prevResult.output : undefined,\n          }),\n          __state: initialState,\n        },\n        prevResult,\n        timeTravel,\n        restart,\n        requestContext,\n        resumeData,\n        activeStepsPath: {},\n        perStep,\n        state: initialState,\n        outputOptions,\n        forEachIndex,\n      },\n    });\n  }\n\n  protected async endWorkflow(args: ProcessorArgs, status: 'success' | 'failed' | 'canceled' | 'paused' = 'success') {\n    const {\n      workflowId,\n      runId,\n      prevResult,\n      perStep,\n      workflow,\n      stepResults,\n      activeStepsPath,\n      executionPath,\n      parentWorkflow,\n    } = args;\n    const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n    const normalizedPrevResult = prevResult ?? ({ status } as StepResult<any, any, any, any>);\n\n    // Check shouldPersistSnapshot option - default to true if not specified\n    const finalStatus = perStep && status === 'success' ? 'paused' : status;\n    const shouldPersist =\n      workflow?.options?.shouldPersistSnapshot?.({\n        stepResults: stepResults ?? {},\n        workflowStatus: finalStatus,\n      }) ?? true;\n\n    if (shouldPersist) {\n      await workflowsStore?.updateWorkflowState({\n        workflowName: workflowId,\n        runId,\n        opts: {\n          status: finalStatus,\n          result: normalizedPrevResult,\n          activePaths: executionPath,\n          activeStepsPath: activeStepsPath,\n        },\n      });\n    } else if (parentWorkflow && finalStatus !== 'paused') {\n      // The nested run reached a terminal state its workflow opted not to\n      // persist (e.g. the internal `executionWorkflow` inside `agentic-loop`).\n      // A row may still exist from an earlier persisted phase — 'pending' at\n      // nested-run start or 'suspended' before a resume — and without the\n      // terminal update it would leak as a stale, resumable-looking record.\n      // Terminal runs can't be resumed, so drop the row entirely. Best-effort:\n      // a storage failure here must not abort run completion.\n      try {\n        await workflowsStore?.deleteWorkflowRunById({ runId, workflowName: workflowId });\n      } catch (e) {\n        this.mastra.getLogger()?.warn('Failed to clean up nested workflow snapshot', { workflowId, runId, error: e });\n      }\n    }\n\n    if (perStep) {\n      await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-paused',\n          payload: {},\n        },\n      });\n    }\n\n    await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n      type: 'watch',\n      runId,\n      data: {\n        type: 'workflow-finish',\n        payload: {\n          runId,\n          workflowStatus: normalizedPrevResult.status,\n          ...(normalizedPrevResult.status === 'success' ? { finalWorkflowResult: normalizedPrevResult.output } : {}),\n        },\n      },\n    });\n\n    await this.mastra.pubsub.publish('workflows', {\n      type: 'workflow.end',\n      runId,\n      data: { ...args, prevResult: normalizedPrevResult, workflow: undefined },\n    });\n  }\n\n  protected async processWorkflowEnd(args: ProcessorArgs) {\n    const {\n      resumeSteps,\n      prevResult,\n      resumeData,\n      parentWorkflow,\n      activeStepsPath,\n      requestContext,\n      runId,\n      timeTravel,\n      perStep,\n      stepResults,\n      state,\n      workflowId,\n    } = args;\n\n    // Extract final state from stepResults or args\n    const finalState = resolveCurrentState({ stepResults, state });\n\n    // Clean up abort controller and parent-child tracking\n    this.cleanupRun(runId);\n\n    // A per-step run publishes `workflow.end` while merely paused — it will\n    // keep writing to its watch topic when the next step executes, so only\n    // truly terminal runs get their topic cleared.\n    if (!perStep) {\n      this.scheduleRunTopicCleanup(workflowId, runId);\n    }\n\n    // handle nested workflow\n    if (parentWorkflow) {\n      // get the step from the parent workflow and process it if it's a loop\n      const step = parentWorkflow.stepGraph[parentWorkflow.executionPath[0]!];\n      if (step?.type === 'loop') {\n        // pick workflow information from parentWorkflow as the workflow end being processed here is actually a step in the parentWorkflow\n        await processWorkflowLoop(\n          {\n            workflow: parentWorkflow as unknown as Workflow,\n            workflowId: parentWorkflow.workflowId,\n            prevResult,\n            runId: parentWorkflow.runId,\n            executionPath: parentWorkflow.executionPath,\n            stepResults: parentWorkflow.stepResults,\n            activeStepsPath: parentWorkflow.activeStepsPath,\n            resumeSteps: parentWorkflow.resumeSteps,\n            resumeData: parentWorkflow.resumeData,\n            parentWorkflow: parentWorkflow.parentWorkflow,\n            requestContext,\n            retryCount: 0,\n          },\n          {\n            pubsub: this.mastra.pubsub,\n            stepExecutor: this.stepExecutor,\n            step,\n            stepResult: prevResult,\n          },\n        );\n      } else {\n        await this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.step.end',\n          runId: parentWorkflow.runId, // Use parent's runId for event routing\n          data: {\n            workflowId: parentWorkflow.workflowId,\n            runId: parentWorkflow.runId,\n            executionPath: parentWorkflow.executionPath,\n            resumeSteps,\n            stepResults: parentWorkflow.stepResults,\n            prevResult,\n            resumeData,\n            activeStepsPath,\n            parentWorkflow: parentWorkflow.parentWorkflow,\n            parentContext: parentWorkflow,\n            requestContext,\n            timeTravel,\n            perStep,\n            state: finalState,\n            nestedRunId: runId, // Pass nested workflow's runId for step retrieval\n          },\n        });\n      }\n    }\n\n    await this.mastra.pubsub.publish('workflows-finish', {\n      type: 'workflow.end',\n      runId,\n      data: { ...args, workflow: undefined, state: finalState },\n    });\n\n    // Clean up run-scoped internal workflow registrations (e.g. execution-workflow)\n    // now that all events for this run have been processed.\n    if (this.mastra.__hasInternalWorkflow(args.workflowId, runId)) {\n      this.mastra.__unregisterInternalWorkflow(args.workflowId, runId);\n    }\n  }\n\n  protected async processWorkflowSuspend(args: ProcessorArgs) {\n    const {\n      workflow,\n      executionPath,\n      resumeSteps,\n      prevResult,\n      resumeData,\n      parentWorkflow,\n      activeStepsPath,\n      runId,\n      requestContext,\n      timeTravel,\n      restart,\n      stepResults,\n      state,\n      outputOptions,\n    } = args;\n\n    // Extract final state from stepResults or args\n    const finalState = resolveCurrentState({ stepResults, state });\n\n    // TODO: if there are still active paths don't end the workflow yet\n    // handle nested workflow\n    if (parentWorkflow) {\n      // When propagating a suspend up to the parent, the parent stores this result under\n      // the nested-workflow step's id, so the path we hand up must be the path *within\n      // this workflow* to the suspended step (the parent / `execute()` re-prepends the\n      // step id). Prepend the id of the step that suspended here, unless the path already\n      // starts with it (the deepest level — the step that called `suspend()` directly —\n      // already includes its own id via the executor's `path: [step.id]`).\n      const existingPath: string[] = prevResult.suspendPayload?.__workflow_meta?.path ?? [];\n      const suspendedStepId = workflow && executionPath ? (getStepId(workflow, executionPath) ?? undefined) : undefined;\n      const propagatedPath =\n        suspendedStepId && existingPath[0] !== suspendedStepId ? [suspendedStepId, ...existingPath] : existingPath;\n\n      const resumeLabels: Record<string, { stepId: string; foreachIndex?: number }> = {};\n\n      const nestedResumeLabels = prevResult.suspendPayload?.__workflow_meta?.resumeLabels ?? {};\n\n      for (const label of Object.keys(nestedResumeLabels)) {\n        resumeLabels[label] = {\n          stepId: parentWorkflow.stepId,\n          foreachIndex: nestedResumeLabels[label].foreachIndex,\n        };\n      }\n\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.step.end',\n        runId: parentWorkflow.runId, // Use parent's runId for event routing\n        data: {\n          workflowId: parentWorkflow.workflowId,\n          runId: parentWorkflow.runId,\n          executionPath: parentWorkflow.executionPath,\n          resumeSteps,\n          stepResults: parentWorkflow.stepResults,\n          prevResult: {\n            ...prevResult,\n            suspendPayload: {\n              ...prevResult.suspendPayload,\n              __workflow_meta: {\n                // keep resumeLabels / foreachIndex etc. — only the runId and path change as we propagate up\n                ...(prevResult.suspendPayload?.__workflow_meta ?? {}),\n                resumeLabels: Object.keys(resumeLabels).length > 0 ? resumeLabels : undefined,\n                runId: runId,\n                path: propagatedPath,\n              },\n            },\n          },\n          timeTravel,\n          restart,\n          resumeData,\n          activeStepsPath,\n          requestContext,\n          parentWorkflow: parentWorkflow.parentWorkflow,\n          parentContext: parentWorkflow,\n          state: finalState,\n          outputOptions,\n          nestedRunId: runId, // Pass nested workflow's runId for step retrieval\n        },\n      });\n    }\n\n    await this.mastra.pubsub.publish('workflows-finish', {\n      type: 'workflow.suspend',\n      runId,\n      data: { ...args, workflow: undefined, state: finalState },\n    });\n\n    // Clean up run-scoped internal workflow registrations (e.g. execution-workflow)\n    // now that all events for this run have been processed.\n    if (this.mastra.__hasInternalWorkflow(args.workflowId, runId)) {\n      this.mastra.__unregisterInternalWorkflow(args.workflowId, runId);\n    }\n  }\n\n  protected async processWorkflowFail(args: ProcessorArgs) {\n    const {\n      workflowId,\n      runId,\n      resumeSteps,\n      prevResult,\n      resumeData,\n      parentWorkflow,\n      activeStepsPath,\n      requestContext,\n      timeTravel,\n      restart,\n      stepResults,\n      state,\n      outputOptions,\n      workflow,\n      executionPath,\n    } = args;\n\n    // Extract final state from stepResults or args\n    const finalState = resolveCurrentState({ stepResults, state });\n\n    // Clean up abort controller and parent-child tracking\n    this.cleanupRun(runId);\n\n    // 'failed' is terminal: the run stops writing to its watch topic.\n    this.scheduleRunTopicCleanup(workflowId, runId);\n\n    const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n\n    // Check shouldPersistSnapshot option - default to true if not specified\n    const shouldPersist =\n      workflow?.options?.shouldPersistSnapshot?.({\n        stepResults: stepResults ?? {},\n        workflowStatus: 'failed',\n      }) ?? true;\n\n    if (shouldPersist) {\n      await workflowsStore?.updateWorkflowState({\n        workflowName: workflowId,\n        runId,\n        opts: {\n          status: 'failed',\n          error: (prevResult as any).error,\n          activePaths: executionPath,\n          activeStepsPath: activeStepsPath,\n        },\n      });\n    } else if (parentWorkflow) {\n      // Mirrors endWorkflow: a nested run whose workflow opted out of\n      // persisting the terminal 'failed' status would otherwise leak its\n      // earlier-phase ('pending'/'suspended') snapshot row forever.\n      // Best-effort: a storage failure here must not abort run completion.\n      try {\n        await workflowsStore?.deleteWorkflowRunById({ runId, workflowName: workflowId });\n      } catch (e) {\n        this.mastra.getLogger()?.warn('Failed to clean up nested workflow snapshot', { workflowId, runId, error: e });\n      }\n    }\n\n    // handle nested workflow\n    if (parentWorkflow) {\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.step.end',\n        runId: parentWorkflow.runId, // Use parent's runId for event routing\n        data: {\n          workflowId: parentWorkflow.workflowId,\n          runId: parentWorkflow.runId,\n          executionPath: parentWorkflow.executionPath,\n          resumeSteps,\n          stepResults: parentWorkflow.stepResults,\n          prevResult,\n          timeTravel,\n          restart,\n          resumeData,\n          activeStepsPath,\n          requestContext,\n          parentWorkflow: parentWorkflow.parentWorkflow,\n          parentContext: parentWorkflow,\n          state: finalState,\n          outputOptions,\n          nestedRunId: runId, // Pass nested workflow's runId for step retrieval\n        },\n      });\n    }\n\n    await this.mastra.pubsub.publish('workflows-finish', {\n      type: 'workflow.fail',\n      runId,\n      data: { ...args, workflow: undefined, state: finalState },\n    });\n\n    // Clean up run-scoped internal workflow registrations (e.g. execution-workflow)\n    // now that all events for this run have been processed.\n    if (this.mastra.__hasInternalWorkflow(args.workflowId, runId)) {\n      this.mastra.__unregisterInternalWorkflow(args.workflowId, runId);\n    }\n  }\n\n  protected async processWorkflowStepRun(args: ProcessorArgs) {\n    const {\n      workflow,\n      workflowId,\n      runId,\n      executionPath,\n      stepResults,\n      activeStepsPath,\n      resumeSteps,\n      timeTravel,\n      restart,\n      prevResult,\n      resumeData,\n      parentWorkflow,\n      requestContext,\n      perStep,\n      state,\n      outputOptions,\n      forEachIndex,\n    } = args;\n    // Get current state from stepResults.__state or from passed state\n    const currentState = resolveCurrentState({ stepResults, state });\n    const stepGraph: StepFlowEntry[] = workflow.stepGraph;\n\n    if (!executionPath?.length) {\n      return this.errorWorkflow(\n        {\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n        },\n        new MastraError({\n          id: 'MASTRA_WORKFLOW',\n          text: `Execution path is empty: ${JSON.stringify(executionPath)}`,\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.SYSTEM,\n        }),\n      );\n    }\n\n    const rawStep: StepFlowEntry | undefined = stepGraph[executionPath[0]!];\n\n    if (!rawStep) {\n      // If we're past the last step, end the workflow successfully\n      if (executionPath[0]! >= stepGraph.length) {\n        return this.endWorkflow({\n          workflow,\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          stepResults,\n          prevResult,\n          activeStepsPath,\n          requestContext,\n          // Use currentState (resolved from stepResults.__state and state) instead of\n          // the possibly-undefined state parameter, to ensure final state is preserved\n          state: currentState,\n          outputOptions,\n        });\n      }\n      return this.errorWorkflow(\n        {\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n        },\n        new MastraError({\n          id: 'MASTRA_WORKFLOW',\n          text: `Step not found in step graph: ${JSON.stringify(executionPath)}`,\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.SYSTEM,\n        }),\n      );\n    }\n\n    // Keep the raw declarative entry. Control structures are routed below; a\n    // declarative single entry (agent / tool / mapping) is interpreted by its own\n    // per-type handler, and plain steps run through `runLeafStep`.\n    let step: StepFlowEntry = rawStep;\n\n    //if parallel/conditional and execution path is greater than 1\n    // and restart is present but isParallelOrConditionalRestarted is false,\n    // then we need to process the step using processWorkflowParallel/processWorkflowConditional\n    // to ensure all active steps are processed.\n    if (\n      (step.type === 'parallel' || step.type === 'conditional') &&\n      executionPath.length > 1 &&\n      (!restart || (restart && restart.isParallelOrConditionalRestarted))\n    ) {\n      step = step.steps[executionPath[1]!]!;\n    } else if (step.type === 'parallel') {\n      return processWorkflowParallel(\n        {\n          workflow,\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          restart,\n          timeTravel,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n        },\n        {\n          pubsub: this.mastra.pubsub,\n          step,\n        },\n      );\n    } else if (step?.type === 'conditional') {\n      return processWorkflowConditional(\n        {\n          workflow,\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          restart,\n          timeTravel,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n        },\n        {\n          pubsub: this.mastra.pubsub,\n          stepExecutor: this.stepExecutor,\n          step,\n        },\n      );\n    } else if (step?.type === 'sleep') {\n      return processWorkflowSleep(\n        {\n          workflow,\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          timeTravel,\n          restart,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n        },\n        {\n          pubsub: this.mastra.pubsub,\n          stepExecutor: this.stepExecutor,\n          step,\n        },\n      );\n    } else if (step?.type === 'sleepUntil') {\n      return processWorkflowSleepUntil(\n        {\n          workflow,\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          timeTravel,\n          restart,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n        },\n        {\n          pubsub: this.mastra.pubsub,\n          stepExecutor: this.stepExecutor,\n          step,\n        },\n      );\n    } else if (step?.type === 'foreach' && executionPath.length === 1) {\n      return processWorkflowForEach(\n        {\n          workflow,\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          timeTravel,\n          restart,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n          perStep,\n          state: currentState,\n          outputOptions,\n          forEachIndex,\n        },\n        {\n          pubsub: this.mastra.pubsub,\n          mastra: this.mastra,\n          step,\n        },\n      );\n    }\n\n    // Control structures (sleep / sleepUntil / parallel / conditional) already\n    // returned above; what remains is a leaf: a plain `step`, a declarative\n    // `agent` / `tool` / `mapping` entry, or a `loop` / `foreach` body.\n    return this.runLeafStep({\n      ...args,\n      step: step as Extract<StepFlowEntry, { type: 'step' | 'agent' | 'tool' | 'mapping' | 'loop' | 'foreach' }>,\n    });\n  }\n\n  /**\n   * Shared leaf-step runner. Executes a single leaf entry - a plain `step`, a\n   * declarative `agent` / `tool` / `mapping` entry, or a `loop` / `foreach`\n   * body - and emits its lifecycle events (`workflow.step.end`, retries,\n   * suspend, cancel). The per-kind interpretation happens in the step\n   * executor's dispatch; here entries are only inspected via the `step-entry`\n   * accessors.\n   */\n  protected async runLeafStep(\n    args: ProcessorArgs & {\n      step: Extract<StepFlowEntry, { type: 'step' | 'agent' | 'tool' | 'mapping' | 'loop' | 'foreach' }>;\n    },\n  ) {\n    const {\n      workflow,\n      workflowId,\n      runId,\n      executionPath,\n      stepResults,\n      activeStepsPath,\n      resumeSteps,\n      timeTravel,\n      restart,\n      prevResult,\n      resumeData,\n      parentWorkflow,\n      retryCount = 0,\n      perStep,\n      state,\n      outputOptions,\n      forEachIndex,\n      step,\n    } = args;\n    let requestContext = args.requestContext;\n    const streamFormat = this.runFormats.get(runId);\n    const currentState = resolveCurrentState({ stepResults, state });\n    const stepGraph: StepFlowEntry[] = workflow.stepGraph;\n    // The leaf entry this run executes: top-level entries are already\n    // SingleStepEntry-shaped; `loop` / `foreach` carry their body in `step.step`.\n    // It stays a declarative entry - the step executor interprets it per kind.\n    const leaf: SingleStepEntry = step.type === 'loop' || step.type === 'foreach' ? step.step : step;\n    const leafId = getEntryId(leaf);\n\n    if (!isExecutableStep(step)) {\n      return this.errorWorkflow(\n        {\n          workflowId,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          prevResult,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n        },\n        new MastraError({\n          id: 'MASTRA_WORKFLOW',\n          text: `Step is not executable: ${step?.type} -- ${JSON.stringify(executionPath)}`,\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.SYSTEM,\n        }),\n      );\n    }\n\n    activeStepsPath[leafId] = executionPath;\n\n    const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n\n    // Run nested workflow - only a plain `step` entry can wrap a live Workflow\n    const nestedWorkflowStep = getEntryWorkflow(leaf);\n    if (nestedWorkflowStep) {\n      const nestedWorkflow = nestedWorkflowStep;\n      // Handle resume with only nested workflow ID specified (auto-detect suspended inner step)\n      if (resumeSteps?.length === 1 && resumeSteps[0] === leafId) {\n        const stepData = stepResults[leafId];\n        const nestedRunId = stepData?.suspendPayload?.__workflow_meta?.runId;\n        if (!nestedRunId) {\n          return this.errorWorkflow(\n            {\n              workflowId,\n              runId,\n              executionPath,\n              stepResults,\n              activeStepsPath,\n              resumeSteps,\n              prevResult,\n              resumeData,\n              parentWorkflow,\n              requestContext,\n            },\n            new MastraError({\n              id: 'MASTRA_WORKFLOW',\n              text: `Nested workflow run id not found for auto-detection: ${JSON.stringify(stepResults)}`,\n              domain: ErrorDomain.MASTRA_WORKFLOW,\n              category: ErrorCategory.SYSTEM,\n            }),\n          );\n        }\n\n        const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n          workflowName: leafId,\n          runId: nestedRunId,\n        });\n\n        // Auto-detect the suspended step within the nested workflow\n        const suspendedStepId = Object.keys(snapshot?.suspendedPaths ?? {})?.[0];\n        if (!suspendedStepId) {\n          return this.errorWorkflow(\n            {\n              workflowId,\n              runId,\n              executionPath,\n              stepResults,\n              activeStepsPath,\n              resumeSteps,\n              prevResult,\n              resumeData,\n              parentWorkflow,\n              requestContext,\n            },\n            new MastraError({\n              id: 'MASTRA_WORKFLOW',\n              text: `No suspended step found in nested workflow: ${leafId}`,\n              domain: ErrorDomain.MASTRA_WORKFLOW,\n              category: ErrorCategory.SYSTEM,\n            }),\n          );\n        }\n\n        const nestedExecutionPath = snapshot?.suspendedPaths?.[suspendedStepId];\n        const nestedStepResults = snapshot?.context;\n        // The resumed inner step's input is the output of the step that ran before it\n        // inside the nested workflow (i.e. the suspended step's stored payload), not the\n        // input to the nested-workflow step itself.\n        const nestedPrevResult = {\n          status: 'success' as const,\n          output: (nestedStepResults?.[suspendedStepId] as any)?.payload ?? (prevResult as any)?.output,\n        };\n\n        await this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.resume',\n          runId,\n          data: {\n            workflowId: leafId,\n            parentWorkflow: {\n              stepId: leafId,\n              workflowId,\n              runId,\n              stepGraph,\n              executionPath,\n              resumeSteps,\n              stepResults,\n              input: prevResult,\n              parentWorkflow,\n              activeStepsPath,\n              resumeData,\n            },\n            executionPath: nestedExecutionPath as any,\n            runId: nestedRunId,\n            resumeSteps: [suspendedStepId], // Resume the auto-detected inner step\n            stepResults: nestedStepResults,\n            prevResult: nestedPrevResult,\n            resumeData,\n            activeStepsPath,\n            requestContext,\n            perStep,\n            initialState: currentState,\n            state: currentState,\n            outputOptions,\n          },\n        });\n      } else if (resumeSteps?.length > 1 && resumeSteps[0] === leafId) {\n        const stepData = stepResults[leafId];\n        const nestedRunId = stepData?.suspendPayload?.__workflow_meta?.runId;\n        if (!nestedRunId) {\n          return this.errorWorkflow(\n            {\n              workflowId,\n              runId,\n              executionPath,\n              stepResults,\n              activeStepsPath,\n              resumeSteps,\n              prevResult,\n              resumeData,\n              parentWorkflow,\n              requestContext,\n            },\n            new MastraError({\n              id: 'MASTRA_WORKFLOW',\n              text: `Nested workflow run id not found: ${JSON.stringify(stepResults)}`,\n              domain: ErrorDomain.MASTRA_WORKFLOW,\n              category: ErrorCategory.SYSTEM,\n            }),\n          );\n        }\n\n        const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n          workflowName: leafId,\n          runId: nestedRunId,\n        });\n\n        const nestedStepResults = snapshot?.context;\n        const nestedSteps = resumeSteps.slice(1);\n        // The step the nested workflow resumes into receives the output of the step that\n        // ran before it (its stored payload), not the input to the nested-workflow step.\n        const nestedPrevResult = {\n          status: 'success' as const,\n          output: (nestedStepResults?.[nestedSteps[0]!] as any)?.payload ?? (prevResult as any)?.output,\n        };\n\n        await this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.resume',\n          runId,\n          data: {\n            workflowId: leafId,\n            parentWorkflow: {\n              stepId: leafId,\n              workflowId,\n              runId,\n              stepGraph,\n              executionPath,\n              resumeSteps,\n              stepResults,\n              input: prevResult,\n              parentWorkflow,\n              activeStepsPath,\n              resumeData,\n            },\n            executionPath: snapshot?.suspendedPaths?.[nestedSteps[0]!] as any,\n            runId: nestedRunId,\n            resumeSteps: nestedSteps,\n            stepResults: nestedStepResults,\n            prevResult: nestedPrevResult,\n            resumeData,\n            activeStepsPath,\n            requestContext,\n            perStep,\n            initialState: currentState,\n            state: currentState,\n            outputOptions,\n          },\n        });\n      } else if (timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === leafId) {\n        const nestedRunId = stepResults[leafId]?.metadata?.nestedRunId ?? randomUUID();\n        const snapshot =\n          (await workflowsStore?.loadWorkflowSnapshot({\n            workflowName: leafId,\n            runId: nestedRunId,\n          })) ?? ({ context: {} } as WorkflowRunState);\n\n        const timeTravelParams = createTimeTravelExecutionParams({\n          steps: timeTravel.steps.slice(1),\n          inputData: timeTravel.inputData,\n          resumeData: timeTravel.resumeData,\n          context: (timeTravel.nestedStepResults?.[leafId] ?? {}) as any,\n          nestedStepsContext: (timeTravel.nestedStepResults ?? {}) as any,\n          snapshot,\n          graph: nestedWorkflow.buildExecutionGraph(),\n          perStep,\n        });\n\n        const nestedPrevStepId = getStepId(nestedWorkflow, timeTravelParams.executionPath);\n        const nestedPrevResult = timeTravelParams.stepResults[nestedPrevStepId ?? 'input'];\n\n        await this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.start',\n          runId,\n          data: {\n            workflowId: leafId,\n            parentWorkflow: {\n              stepId: leafId,\n              workflowId,\n              runId,\n              stepGraph,\n              executionPath,\n              resumeSteps,\n              stepResults,\n              timeTravel,\n              input: prevResult,\n              parentWorkflow,\n              activeStepsPath,\n              resumeData,\n            },\n            executionPath: timeTravelParams.executionPath,\n            runId: nestedRunId,\n            stepResults: timeTravelParams.stepResults,\n            prevResult: { status: 'success', output: nestedPrevResult?.payload },\n            timeTravel: timeTravelParams,\n            activeStepsPath,\n            requestContext,\n            perStep,\n            initialState: currentState,\n            state: currentState,\n            outputOptions,\n          },\n        });\n      } else if (restart && !!restart.activeStepsPath?.[leafId]) {\n        const nestedRunId = stepResults[leafId]?.metadata?.nestedRunId ?? randomUUID();\n        const snapshot =\n          (await workflowsStore?.loadWorkflowSnapshot({\n            workflowName: leafId,\n            runId: nestedRunId,\n          })) ?? ({ context: {} } as WorkflowRunState);\n\n        const restartParams = createRestartExecutionParams({ snapshot, graph: nestedWorkflow.buildExecutionGraph() });\n\n        const nestedPrevStepId = getStepId(nestedWorkflow, snapshot.activePaths);\n        const nestedPrevResult = restartParams.stepResults[nestedPrevStepId ?? 'input'];\n\n        await this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.start',\n          runId,\n          data: {\n            workflowId: leafId,\n            parentWorkflow: {\n              stepId: leafId,\n              workflowId,\n              runId,\n              stepGraph,\n              executionPath,\n              resumeSteps,\n              stepResults,\n              restart,\n              input: prevResult,\n              parentWorkflow,\n              activeStepsPath,\n              resumeData,\n            },\n            executionPath: restartParams.activePaths,\n            runId: nestedRunId,\n            stepResults: restartParams.stepResults,\n            prevResult: { status: 'success', output: nestedPrevResult?.payload },\n            restart: restartParams,\n            activeStepsPath: restartParams.activeStepsPath,\n            requestContext,\n            perStep,\n            initialState: restartParams.state,\n            state: restartParams.state,\n            outputOptions,\n          },\n        });\n      } else {\n        const nestedRunId = randomUUID();\n        const shouldPersist =\n          nestedWorkflow?.options?.shouldPersistSnapshot?.({\n            stepResults: {},\n            workflowStatus: 'pending',\n          }) ?? true;\n        const parentRun = await workflowsStore?.getWorkflowRunById({ runId, workflowName: workflow.id });\n\n        //create nested workflow run snapshot in storage. use parent workflow resource id in nested workflow\n        if (shouldPersist) {\n          const pendingSnapshot: WorkflowRunState = {\n            runId: nestedRunId,\n            status: 'pending',\n            value: {},\n            context: {} as WorkflowRunState['context'],\n            activePaths: [],\n            serializedStepGraph: nestedWorkflow.serializedStepGraph,\n            activeStepsPath: {},\n            suspendedPaths: {},\n            resumeLabels: {},\n            waitingPaths: {},\n            result: undefined,\n            error: undefined,\n            timestamp: Date.now(),\n          };\n          await workflowsStore?.persistWorkflowSnapshot({\n            workflowName: nestedWorkflow.id,\n            runId: nestedRunId,\n            resourceId: parentRun?.resourceId,\n            snapshot: nestedWorkflow?.options?.pruneSnapshot\n              ? nestedWorkflow.options.pruneSnapshot({ snapshot: pendingSnapshot, workflowStatus: 'pending' })\n              : pendingSnapshot,\n          });\n        }\n\n        await this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.start',\n          runId,\n          data: {\n            workflowId: leafId,\n            parentWorkflow: {\n              stepId: leafId,\n              workflowId,\n              stepGraph,\n              runId,\n              executionPath,\n              resumeSteps,\n              stepResults,\n              input: prevResult,\n              parentWorkflow,\n              activeStepsPath,\n              resumeData,\n            },\n            executionPath: [0],\n            runId: nestedRunId,\n            resumeSteps,\n            prevResult,\n            resumeData,\n            activeStepsPath,\n            requestContext,\n            perStep,\n            initialState: currentState,\n            state: currentState,\n            outputOptions,\n          },\n        });\n      }\n\n      return;\n    }\n\n    if (isSingleStepEntry(step)) {\n      await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-step-start',\n          payload: {\n            id: leafId,\n            startedAt: Date.now(),\n            payload: prevResult.status === 'success' ? prevResult.output : undefined,\n            status: 'running',\n          },\n        },\n      });\n    }\n\n    const ee = new EventEmitter();\n    ee.on('watch', async (event: any) => {\n      await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: event,\n      });\n    });\n    const rc = new RequestContext();\n    for (const [key, value] of Object.entries(requestContext)) {\n      rc.set(key, value);\n    }\n    const { resumeData: timeTravelResumeData, validationError: timeTravelResumeValidationError } =\n      await validateStepResumeData({\n        resumeData: timeTravel?.stepResults[leafId]?.status === 'suspended' ? timeTravel?.resumeData : undefined,\n        step: getEntrySchemas(leaf, this.mastra),\n      });\n\n    let resumeDataToUse;\n    if (timeTravelResumeData && !timeTravelResumeValidationError) {\n      resumeDataToUse = timeTravelResumeData;\n    } else if (timeTravelResumeData && timeTravelResumeValidationError) {\n      this.mastra.getLogger()?.warn('Time travel resume data validation failed', {\n        stepId: leafId,\n        error: timeTravelResumeValidationError.message,\n      });\n    } else if (resumeSteps?.length > 0 && resumeSteps?.[0] === leafId) {\n      resumeDataToUse = resumeData;\n    }\n\n    // Get the abort controller for this workflow run\n    const abortController = this.getOrCreateAbortController(runId);\n\n    let stepResult: StepResult<any, any, any, any>;\n\n    if (this.stepExecutionStrategy) {\n      stepResult = await this.stepExecutionStrategy.executeStep({\n        workflowId,\n        runId,\n        stepId: leafId,\n        executionPath,\n        stepResults,\n        state: currentState,\n        requestContext: Object.fromEntries(rc.entries()),\n        input: (prevResult as any)?.output,\n        resumeData: resumeDataToUse,\n        retryCount,\n        foreachIdx: step.type === 'foreach' ? executionPath[1] : undefined,\n        format: streamFormat,\n        perStep,\n        validateInputs: workflow.options.validateInputs,\n        abortSignal: abortController.signal,\n      });\n    } else {\n      stepResult = await this.stepExecutor.execute({\n        workflowId,\n        entry: leaf,\n        runId,\n        stepResults,\n        state: currentState,\n        requestContext: rc,\n        input: (prevResult as any)?.output,\n        resumeData: resumeDataToUse,\n        retryCount,\n        foreachIdx: step.type === 'foreach' ? executionPath[1] : undefined,\n        validateInputs: workflow.options.validateInputs,\n        abortController,\n        format: streamFormat,\n        perStep,\n        // Non-serializable parent span for span nesting; held on Mastra by\n        // `EventedRun.start` since it can't ride pubsub events. Walk the parent\n        // chain so nested workflow runs inherit it.\n        tracingContext: this.resolveRunTracingContext(runId),\n        tracingPolicy: workflow.options?.tracingPolicy,\n      });\n    }\n    requestContext = Object.fromEntries(rc.entries());\n\n    if (abortController?.signal?.aborted) {\n      // Extract updated state from step result\n      const updatedState = (stepResult as any).__state ?? currentState;\n      //cancel the workflow\n      return this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.cancel',\n        runId,\n        data: {\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          timeTravel,\n          stepResults: {\n            ...stepResults,\n            [leafId]: stepResult,\n            __state: updatedState,\n          },\n          prevResult: { ...stepResult, status: 'canceled' }, //set the status to canceled to indicate the workflow was canceled\n          activeStepsPath,\n          requestContext,\n          perStep,\n          state: updatedState,\n          outputOptions,\n        },\n      });\n    }\n\n    // @ts-expect-error - bailed status not in type\n    if (stepResult.status === 'bailed') {\n      // @ts-expect-error - bailed status not in type\n      stepResult.status = 'success';\n\n      await this.endWorkflow({\n        workflow,\n        resumeData,\n        parentWorkflow,\n        workflowId,\n        runId,\n        executionPath,\n        resumeSteps,\n        stepResults: {\n          ...stepResults,\n          [leafId]: stepResult,\n        },\n        prevResult: stepResult,\n        activeStepsPath,\n        requestContext,\n        perStep,\n        state: currentState,\n        outputOptions,\n      });\n      return;\n    }\n\n    if (stepResult.status === 'failed') {\n      const retries = getEntryRetries(leaf) ?? workflow.retryConfig.attempts ?? 0;\n      if (retryCount >= retries || stepResult.nonRetryable) {\n        await this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.step.end',\n          runId,\n          data: {\n            parentWorkflow,\n            workflowId,\n            runId,\n            executionPath,\n            resumeSteps,\n            stepResults,\n            prevResult: stepResult,\n            activeStepsPath,\n            requestContext,\n            state: currentState,\n            outputOptions,\n          },\n        });\n      } else {\n        return this.mastra.pubsub.publish('workflows', {\n          type: 'workflow.step.run',\n          runId,\n          data: {\n            parentWorkflow,\n            workflowId,\n            runId,\n            executionPath,\n            resumeSteps,\n            stepResults,\n            timeTravel,\n            restart,\n            prevResult,\n            activeStepsPath,\n            requestContext,\n            retryCount: retryCount + 1,\n            state: currentState,\n            outputOptions,\n          },\n        });\n      }\n    }\n\n    if (step.type === 'loop' && stepResult.status === 'suspended') {\n      // The loop body suspended — we can't evaluate the loop condition yet (there's no\n      // output). Propagate the suspend like any other step; the body re-runs on resume,\n      // at which point processWorkflowLoop evaluates the condition with its output.\n      const updatedState = (stepResult as any).__state ?? currentState;\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.step.end',\n        runId,\n        data: {\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          timeTravel,\n          restart,\n          stepResults: {\n            ...stepResults,\n            [leafId]: stepResult,\n            __state: updatedState,\n          },\n          prevResult: stepResult,\n          activeStepsPath,\n          requestContext,\n          perStep,\n          state: updatedState,\n          outputOptions,\n        },\n      });\n      return;\n    }\n\n    if (step.type === 'loop') {\n      //timeTravel is not passed to the processWorkflowLoop function becuase the step already ran the first time\n      // with whatever information it needs from timeTravel, subsequent loop runs use the previous loop run result as it's input.\n      await processWorkflowLoop(\n        {\n          workflow,\n          workflowId,\n          prevResult: stepResult,\n          runId,\n          executionPath,\n          stepResults,\n          activeStepsPath,\n          resumeSteps,\n          resumeData,\n          parentWorkflow,\n          requestContext,\n          retryCount: retryCount + 1,\n        },\n        {\n          pubsub: this.mastra.pubsub,\n          stepExecutor: this.stepExecutor,\n          step,\n          stepResult,\n        },\n      );\n    } else {\n      // Extract updated state from step result\n      const updatedState = (stepResult as any).__state ?? currentState;\n\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.step.end',\n        runId,\n        data: {\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          timeTravel, //timeTravel is passed in as workflow.step.end ends the step, not the workflow, the timeTravel info is passed to the next step to run.\n          restart,\n          stepResults: {\n            ...stepResults,\n            [leafId]: stepResult,\n            __state: updatedState,\n          },\n          prevResult: stepResult,\n          activeStepsPath,\n          requestContext,\n          perStep,\n          state: updatedState,\n          outputOptions,\n          forEachIndex,\n        },\n      });\n    }\n  }\n\n  /**\n   * Aggregate the results of all branches of a `parallel` / `conditional` entry once\n   * every branch has reached a terminal state (`success` / `skipped`) or `suspended`.\n   *\n   * This runs once per branch completion. It only acts when every branch is accounted\n   * for; otherwise it returns and lets a later branch finish the aggregation. Because\n   * `stepResults` is the snapshot returned by the caller's `updateWorkflowResults`\n   * call — which grows monotonically per branch — only the branch whose write landed\n   * last observes the full set, so exactly one branch emits (no double emit).\n   *\n   * - if any branch is still suspended → re-emit `workflow.suspend` with the full set\n   *   of suspended paths and persist the workflow state. This both fixes the race where\n   *   each branch would overwrite `suspendedPaths` on its own, and lets the workflow\n   *   stay suspended while only some branches have been resumed.\n   * - otherwise → emit `workflow.step.end` for the parallel/conditional entry with the\n   *   merged branch outputs (the existing behaviour).\n   */\n  protected async aggregateBranchResults({\n    workflow,\n    workflowId,\n    runId,\n    branchEntry,\n    branchExecutionPath,\n    latestBranchResult,\n    resumeSteps,\n    timeTravel,\n    restart,\n    parentWorkflow,\n    stepResults,\n    activeStepsPath,\n    requestContext,\n    state,\n    outputOptions,\n  }: {\n    workflow: Workflow;\n    workflowId: string;\n    runId: string;\n    branchEntry: Extract<StepFlowEntry, { type: 'parallel' | 'conditional' }>;\n    branchExecutionPath: number[];\n    /**\n     * The in-flight result of the branch that just finished (i.e. the one at\n     * `branchExecutionPath`). Used for that branch's output so non-JSON values (e.g.\n     * `Date`) survive — the copy in `stepResults` has been round-tripped through storage\n     * serialization. Other branches' outputs unavoidably come from `stepResults`.\n     */\n    latestBranchResult?: StepResult<any, any, any, any>;\n    resumeSteps: string[];\n    timeTravel?: TimeTravelExecutionParams;\n    restart?: RestartExecutionParams;\n    parentWorkflow?: ParentWorkflow;\n    stepResults: Record<string, any>;\n    activeStepsPath: Record<string, number[]>;\n    requestContext: Record<string, any>;\n    state: Record<string, any>;\n    outputOptions?: { includeState?: boolean; includeResumeLabels?: boolean };\n  }) {\n    const currentState = resolveCurrentState({ stepResults, state });\n    const parentIdx = branchExecutionPath[0]!;\n    const finishedBranchIdx = branchExecutionPath.length > 1 ? branchExecutionPath[1]! : undefined;\n\n    let suspendedCount = 0;\n    let skippedCount = 0;\n    const allResults: Record<string, any> = {};\n    const suspendedPaths: Record<string, number[]> = {};\n    const resumeLabels: Record<string, { stepId: string; foreachIndex?: number }> = {};\n\n    branchEntry.steps.forEach((branch, idx) => {\n      if (!isSingleStepEntry(branch)) {\n        return;\n      }\n      const branchId = getSingleStepEntryId(branch);\n      const res = stepResults?.[branchId] as any;\n      if (!res || !res.status) {\n        return; // branch not finished yet\n      }\n      if (res.status === 'success') {\n        // For the branch that just completed, prefer its in-flight result so structured\n        // values (Date, Map, ...) aren't flattened by the storage round-trip.\n        const output =\n          idx === finishedBranchIdx && latestBranchResult?.status === 'success'\n            ? (latestBranchResult as any).output\n            : res.output;\n        allResults[branchId] = output;\n      } else if (res.status === 'skipped') {\n        skippedCount++;\n      } else if (res.status === 'suspended') {\n        suspendedCount++;\n        suspendedPaths[branchId] = [parentIdx, idx];\n        Object.assign(resumeLabels, res.suspendPayload?.__workflow_meta?.resumeLabels ?? {});\n      }\n      // failed / canceled branches short-circuit the workflow before reaching here\n    });\n\n    const finishedCount = Object.keys(allResults).length + skippedCount + suspendedCount;\n    if (finishedCount < branchEntry.steps.length) {\n      return; // wait for the remaining branches to finish\n    }\n\n    if (suspendedCount > 0) {\n      const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n      const shouldPersist =\n        workflow?.options?.shouldPersistSnapshot?.({\n          stepResults: stepResults ?? {},\n          workflowStatus: 'suspended',\n        }) ?? true;\n      if (shouldPersist) {\n        await workflowsStore?.updateWorkflowResults({\n          workflowName: workflow.id,\n          runId,\n          stepId: '__state',\n          result: currentState as any,\n          requestContext,\n        });\n        const suspendTracingContext = this.resolveSuspendTracingContext(runId);\n        await workflowsStore?.updateWorkflowState({\n          workflowName: workflowId,\n          runId,\n          opts: {\n            status: 'suspended',\n            result: { status: 'suspended' } as any,\n            suspendedPaths,\n            resumeLabels,\n            ...(suspendTracingContext ? { tracingContext: suspendTracingContext } : {}),\n          },\n        });\n        await this.pruneAndRepersistSnapshot({ workflow, workflowId, runId });\n      }\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.suspend',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath: branchExecutionPath,\n          resumeSteps,\n          parentWorkflow,\n          stepResults,\n          prevResult: { status: 'suspended' } as any,\n          activeStepsPath,\n          requestContext,\n          timeTravel,\n          restart,\n          state: currentState,\n          outputOptions,\n        },\n      });\n      return;\n    }\n\n    await this.mastra.pubsub.publish('workflows', {\n      type: 'workflow.step.end',\n      runId,\n      data: {\n        parentWorkflow,\n        workflowId,\n        runId,\n        executionPath: branchExecutionPath.slice(0, -1),\n        resumeSteps,\n        stepResults,\n        prevResult: { status: 'success', output: allResults },\n        activeStepsPath,\n        requestContext,\n        timeTravel,\n        restart,\n        state: currentState,\n        outputOptions,\n      },\n    });\n  }\n\n  protected async processWorkflowStepEnd({\n    workflow,\n    workflowId,\n    runId,\n    executionPath,\n    resumeSteps,\n    timeTravel,\n    restart,\n    prevResult,\n    parentWorkflow,\n    stepResults,\n    activeStepsPath,\n    parentContext,\n    requestContext,\n    perStep,\n    state,\n    outputOptions,\n    forEachIndex,\n    nestedRunId,\n  }: ProcessorArgs) {\n    // Extract state from prevResult if it was updated by the step\n    // For nested workflow completion (parentContext present), prefer the passed state\n    // as it contains the nested workflow's updated state\n    const currentState = parentContext\n      ? (state ?? (prevResult as any)?.__state ?? stepResults?.__state ?? {})\n      : ((prevResult as any)?.__state ?? stepResults?.__state ?? state ?? {});\n\n    // Create a clean version of prevResult without __state for storing\n    const { __state: _removedState, ...cleanPrevResult } = prevResult as any;\n    prevResult = cleanPrevResult as typeof prevResult;\n\n    const rawStep = workflow.stepGraph[executionPath[0]!];\n\n    // The just-finished entry. Keep it raw (declarative agent / tool / mapping\n    // entries are not materialized); we only need its id and type here.\n    let step: StepFlowEntry | undefined = rawStep;\n\n    if ((step?.type === 'parallel' || step?.type === 'conditional') && executionPath.length > 1) {\n      step = step.steps[executionPath[1]!];\n    }\n\n    if (!step) {\n      return this.errorWorkflow(\n        {\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          prevResult,\n          stepResults,\n          activeStepsPath,\n          requestContext,\n        },\n        new MastraError({\n          id: 'MASTRA_WORKFLOW',\n          text: `Step not found: ${JSON.stringify(executionPath)}`,\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.SYSTEM,\n        }),\n      );\n    }\n\n    // The finished step's id. Works for plain steps, declarative agent/tool/mapping\n    // entries (their own id) and loop/foreach bodies (the wrapped step's id).\n    const stepId = getStepIds(step)[0]!;\n\n    // Cache workflows store to avoid redundant async calls\n    const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n\n    if (step.type === 'foreach') {\n      const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n        workflowName: workflowId,\n        runId,\n      });\n\n      const currentIdx = executionPath[1];\n      const snapshotContext = snapshot?.context as Record<string, ForeachStepResult> | undefined;\n      const existingStepResult = snapshotContext?.[getEntryId(step.step)];\n      const currentResult = existingStepResult?.output;\n      // Preserve the original payload (the input array) from the existing step result\n      const originalPayload = existingStepResult?.payload;\n\n      let newResult = prevResult;\n      if (currentIdx !== undefined) {\n        // Check for bail - short circuit foreach execution\n        // @ts-expect-error - bailed status not in type\n        if (prevResult.status === 'bailed') {\n          const bailedResult = {\n            status: 'success' as const,\n            output: (prevResult as any).output,\n            startedAt: existingStepResult?.startedAt ?? Date.now(),\n            endedAt: Date.now(),\n            payload: originalPayload,\n          };\n\n          // Store final result\n          await workflowsStore?.updateWorkflowResults({\n            workflowName: workflow.id,\n            runId,\n            stepId: getEntryId(step.step),\n            result: bailedResult as any,\n            requestContext,\n          });\n\n          // End workflow with bail result\n          return this.endWorkflow({\n            workflow,\n            parentWorkflow,\n            workflowId,\n            runId,\n            executionPath: [executionPath[0]!],\n            resumeSteps,\n            stepResults: { ...stepResults, [getEntryId(step.step)]: bailedResult },\n            prevResult: bailedResult,\n            activeStepsPath,\n            requestContext,\n            perStep,\n            state: currentState,\n            outputOptions,\n          });\n        }\n\n        // For foreach, store the full iteration result (including status, suspendPayload, etc.)\n        // not just the output, so suspend state is preserved\n        const iterationResult =\n          prevResult.status === 'suspended'\n            ? prevResult // Keep full result for suspended iterations\n            : (prevResult as any).output; // Just output for completed iterations\n\n        if (currentResult) {\n          currentResult[currentIdx] = iterationResult;\n          // Merge foreach step-level properties (suspendPayload, resumePayload, suspendedAt, resumedAt)\n          // New iteration's resume properties take precedence for resumePayload/resumedAt (most recent resume)\n          // Existing step's suspend properties are preserved (first suspend)\n          newResult = {\n            ...existingStepResult, // Preserve step-level properties\n            ...prevResult, // Get iteration timing info\n            output: currentResult,\n            payload: originalPayload,\n            // Preserve suspend metadata from first suspension\n            suspendPayload: existingStepResult?.suspendPayload ?? prevResult.suspendPayload,\n            suspendedAt: existingStepResult?.suspendedAt ?? (prevResult as any).suspendedAt,\n            // Update resume metadata to most recent resume (new iteration takes precedence)\n            resumePayload: (prevResult as any).resumePayload ?? existingStepResult?.resumePayload,\n            resumedAt: (prevResult as any).resumedAt ?? existingStepResult?.resumedAt,\n          } as any;\n        } else {\n          newResult = { ...prevResult, output: [iterationResult], payload: originalPayload } as any;\n        }\n      }\n      const newStepResults = await workflowsStore?.updateWorkflowResults({\n        workflowName: workflow.id,\n        runId,\n        stepId: getEntryId(step.step),\n        result: newResult,\n        requestContext,\n      });\n\n      // Persist (and thread forward) any state changes made inside the foreach body.\n      // Each iteration is a separate event in the evented engine, so unless we write\n      // the updated state back here, the next iteration / the step after the foreach\n      // would re-read the stale `__state` from storage instead of `state` (see\n      // resolveCurrentState's priority order). This is what makes setState() inside a\n      // foreach body propagate across iterations.\n      if (currentState) {\n        await workflowsStore?.updateWorkflowResults({\n          workflowName: workflow.id,\n          runId,\n          stepId: '__state',\n          result: currentState as any,\n          requestContext,\n        });\n      }\n\n      // Same fallback as the regular step path: when no run record was\n      // persisted (shouldPersistSnapshot opted out of running) the store\n      // returns `{}`, and when there's no storage at all newStepResults is\n      // undefined. In both cases preserve the inline stepResults instead of\n      // discarding everything but the foreach step's result.\n      const mergedForeachStepResults =\n        !newStepResults || Object.keys(newStepResults).length === 0\n          ? { ...(stepResults ?? {}), [getEntryId(step.step)]: newResult }\n          : newStepResults;\n      stepResults = { ...mergedForeachStepResults, __state: currentState };\n\n      // For foreach iterations, check if all iterations are complete before emitting events\n      // This prevents emitting workflow.suspend when only some concurrent iterations have finished\n      if (currentIdx !== undefined) {\n        const foreachResult = readForeachResult(stepResults, getEntryId(step.step));\n        const iterationResults: ForeachIterationResult[] = foreachResult?.output ?? [];\n        const targetLen = foreachResult?.payload?.length ?? 0;\n\n        // Count iterations by status - pending iterations appear as null in stepResults after\n        // storage merge (pending markers are converted to null by the storage layer).\n        const pendingCount = iterationResults.filter((r: any) => r === null).length;\n        const suspendedCount = iterationResults.filter(\n          (r: any) => r && typeof r === 'object' && r.status === 'suspended',\n        ).length;\n        const iterationsStarted = iterationResults.length;\n\n        // Emit per-iteration progress event\n        const completedCount = iterationResults.filter(\n          (r: any) => r !== null && !(typeof r === 'object' && r.status === 'suspended'),\n        ).length;\n        const iterationStatus =\n          prevResult.status === 'suspended'\n            ? ('suspended' as const)\n            : prevResult.status === 'success'\n              ? ('success' as const)\n              : ('failed' as const);\n\n        await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n          type: 'watch',\n          runId,\n          data: {\n            type: 'workflow-step-progress',\n            payload: {\n              id: getEntryId(step.step),\n              completedCount,\n              totalCount: targetLen,\n              currentIndex: currentIdx,\n              iterationStatus,\n              ...(prevResult.status === 'success' ? { iterationOutput: (prevResult as any).output } : {}),\n            },\n          },\n        });\n\n        if (pendingCount > 0) {\n          // There are still pending (null) iterations - concurrent execution in progress\n          // Wait for them to complete\n          return;\n        }\n\n        // Check if there are more iterations to start before deciding to suspend\n        // This handles partial concurrency: don't suspend until all iterations have been started\n        if (iterationsStarted < targetLen) {\n          // More iterations need to be started - call processWorkflowForEach to continue\n          await processWorkflowForEach(\n            {\n              workflow,\n              workflowId,\n              prevResult: { status: 'success', output: foreachResult!.payload } as any,\n              runId,\n              executionPath: [executionPath[0]!],\n              stepResults,\n              activeStepsPath,\n              resumeSteps,\n              timeTravel,\n              restart,\n              resumeData: undefined, // Don't pass resumeData when starting new iterations\n              parentWorkflow,\n              requestContext,\n              perStep,\n              state: currentState,\n              outputOptions,\n            },\n            {\n              pubsub: this.mastra.pubsub,\n              mastra: this.mastra,\n              step,\n            },\n          );\n          return;\n        }\n\n        if (suspendedCount > 0) {\n          // Some iterations are suspended - emit workflow suspend\n          // Build aggregated suspend metadata from all suspended iterations\n          const collectedResumeLabels: Record<string, { stepId: string; foreachIndex?: number }> = {};\n          // suspendedPaths maps stepId -> executionPath, using the step ID (not stepId[index])\n          const suspendedPaths: Record<string, number[]> = {\n            [getEntryId(step.step)]: [executionPath[0]!],\n          };\n\n          let firstSuspendedIterationPayload: Record<string, unknown> | undefined;\n          for (let i = 0; i < iterationResults.length; i++) {\n            const iterResult = iterationResults[i];\n            if (iterResult && typeof iterResult === 'object' && iterResult.status === 'suspended') {\n              // Collect resume labels\n              if (iterResult.suspendPayload?.__workflow_meta?.resumeLabels) {\n                Object.assign(collectedResumeLabels, iterResult.suspendPayload.__workflow_meta.resumeLabels);\n              }\n              if (firstSuspendedIterationPayload === undefined) {\n                firstSuspendedIterationPayload = iterResult.suspendPayload;\n              }\n            }\n          }\n\n          // Create the aggregated foreach step suspend result.\n          // Preserve non-__workflow_meta keys (e.g. __streamState stashed by the agent loop's\n          // tool-call-step) from a suspended iteration so callers reading the step-level\n          // suspendPayload still see that state. The agent-loop snapshot reader only inspects\n          // step.suspendPayload, not the nested per-iteration payloads, so without this spread\n          // __streamState would be lost on resume.\n          const foreachSuspendResult = {\n            status: 'suspended' as const,\n            output: iterationResults,\n            payload: foreachResult!.payload,\n            suspendedAt: Date.now(),\n            startedAt: foreachResult!.startedAt ?? Date.now(),\n            suspendPayload: {\n              ...firstSuspendedIterationPayload,\n              __workflow_meta: {\n                path: executionPath,\n                resumeLabels: collectedResumeLabels,\n              },\n            },\n          };\n\n          // Update the step result with aggregated suspend status\n          await workflowsStore?.updateWorkflowResults({\n            workflowName: workflow.id,\n            runId,\n            stepId: getEntryId(step.step),\n            result: foreachSuspendResult as any,\n            requestContext,\n          });\n\n          // Check shouldPersistSnapshot option - default to true if not specified\n          const shouldPersist =\n            workflow?.options?.shouldPersistSnapshot?.({\n              stepResults: stepResults ?? {},\n              workflowStatus: 'suspended',\n            }) ?? true;\n\n          if (shouldPersist) {\n            // Persist state to snapshot context before suspending\n            await workflowsStore?.updateWorkflowResults({\n              workflowName: workflow.id,\n              runId,\n              stepId: '__state',\n              result: currentState as any,\n              requestContext,\n            });\n\n            const suspendTracingContext = this.resolveSuspendTracingContext(runId);\n            await workflowsStore?.updateWorkflowState({\n              workflowName: workflowId,\n              runId,\n              opts: {\n                status: 'suspended',\n                result: foreachSuspendResult,\n                suspendedPaths,\n                resumeLabels: collectedResumeLabels,\n                activePaths: executionPath,\n                activeStepsPath,\n                ...(suspendTracingContext ? { tracingContext: suspendTracingContext } : {}),\n              },\n            });\n            await this.pruneAndRepersistSnapshot({ workflow, workflowId, runId });\n          }\n\n          await this.mastra.pubsub.publish('workflows', {\n            type: 'workflow.suspend',\n            runId,\n            data: {\n              workflowId,\n              runId,\n              executionPath: [executionPath[0]!],\n              resumeSteps,\n              parentWorkflow,\n              stepResults: { ...stepResults, [getEntryId(step.step)]: foreachSuspendResult },\n              prevResult: foreachSuspendResult,\n              activeStepsPath,\n              requestContext,\n              timeTravel,\n              restart,\n              state: currentState,\n              outputOptions,\n            },\n          });\n\n          return;\n        }\n\n        // All iterations succeeded - call processWorkflowForEach to advance to next step\n        await processWorkflowForEach(\n          {\n            workflow,\n            workflowId,\n            prevResult: { status: 'success', output: foreachResult!.payload } as any,\n            runId,\n            executionPath: [executionPath[0]!],\n            stepResults,\n            activeStepsPath,\n            resumeSteps,\n            timeTravel,\n            restart,\n            resumeData: undefined,\n            parentWorkflow,\n            requestContext,\n            perStep,\n            state: currentState,\n            outputOptions,\n          },\n          {\n            pubsub: this.mastra.pubsub,\n            mastra: this.mastra,\n            step,\n          },\n        );\n        return;\n      }\n    } else if (isExecutableStep(step)) {\n      // clear from activeStepsPath\n      delete activeStepsPath[stepId];\n\n      // handle nested workflow\n      if (parentContext) {\n        prevResult = stepResults[stepId] = {\n          ...prevResult,\n          payload: parentContext.input?.output ?? {},\n          // Store nestedRunId in metadata for getWorkflowRunById retrieval\n          ...(nestedRunId && {\n            metadata: {\n              ...(prevResult as any).metadata,\n              nestedRunId,\n            },\n          }),\n        };\n      }\n\n      const newStepResults = await workflowsStore?.updateWorkflowResults({\n        workflowName: workflow.id,\n        runId,\n        stepId,\n        result: prevResult,\n        requestContext,\n      });\n\n      // When the Mastra has no storage configured, workflowsStore is undefined\n      // and updateWorkflowResults returns undefined. When it has storage but no\n      // run record yet (shouldPersistSnapshot skipped the initial running\n      // snapshot), it returns `{}`. In both cases the event payload is the\n      // source of truth — merge prevResult into the inline stepResults instead\n      // of treating it as a hard early-return.\n      if (!newStepResults || Object.keys(newStepResults).length === 0) {\n        stepResults = { ...(stepResults ?? {}), [stepId]: prevResult };\n      } else {\n        stepResults = newStepResults;\n      }\n    }\n\n    // Update stepResults with current state\n    stepResults = { ...stepResults, __state: currentState };\n\n    if (!prevResult?.status || prevResult.status === 'failed') {\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.fail',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          parentWorkflow,\n          stepResults,\n          timeTravel,\n          restart,\n          prevResult,\n          activeStepsPath,\n          requestContext,\n          state: currentState,\n          outputOptions,\n        },\n      });\n\n      return;\n    } else if (prevResult.status === 'suspended') {\n      // Emit the per-step suspended watch event (fires per branch even inside a parallel/conditional)\n      await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-step-suspended',\n          payload: {\n            id: stepId,\n            ...prevResult,\n            suspendedAt: Date.now(),\n            suspendPayload: prevResult.suspendPayload,\n          },\n        },\n      });\n\n      const parentEntry = workflow.stepGraph[executionPath[0]!];\n      if ((parentEntry?.type === 'parallel' || parentEntry?.type === 'conditional') && executionPath.length > 1) {\n        // A branch of a parallel/conditional suspended. Wait for all sibling branches and\n        // aggregate their suspended paths into a single workflow.suspend so resume() can\n        // target any of them (each branch publishing its own workflow.suspend would\n        // otherwise race and clobber suspendedPaths).\n        await this.aggregateBranchResults({\n          workflow,\n          workflowId,\n          runId,\n          branchEntry: parentEntry,\n          branchExecutionPath: executionPath,\n          latestBranchResult: prevResult,\n          resumeSteps,\n          timeTravel,\n          restart,\n          parentWorkflow,\n          stepResults,\n          activeStepsPath,\n          requestContext,\n          state: currentState,\n          outputOptions,\n        });\n        return;\n      }\n\n      const suspendedPaths: Record<string, number[]> = {};\n      const suspendedStepId = getStepId(workflow, executionPath);\n      if (suspendedStepId) {\n        suspendedPaths[suspendedStepId] = executionPath;\n      }\n\n      // Extract resume labels from suspend payload metadata\n      const resumeLabels: Record<string, { stepId: string; foreachIndex?: number }> =\n        prevResult.suspendPayload?.__workflow_meta?.resumeLabels ?? {};\n\n      // Check shouldPersistSnapshot option - default to true if not specified\n      const shouldPersist =\n        workflow?.options?.shouldPersistSnapshot?.({\n          stepResults: stepResults ?? {},\n          workflowStatus: 'suspended',\n        }) ?? true;\n\n      if (shouldPersist) {\n        // Persist state to snapshot context before suspending\n        // We use a special '__state' key to store state at the context level\n        await workflowsStore?.updateWorkflowResults({\n          workflowName: workflow.id,\n          runId,\n          stepId: '__state',\n          result: currentState as any,\n          requestContext,\n        });\n\n        const suspendTracingContext = this.resolveSuspendTracingContext(runId);\n        await workflowsStore?.updateWorkflowState({\n          workflowName: workflowId,\n          runId,\n          opts: {\n            status: 'suspended',\n            result: prevResult,\n            suspendedPaths,\n            resumeLabels,\n            activePaths: executionPath,\n            activeStepsPath,\n            ...(suspendTracingContext ? { tracingContext: suspendTracingContext } : {}),\n          },\n        });\n        await this.pruneAndRepersistSnapshot({ workflow, workflowId, runId });\n      }\n\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.suspend',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          parentWorkflow,\n          stepResults,\n          prevResult,\n          activeStepsPath,\n          requestContext,\n          timeTravel,\n          restart,\n          state: currentState,\n          outputOptions,\n        },\n      });\n\n      return;\n    }\n\n    if (step && isSingleStepEntry(step)) {\n      await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-step-result',\n          payload: {\n            id: stepId,\n            ...prevResult,\n          },\n        },\n      });\n\n      if (prevResult.status === 'success') {\n        await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n          type: 'watch',\n          runId,\n          data: {\n            type: 'workflow-step-finish',\n            payload: {\n              id: stepId,\n              metadata: {},\n            },\n          },\n        });\n      }\n    }\n\n    // Re-resolve the top-level entry at this path to drive next-step routing\n    // (parallel/conditional aggregation, foreach re-run, or advancing the index).\n    const rawNextStep = workflow.stepGraph[executionPath[0]!];\n    step = rawNextStep;\n    if (perStep) {\n      if (parentWorkflow && executionPath[0]! < workflow.stepGraph.length - 1) {\n        const { endedAt, output, status, ...nestedPrevResult } = prevResult as StepSuccess<any, any, any, any>;\n        await this.endWorkflow({\n          workflow,\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          stepResults,\n          prevResult: { ...nestedPrevResult, status: 'paused' },\n          activeStepsPath,\n          requestContext,\n          perStep,\n        });\n      } else {\n        await this.endWorkflow({\n          workflow,\n          parentWorkflow,\n          workflowId,\n          runId,\n          executionPath,\n          resumeSteps,\n          stepResults,\n          prevResult,\n          activeStepsPath,\n          requestContext,\n          perStep,\n        });\n      }\n    } else if ((step?.type === 'parallel' || step?.type === 'conditional') && executionPath.length > 1) {\n      await this.aggregateBranchResults({\n        workflow,\n        workflowId,\n        runId,\n        branchEntry: step,\n        branchExecutionPath: executionPath,\n        latestBranchResult: prevResult,\n        resumeSteps,\n        timeTravel,\n        restart,\n        parentWorkflow,\n        stepResults,\n        activeStepsPath,\n        requestContext,\n        state: currentState,\n        outputOptions,\n      });\n    } else if (step?.type === 'foreach') {\n      // Get the original array from the foreach step's stored payload\n      const foreachStepResult = readForeachResult(stepResults, getEntryId(step.step));\n      const originalArray = foreachStepResult?.payload;\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.step.run',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath: executionPath.slice(0, -1),\n          resumeSteps,\n          parentWorkflow,\n          stepResults,\n          prevResult: { ...prevResult, output: originalArray },\n          activeStepsPath,\n          requestContext,\n          timeTravel,\n          restart,\n          state: currentState,\n          outputOptions,\n          forEachIndex,\n        },\n      });\n    } else if (executionPath[0]! >= workflow.stepGraph.length - 1) {\n      await this.endWorkflow({\n        workflow,\n        parentWorkflow,\n        workflowId,\n        runId,\n        executionPath,\n        resumeSteps,\n        stepResults,\n        prevResult,\n        activeStepsPath,\n        requestContext,\n        state: currentState,\n        outputOptions,\n      });\n    } else {\n      const nextExecutionPath = executionPath.slice(0, -1).concat([executionPath[executionPath.length - 1]! + 1]);\n      await this.mastra.pubsub.publish('workflows', {\n        type: 'workflow.step.run',\n        runId,\n        data: {\n          workflowId,\n          runId,\n          executionPath: nextExecutionPath,\n          resumeSteps,\n          parentWorkflow,\n          stepResults,\n          prevResult,\n          activeStepsPath,\n          requestContext,\n          timeTravel,\n          restart,\n          state: currentState,\n          outputOptions,\n        },\n      });\n    }\n  }\n\n  async loadData({\n    workflowId,\n    runId,\n  }: {\n    workflowId: string;\n    runId: string;\n  }): Promise<WorkflowRunState | null | undefined> {\n    const workflowsStore = await this.mastra.getStorage()?.getStore('workflows');\n    const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n      workflowName: workflowId,\n      runId,\n    });\n\n    return snapshot;\n  }\n\n  /**\n   * Result of handling a single workflow event.\n   *\n   * - `ok: true` — event was processed; the transport should ack.\n   * - `ok: false, retry: true` — transient failure, the transport should\n   *   nack/redeliver (or, for HTTP push, return 5xx so the broker retries).\n   * - `ok: false, retry: false` — terminal/poison failure, the transport\n   *   should drop the event (or return 4xx for HTTP push).\n   */\n  async handle(event: Event): Promise<{ ok: true } | { ok: false; retry: boolean }> {\n    // Build a stable retry key once per call. If event.id is missing we fall\n    // back to a deterministic composite of type/runId/workflowId/executionPath\n    // so the same logical event lands in the same bucket on each redelivery\n    // and eventually reaches MAX_DELIVERY_ATTEMPTS. Never include a timestamp\n    // (or any monotonically-changing token) here — that resets the counter\n    // every attempt and reopens the infinite-retry path this guards against.\n    const baseWorkflowData = event.data as Partial<Pick<ProcessorArgs, 'workflowId' | 'executionPath'>>;\n    const eventKey =\n      event.id ??\n      JSON.stringify({\n        type: event.type,\n        runId: event.runId,\n        workflowId: baseWorkflowData?.workflowId,\n        executionPath: baseWorkflowData?.executionPath,\n      });\n\n    // If we've already declared this event terminal, stay terminal. A buggy\n    // transport that re-delivers a poisoned event must not rerun\n    // errorWorkflow on every redelivery or reset the per-event budget.\n    if (this.deliveryAttempts.get(eventKey) === WorkflowEventProcessor.TERMINAL_SENTINEL) {\n      return { ok: false, retry: false };\n    }\n\n    try {\n      await this.#dispatch(event);\n      this.deliveryAttempts.delete(eventKey);\n      return { ok: true };\n    } catch (err) {\n      const attempts = (this.deliveryAttempts.get(eventKey) ?? 0) + 1;\n      this.#setDeliveryAttempts(eventKey, attempts);\n      const exhausted = attempts >= WorkflowEventProcessor.MAX_DELIVERY_ATTEMPTS;\n\n      this.mastra.getLogger()?.error('WorkflowEventProcessor.handle: error processing event', {\n        type: event.type,\n        runId: event.runId,\n        attempts,\n        maxAttempts: WorkflowEventProcessor.MAX_DELIVERY_ATTEMPTS,\n        terminal: exhausted,\n        error: err,\n      });\n\n      if (!exhausted) {\n        return { ok: false, retry: true };\n      }\n\n      // Transport-level retries are exhausted. Surface as a terminal workflow\n      // failure so any caller awaiting workflows-finish (e.g. agent.generate())\n      // sees an error instead of hanging forever. Replace the counter with a\n      // TERMINAL sentinel so any later redelivery of the same logical event\n      // short-circuits at the top of handle() instead of rerunning\n      // errorWorkflow or resetting the budget.\n      this.#setDeliveryAttempts(eventKey, WorkflowEventProcessor.TERMINAL_SENTINEL);\n      try {\n        const failWorkflowData = event.data as Omit<ProcessorArgs, 'workflow'>;\n        // Never republish workflow.fail for an event that IS workflow.fail.\n        // Each publish gets a fresh event id (fresh retry bucket), so with a\n        // persistently-broken dependency (e.g. missing workflows table) the\n        // fail event would exhaust its own budget and publish another\n        // workflow.fail forever.\n        if (\n          event.type !== 'workflow.fail' &&\n          failWorkflowData &&\n          failWorkflowData.workflowId &&\n          failWorkflowData.runId\n        ) {\n          await this.errorWorkflow(failWorkflowData, getErrorFromUnknown(err));\n        }\n      } catch (failErr) {\n        this.mastra\n          .getLogger()\n          ?.error('WorkflowEventProcessor.handle: failed to publish workflow.fail after retry exhaustion', {\n            type: event.type,\n            runId: event.runId,\n            error: failErr,\n          });\n      }\n      return { ok: false, retry: false };\n    }\n  }\n\n  /**\n   * Set a deliveryAttempts entry and evict the oldest entries (FIFO via Map's\n   * insertion-order iteration) if we've exceeded DELIVERY_ATTEMPTS_MAX_ENTRIES.\n   * Re-setting an existing key first deletes then re-inserts so that the entry\n   * moves to the tail of the iteration order; this keeps actively-retrying\n   * events from being evicted while idle TERMINAL_SENTINEL entries age out.\n   */\n  #setDeliveryAttempts(eventKey: string, value: number): void {\n    if (this.deliveryAttempts.has(eventKey)) {\n      this.deliveryAttempts.delete(eventKey);\n    }\n    this.deliveryAttempts.set(eventKey, value);\n    while (this.deliveryAttempts.size > WorkflowEventProcessor.DELIVERY_ATTEMPTS_MAX_ENTRIES) {\n      const oldestKey = this.deliveryAttempts.keys().next().value;\n      if (oldestKey === undefined) break;\n      this.deliveryAttempts.delete(oldestKey);\n    }\n  }\n\n  /**\n   * @deprecated prefer {@link WorkflowEventProcessor.handle}, which returns a\n   * structured result instead of relying on an ack callback. Kept as a thin\n   * wrapper so existing pull-mode call sites continue to work.\n   */\n  async process(event: Event, ack?: () => Promise<void>) {\n    const result = await this.handle(event);\n    if (result.ok) {\n      try {\n        await ack?.();\n      } catch (e) {\n        this.mastra.getLogger()?.error('Error acking event', e);\n      }\n    }\n  }\n\n  async #dispatch(event: Event) {\n    const { type, data } = event;\n\n    const workflowData = data as Omit<ProcessorArgs, 'workflow'>;\n\n    const currentState = await this.loadData({\n      workflowId: workflowData.workflowId,\n      runId: workflowData.runId,\n    });\n\n    if (currentState?.status === 'canceled' && type !== 'workflow.end' && type !== 'workflow.cancel') {\n      return;\n    }\n\n    if (type.startsWith('workflow.user-event.')) {\n      const userEventWorkflow = this.#tryResolveWorkflow(workflowData.workflowId);\n      if (!userEventWorkflow) {\n        // Workflow no longer registered (e.g. deleted from code). Treat as a\n        // terminal failure rather than throwing — otherwise the transport\n        // would redeliver this event indefinitely.\n        return this.errorWorkflow(\n          workflowData,\n          new MastraError({\n            id: 'MASTRA_WORKFLOW',\n            text: `Workflow not found: ${workflowData.workflowId}`,\n            domain: ErrorDomain.MASTRA_WORKFLOW,\n            category: ErrorCategory.SYSTEM,\n          }),\n        );\n      }\n      await processWorkflowWaitForEvent(\n        {\n          ...workflowData,\n          workflow: userEventWorkflow,\n        },\n        {\n          pubsub: this.mastra.pubsub,\n          eventName: type.split('.').slice(2).join('.'),\n          currentState: currentState!,\n        },\n      );\n      return;\n    }\n\n    let workflow;\n    if (this.mastra.__hasInternalWorkflow(workflowData.workflowId, workflowData.runId)) {\n      workflow = this.mastra.__getInternalWorkflow(workflowData.workflowId, workflowData.runId);\n    } else if (workflowData.parentWorkflow) {\n      workflow = getNestedWorkflow(this.mastra, workflowData.parentWorkflow);\n    } else {\n      workflow = this.#tryResolveWorkflow(workflowData.workflowId);\n    }\n\n    if (!workflow) {\n      // For terminal/cleanup events (`workflow.fail`, `workflow.end`,\n      // `workflow.cancel`), we deliberately keep dispatching with\n      // `workflow=undefined` so the processors can finish their cleanup work\n      // (persist final state, notify parent workflow, publish to\n      // workflows-finish). Republishing `workflow.fail` here would loop\n      // forever because the redelivered event would hit this same branch.\n      if (type === 'workflow.fail' || type === 'workflow.end' || type === 'workflow.cancel') {\n        // fall through to switch below with workflow=undefined\n      } else {\n        return this.errorWorkflow(\n          workflowData,\n          new MastraError({\n            id: 'MASTRA_WORKFLOW',\n            text: `Workflow not found: ${workflowData.workflowId}`,\n            domain: ErrorDomain.MASTRA_WORKFLOW,\n            category: ErrorCategory.SYSTEM,\n          }),\n        );\n      }\n    }\n\n    if (type === 'workflow.start' || type === 'workflow.resume') {\n      const { runId } = workflowData;\n      await this.mastra.pubsub.publish(`workflow.events.v2.${runId}`, {\n        type: 'watch',\n        runId,\n        data: {\n          type: 'workflow-start',\n          payload: {\n            runId,\n          },\n        },\n      });\n    }\n\n    // For the cleanup-path events (`workflow.fail`/`workflow.end`/\n    // `workflow.cancel`) we may have fallen through above with no resolved\n    // workflow. The processors for those events tolerate `workflow=undefined`\n    // (they rely on optional chaining / persisted state), so we cast here to\n    // avoid widening the shared `ProcessorArgs.workflow` type across the\n    // hundreds of usage sites in this file.\n    const workflowArg = workflow as Workflow;\n\n    switch (type) {\n      case 'workflow.cancel':\n        await this.processWorkflowCancel({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      case 'workflow.start':\n        await this.processWorkflowStart({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      case 'workflow.resume':\n        await this.processWorkflowStart({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      case 'workflow.end':\n        await this.processWorkflowEnd({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      case 'workflow.step.end':\n        await this.processWorkflowStepEnd({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      case 'workflow.step.run':\n        await this.processWorkflowStepRun({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      case 'workflow.suspend':\n        await this.processWorkflowSuspend({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      case 'workflow.fail':\n        await this.processWorkflowFail({\n          workflow: workflowArg,\n          ...workflowData,\n        });\n        break;\n      default:\n        break;\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,eAAsB,wBAAwB,EAC5C,QACA,SAIgB;CAChB,IAAI,CAAC,QACH;CAGF,MAAM,OAAO,MAAM,KAAK;AAC1B;;;ACkKA,MAAa,iBAAiB,aAA6D,SAAc;CACvG,IAAI;CAEJ,IAAI,OAAO,SAAS,UAClB,SAAS,YAAY;MAChB;EACL,IAAI,CAAC,MAAM,IACT,OAAO;EAGT,SAAS,YAAY,KAAK;CAC5B;CAEA,OAAO,QAAQ,WAAW,YAAY,OAAO,SAAS;AACxD;;;;;;;;;;;;;;;;;AC1KA,SAAgB,WAAW,OAAgC;CACzD,OA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cAAAA,YAAY;IACd,IAAI;IACJ,MAAM,iCAAiC,KAAK,UAAU,aAAa;IACnE,QAAQC,cAAAA,YAAY;IACpB,UAAUC,cAAAA,cAAc;GAC1B,CAAC,CACH;EACF;EAKA,IAAI,OAAsB;EAM1B,KACG,KAAK,SAAS,cAAc,KAAK,SAAS,kBAC3C,cAAc,SAAS,MACtB,CAAC,WAAY,WAAW,QAAQ,mCAEjC,OAAO,KAAK,MAAM,cAAc;OAC3B,IAAI,KAAK,SAAS,YACvB,OAAO,wBACL;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;GACP;EACF,GACA;GACE,QAAQ,KAAK,OAAO;GACpB;EACF,CACF;OACK,IAAI,MAAM,SAAS,eACxB,OAAO,2BACL;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;GACP;EACF,GACA;GACE,QAAQ,KAAK,OAAO;GACpB,cAAc,KAAK;GACnB;EACF,CACF;OACK,IAAI,MAAM,SAAS,SACxB,OAAO,qBACL;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;GACP;EACF,GACA;GACE,QAAQ,KAAK,OAAO;GACpB,cAAc,KAAK;GACnB;EACF,CACF;OACK,IAAI,MAAM,SAAS,cACxB,OAAO,0BACL;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;GACP;EACF,GACA;GACE,QAAQ,KAAK,OAAO;GACpB,cAAc,KAAK;GACnB;EACF,CACF;OACK,IAAI,MAAM,SAAS,aAAa,cAAc,WAAW,GAC9D,OAAO,uBACL;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,OAAO;GACP;GACA;EACF,GACA;GACE,QAAQ,KAAK,OAAO;GACpB,QAAQ,KAA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