Tesla has agreed to buy energy storage company Maxwell Technologies for $218 million US in an all-stock deal that could help the electric car maker produce batteries that hold more energy and last longer at a time when it needs to cut costs and faces growing competition.