Hundreds of jobs at a County Durham train factory have been given a lifeline after owners Hitachi struck a £500 million deal with rail operator FirstGroup.