How do packaged cookies stay good for so long?
The sugar answers are spot on.

Also, let's give a shout out to modern packaging--particularly the vapor barriers in use today.  Light years ahead of the old days.  That vapor barrier is a significant contributor to the longevity of the modern packaged cookie.

Also impressive, is Modified Atmosphere Packaging. That allows products today that were unthinkable 20 years or so ago. Pre-sliced lunch meats, shredded cheeses, Lunchables, prefab sandwiches etc.