Former national security advisor John Bolton, the hawk with a bushy mustache, argues the U.S. did not lose the war in Afghanistan. He is certainly correct that U.S. forces were not defeated on the battlefield.
It is probably more accurate to say we failed at nation building, got tired of the attempt, and decided to stop trying. Once nation building was off the table, staying no longer made sense unless we were prepared to garrison the country essentially forever.
U.S. Presidents of both parties have decided staying indefinitely is a non-starter. Hindsight may or may not support that decision. We have permanent garrisons in S. Korea, Japan, Germany, the U.K., Spain and Italy, but none of those are under attack.
It is possible we'll have to return briefly to punish whoever is running Afghanistan if they once again harbor anti-U.S. activists. Or the Taliban may decide they'd rather govern their nation in peace and leave us alone, as the North Koreans and Vietnamese have mostly done. I think this would suit Americans and perhaps many Afghans.