Mr. Trump not only accepted the spending-and-debt plan advanced by Senator Chuck Schumer of New York and Representative Nancy Pelosi of California, the Democratic leaders, but also aligned himself with them on immigration. A day after rescinding President Barack Obama’s program protecting younger illegal immigrants on the grounds that it went beyond a president’s authority, Mr. Trump said he wanted to work with Democrats to legalize the program.

“We had a very good meeting with Nancy Pelosi and Chuck Schumer,” Mr. Trump told reporters after the Oval Office session without mentioning that Mr. Ryan and other Republican leaders had also attended. Regarding the immigration program, Mr. Trump said, “Chuck and Nancy would like to see something happen, and so do I.”

Republican leaders looked grim but resigned afterward and attributed Mr. Trump’s fiscal deal to a need for unity after Harvey struck Texas and as Hurricane Irma barreled toward Florida. “Look, the president can speak for himself, but his feeling was that we needed to come together to not create a picture of divisiveness at a time of genuine national crisis, and that was the rationale,” said Senator Mitch McConnell of Kentucky, the majority leader.

Democrats were grinning at their surprise victory and happy to rub it in. “It was a really good moment of some bipartisanship,” Mr. Schumer said. He added: “The bottom line is the president listened to the arguments. We think we made a very reasonable and strong argument. And to his credit, he went with the better argument.”

Until now, Mr. Trump has sought to govern through the strength of Republican majorities in Congress, an approach that has not secured top priorities like repealing Mr. Obama’s health care program. After castigating Democrats as obstructionists, Mr. Trump may now seek common cause on areas of mutual interest like infrastructure projects, immigration and taxes.