Read the latest details on the freeing of this couple here.

WASHINGTON — An American woman and her Canadian husband who were held hostage by militants in Afghanistan for five years have been freed along with their young children, President Trump said on Thursday, ending a case that has long frustrated diplomats and F.B.I. agents trying to secure their release.

Pakistan’s military said that “through an intelligence-based operation,” it took custody on Wednesday of the hostages from the Haqqani network, the Taliban faction that had seized Caitlan Coleman, 31, and her husband, Josh Boyle, 34, in 2012. The Pakistani military pledged to repatriate them, and American intelligence agencies were tracking the hostages as they crossed into the rugged tribal areas of northwest Pakistan.

The Trump administration and the Pakistani government worked together to free them, Mr. Trump said, but a senior American official said Pakistan’s intelligence service arranged the handover of the family after being pressured by American officials. It was not clear what, if any, concessions were made to the Haqqani network to ensure the family’s release.

“This is a positive moment for our country’s relationship with Pakistan,” Mr. Trump said in a statement. “The Pakistani government’s cooperation is a sign that it is honoring America’s wishes for it to do more to provide security in the region. We hope to see this type of cooperation and teamwork in helping secure the release of remaining hostages and in our future joint counterterrorism operations.”