Inner Workings of a Thermos
One way to build a thermos-like container would be to take a jar and wrap it in, for example, foam insulation. Insulation works by two principles. First, the plastic in the foam is not a very good heat conductor. Second, the air trapped in the foam is an even worse heat conductor. So conduction has been reduced. Because the air is broken into tiny bubbles, the other thing foam insulation does is largely eliminate convection inside the foam. Heat transfer through foam is therefore pretty small.
It turns out that there is an even better insulator than foam: a vacuum. A vacuum is a lack of atoms. A "perfect vacuum" contains zero atoms. It is nearly impossible to create a perfect vacuum, but you can get close. Without atoms you eliminate conduction and convection completely.
What you find in a thermos is a glass envelope holding a vacuum. Inside a thermos is glass, and around the glass is a vacuum. The glass envelope is fragile, so it is encased in a plastic or metal case. In many thermoses you can actually unscrew and remove this glass envelope.
A thermos then goes one step further. The glass is silvered (like a mirror) to reduce infrared radiation. The combination of a vacuum and the silvering greatly reduces heat transfer by convection, conduction and radiation.
So why do hot things in a thermos ever cool down? You can see in the figure two paths for heat transfer. The big one is the cap. The other one is the glass, which provides a conduction path at the top of the flask where the inner and outer walls meet. Although heat transfer through these paths is small, it is not zero.
Does the thermos know whether the fluid inside it is hot or cold? No. All the thermos is doing is limiting heat transfer through the walls of the thermos. That lets the fluid inside the thermos keep its temperature nearly constant for a long period of time (whether the temperature is hot or cold).