In the introduction, Lillie escapes the Aether Foundation with Cosmog, nicknamed Nebby, in her bag. Throughout the story Nebby repeatedly wanders away from Lillie, but no real harm comes about until the climax of the game where Team Skull takes Lillie to Aether Paradise where it is used to open holes to the Ultra Beast Dimension. It then evolves into Cosmoem and then Solgaleo/Lunala.
Another one becomes available in the post-game at the Lake of the Sunne/Moone in the alternate world accessed through the Altar of the Sunne/Moone with Nebby in the party.