When Eric O’Neill’s supervisor turned up unannounced at his Washington, DC-area home early on a Sunday morning, the still-groggy FBI employee was perplexed.

“Couldn’t this have waited till Monday?” he asked.

The answer shocked O’Neill, then 26. After five years working at the bureau as a “ghost” — following suspects for a living — he would be stepping out of the shadows: spying on someone in plain sight.

His target would be Robert Hanssen, a 25-year FBI veteran that the bureau suspected might be the most treacherous and damaging double agent in US history.

The wildest part? Hanssen would now be O’Neill’s boss.

In his new book, “Gray Day: My Undercover Mission to Expose America’s First ­Cyber Spy” (Crown), O’Neill tells his story of risking his life in 2001 to bring down the ­operative.

To get the ball rolling, Hanssen was promoted from a desk job at the State Department and O’Neill was given a role as Hanssen’s assistant. (The bureau wanted someone pretty green so as not to arouse suspicion.) After work each day, O’Neill would secretly meet with his actual boss, Special Agent Kate ­Alleman, recalling everything Hanssen said and did — which, as it turned out, would be nothing pleasant.

Hanssen had a reputation for being wildly arrogant and dour. At their very first meeting, O’Neill reached out his hand and began to introduce himself.

“Bob Hanssen? Hello, I’m . . .”

The man cut him off.

“You can call me sir, or boss,” Hanssen said.

The tension would not lessen over the next few days, with Hanssen telling O’Neill he was a “worthless clerk.”

So O’Neill was torn when he got his next assignment: “We’d like you to make [Hanssen] angry,” ­Alleman said, hoping the suspected operative’s reaction would deepen the psychological profile of him.

O’Neill would have no problem achieving that — but he did have a major concern.

“You know he’s armed and I’m not. He wears a revolver in an ankle holster and keeps an automatic [weapon] in his desk.”

In response, Alleman took a sip of her coffee “to hide her smile.”

“Fine,” O’Neill said. “Make him angry. Anything else while we’re at it? Should I get him to confess?”

This would be the first of many heart-stopping requests from Alleman. She next asked O’Neill to retrieve Hanssen’s keys so the FBI could copy them, but his “boss” kept his keys on him at all times.

So Alleman instead asked O’Neill to drive Hanssen to a meeting at the Defense Intelligence Agency (DIA) in an FBI vehicle — that way, she could have someone search Hanssen’s car while he was out of the office.

But something went wrong and when the two men showed up in the parking garage, the FBI car wasn’t there.

Annoyed at O’Neill’s seeming incompetence, Hanssen lashed out, calling him an “imbecile” and a “moron.” Finally, he said, “We’ll take my car, and that’s final.”

Here was O’Neill’s opportunity to push Hanssen to his limits.

“I raised my chin and met his eyes, puffed out my chest and stood with my feet shoulder-width apart. Classic animal aggression,” O’Neill writes. “I said, ‘No way we are taking your beat-up, boring, outdated old Ford Taurus to the DIA.'”

It worked.

“Before I could blink, [Hanssen] had the lapels of my sport coat twisted in his fists and curled me up to eye level, leaving my toes tipping for balance on the floor. Blood rushed to my face. One eye twitched.”

“Why is it so important to take [that] car?” Hanssen demanded to know.

O’Neill now feared he may have “pushed Hanssen over the line from suspicion to paranoia.” So he leaned back, forcing Hanssen off balance a bit, and apologized for his outburst — claiming he just wanted to make sure they “roll into the DIA in style, in that big black FBI SUV.”

This seemed to pacify his boss. (They took Hanssen’s Ford and the plan to search his car was dropped for the time being.)

O’Neill’s next assignment would put him right into the lion’s den.

Alleman tasked him with purloining Hanssen’s PalmPilot. If the device wasn’t in Hanssen’s hand or on the desk in front of him, it was always in his left back pocket.

One day in February, when Hanssen was away, O’Neill took a risk and snuck into his boss’ office.

He didn’t see the PalmPilot, but there was a messenger bag — and it was a jackpot: full of data disks, financial statements, a passport and a second cellphone. Among the files was a letter from Hanssen to the Russians arranging to meet.

In the letter, Hanssen revealed that he had dreamed of being a spy against his country since the age of 14, after reading a book about Kim Philby — the British intelligence officer who was also a Russian double agent.

“One might propose that I am either insanely brave or quite insane. I’d answer neither. I’d say insanely loyal,” Hanssen wrote. “Take your pick. There is insanity in all the answers.”

He also expressed his trademark annoyance. (“I have come about as close as I ever want to come to sacrificing myself to help you, and I get silence. I hate silence . . .”) And there was more than a touch of obvious paranoia: “My security concerns have proven reality-based,” Hanssen wrote. He lobbied his Russian masters to buy him a newer PalmPilot, with wireless Internet capabilities, which would allow the rapid transmission of encrypted messages.

