WASHINGTON — The United States and Canada reached a last-minute deal to salvage the North American Free Trade Agreement on Sunday, overcoming deep divisions to keep the 25-year-old trilateral pact intact.

The deal came after a weekend of frantic talks to try and preserve a trade agreement that has stitched together the economies of Mexico, Canada and the United States but that was on the verge of collapsing. After more than a year of tense talks and strained relations between President Trump and Prime Minister Justin Trudeau of Canada, negotiators from both sides came to a resolution just ahead of a midnight deadline set by the White House.

The 11th-hour agreement was punctuated by a frenetic Sunday, with Canada’s leaders teleconferencing throughout the day with top American officials in Washington. Mr. Trudeau convened a 10 p.m. cabinet meeting in Ottawa to brief officials on the deal, as Jared Kushner, one of Mr. Trump’s closest advisers, and Robert E. Lighthizer, the president’s top trade negotiator, hashed out the final details. Mexico’s under secretary of foreign trade, Juan Carlos Baker, was expected to present the texts of the agreement to the Mexican senate just before midnight.

In a joint statement, Mr. Lighthizer and Canada’s foreign affairs minister, Chrystia Freeland, said the new deal “will give our workers, farmers, ranchers and businesses a high-standard trade agreement that will result in freer markets, fairer trade and robust economic growth in our region.”