The ruling on Thursday focused in large part on the centuries old writ of habeas corpus (“you have the body,” in Latin), a means by which prisoners can challenge their incarceration. Noting that the Constitution provides for suspension of the writ only in times of rebellion or invasion, Justice Kennedy called it “an indispensable mechanism for monitoring the separation of powers.”

In the years-long debate over the treatment of detainees, some critics of administration policy have asserted that those held at Guantánamo have fewer rights than people accused of crimes under American civilian and military law and that they are trapped in a sort of legal limbo.

Justice Kennedy wrote that the cases involving the detainees “lack any precise historical parallel. They involve individuals detained by executive order for the duration of a conflict that, if measure from September 11, 2001, to the present, is already among the longest wars in American history.”

The detainees at the center of the case decided on Thursday are not all typical of the people confined at Guantánamo. True, the majority were captured in Afghanistan or Pakistan. But the man who gave the case its title, Lakhdar Boumediene, is one of six Algerians who immigrated to Bosnia in the 1990’s and were legal residents there. They were arrested by Bosnian police within weeks of the Sept. 11 attacks on suspicion of plotting to attack the United States embassy in Sarajevo  “plucked from their homes, from their wives and children,” as their lawyer, Seth P. Waxman, a former solicitor general put it in the argument before the justices on Dec. 5.

The Supreme Court of Bosnia and Herzegovina ordered them released three months later for lack of evidence, whereupon the Bosnian police seized them and turned them over to the United States military, which sent them to Guantánamo.

Mr. Waxman argued before the United States Supreme Court that the six Algerians did not fit any authorized definition of enemy combatant, and therefore ought to be released.

The head of the New York-based Center for Constitutional Rights, which represents dozens of prisoners at Guantánamo, hailed the ruling. “The Supreme Court has finally brought an end to one of our nation’s most egregious injustices,” Vincent Warren, the organization’s executive director, told The Associated Press.