> How else does a 21st century military lose to someone living in the sixth century?
Part of the reason is this type of chronic underestimation of the enemy. The Taliban may hold some socially outdated ideas, but their use of digital communications and machine guns is absolutely not "from the sixth century". Rule 1 of warfare is to never underestimate your opponent.
The main problem the US had was that from basically day 2 (day 1 being spent winning the conventional war) they were looking for a way to leave the country again and everybody there knew it. If you are not looking to annex the conquered territory indefinitely (which is extremely unpopular in western countries for PR reasons) then eventually you will have to leave and so your opponents only need to find a way to survive until then.