WASHINGTON – A last-minute budget deal forged amid bluster and tough bargaining averted an embarrassing federal shutdown, cut billions in spending and provided the first major test of the divided government that voters ushered in five months ago.

Working late into Friday night, congressional and White House negotiators finally agreed on a plan to pay for government operations through the end of September while trimming $38.5 billion in spending.

Lawmakers then approved a measure to keep the government running for a few more days while the details of the new spending plan are written into legislation.

Actual approval of the deal is expected in the middle of next week.

"Americans of different beliefs came together again," President Barack Obama said from the White House Blue Room, a setting chosen to offer a clear view of the Washington Monument over his right shoulder.

The agreement was negotiated by Obama, House Speaker John Boehner, R-Ohio, and Senate Majority Leader Harry Reid, D-Nev. The administration was poised to shutter federal services, from national parks to tax-season help centers, and to send furlough notices to hundreds of thousands of federal workers.

All sides insisted they wanted to avoid that outcome, which at times seemed inevitable.

Shortly after midnight, White House budget director Jacob Lew issued a memo instructing departments and agencies to continue normal operations.

Boehner said the deal came after "a lot of discussion and a long fight." He won an ovation from his rank and file, including the new tea party adherents whose victories last November shifted control of the House to the GOP.

Reid declared the deal "historic."

The deal marked the end of a three-way clash of wills. It also set the tone for coming confrontations over raising the government's borrowing limit, the spending plan for the budget year that begins Oct. 1 and long-term deficit reduction.

In the end, all sides claimed victory.

For Republicans, it was the sheer size of the spending cuts. For Obama and Reid, it was casting aside GOP policy initiatives that would have blocked environmental rules and changed a program that provides family planning services.

Not all policy provisions were struck.

One in the final deal would ban the use of federal or local government funds to pay for abortions in the District of Columbia. A program dear to Boehner that lets District of Columbia students use federally funded vouchers to attend private schools also survived.

Republicans had included language to deny federal money to put in place Obama's year-old health care law. The deal only requires such a proposal to be voted on by the Democratic-controlled Senate, where it is certain to fall short of the necessary 60 votes.

The deal came together after six grueling weeks as negotiators virtually dared each other to shut down the government.