How to use a script field inside Aggregate?

Script fields are a feature which produce field values on the fly for the top N documents that match the given query. They are not useable in other parts of the API. In particular, since they are only calculated for top N, it would not be possible to use them for aggregations which operate on every document the query matches.

You will need to duplicate your script inside your sum aggregation. There is a documented example using a script for a sum aggregation which may help. To avoid duplication, you could also store the script and reference in both locations by name.