Finally, he warned: “The US can be ­errantly likened to a powerfully built but ­retarded child, potentially dangerous, but young, immature and easily manipulated. But don’t be fooled by that appearance. It is also one which can turn ingenious quickly, like an idiot savant, once convinced of a goal.”

The astonishing letter gave the FBI what it had long sought — definitive proof that Hanssen was the spy who had been betraying them since 1985, doing colossal damage to the US’s counterintelligence capabilities by, among other things, revealing the identities of their undercover agents.

But while the FBI could have arrested Hanssen on the spot, they would have had him only on a conspiracy charge.

O’Neill rushed everything he found to Alleman, who had all of it copied, and then quickly returned the contents to Hanssen’s bag.

In order to put the double-crosser away forever, O’Neill would need to put his life on the line again.

Alleman explained to O’Neill that the smoking gun would be an actual information drop for the Russians.

As it turned out, Hanssen had just been spotted by agents driving at a snail’s pace past the sign for Foxstone Park in Vienna, Va. The FBI believed this was his “signal site” — where the Russians would signal when they were ready to receive his intel.

Hanssen checked the sign three times that night.

The next day he ordered O’Neill to drive him to a meeting. The underling had 15 minutes to arrange for a car from the FBI — who, this time, didn’t blow its shot.

But while agents moved and searched Hanssen’s car, he unexpectedly cut the meeting short, stalking out and leaving O’Neill no time to notify Alleman.

On the drive back, O’Neill tried to play it cool even though he was riddled with fear that Hanssen’s car would not be at the office when they returned. In that case, Hanssen would immediately know why — no one stole cars from the FBI garage — and there was no telling how the almost certainly armed Hanssen would react.

O’Neill needed to stall, but without arousing further suspicion.

He turned off the highway onto a side street, trying to persuade Hanssen that it was faster even though, as he writes, “anyone who has lived in the DC area for two weeks could call bulls–t.”

Enraged to the point that his fist was clenched in a tight ball, Hanssen ran through his usual list of insults — Idiot! Moron! Imbecile! — and finally hopped out of the car, determined to walk back to the office.

O’Neill also jumped out — and groveled.

Playing to Hanssen’s ego, the underling, a newlywed, said he needed relationship advice about his wife wanting to wait to have children. Hanssen had freely expressed his views on marriage before, once telling O’Neill: “Your genetic code demands that you make money and provide for the family. [Your wife’s genetic code] demands she stay home and nurture the children. Anything different goes against biology.”

Hanssen, in full blowhard mode, got back in the car and the two took the slow route as he lectured O’Neill.

Meanwhile, the FBI had discovered medical tape and chalk — Hanssen’s tools for signaling the Russians — in the car, along with classified documents that had no business being there. By the time Hanssen and O’Neill returned to the office, things seemed normal.

Days later, O’Neill helped devise another plan to get Hanssen out of the office: Two senior officers dropped in unexpectedly and said they wanted to go to the shooting practice range with Hanssen during lunch. As they outranked him, he didn’t have much of a choice.

Caught off guard, he grabbed his guns — but not his PalmPilot.

Minutes later, O’Neill extracted it from the man’s bag, along with a floppy disc and a flash drive, running everything downstairs for a tech team to copy. They were finishing just as Hanssen texted that he was on his way back.

“I scooped the devices into my arms and sprinted for the stairway,” writes O’Neill, who refers to this as his one true James Bond moment. “I slammed the door behind me and slid to a halt in Hanssen’s ­office.”

Just then the door buzzed, indicating Hanssen’s return. O’Neill quickly replaced the items and ran out of the office.

A moment later, a dark shadow crossed his door.

“ ‘Were you in my office?’ Hanssen leaned over my desk, his face inches from mine. I imagined I could smell gunpowder on his breath,” O’Neill writes.

“I left that memo in your inbox,” O’Neill replied. “Did you see it?”

“I never want you in my office again,” Hanssen said.

The purloined PalmPilot gave the FBI the final piece of the puzzle: Hanssen’s next meeting with the Russians was scheduled for the ­following weekend.

On Feb. 18, 2001, Hanssen left a package — presumably full of classified documents — wrapped in trash bags underneath a bridge in Foxstone Park, then placed a piece of tape at a nearby location, indicating the drop had been made.

He was en route to a third spot to pick up his payment of $50,000 when he was stopped by screeching FBI vans and a slew of armed agents.

As they took him into custody, Hanssen turned to one and said, “What took you so long?”

The US government took the death penalty off the table in exchange for Hanssen’s full cooperation. He pleaded guilty to 13 counts of espionage plus two related counts and was sentenced to life without the possibility of parole. Now 74, he is serving time at ADX Florence, the federal supermax prison in Colorado.

O’Neill, 46, left the FBI in May 2001. Today he’s a national-security strategist for the ­cyber-security company Carbon Black and runs his own investigative and security-services firm. His tale was also made into the 2007 movie “Breach.”

He wanted to interview Hanssen for the book but was refused.

“I would like to ask him why he did it,” O’Neill told The Post. “He has never answered that question for anyone. It’s the one scrap of power he’s kept for himself.”