More info on my "fix" that sometimes throws an error. It only throws an error if System Events is not already running.
If System Events is not already running when I run the script, it throws the same error we initially got in 10.12.5. The next time I run the script, when System Events has been launched, the script works fine. When System Events quits itself after whatever period of inactivity, the script throws the error again the first time it is run with System Events not running. Run it again immediately and it works fine since System Events was activated on the last script run.
I don't know if that is tied to the original 10.12.5 bug, but I think they are related since they throw the same error.
I'm going to play with activating System Events early in the script and delaying by half a second.