The US military and the Afghan government have sealed an agreement on the gradual transfer of control of the main US prison in the country, a last-minute breakthrough that brings the first progress in months in contentious negotiations over a long-term partnership.