Improve session and script lifetime logic