Stuyvesant Town-Peter Cooper Village, the largest apartment complex in Manhattan, is expected to be sold for more than $5.3 billion, an agreement that will preserve nearly half the 11,232-unit complex for middle-class families, according to officials involved in the negotiations.

The sale, to the Blackstone Group, a Wall Street investment firm and one of the country’s largest landlords, includes an unusual regulatory agreement with the administration of Mayor Bill de Blasio that would ensure that a block of 5,000 apartments would be affordable for the next 20 years for families of teachers, construction workers, firefighters and others who have traditionally made their homes at Stuyvesant Town.

The agreement, which covers a high-profile complex that symbolized the rapidly changing nature of New York City housing, represents a victory for Mr. de Blasio, who has made affordable housing a central tenet of his administration. Up to now, tenant activists and elected officials have feared that Stuyvesant Town’s 65-year history as a middle-class bastion was ending.

“This has been a priority for us since Day 1,” Mr. de Blasio said in a statement released on Monday afternoon. “We weren’t going to lose StuyTown on our watch.”