An Algorithmic Theory of Metacognition in Minds and Machines