Barack Obama has pledged America’s continued support for Afghanistan as he flew to the country to sign a deal outlining the commitment after US combat troops leave in 2014.
The president’s unannounced trip took place on the first anniversary of the killing by US special forces of al Qaeda leader Osama bin Laden in Pakistan.
Mr Obama and Afghan President Hamid Karzai signed the US-Afghan Strategic Partnership Agreement in Mr Karzai’s palace in the capital Kabul.
The deal sets out the US relationship with Afghanistan beyond 2014, covering security, economics and governance.
It is limited in scope but means Afghanistan is guaranteed its sovereignty, with a promise that it will not be abandoned.
And the US is able to end its combat mission in the long and unpopular war, which began in 2001, but keep a foothold in the country.
The agreement does not commit the US to any specific troop presence or spending.
But it does allow America to potentially keep troops in Afghanistan after the war ends for two specific purposes: continued training of Afghan forces and targeted operations against al Qaeda.
Presidents Obama and Karzai signed an agreement in Kabul
The terror group is present in neighbouring Pakistan but has only a nominal presence inside Afghanistan.
Mr Obama declared: “Together, we’re now committed to replacing war with peace.”
The US leader admitted there would be difficult days ahead for Afghanistan, but said the Afghan people were taking control of their own future.
He said: “The wages of war have been great for both our nations,” adding he looked forward to a “future of peace”.
Mr Karzai said his people “will never forget” the help of US forces over the past decade.
He said the partnership agreement shows the two nations will continue to fight terrorism together. The leaders shook hands after the signing.
Later, Mr Obama, the commander-in-chief of American troops, addressed soldiers at Bagram air force base.
“It’s still tough, the battle is not yet over. Some of your buddies are going to get injured, some of your buddies may get killed,” he said.
“There is going to be heartbreak and pain and difficulty ahead, but there is a light on the horizon because of the sacrifices you have made.”
Mr Obama and Mr Karzai approved the Strategic Partnership Agreement before the American leader delivers a televised address to the American people on the war effort later.
Mr Obama’s message will be that the war is ending on his watch but America’s commitment to the country is not.
Earlier, his plane, Air Force One, touched down late at night at Bagram airfield.