A library building previously destined for auction has been saved after a last-minute agreement was struck to bring it back into a “community asset”.