Pakistan's Supreme Court has ruled that former Prime Minister Imran Khan's arrest earlier this week was illegal and that he should be released immediately.
The announcement came a day after a court announced that Khan can be held for eight days.
Khan was arrested on Tuesday, accused of corruption.
Announcing the Supreme Court decision on Thursday, Chief Justice Umar Ata Bandial told Khan that his arrest was "invalid, therefore the whole process needs to be backtracked."
The chief justice urged Khan to appeal to his supporters to remain peaceful. Since his detention, violent clashes have erupted across several major Pakistani cities, where pro-Khan supporters denounced the powerful army. On Wednesday night, some protesters tried to set a police station ablaze in the capital, Islamabad. Others, in rare defiance, publicly questioned the military's role in the day-to-day running of the country.
Amid the chaos, the military accused what it called "evil elements" of inciting attacks against security installations and accused protesters of wanting to push Pakistan into "a civil war."
Police said on Thursday that at least 10 people had died and 2,000 had been arrested.
Khan's Tehreek-e-Insaaf party called his arrest an "abduction" and vowed to challenge it. But Pakistan's Interior Minister Rana Sanaullah said Khan was arrested in relation to a case filed in Pakistan's anti-corruption court, which Khan had not attended. Other party leaders have been arrested this week as well.
Outside the Supreme Court on Thursday, Khan's lawyers told reporters that the former prime minister will still need to appear at the Islamabad High Court Friday morning to complete the hearing that was abruptly interrupted on Tuesday.
They said that Khan would remain under the Supreme Court's custody and he is now allowed to meet his family and a limited number of friends. It is not immediately clear when Khan, who faces multiple corruption charges in Pakistani courts, will be allowed to return home.
The political turmoil comes as Pakistan continues to be mired in an economic crisis. Analysts warn that hopes are eroding that the South Asian nation can get a much-needed rescue package from the International Monetary Fund.
Khan, 70, was ousted as prime minister after a no-confidence vote in Parliament last April.
He has blamed the U.S. government for engineering his ouster, an allegation the U.S. denies.
Derek Chollet, counselor to Secretary of State Antony Blinken, told NPR's Morning Edition on Wednesday that statements about any U.S. role in Pakistan's politics are "completely false."
Diaa Hadid and Abdul Sattar contributed to this report from Islamabad.