KABUL, Afghanistan — The Taliban assailants apparently thought they were attacking an unprotected Christian-run day care center. But they mistakenly burst into the compound next door, where an American government contractor’s employees were heavily armed and ready, according to accounts that the contractor and the Afghan police gave on Friday of a wild four-hour shootout here.

The contractor, Roots of Peace, which runs agricultural projects financed by the United States Agency for International Development, had taken the precaution of blocking its front gate with an armored Land Cruiser, which guards used to take cover behind and shoot at the attackers, said Gary Kuhn, the group’s president, interviewed by telephone from its headquarters in San Rafael, Calif.

That slowed the attackers enough for the guards and the five foreign residents to retreat into the house and upstairs. “There’s a circular staircase which is very hard to take cover on. One tried coming up it, and the guard shot him,” Mr. Kuhn said, citing accounts from his staff members in Kabul.

Two of the residents, Americans, hid in their bedroom closets. “One very big, tall man hid in a closet and piled clothes on top of himself, while the Taliban were shooting in his room, throwing flash grenades, and even opened the closet door but didn’t see him,” said Heidi Kuhn, the group’s chief executive and Mr. Kuhn’s wife, who also was interviewed by telephone in California. “It’s a miracle all of them escaped.”