SKOPJE, Macedonia — Prime Minister Nikola Gruevski of Macedonia, reeling from a long-running scandal over the wiretapping of thousands of people, has agreed to step down by Jan. 15 to pave the way for new elections in the spring.

The deal was announced early Wednesday after 13 hours of final negotiations between Mr. Gruevski and leaders of the opposition. Johannes Hahn, a European Union commissioner, mediated the talks.

The agreement calls for the Social Democratic Union of Macedonia, the main opposition party, which had walked out of Parliament in a dispute with the governing party, to return to the legislature. After the prime minister resigns, a new government will take control and ease the way for elections on April 24.

“The political crisis is over,” said Mr. Gruevski, who will be eligible to run again for prime minister in the spring. “I am happy with the agreement reached.”