Nepal's prime minister has agreed to resign as part of a last-minute deal with the country's former Maoist rebels to avert a political crisis.