KABUL, Afghanistan — After more than a week of hard-line posturing by Afghan and American officials, Secretary of State John Kerry and President Hamid Karzai defied expectations and agreed on key elements of a deal that, if completed, would keep American troops in Afghanistan beyond next year.

Making the announcement on Saturday evening after nearly 24 hours of talks and meetings, Mr. Kerry and Mr. Karzai said one major issue remained: legal jurisdiction, or immunity from prosecution under Afghan law, for American troops who remain in Afghanistan after 2014.

Immunity is a deal-breaking issue for the United States. The Iraqi government’s refusal to grant the same immunity was what forced American troops to withdraw from Iraq two years ago. Mr. Karzai suggested on Saturday that he, too, was uncomfortable with it, saying he and Mr. Kerry “don’t have a single view of judicial immunity for foreign forces.”

The matter, though, was ultimately beyond the authority of the government to decide, he said, and instead must be decided by “the Afghan people.” By that, he meant a loya jirga — a traditional gathering of elders and other powerful people — that the Afghan government is organizing in the coming weeks to approve the entire deal, known as a bilateral security agreement. It would then go before Parliament, Mr. Karzai said.