(Numbers 22:20:) "And God came to Balaam at night." This is what Scripture says (Job 33:15-17): "In a dream, in a vision of the night... then He opens the ears of men... to turn man away from his deed, and He hides pride from a man." What is the meaning of "and He hides from a man"? The Holy One, blessed be He, hid from him that his going would destroy him from the world and lead him to the pit of corruption. For at the hour when a person goes to sin, Ha-Satan dances before him until he completes the transgression. Once he has destroyed him, he turns back and informs him, as it is said (Proverbs 7:22-23): "He goes after her suddenly... until an arrow pierces his liver." So did the Holy One, blessed be He, hide it from Balaam until he went and destroyed his soul. After he had departed from his honor and gone and destroyed his soul, and knew the state he was in, he began to plead for his soul (Numbers 23:10): "Let my soul die the death of the upright."
How Ha-Satan Danced Before Balaam Until His Soul Was Lost
Midrash Tanchuma Buber, Balak 10:1
ויבא אלהים אל בלעם לילה (שם שם כ). זש"ה בחלום (בחזיון) [חזיון] לילה וגו', אז יגלה אוזן אנשים וגו', להסיר (מאדם) [אדם] מעשה וגוה מגבר יכסה (איוב לג טו טז יז), מהו מגבר יכסה, העלים הקב"ה ממנו, שהליכתו מאבדתו מן העולם, ומוליכו לבאר שחת, שבשעה שאדם הולך לחטא השטן מרקד לפניו, עד שהוא גומר את העבירה, כיון שאיבדו חוזר ומודיעו, שנאמר הולך אחריה פתאום וגו' עד יפלח חץ כבדו (משלי ז כב כג), כך העלים הקב"ה מבלעם עד שהלך ואיבד את נפשו, משיצא מכבודו והלך ואיבד את נפשו וידע במה שהוא בו, התחיל לבקש על נפשו, תמות נפשי מות ישרים (במדבר כג י).